diff --git a/.ci.yaml b/.ci.yaml index 208528bffb7..23415a90390 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -325,10 +325,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 analyze_legacy N-2 @@ -336,10 +336,10 @@ targets: timeout: 30 properties: target_file: analyze_legacy.yaml - channel: "3.27.4" + channel: "3.29.3" env_variables: >- { - "CHANNEL": "3.27.4" + "CHANNEL": "3.29.3" } - name: Linux_android custom_package_tests master diff --git a/.ci/flutter_stable.version b/.ci/flutter_stable.version index e4b4d426104..5d78b52679e 100644 --- a/.ci/flutter_stable.version +++ b/.ci/flutter_stable.version @@ -1 +1 @@ -edada7c56edf4a183c1735310e123c7f923584f1 +b8962555571d8c170cff8e76023ea7bf60e5ec4b diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7c1701a51b5..8bc0e8932ba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,7 +31,7 @@ jobs: # the change if it doesn't. run: | cd $HOME - git clone https://github.com/flutter/flutter.git --depth 1 -b 3.32.0 _flutter + git clone https://github.com/flutter/flutter.git --depth 1 -b 3.35.0 _flutter echo "$HOME/_flutter/bin" >> $GITHUB_PATH cd $GITHUB_WORKSPACE # Checks out a copy of the repo. diff --git a/packages/animations/CHANGELOG.md b/packages/animations/CHANGELOG.md index d10278912a3..1630957ffa5 100644 --- a/packages/animations/CHANGELOG.md +++ b/packages/animations/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.0.11 diff --git a/packages/animations/example/lib/container_transition.dart b/packages/animations/example/lib/container_transition.dart index e35ddf74a68..c50f363e1ef 100644 --- a/packages/animations/example/lib/container_transition.dart +++ b/packages/animations/example/lib/container_transition.dart @@ -55,9 +55,9 @@ class _OpenContainerTransformDemoState void _showMarkedAsDoneSnackbar(bool? isMarkedAsDone) { if (isMarkedAsDone ?? false) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar( - content: Text('Marked as done!'), - )); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Marked as done!'))); } } @@ -84,9 +84,10 @@ class _OpenContainerTransformDemoState onPressed: (int index) { setModalState(() { setState(() { - _transitionType = index == 0 - ? ContainerTransitionType.fade - : ContainerTransitionType.fadeThrough; + _transitionType = + index == 0 + ? ContainerTransitionType.fade + : ContainerTransitionType.fadeThrough; }); }); }, @@ -229,10 +230,7 @@ class _OpenContainerTransformDemoState closedElevation: 0.0, closedBuilder: (BuildContext _, VoidCallback openContainer) { return ListTile( - leading: Image.asset( - 'assets/avatar_logo.png', - width: 40, - ), + leading: Image.asset('assets/avatar_logo.png', width: 40), onTap: openContainer, title: Text('List item ${index + 1}'), subtitle: const Text('Secondary text'), @@ -245,15 +243,11 @@ class _OpenContainerTransformDemoState floatingActionButton: OpenContainer( transitionType: _transitionType, openBuilder: (BuildContext context, VoidCallback _) { - return const _DetailsPage( - includeMarkAsDoneButton: false, - ); + return const _DetailsPage(includeMarkAsDoneButton: false); }, closedElevation: 6.0, closedShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(_fabDimension / 2), - ), + borderRadius: BorderRadius.all(Radius.circular(_fabDimension / 2)), ), closedColor: Theme.of(context).colorScheme.secondary, closedBuilder: (BuildContext context, VoidCallback openContainer) { @@ -315,10 +309,7 @@ class _ExampleCard extends StatelessWidget { child: ColoredBox( color: Colors.black38, child: Center( - child: Image.asset( - 'assets/placeholder_image.png', - width: 100, - ), + child: Image.asset('assets/placeholder_image.png', width: 100), ), ), ), @@ -335,10 +326,9 @@ class _ExampleCard extends StatelessWidget { child: Text( 'Lorem ipsum dolor sit amet, consectetur ' 'adipiscing elit, sed do eiusmod tempor.', - style: Theme.of(context) - .textTheme - .bodyMedium! - .copyWith(color: Colors.black54), + style: Theme.of( + context, + ).textTheme.bodyMedium!.copyWith(color: Colors.black54), ), ), ], @@ -348,10 +338,7 @@ class _ExampleCard extends StatelessWidget { } class _SmallerCard extends StatelessWidget { - const _SmallerCard({ - required this.openContainer, - required this.subtitle, - }); + const _SmallerCard({required this.openContainer, required this.subtitle}); final VoidCallback openContainer; final String subtitle; @@ -368,10 +355,7 @@ class _SmallerCard extends StatelessWidget { color: Colors.black38, height: 150, child: Center( - child: Image.asset( - 'assets/placeholder_image.png', - width: 80, - ), + child: Image.asset('assets/placeholder_image.png', width: 80), ), ), Expanded( @@ -381,15 +365,9 @@ class _SmallerCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - 'Title', - style: Theme.of(context).textTheme.titleLarge, - ), + Text('Title', style: Theme.of(context).textTheme.titleLarge), const SizedBox(height: 4), - Text( - subtitle, - style: Theme.of(context).textTheme.bodySmall, - ), + Text(subtitle, style: Theme.of(context).textTheme.bodySmall), ], ), ), @@ -419,10 +397,7 @@ class _ExampleSingleTile extends StatelessWidget { height: height, width: height, child: Center( - child: Image.asset( - 'assets/placeholder_image.png', - width: 60, - ), + child: Image.asset('assets/placeholder_image.png', width: 60), ), ), Expanded( @@ -431,15 +406,13 @@ class _ExampleSingleTile extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - 'Title', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Title', style: Theme.of(context).textTheme.titleMedium), const SizedBox(height: 8), Text( - 'Lorem ipsum dolor sit amet, consectetur ' - 'adipiscing elit,', - style: Theme.of(context).textTheme.bodySmall), + 'Lorem ipsum dolor sit amet, consectetur ' + 'adipiscing elit,', + style: Theme.of(context).textTheme.bodySmall, + ), ], ), ), @@ -451,11 +424,7 @@ class _ExampleSingleTile extends StatelessWidget { } class _InkWellOverlay extends StatelessWidget { - const _InkWellOverlay({ - this.openContainer, - this.height, - this.child, - }); + const _InkWellOverlay({this.openContainer, this.height, this.child}); final VoidCallback? openContainer; final double? height; @@ -465,10 +434,7 @@ class _InkWellOverlay extends StatelessWidget { Widget build(BuildContext context) { return SizedBox( height: height, - child: InkWell( - onTap: openContainer, - child: child, - ), + child: InkWell(onTap: openContainer, child: child), ); } } @@ -489,7 +455,7 @@ class _DetailsPage extends StatelessWidget { icon: const Icon(Icons.done), onPressed: () => Navigator.pop(context, true), tooltip: 'Mark as done', - ) + ), ], ), body: ListView( @@ -499,9 +465,7 @@ class _DetailsPage extends StatelessWidget { height: 250, child: Padding( padding: const EdgeInsets.all(70.0), - child: Image.asset( - 'assets/placeholder_image.png', - ), + child: Image.asset('assets/placeholder_image.png'), ), ), Padding( @@ -512,18 +476,18 @@ class _DetailsPage extends StatelessWidget { Text( 'Title', style: Theme.of(context).textTheme.headlineSmall!.copyWith( - color: Colors.black54, - fontSize: 30.0, - ), + color: Colors.black54, + fontSize: 30.0, + ), ), const SizedBox(height: 10), Text( _loremIpsumParagraph, style: Theme.of(context).textTheme.bodyMedium!.copyWith( - color: Colors.black54, - height: 1.5, - fontSize: 16.0, - ), + color: Colors.black54, + height: 1.5, + fontSize: 16.0, + ), ), ], ), diff --git a/packages/animations/example/lib/fade_scale_transition.dart b/packages/animations/example/lib/fade_scale_transition.dart index 7a633f21e50..b4e15bdc7ba 100644 --- a/packages/animations/example/lib/fade_scale_transition.dart +++ b/packages/animations/example/lib/fade_scale_transition.dart @@ -27,12 +27,12 @@ class _FadeScaleTransitionDemoState extends State 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]. - }); + 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(); } @@ -60,10 +60,7 @@ class _FadeScaleTransitionDemoState extends State floatingActionButton: AnimatedBuilder( animation: _controller, builder: (BuildContext context, Widget? child) { - return FadeScaleTransition( - animation: _controller, - child: child, - ); + return FadeScaleTransition(animation: _controller, child: child); }, child: Visibility( visible: _controller.status != AnimationStatus.dismissed, @@ -102,9 +99,10 @@ 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 7b8e30e7a76..c929e99cbcb 100644 --- a/packages/animations/example/lib/fade_through_transition.dart +++ b/packages/animations/example/lib/fade_through_transition.dart @@ -18,11 +18,7 @@ class FadeThroughTransitionDemo extends StatefulWidget { class _FadeThroughTransitionDemoState extends State { int pageIndex = 0; - List pageList = [ - _FirstPage(), - _SecondPage(), - _ThirdPage(), - ]; + List pageList = [_FirstPage(), _SecondPage(), _ThirdPage()]; @override Widget build(BuildContext context) { @@ -54,14 +50,8 @@ class _FadeThroughTransitionDemoState extends State { icon: Icon(Icons.photo_library), label: 'Albums', ), - BottomNavigationBarItem( - icon: Icon(Icons.photo), - label: 'Photos', - ), - BottomNavigationBarItem( - icon: Icon(Icons.search), - label: 'Search', - ), + BottomNavigationBarItem(icon: Icon(Icons.photo), label: 'Photos'), + BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'), ], ), ); @@ -107,10 +97,7 @@ class _ExampleCard extends StatelessWidget { ), ], ), - InkWell( - splashColor: Colors.black38, - onTap: () {}, - ), + InkWell(splashColor: Colors.black38, onTap: () {}), ], ), ), @@ -126,28 +113,19 @@ class _FirstPage extends StatelessWidget { Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _ExampleCard(), - _ExampleCard(), - ], + children: [_ExampleCard(), _ExampleCard()], ), ), Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _ExampleCard(), - _ExampleCard(), - ], + children: [_ExampleCard(), _ExampleCard()], ), ), Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _ExampleCard(), - _ExampleCard(), - ], + children: [_ExampleCard(), _ExampleCard()], ), ), ], @@ -158,12 +136,7 @@ class _FirstPage extends StatelessWidget { class _SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { - return Column( - children: [ - _ExampleCard(), - _ExampleCard(), - ], - ); + return Column(children: [_ExampleCard(), _ExampleCard()]); } } @@ -173,10 +146,7 @@ class _ThirdPage extends StatelessWidget { return ListView.builder( itemBuilder: (BuildContext context, int index) { return ListTile( - leading: Image.asset( - 'assets/avatar_logo.png', - width: 40, - ), + leading: Image.asset('assets/avatar_logo.png', width: 40), title: Text('List item ${index + 1}'), subtitle: const Text('Secondary text'), ); diff --git a/packages/animations/example/lib/main.dart b/packages/animations/example/lib/main.dart index 6a94ceaf4e1..178400cc3aa 100644 --- a/packages/animations/example/lib/main.dart +++ b/packages/animations/example/lib/main.dart @@ -13,9 +13,7 @@ import 'shared_axis_transition.dart'; void main() { runApp( MaterialApp( - theme: ThemeData.from( - colorScheme: const ColorScheme.light(), - ).copyWith( + theme: ThemeData.from(colorScheme: const ColorScheme.light()).copyWith( pageTransitionsTheme: const PageTransitionsTheme( builders: { TargetPlatform.android: ZoomPageTransitionsBuilder(), @@ -137,22 +135,15 @@ class _TransitionListTile extends StatelessWidget { @override Widget build(BuildContext context) { return ListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 15.0, - ), + contentPadding: const EdgeInsets.symmetric(horizontal: 15.0), leading: Container( width: 40.0, height: 40.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.0), - border: Border.all( - color: Colors.black54, - ), - ), - child: const Icon( - Icons.play_arrow, - size: 35, + border: Border.all(color: Colors.black54), ), + child: const Icon(Icons.play_arrow, size: 35), ), onTap: onTap, title: Text(title), diff --git a/packages/animations/example/lib/shared_axis_transition.dart b/packages/animations/example/lib/shared_axis_transition.dart index ce1710810b6..b38acb32a44 100644 --- a/packages/animations/example/lib/shared_axis_transition.dart +++ b/packages/animations/example/lib/shared_axis_transition.dart @@ -129,10 +129,7 @@ class _CoursePage extends StatelessWidget { child: Text( 'Bundled categories appear as groups in your feed. ' 'You can always change this later.', - style: TextStyle( - fontSize: 12.0, - color: Colors.grey, - ), + style: TextStyle(fontSize: 12.0, color: Colors.grey), textAlign: TextAlign.center, ), ), @@ -147,9 +144,7 @@ class _CoursePage extends StatelessWidget { } class _CourseSwitch extends StatefulWidget { - const _CourseSwitch({ - required this.course, - }); + const _CourseSwitch({required this.course}); final String course; @@ -185,10 +180,7 @@ class _SignInPage extends StatelessWidget { return Column( children: [ Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 20)), - Image.asset( - 'assets/avatar_logo.png', - width: 80, - ), + Image.asset('assets/avatar_logo.png', width: 80), Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 50)), Text( 'Hi David Park', @@ -197,10 +189,7 @@ class _SignInPage extends StatelessWidget { Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 50)), const Text( 'Sign in with your account', - style: TextStyle( - fontSize: 12.0, - color: Colors.grey, - ), + style: TextStyle(fontSize: 12.0, color: Colors.grey), ), Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/packages/animations/example/pubspec.yaml b/packages/animations/example/pubspec.yaml index 0117837fc1c..75e7e2118e4 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: animations: diff --git a/packages/animations/lib/src/fade_scale_transition.dart b/packages/animations/lib/src/fade_scale_transition.dart index 44487e04260..b72aab3a828 100644 --- a/packages/animations/lib/src/fade_scale_transition.dart +++ b/packages/animations/lib/src/fade_scale_transition.dart @@ -79,10 +79,7 @@ class FadeScaleTransitionConfiguration extends ModalConfiguration { Animation secondaryAnimation, Widget child, ) { - return FadeScaleTransition( - animation: animation, - child: child, - ); + return FadeScaleTransition(animation: animation, child: child); } } @@ -108,11 +105,7 @@ class FadeScaleTransition extends StatelessWidget { /// /// [animation] is typically an [AnimationController] that drives the transition /// animation. [animation] cannot be null. - const FadeScaleTransition({ - super.key, - required this.animation, - this.child, - }); + const FadeScaleTransition({super.key, required this.animation, this.child}); /// The animation that drives the [child]'s entrance and exit. /// diff --git a/packages/animations/lib/src/fade_through_transition.dart b/packages/animations/lib/src/fade_through_transition.dart index 7be2e883c16..14d33480ea0 100644 --- a/packages/animations/lib/src/fade_through_transition.dart +++ b/packages/animations/lib/src/fade_through_transition.dart @@ -227,20 +227,14 @@ class _ZoomedFadeInFadeOut extends StatelessWidget { Animation animation, Widget? child, ) { - return _ZoomedFadeIn( - animation: animation, - child: child, - ); + return _ZoomedFadeIn(animation: animation, child: child); }, reverseBuilder: ( BuildContext context, Animation animation, Widget? child, ) { - return _FadeOut( - animation: animation, - child: child, - ); + return _FadeOut(animation: animation, child: child); }, child: child, ); @@ -248,10 +242,7 @@ class _ZoomedFadeInFadeOut extends StatelessWidget { } class _ZoomedFadeIn extends StatelessWidget { - const _ZoomedFadeIn({ - this.child, - required this.animation, - }); + const _ZoomedFadeIn({this.child, required this.animation}); final Widget? child; final Animation animation; @@ -259,48 +250,40 @@ class _ZoomedFadeIn extends StatelessWidget { static final CurveTween _inCurve = CurveTween( curve: const Cubic(0.0, 0.0, 0.2, 1.0), ); - static final TweenSequence _scaleIn = TweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(0.92), - weight: 6 / 20, - ), - TweenSequenceItem( - tween: Tween(begin: 0.92, end: 1.0).chain(_inCurve), - weight: 14 / 20, - ), - ], - ); - static final TweenSequence _fadeInOpacity = TweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 6 / 20, - ), - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0).chain(_inCurve), - weight: 14 / 20, - ), - ], - ); + static final TweenSequence _scaleIn = + TweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(0.92), + weight: 6 / 20, + ), + TweenSequenceItem( + tween: Tween(begin: 0.92, end: 1.0).chain(_inCurve), + weight: 14 / 20, + ), + ]); + static final TweenSequence _fadeInOpacity = + TweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 6 / 20, + ), + TweenSequenceItem( + tween: Tween(begin: 0.0, end: 1.0).chain(_inCurve), + weight: 14 / 20, + ), + ]); @override Widget build(BuildContext context) { return FadeTransition( opacity: _fadeInOpacity.animate(animation), - child: ScaleTransition( - scale: _scaleIn.animate(animation), - child: child, - ), + child: ScaleTransition(scale: _scaleIn.animate(animation), child: child), ); } } class _FadeOut extends StatelessWidget { - const _FadeOut({ - this.child, - required this.animation, - }); + const _FadeOut({this.child, required this.animation}); final Widget? child; final Animation animation; @@ -308,18 +291,17 @@ class _FadeOut extends StatelessWidget { static final CurveTween _outCurve = CurveTween( curve: const Cubic(0.4, 0.0, 1.0, 1.0), ); - static final TweenSequence _fadeOutOpacity = TweenSequence( - >[ - TweenSequenceItem( - tween: Tween(begin: 1.0, end: 0.0).chain(_outCurve), - weight: 6 / 20, - ), - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 14 / 20, - ), - ], - ); + static final TweenSequence _fadeOutOpacity = + TweenSequence(>[ + TweenSequenceItem( + tween: Tween(begin: 1.0, end: 0.0).chain(_outCurve), + weight: 6 / 20, + ), + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 14 / 20, + ), + ]); @override Widget build(BuildContext context) { diff --git a/packages/animations/lib/src/modal.dart b/packages/animations/lib/src/modal.dart index c4348a9f0ee..11488a4178a 100644 --- a/packages/animations/lib/src/modal.dart +++ b/packages/animations/lib/src/modal.dart @@ -12,12 +12,13 @@ import 'fade_scale_transition.dart'; /// transition. /// /// Used by [PopupRoute]. -typedef _ModalTransitionBuilder = Widget Function( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, -); +typedef _ModalTransitionBuilder = + Widget Function( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ); /// Displays a modal above the current contents of the app. /// @@ -99,9 +100,9 @@ class _ModalRoute extends PopupRoute { required this.builder, RouteSettings? routeSettings, super.filter, - }) : assert(!barrierDismissible || barrierLabel != null), - _transitionBuilder = transitionBuilder, - super(settings: routeSettings); + }) : assert(!barrierDismissible || barrierLabel != null), + _transitionBuilder = transitionBuilder, + super(settings: routeSettings); @override final Color? barrierColor; @@ -151,12 +152,7 @@ class _ModalRoute extends PopupRoute { Animation secondaryAnimation, Widget child, ) { - return _transitionBuilder( - context, - animation, - secondaryAnimation, - child, - ); + return _transitionBuilder(context, animation, secondaryAnimation, child); } } diff --git a/packages/animations/lib/src/open_container.dart b/packages/animations/lib/src/open_container.dart index 438251eb8be..59d33e350e2 100644 --- a/packages/animations/lib/src/open_container.dart +++ b/packages/animations/lib/src/open_container.dart @@ -16,20 +16,19 @@ typedef CloseContainerActionCallback = void Function({S? returnValue}); /// /// The `action` callback provided to [OpenContainer.openBuilder] can be used /// to close the container. -typedef OpenContainerBuilder = Widget Function( - BuildContext context, - CloseContainerActionCallback action, -); +typedef OpenContainerBuilder = + Widget Function( + BuildContext context, + CloseContainerActionCallback action, + ); /// Signature for a function that creates a [Widget] in closed state within an /// [OpenContainer]. /// /// The `action` callback provided to [OpenContainer.closedBuilder] can be used /// to open the container. -typedef CloseContainerBuilder = Widget Function( - BuildContext context, - VoidCallback action, -); +typedef CloseContainerBuilder = + Widget Function(BuildContext context, VoidCallback action); /// The [OpenContainer] widget's fade transition type. /// @@ -283,23 +282,25 @@ class _OpenContainerState extends State> { 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, - )); + ).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); } @@ -340,10 +341,7 @@ class _OpenContainerState extends State> { /// specified by `placeholderSize` is included in the tree. (The value of /// `isVisible` is ignored). class _Hideable extends StatefulWidget { - const _Hideable({ - super.key, - required this.child, - }); + const _Hideable({super.key, required this.child}); final Widget child; @@ -416,23 +414,20 @@ class _OpenContainerRoute extends ModalRoute { required this.transitionType, required this.useRootNavigator, required RouteSettings? routeSettings, - }) : _elevationTween = Tween( - begin: closedElevation, - end: openElevation, - ), - _shapeTween = ShapeBorderTween( - begin: closedShape, - end: openShape, - ), - _colorTween = _getColorTween( - transitionType: transitionType, - closedColor: closedColor, - openColor: openColor, - middleColor: middleColor, - ), - _closedOpacityTween = _getClosedOpacityTween(transitionType), - _openOpacityTween = _getOpenOpacityTween(transitionType), - super(settings: routeSettings); + }) : _elevationTween = Tween( + begin: closedElevation, + end: openElevation, + ), + _shapeTween = ShapeBorderTween(begin: closedShape, end: openShape), + _colorTween = _getColorTween( + transitionType: transitionType, + closedColor: closedColor, + openColor: openColor, + middleColor: middleColor, + ), + _closedOpacityTween = _getClosedOpacityTween(transitionType), + _openOpacityTween = _getOpenOpacityTween(transitionType), + super(settings: routeSettings); static _FlippableTweenSequence _getColorTween({ required ContainerTransitionType transitionType, @@ -442,99 +437,89 @@ class _OpenContainerRoute extends ModalRoute { }) { switch (transitionType) { case ContainerTransitionType.fade: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(closedColor), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ColorTween(begin: closedColor, end: openColor), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(openColor), - weight: 3 / 5, - ), - ], - ); + return _FlippableTweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(closedColor), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ColorTween(begin: closedColor, end: openColor), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(openColor), + weight: 3 / 5, + ), + ]); case ContainerTransitionType.fadeThrough: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ColorTween(begin: closedColor, end: middleColor), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ColorTween(begin: middleColor, end: openColor), - weight: 4 / 5, - ), - ], - ); + return _FlippableTweenSequence(>[ + TweenSequenceItem( + tween: ColorTween(begin: closedColor, end: middleColor), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ColorTween(begin: middleColor, end: openColor), + weight: 4 / 5, + ), + ]); } } static _FlippableTweenSequence _getClosedOpacityTween( - ContainerTransitionType transitionType) { + ContainerTransitionType transitionType, + ) { switch (transitionType) { case ContainerTransitionType.fade: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 1, - ), - ], - ); + return _FlippableTweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(1.0), + weight: 1, + ), + ]); case ContainerTransitionType.fadeThrough: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: Tween(begin: 1.0, end: 0.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 4 / 5, - ), - ], - ); + return _FlippableTweenSequence(>[ + TweenSequenceItem( + tween: Tween(begin: 1.0, end: 0.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 4 / 5, + ), + ]); } } static _FlippableTweenSequence _getOpenOpacityTween( - ContainerTransitionType transitionType) { + ContainerTransitionType transitionType, + ) { switch (transitionType) { case ContainerTransitionType.fade: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 3 / 5, - ), - ], - ); + return _FlippableTweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: Tween(begin: 0.0, end: 1.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(1.0), + weight: 3 / 5, + ), + ]); case ContainerTransitionType.fadeThrough: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 4 / 5, - ), - ], - ); + return _FlippableTweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: Tween(begin: 0.0, end: 1.0), + weight: 4 / 5, + ), + ]); } } @@ -564,18 +549,17 @@ class _OpenContainerRoute extends ModalRoute { final _FlippableTweenSequence _openOpacityTween; final _FlippableTweenSequence _colorTween; - static final TweenSequence _scrimFadeInTween = TweenSequence( - >[ - TweenSequenceItem( - tween: ColorTween(begin: Colors.transparent, end: Colors.black54), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(Colors.black54), - weight: 4 / 5, - ), - ], - ); + static final TweenSequence _scrimFadeInTween = + TweenSequence(>[ + TweenSequenceItem( + tween: ColorTween(begin: Colors.transparent, end: Colors.black54), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(Colors.black54), + weight: 4 / 5, + ), + ]); static final Tween _scrimFadeOutTween = ColorTween( begin: Colors.transparent, end: Colors.black54, @@ -629,8 +613,9 @@ class _OpenContainerRoute extends ModalRoute { if (hideableKey.currentState?.isVisible == false) { // This route may be disposed without dismissing its animation if it is // removed by the navigator. - SchedulerBinding.instance - .addPostFrameCallback((Duration d) => _toggleHideable(hide: false)); + SchedulerBinding.instance.addPostFrameCallback( + (Duration d) => _toggleHideable(hide: false), + ); } super.dispose(); } @@ -647,10 +632,12 @@ class _OpenContainerRoute extends ModalRoute { required BuildContext navigatorContext, bool delayForSourceRoute = false, }) { - final RenderBox navigator = Navigator.of( - navigatorContext, - rootNavigator: useRootNavigator, - ).context.findRenderObject()! as RenderBox; + final RenderBox navigator = + Navigator.of( + navigatorContext, + rootNavigator: useRootNavigator, + ).context.findRenderObject()! + as RenderBox; final Size navSize = _getSize(navigator); _rectTween.end = Offset.zero & navSize; @@ -663,8 +650,9 @@ class _OpenContainerRoute extends ModalRoute { } if (delayForSourceRoute) { - SchedulerBinding.instance - .addPostFrameCallback(takeMeasurementsInSourceRoute); + SchedulerBinding.instance.addPostFrameCallback( + takeMeasurementsInSourceRoute, + ); } else { takeMeasurementsInSourceRoute(); } @@ -810,21 +798,25 @@ class _OpenContainerRoute extends ModalRoute { child: SizedBox( width: _rectTween.begin!.width, 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, () {}); - }, + 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, + () {}, + ); + }, + ), ), - ), ), ), @@ -885,10 +877,12 @@ class _FlippableTweenSequence extends TweenSequence { if (_flipped == null) { final List> newItems = >[]; for (int i = 0; i < _items.length; i++) { - newItems.add(TweenSequenceItem( - tween: _items[i].tween, - weight: _items[_items.length - 1 - i].weight, - )); + newItems.add( + TweenSequenceItem( + tween: _items[i].tween, + weight: _items[_items.length - 1 - i].weight, + ), + ); } _flipped = _FlippableTweenSequence(newItems); } diff --git a/packages/animations/lib/src/page_transition_switcher.dart b/packages/animations/lib/src/page_transition_switcher.dart index 78d880bd697..94f787af18b 100644 --- a/packages/animations/lib/src/page_transition_switcher.dart +++ b/packages/animations/lib/src/page_transition_switcher.dart @@ -56,9 +56,8 @@ class _ChildEntry { /// The builder should return a widget which contains the given children, laid /// out as desired. It must not return null. The builder should be able to /// handle an empty list of `entries`. -typedef PageTransitionSwitcherLayoutBuilder = Widget Function( - List entries, -); +typedef PageTransitionSwitcherLayoutBuilder = + Widget Function(List entries); /// Signature for builders used to generate custom transitions for /// [PageTransitionSwitcher]. @@ -74,11 +73,12 @@ typedef PageTransitionSwitcherLayoutBuilder = Widget Function( /// incorporate both animations. It will use the primary animation to define how /// its child appears, and the secondary animation to define how its child /// disappears. -typedef PageTransitionSwitcherTransitionBuilder = Widget Function( - Widget child, - Animation primaryAnimation, - Animation secondaryAnimation, -); +typedef PageTransitionSwitcherTransitionBuilder = + Widget Function( + Widget child, + Animation primaryAnimation, + Animation secondaryAnimation, + ); /// A widget that transitions from an old child to a new child whenever [child] /// changes using an animation specified by [transitionBuilder]. @@ -264,10 +264,7 @@ class PageTransitionSwitcher extends StatefulWidget { /// See [PageTransitionSwitcherTransitionBuilder] for more information on the function /// signature. static Widget defaultLayoutBuilder(List entries) { - return Stack( - alignment: Alignment.center, - children: entries, - ); + return Stack(alignment: Alignment.center, children: entries); } @override @@ -378,10 +375,7 @@ class _PageTransitionSwitcherState extends State ); final _ChildEntry entry = _ChildEntry( widgetChild: child, - transition: KeyedSubtree.wrap( - transition, - _childNumber, - ), + transition: KeyedSubtree.wrap(transition, _childNumber), primaryController: primaryController, secondaryController: secondaryController, ); @@ -430,8 +424,10 @@ class _PageTransitionSwitcherState extends State @override Widget build(BuildContext context) { - return widget.layoutBuilder(_activeEntries - .map((_ChildEntry entry) => entry.transition) - .toList()); + return widget.layoutBuilder( + _activeEntries + .map((_ChildEntry entry) => entry.transition) + .toList(), + ); } } diff --git a/packages/animations/lib/src/shared_axis_transition.dart b/packages/animations/lib/src/shared_axis_transition.dart index cbb3f719507..cc6595c1aa0 100644 --- a/packages/animations/lib/src/shared_axis_transition.dart +++ b/packages/animations/lib/src/shared_axis_transition.dart @@ -471,9 +471,7 @@ class _ExitTransition extends StatelessWidget { /// between 0.0 and 1.0. class _FlippedCurveTween extends CurveTween { /// Creates a vertically flipped [CurveTween]. - _FlippedCurveTween({ - required super.curve, - }); + _FlippedCurveTween({required super.curve}); @override double transform(double t) => 1.0 - super.transform(t); diff --git a/packages/animations/pubspec.yaml b/packages/animations/pubspec.yaml index 8591c41c922..96a682100af 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.0.11 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/animations/test/dual_transition_builder_test.dart b/packages/animations/test/dual_transition_builder_test.dart index ecae27fad53..99cc414b93f 100644 --- a/packages/animations/test/dual_transition_builder_test.dart +++ b/packages/animations/test/dual_transition_builder_test.dart @@ -12,36 +12,31 @@ void main() { duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(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, - ); - }, - child: Container( - color: Colors.green, - height: 100, - width: 100, + await tester.pumpWidget( + 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, + ); + }, + child: Container(color: Colors.green, height: 100, width: 100), ), ), - )); + ); expect(_getScale(tester), 0.0); expect(_getOpacity(tester), 1.0); @@ -80,37 +75,37 @@ void main() { duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - 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, - ); - }, - child: const _StatefulTestWidget(name: 'Foo'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + 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, + ); + }, + child: const _StatefulTestWidget(name: 'Foo'), + ), ), ), - )); - final State state = - tester.state(find.byType(_StatefulTestWidget)); + ); + final State state = tester.state( + find.byType(_StatefulTestWidget), + ); expect(state, isNotNull); controller.forward(); @@ -138,42 +133,38 @@ void main() { expect(state, same(tester.state(find.byType(_StatefulTestWidget)))); }); - testWidgets('does not jump when interrupted - forward', - (WidgetTester tester) async { + testWidgets('does not jump when interrupted - forward', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(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, - ); - }, - child: Container( - color: Colors.green, - height: 100, - width: 100, + await tester.pumpWidget( + 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, + ); + }, + child: Container(color: Colors.green, height: 100, width: 100), ), ), - )); + ); expect(_getScale(tester), 0.0); expect(_getOpacity(tester), 1.0); @@ -203,43 +194,39 @@ void main() { expect(_getOpacity(tester), 1.0); }); - testWidgets('does not jump when interrupted - reverse', - (WidgetTester tester) async { + testWidgets('does not jump when interrupted - reverse', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController( value: 1.0, vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(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, - ); - }, - child: Container( - color: Colors.green, - height: 100, - width: 100, + await tester.pumpWidget( + 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, + ); + }, + child: Container(color: Colors.green, height: 100, width: 100), ), ), - )); + ); expect(_getScale(tester), 1.0); expect(_getOpacity(tester), 1.0); diff --git a/packages/animations/test/fade_scale_transition_test.dart b/packages/animations/test/fade_scale_transition_test.dart index 3af46511533..510babbb4a0 100644 --- a/packages/animations/test/fade_scale_transition_test.dart +++ b/packages/animations/test/fade_scale_transition_test.dart @@ -8,13 +8,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets( - 'FadeScaleTransitionConfiguration builds a new route', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('FadeScaleTransitionConfiguration builds a new route', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -28,24 +29,25 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); - expect(find.byType(_FlutterLogoModal), findsOneWidget); - }, - ); + ), + ); + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + expect(find.byType(_FlutterLogoModal), findsOneWidget); + }); - testWidgets( - 'FadeScaleTransitionConfiguration runs forward', - (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('FadeScaleTransitionConfiguration runs forward', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -59,60 +61,61 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); - await tester.tap(find.byType(ElevatedButton)); - await tester.pump(); - // Opacity duration: First 30% of 150ms, linear transition - double topFadeTransitionOpacity = _getOpacity(key, tester); - double topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, 0.0); - expect(topScale, 0.80); - - // 3/10 * 150ms = 45ms (total opacity animation duration) - // 1/2 * 45ms = ~23ms elapsed for halfway point of opacity - // animation - await tester.pump(const Duration(milliseconds: 23)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, closeTo(0.5, 0.05)); - topScale = _getScale(key, tester); - expect(topScale, greaterThan(0.80)); - expect(topScale, lessThan(1.0)); - - // End of opacity animation - await tester.pump(const Duration(milliseconds: 22)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 1.0); - topScale = _getScale(key, tester); - expect(topScale, greaterThan(0.80)); - expect(topScale, lessThan(1.0)); - - // 100ms into the animation - await tester.pump(const Duration(milliseconds: 55)); - topScale = _getScale(key, tester); - expect(topScale, greaterThan(0.80)); - expect(topScale, lessThan(1.0)); - - // Get to the end of the animation - await tester.pump(const Duration(milliseconds: 50)); - topScale = _getScale(key, tester); - expect(topScale, 1.0); - - await tester.pump(); - expect(find.byType(_FlutterLogoModal), findsOneWidget); - }, - ); + ), + ); + await tester.tap(find.byType(ElevatedButton)); + await tester.pump(); + // Opacity duration: First 30% of 150ms, linear transition + double topFadeTransitionOpacity = _getOpacity(key, tester); + double topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, 0.0); + expect(topScale, 0.80); + + // 3/10 * 150ms = 45ms (total opacity animation duration) + // 1/2 * 45ms = ~23ms elapsed for halfway point of opacity + // animation + await tester.pump(const Duration(milliseconds: 23)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, closeTo(0.5, 0.05)); + topScale = _getScale(key, tester); + expect(topScale, greaterThan(0.80)); + expect(topScale, lessThan(1.0)); + + // End of opacity animation + await tester.pump(const Duration(milliseconds: 22)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 1.0); + topScale = _getScale(key, tester); + expect(topScale, greaterThan(0.80)); + expect(topScale, lessThan(1.0)); + + // 100ms into the animation + await tester.pump(const Duration(milliseconds: 55)); + topScale = _getScale(key, tester); + expect(topScale, greaterThan(0.80)); + expect(topScale, lessThan(1.0)); + + // Get to the end of the animation + await tester.pump(const Duration(milliseconds: 50)); + topScale = _getScale(key, tester); + expect(topScale, 1.0); + + await tester.pump(); + expect(find.byType(_FlutterLogoModal), findsOneWidget); + }); - testWidgets( - 'FadeScaleTransitionConfiguration runs forward', - (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('FadeScaleTransitionConfiguration runs forward', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -126,48 +129,48 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); - // Show the incoming modal and let it animate in fully. - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); - - // Tap on modal barrier to start reverse animation. - await tester.tapAt(Offset.zero); - await tester.pump(); - - // Opacity duration: Linear transition throughout 75ms - // No scale animations on exit transition. - double topFadeTransitionOpacity = _getOpacity(key, tester); - double topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, 1.0); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 25)); - topFadeTransitionOpacity = _getOpacity(key, tester); - topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, closeTo(0.66, 0.05)); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 25)); - topFadeTransitionOpacity = _getOpacity(key, tester); - topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, closeTo(0.33, 0.05)); - expect(topScale, 1.0); - - // End of opacity animation - await tester.pump(const Duration(milliseconds: 25)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 0.0); - topScale = _getScale(key, tester); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.byType(_FlutterLogoModal), findsNothing); - }, - ); + ), + ); + // Show the incoming modal and let it animate in fully. + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + // Tap on modal barrier to start reverse animation. + await tester.tapAt(Offset.zero); + await tester.pump(); + + // Opacity duration: Linear transition throughout 75ms + // No scale animations on exit transition. + double topFadeTransitionOpacity = _getOpacity(key, tester); + double topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, 1.0); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 25)); + topFadeTransitionOpacity = _getOpacity(key, tester); + topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, closeTo(0.66, 0.05)); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 25)); + topFadeTransitionOpacity = _getOpacity(key, tester); + topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, closeTo(0.33, 0.05)); + expect(topScale, 1.0); + + // End of opacity animation + await tester.pump(const Duration(milliseconds: 25)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 0.0); + topScale = _getScale(key, tester); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.byType(_FlutterLogoModal), findsNothing); + }); testWidgets( 'FadeScaleTransitionConfiguration does not jump when interrupted', @@ -176,21 +179,23 @@ void main() { await tester.pumpWidget( MaterialApp( home: Scaffold( - body: Builder(builder: (BuildContext context) { - return Center( - child: ElevatedButton( - onPressed: () { - showModal( - context: context, - builder: (BuildContext context) { - return _FlutterLogoModal(key: key); - }, - ); - }, - child: const Icon(Icons.add), - ), - ); - }), + body: Builder( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + onPressed: () { + showModal( + context: context, + builder: (BuildContext context) { + return _FlutterLogoModal(key: key); + }, + ); + }, + child: const Icon(Icons.add), + ), + ); + }, + ), ), ), ); @@ -265,16 +270,17 @@ void main() { }, ); - testWidgets( - 'State is not lost when transitioning', - (WidgetTester tester) async { - final GlobalKey bottomKey = GlobalKey(); - final GlobalKey topKey = GlobalKey(); - - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('State is not lost when transitioning', ( + WidgetTester tester, + ) async { + final GlobalKey bottomKey = GlobalKey(); + final GlobalKey topKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: Column( children: [ @@ -292,154 +298,116 @@ void main() { }, child: const Icon(Icons.add), ), - _FlutterLogoModal( - key: bottomKey, - name: 'bottom route', - ), + _FlutterLogoModal(key: bottomKey, name: 'bottom route'), ], ), ); - }), + }, ), ), - ); - - // The bottom route's state should already exist. - final _FlutterLogoModalState bottomState = tester.state( - find.byKey(bottomKey), - ); - expect(bottomState.widget.name, 'bottom route'); - - // Start the enter transition of the modal route. - await tester.tap(find.byType(ElevatedButton)); - await tester.pump(); - await tester.pump(); - - // The bottom route's state should be retained at the start of the - // transition. - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - // The top route's state should be created. - final _FlutterLogoModalState topState = tester.state( - find.byKey(topKey), - ); - expect(topState.widget.name, 'top route'); - - // Halfway point of forwards animation. - await tester.pump(const Duration(milliseconds: 75)); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); - - // End the transition and see if top and bottom routes' - // states persist. - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey( - bottomKey, - skipOffstage: false, - )), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); - - // Start the reverse animation. Both top and bottom - // routes' states should persist. - await tester.tapAt(Offset.zero); - await tester.pump(); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); - - // Halfway point of the exit transition. - await tester.pump(const Duration(milliseconds: 38)); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); + ), + ); - // End the exit transition. The bottom route's state should - // persist, whereas the top route's state should no longer - // be present. - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect(find.byKey(topKey), findsNothing); - }, - ); + // The bottom route's state should already exist. + final _FlutterLogoModalState bottomState = tester.state( + find.byKey(bottomKey), + ); + expect(bottomState.widget.name, 'bottom route'); + + // Start the enter transition of the modal route. + await tester.tap(find.byType(ElevatedButton)); + await tester.pump(); + await tester.pump(); + + // The bottom route's state should be retained at the start of the + // transition. + expect(tester.state(find.byKey(bottomKey)), bottomState); + // The top route's state should be created. + final _FlutterLogoModalState topState = tester.state(find.byKey(topKey)); + expect(topState.widget.name, 'top route'); + + // Halfway point of forwards animation. + await tester.pump(const Duration(milliseconds: 75)); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(tester.state(find.byKey(topKey)), topState); + + // End the transition and see if top and bottom routes' + // states persist. + await tester.pumpAndSettle(); + expect( + tester.state(find.byKey(bottomKey, skipOffstage: false)), + bottomState, + ); + expect(tester.state(find.byKey(topKey)), topState); + + // Start the reverse animation. Both top and bottom + // routes' states should persist. + await tester.tapAt(Offset.zero); + await tester.pump(); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(tester.state(find.byKey(topKey)), topState); + + // Halfway point of the exit transition. + await tester.pump(const Duration(milliseconds: 38)); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(tester.state(find.byKey(topKey)), topState); + + // End the exit transition. The bottom route's state should + // persist, whereas the top route's state should no longer + // be present. + await tester.pumpAndSettle(); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(find.byKey(topKey), findsNothing); + }); - testWidgets( - 'should preserve state', - (WidgetTester tester) async { - final AnimationController controller = AnimationController( - vsync: const TestVSync(), - duration: const Duration(milliseconds: 300), - ); + testWidgets('should preserve state', (WidgetTester tester) async { + final AnimationController controller = AnimationController( + vsync: const TestVSync(), + duration: const Duration(milliseconds: 300), + ); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: FadeScaleTransition( - animation: controller, - child: const _FlutterLogoModal(), - ), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: FadeScaleTransition( + animation: controller, + child: const _FlutterLogoModal(), ), ), ), - ); - - final State state = tester.state( - find.byType(_FlutterLogoModal), - ); - expect(state, isNotNull); - - controller.forward(); - await tester.pump(); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - await tester.pump(const Duration(milliseconds: 150)); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - await tester.pumpAndSettle(); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - - controller.reverse(); - await tester.pump(); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - await tester.pump(const Duration(milliseconds: 150)); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - await tester.pumpAndSettle(); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + ), + ); - controller.forward(); - await tester.pump(); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - await tester.pump(const Duration(milliseconds: 150)); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - await tester.pumpAndSettle(); - expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); - }, - ); + final State state = tester.state( + find.byType(_FlutterLogoModal), + ); + expect(state, isNotNull); + + controller.forward(); + await tester.pump(); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + await tester.pump(const Duration(milliseconds: 150)); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + await tester.pumpAndSettle(); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + + controller.reverse(); + await tester.pump(); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + await tester.pump(const Duration(milliseconds: 150)); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + await tester.pumpAndSettle(); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + + controller.forward(); + await tester.pump(); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + await tester.pump(const Duration(milliseconds: 150)); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + await tester.pumpAndSettle(); + expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); + }); } double _getOpacity(GlobalKey key, WidgetTester tester) { @@ -465,10 +433,7 @@ double _getScale(GlobalKey key, WidgetTester tester) { } class _FlutterLogoModal extends StatefulWidget { - const _FlutterLogoModal({ - super.key, - this.name, - }); + const _FlutterLogoModal({super.key, this.name}); final String? name; @@ -483,11 +448,7 @@ class _FlutterLogoModalState extends State<_FlutterLogoModal> { child: SizedBox( width: 250, height: 250, - child: Material( - child: Center( - child: FlutterLogo(size: 250), - ), - ), + child: Material(child: Center(child: FlutterLogo(size: 250))), ), ); } diff --git a/packages/animations/test/fade_through_transition_test.dart b/packages/animations/test/fade_through_transition_test.dart index 3075dd80586..c60352d9d48 100644 --- a/packages/animations/test/fade_through_transition_test.dart +++ b/packages/animations/test/fade_through_transition_test.dart @@ -8,38 +8,37 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( - 'FadeThroughPageTransitionsBuilder builds a FadeThroughTransition', - (WidgetTester tester) async { - final AnimationController animation = AnimationController( - vsync: const TestVSync(), - ); - final AnimationController secondaryAnimation = AnimationController( - vsync: const TestVSync(), - ); - - await tester.pumpWidget( + 'FadeThroughPageTransitionsBuilder builds a FadeThroughTransition', + (WidgetTester tester) async { + final AnimationController animation = AnimationController( + vsync: const TestVSync(), + ); + final AnimationController secondaryAnimation = AnimationController( + vsync: const TestVSync(), + ); + + await tester.pumpWidget( const FadeThroughPageTransitionsBuilder().buildTransitions( - null, - null, - animation, - secondaryAnimation, - const Placeholder(), - )); - - expect(find.byType(FadeThroughTransition), findsOneWidget); - }); + null, + null, + animation, + secondaryAnimation, + const Placeholder(), + ), + ); + + expect(find.byType(FadeThroughTransition), findsOneWidget); + }, + ); - testWidgets('FadeThroughTransition runs forward', - (WidgetTester tester) async { + testWidgets('FadeThroughTransition runs forward', ( + WidgetTester tester, + ) async { final GlobalKey navigator = GlobalKey(); const String bottomRoute = '/'; const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - ), - ); + await tester.pumpWidget(_TestWidget(navigatorKey: navigator)); expect(find.text(bottomRoute), findsOneWidget); expect(_getScale(bottomRoute, tester), 1.0); expect(_getOpacity(bottomRoute, tester), 1.0); @@ -114,17 +113,14 @@ void main() { expect(find.text(topRoute), findsOneWidget); }); - testWidgets('FadeThroughTransition runs backwards', - (WidgetTester tester) async { + testWidgets('FadeThroughTransition runs backwards', ( + WidgetTester tester, + ) async { final GlobalKey navigator = GlobalKey(); const String bottomRoute = '/'; const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - ), - ); + await tester.pumpWidget(_TestWidget(navigatorKey: navigator)); navigator.currentState!.pushNamed('/a'); await tester.pumpAndSettle(); @@ -207,17 +203,14 @@ void main() { expect(find.text(bottomRoute), findsOneWidget); }); - testWidgets('FadeThroughTransition does not jump when interrupted', - (WidgetTester tester) async { + testWidgets('FadeThroughTransition does not jump when interrupted', ( + WidgetTester tester, + ) async { final GlobalKey navigator = GlobalKey(); const String bottomRoute = '/'; const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - ), - ); + await tester.pumpWidget(_TestWidget(navigatorKey: navigator)); expect(find.text(bottomRoute), findsOneWidget); expect(find.text(topRoute), findsNothing); @@ -275,8 +268,9 @@ void main() { expect(find.text(bottomRoute), findsOneWidget); }); - testWidgets('State is not lost when transitioning', - (WidgetTester tester) async { + testWidgets('State is not lost when transitioning', ( + WidgetTester tester, + ) async { final GlobalKey navigator = GlobalKey(); const String bottomRoute = '/'; const String topRoute = '/a'; @@ -293,8 +287,9 @@ void main() { ), ); - final _StatefulTestWidgetState bottomState = - tester.state(find.byKey(const ValueKey(bottomRoute))); + final _StatefulTestWidgetState bottomState = tester.state( + find.byKey(const ValueKey(bottomRoute)), + ); expect(bottomState.widget.name, bottomRoute); navigator.currentState!.pushNamed(topRoute); @@ -322,10 +317,9 @@ void main() { await tester.pumpAndSettle(); expect( - tester.state(find.byKey( - const ValueKey(bottomRoute), - skipOffstage: false, - )), + tester.state( + find.byKey(const ValueKey(bottomRoute), skipOffstage: false), + ), bottomState, ); expect( @@ -372,16 +366,18 @@ void main() { vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: FadeThroughTransition( - animation: animation, - secondaryAnimation: secondaryAnimation, - child: const _StatefulTestWidget(name: 'Foo'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: FadeThroughTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + child: const _StatefulTestWidget(name: 'Foo'), + ), ), ), - )); + ); final State state = tester.state( find.byType(_StatefulTestWidget), ); @@ -476,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 28b8a4deb77..1c44c5e0cc3 100644 --- a/packages/animations/test/modal_test.dart +++ b/packages/animations/test/modal_test.dart @@ -15,22 +15,24 @@ void main() { await tester.pumpWidget( MaterialApp( home: Scaffold( - body: Builder(builder: (BuildContext context) { - return Center( - child: ElevatedButton( - onPressed: () { - showModal( - context: context, - configuration: _TestModalConfiguration(), - builder: (BuildContext context) { - return const _FlutterLogoModal(); - }, - ); - }, - child: const Icon(Icons.add), - ), - ); - }), + body: Builder( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + onPressed: () { + showModal( + context: context, + configuration: _TestModalConfiguration(), + builder: (BuildContext context) { + return const _FlutterLogoModal(); + }, + ); + }, + child: const Icon(Icons.add), + ), + ); + }, + ), ), ), ); @@ -50,14 +52,13 @@ void main() { }, ); - testWidgets( - 'showModal forwards animation', - (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('showModal forwards animation', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -72,42 +73,41 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); + ), + ); - // Start forwards animation - await tester.tap(find.byType(ElevatedButton)); - await tester.pump(); + // Start forwards animation + await tester.tap(find.byType(ElevatedButton)); + await tester.pump(); - // Opacity duration: Linear transition throughout 300ms - double topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 0.0); + // Opacity duration: Linear transition throughout 300ms + double topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 0.0); - // Halfway through forwards animation. - await tester.pump(const Duration(milliseconds: 150)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 0.5); + // Halfway through forwards animation. + await tester.pump(const Duration(milliseconds: 150)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 0.5); - // The end of the transition. - await tester.pump(const Duration(milliseconds: 150)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 1.0); + // The end of the transition. + await tester.pump(const Duration(milliseconds: 150)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 1.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.byType(_FlutterLogoModal), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.byType(_FlutterLogoModal), findsOneWidget); + }); - testWidgets( - 'showModal reverse animation', - (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('showModal reverse animation', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -122,46 +122,47 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); + ), + ); - // Start forwards animation - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); - expect(find.byType(_FlutterLogoModal), findsOneWidget); + // Start forwards animation + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + expect(find.byType(_FlutterLogoModal), findsOneWidget); - await tester.tapAt(Offset.zero); - await tester.pump(); + await tester.tapAt(Offset.zero); + await tester.pump(); - // Opacity duration: Linear transition throughout 200ms - double topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 1.0); + // Opacity duration: Linear transition throughout 200ms + double topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 1.0); - // Halfway through forwards animation. - await tester.pump(const Duration(milliseconds: 100)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 0.5); + // Halfway through forwards animation. + await tester.pump(const Duration(milliseconds: 100)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 0.5); - // The end of the transition. - await tester.pump(const Duration(milliseconds: 100)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 0.0); + // The end of the transition. + await tester.pump(const Duration(milliseconds: 100)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 0.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.byType(_FlutterLogoModal), findsNothing); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.byType(_FlutterLogoModal), findsNothing); + }); - testWidgets( - 'showModal builds a new route with specified barrier properties ' - 'with default configuration(FadeScaleTransitionConfiguration)', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('showModal builds a new route with specified barrier properties ' + 'with default configuration(FadeScaleTransitionConfiguration)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -175,35 +176,36 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); + ), + ); + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); - // New route containing _FlutterLogoModal is present. - expect(find.byType(_FlutterLogoModal), findsOneWidget); - final ModalBarrier topModalBarrier = tester.widget( - find.byType(ModalBarrier).at(1), - ); + // New route containing _FlutterLogoModal is present. + expect(find.byType(_FlutterLogoModal), findsOneWidget); + final ModalBarrier topModalBarrier = tester.widget( + find.byType(ModalBarrier).at(1), + ); - // Verify new route's modal barrier properties are correct. - expect(topModalBarrier.color, Colors.black54); - expect(topModalBarrier.barrierSemanticsDismissible, true); - expect(topModalBarrier.semanticsLabel, 'Dismiss'); - }, - ); + // Verify new route's modal barrier properties are correct. + expect(topModalBarrier.color, Colors.black54); + expect(topModalBarrier.barrierSemanticsDismissible, true); + expect(topModalBarrier.semanticsLabel, 'Dismiss'); + }); - testWidgets( - 'showModal forwards animation ' - 'with default configuration(FadeScaleTransitionConfiguration)', - (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('showModal forwards animation ' + 'with default configuration(FadeScaleTransitionConfiguration)', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -217,64 +219,65 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); + ), + ); - // Start forwards animation - await tester.tap(find.byType(ElevatedButton)); - await tester.pump(); - - // Opacity duration: First 30% of 150ms, linear transition - double topFadeTransitionOpacity = _getOpacity(key, tester); - double topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, 0.0); - expect(topScale, 0.80); - - // 3/10 * 150ms = 45ms (total opacity animation duration) - // 1/2 * 45ms = ~23ms elapsed for halfway point of opacity - // animation - await tester.pump(const Duration(milliseconds: 23)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, closeTo(0.5, 0.05)); - topScale = _getScale(key, tester); - expect(topScale, greaterThan(0.80)); - expect(topScale, lessThan(1.0)); - - // End of opacity animation. - await tester.pump(const Duration(milliseconds: 22)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 1.0); - topScale = _getScale(key, tester); - expect(topScale, greaterThan(0.80)); - expect(topScale, lessThan(1.0)); - - // 100ms into the animation - await tester.pump(const Duration(milliseconds: 55)); - topScale = _getScale(key, tester); - expect(topScale, greaterThan(0.80)); - expect(topScale, lessThan(1.0)); - - // Get to the end of the animation - await tester.pump(const Duration(milliseconds: 50)); - topScale = _getScale(key, tester); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.byType(_FlutterLogoModal), findsOneWidget); - }, - ); + // Start forwards animation + await tester.tap(find.byType(ElevatedButton)); + await tester.pump(); + + // Opacity duration: First 30% of 150ms, linear transition + double topFadeTransitionOpacity = _getOpacity(key, tester); + double topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, 0.0); + expect(topScale, 0.80); + + // 3/10 * 150ms = 45ms (total opacity animation duration) + // 1/2 * 45ms = ~23ms elapsed for halfway point of opacity + // animation + await tester.pump(const Duration(milliseconds: 23)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, closeTo(0.5, 0.05)); + topScale = _getScale(key, tester); + expect(topScale, greaterThan(0.80)); + expect(topScale, lessThan(1.0)); + + // End of opacity animation. + await tester.pump(const Duration(milliseconds: 22)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 1.0); + topScale = _getScale(key, tester); + expect(topScale, greaterThan(0.80)); + expect(topScale, lessThan(1.0)); + + // 100ms into the animation + await tester.pump(const Duration(milliseconds: 55)); + topScale = _getScale(key, tester); + expect(topScale, greaterThan(0.80)); + expect(topScale, lessThan(1.0)); + + // Get to the end of the animation + await tester.pump(const Duration(milliseconds: 50)); + topScale = _getScale(key, tester); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.byType(_FlutterLogoModal), findsOneWidget); + }); - testWidgets( - 'showModal reverse animation ' - 'with default configuration(FadeScaleTransitionConfiguration)', - (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('showModal reverse animation ' + 'with default configuration(FadeScaleTransitionConfiguration)', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -288,61 +291,62 @@ void main() { child: const Icon(Icons.add), ), ); - }), + }, ), ), - ); - - // Start forwards animation - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); - expect(find.byType(_FlutterLogoModal), findsOneWidget); - - // Tap on modal barrier to start reverse animation. - await tester.tapAt(Offset.zero); - await tester.pump(); - - // Opacity duration: Linear transition throughout 75ms - // No scale animations on exit transition. - double topFadeTransitionOpacity = _getOpacity(key, tester); - double topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, 1.0); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 25)); - topFadeTransitionOpacity = _getOpacity(key, tester); - topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, closeTo(0.66, 0.05)); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 25)); - topFadeTransitionOpacity = _getOpacity(key, tester); - topScale = _getScale(key, tester); - expect(topFadeTransitionOpacity, closeTo(0.33, 0.05)); - expect(topScale, 1.0); - - // End of opacity animation - await tester.pump(const Duration(milliseconds: 25)); - topFadeTransitionOpacity = _getOpacity(key, tester); - expect(topFadeTransitionOpacity, 0.0); - topScale = _getScale(key, tester); - expect(topScale, 1.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.byType(_FlutterLogoModal), findsNothing); - }, - ); + ), + ); - testWidgets( - 'State is not lost when transitioning', - (WidgetTester tester) async { - final GlobalKey bottomKey = GlobalKey(); - final GlobalKey topKey = GlobalKey(); + // Start forwards animation + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + expect(find.byType(_FlutterLogoModal), findsOneWidget); + + // Tap on modal barrier to start reverse animation. + await tester.tapAt(Offset.zero); + await tester.pump(); + + // Opacity duration: Linear transition throughout 75ms + // No scale animations on exit transition. + double topFadeTransitionOpacity = _getOpacity(key, tester); + double topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, 1.0); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 25)); + topFadeTransitionOpacity = _getOpacity(key, tester); + topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, closeTo(0.66, 0.05)); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 25)); + topFadeTransitionOpacity = _getOpacity(key, tester); + topScale = _getScale(key, tester); + expect(topFadeTransitionOpacity, closeTo(0.33, 0.05)); + expect(topScale, 1.0); + + // End of opacity animation + await tester.pump(const Duration(milliseconds: 25)); + topFadeTransitionOpacity = _getOpacity(key, tester); + expect(topFadeTransitionOpacity, 0.0); + topScale = _getScale(key, tester); + expect(topScale, 1.0); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.byType(_FlutterLogoModal), findsNothing); + }); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder(builder: (BuildContext context) { + testWidgets('State is not lost when transitioning', ( + WidgetTester tester, + ) async { + final GlobalKey bottomKey = GlobalKey(); + final GlobalKey topKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { return Center( child: Column( children: [ @@ -361,112 +365,78 @@ void main() { }, child: const Icon(Icons.add), ), - _FlutterLogoModal( - key: bottomKey, - name: 'bottom route', - ), + _FlutterLogoModal(key: bottomKey, name: 'bottom route'), ], ), ); - }), + }, ), ), - ); - - // The bottom route's state should already exist. - final _FlutterLogoModalState bottomState = tester.state( - find.byKey(bottomKey), - ); - expect(bottomState.widget.name, 'bottom route'); - - // Start the enter transition of the modal route. - await tester.tap(find.byType(ElevatedButton)); - await tester.pump(); - await tester.pump(); - - // The bottom route's state should be retained at the start of the - // transition. - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - // The top route's state should be created. - final _FlutterLogoModalState topState = tester.state( - find.byKey(topKey), - ); - expect(topState.widget.name, 'top route'); - - // Halfway point of forwards animation. - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); - - // End the transition and see if top and bottom routes' - // states persist. - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey( - bottomKey, - skipOffstage: false, - )), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); - - // Start the reverse animation. Both top and bottom - // routes' states should persist. - await tester.tapAt(Offset.zero); - await tester.pump(); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); - - // Halfway point of the exit transition. - await tester.pump(const Duration(milliseconds: 100)); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect( - tester.state(find.byKey(topKey)), - topState, - ); + ), + ); - // End the exit transition. The bottom route's state should - // persist, whereas the top route's state should no longer - // be present. - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey(bottomKey)), - bottomState, - ); - expect(find.byKey(topKey), findsNothing); - }, - ); + // The bottom route's state should already exist. + final _FlutterLogoModalState bottomState = tester.state( + find.byKey(bottomKey), + ); + expect(bottomState.widget.name, 'bottom route'); + + // Start the enter transition of the modal route. + await tester.tap(find.byType(ElevatedButton)); + await tester.pump(); + await tester.pump(); + + // The bottom route's state should be retained at the start of the + // transition. + expect(tester.state(find.byKey(bottomKey)), bottomState); + // The top route's state should be created. + final _FlutterLogoModalState topState = tester.state(find.byKey(topKey)); + expect(topState.widget.name, 'top route'); + + // Halfway point of forwards animation. + await tester.pump(const Duration(milliseconds: 150)); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(tester.state(find.byKey(topKey)), topState); + + // End the transition and see if top and bottom routes' + // states persist. + await tester.pumpAndSettle(); + expect( + tester.state(find.byKey(bottomKey, skipOffstage: false)), + bottomState, + ); + expect(tester.state(find.byKey(topKey)), topState); + + // Start the reverse animation. Both top and bottom + // routes' states should persist. + await tester.tapAt(Offset.zero); + await tester.pump(); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(tester.state(find.byKey(topKey)), topState); + + // Halfway point of the exit transition. + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(tester.state(find.byKey(topKey)), topState); + + // End the exit transition. The bottom route's state should + // persist, whereas the top route's state should no longer + // be present. + await tester.pumpAndSettle(); + expect(tester.state(find.byKey(bottomKey)), bottomState); + expect(find.byKey(topKey), findsNothing); + }); - testWidgets( - 'showModal builds a new route with specified route settings', - (WidgetTester tester) async { - const RouteSettings routeSettings = RouteSettings( - name: 'route-name', - arguments: 'arguments', - ); + testWidgets('showModal builds a new route with specified route settings', ( + WidgetTester tester, + ) async { + const RouteSettings routeSettings = RouteSettings( + name: 'route-name', + arguments: 'arguments', + ); - final Widget button = Builder(builder: (BuildContext context) { + final Widget button = Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -482,30 +452,30 @@ void main() { child: const Icon(Icons.add), ), ); - }); + }, + ); - await tester.pumpWidget(_boilerplate(button)); - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); + await tester.pumpWidget(_boilerplate(button)); + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); - // New route containing _FlutterLogoModal is present. - expect(find.byType(_FlutterLogoModal), findsOneWidget); + // New route containing _FlutterLogoModal is present. + expect(find.byType(_FlutterLogoModal), findsOneWidget); - // 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)), - )!; - expect(modalRoute.settings, routeSettings); - }, - ); + // 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)))!; + expect(modalRoute.settings, routeSettings); + }); - testWidgets( - 'showModal builds a new route with specified image filter', - (WidgetTester tester) async { - final ui.ImageFilter filter = ui.ImageFilter.blur(sigmaX: 1, sigmaY: 1); + testWidgets('showModal builds a new route with specified image filter', ( + WidgetTester tester, + ) async { + final ui.ImageFilter filter = ui.ImageFilter.blur(sigmaX: 1, sigmaY: 1); - final Widget button = Builder(builder: (BuildContext context) { + final Widget button = Builder( + builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { @@ -521,22 +491,22 @@ void main() { child: const Icon(Icons.add), ), ); - }); + }, + ); - await tester.pumpWidget(_boilerplate(button)); - await tester.tap(find.byType(ElevatedButton)); - await tester.pumpAndSettle(); + await tester.pumpWidget(_boilerplate(button)); + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); - // New route containing _FlutterLogoModal is present. - expect(find.byType(_FlutterLogoModal), findsOneWidget); - final BackdropFilter backdropFilter = tester.widget( - find.byType(BackdropFilter), - ); + // New route containing _FlutterLogoModal is present. + expect(find.byType(_FlutterLogoModal), findsOneWidget); + final BackdropFilter backdropFilter = tester.widget( + find.byType(BackdropFilter), + ); - // Verify new route's backdrop filter has been applied - expect(backdropFilter.filter, filter); - }, - ); + // Verify new route's backdrop filter has been applied + expect(backdropFilter.filter, filter); + }); } Widget _boilerplate(Widget child) => MaterialApp(home: Scaffold(body: child)); @@ -564,10 +534,7 @@ double _getScale(GlobalKey key, WidgetTester tester) { } class _FlutterLogoModal extends StatefulWidget { - const _FlutterLogoModal({ - super.key, - this.name, - }); + const _FlutterLogoModal({super.key, this.name}); final String? name; @@ -582,11 +549,7 @@ class _FlutterLogoModalState extends State<_FlutterLogoModal> { child: SizedBox( width: 250, height: 250, - child: Material( - child: Center( - child: FlutterLogo(size: 250), - ), - ), + child: Material(child: Center(child: FlutterLogo(size: 250))), ), ); } @@ -594,13 +557,13 @@ class _FlutterLogoModalState extends State<_FlutterLogoModal> { class _TestModalConfiguration extends ModalConfiguration { _TestModalConfiguration() - : super( - barrierColor: Colors.green, - barrierDismissible: true, - barrierLabel: 'customLabel', - transitionDuration: const Duration(milliseconds: 300), - reverseTransitionDuration: const Duration(milliseconds: 200), - ); + : super( + barrierColor: Colors.green, + barrierDismissible: true, + barrierLabel: 'customLabel', + transitionDuration: const Duration(milliseconds: 300), + reverseTransitionDuration: const Duration(milliseconds: 200), + ); @override Widget transitionBuilder( @@ -609,9 +572,6 @@ class _TestModalConfiguration extends ModalConfiguration { Animation secondaryAnimation, Widget child, ) { - return FadeTransition( - opacity: animation, - child: child, - ); + return FadeTransition(opacity: animation, child: child); } } diff --git a/packages/animations/test/open_container_test.dart b/packages/animations/test/open_container_test.dart index 5d4ae961418..f397daf7cda 100644 --- a/packages/animations/test/open_container_test.dart +++ b/packages/animations/test/open_container_test.dart @@ -7,16 +7,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets( - 'Container opens - Fade (by default)', - (WidgetTester tester) async { - const ShapeBorder shape = RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8.0)), - ); - bool closedBuilderCalled = false; - bool openBuilderCalled = false; + testWidgets('Container opens - Fade (by default)', ( + WidgetTester tester, + ) async { + const ShapeBorder shape = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8.0)), + ); + bool closedBuilderCalled = false; + bool openBuilderCalled = false; - await tester.pumpWidget(_boilerplate( + await tester.pumpWidget( + _boilerplate( child: Center( child: OpenContainer( closedColor: Colors.green, @@ -34,162 +35,150 @@ void main() { }, ), ), - )); + ), + ); - // Closed container has the expected properties. - final Element srcMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ), - ); - final Material srcMaterial = srcMaterialElement.widget as Material; - expect(srcMaterial.color, Colors.green); - expect(srcMaterial.elevation, 4.0); - expect(srcMaterial.shape, shape); - expect(find.text('Closed'), findsOneWidget); - expect(find.text('Open'), findsNothing); - expect(closedBuilderCalled, isTrue); - expect(openBuilderCalled, isFalse); - final Rect srcMaterialRect = tester.getRect( - find.byElementPredicate((Element e) => e == srcMaterialElement), - ); + // Closed container has the expected properties. + final Element srcMaterialElement = tester.firstElement( + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), + ); + final Material srcMaterial = srcMaterialElement.widget as Material; + expect(srcMaterial.color, Colors.green); + expect(srcMaterial.elevation, 4.0); + expect(srcMaterial.shape, shape); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Open'), findsNothing); + expect(closedBuilderCalled, isTrue); + expect(openBuilderCalled, isFalse); + final Rect srcMaterialRect = tester.getRect( + find.byElementPredicate((Element e) => e == srcMaterialElement), + ); - // Open the container. - await tester.tap(find.text('Closed')); - expect(find.text('Closed'), findsOneWidget); - expect(find.text('Open'), findsNothing); - await tester.pump(); + // Open the container. + await tester.tap(find.text('Closed')); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Open'), findsNothing); + await tester.pump(); - // On the first frame of the animation everything still looks like before. - final Element destMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ), - ); - final Material closedMaterial = destMaterialElement.widget as Material; - expect(closedMaterial.color, Colors.green); - expect(closedMaterial.elevation, 4.0); - expect(closedMaterial.shape, shape); - expect(find.text('Closed'), findsOneWidget); - expect(find.text('Open'), findsOneWidget); - final Rect closedMaterialRect = tester.getRect( + // On the first frame of the animation everything still looks like before. + final Element destMaterialElement = tester.firstElement( + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), + ); + final Material closedMaterial = destMaterialElement.widget as Material; + expect(closedMaterial.color, Colors.green); + expect(closedMaterial.elevation, 4.0); + expect(closedMaterial.shape, shape); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Open'), findsOneWidget); + final Rect closedMaterialRect = tester.getRect( + find.byElementPredicate((Element e) => e == destMaterialElement), + ); + expect(closedMaterialRect, srcMaterialRect); + expect(_getOpacity(tester, 'Open'), 0.0); + expect(_getOpacity(tester, 'Closed'), 1.0); + + final _TrackedData dataClosed = _TrackedData( + closedMaterial, + closedMaterialRect, + ); + + // Jump to the start of the fade in. + await tester.pump(const Duration(milliseconds: 60)); // 300ms * 1/5 = 60ms + final _TrackedData dataPreFade = _TrackedData( + destMaterialElement.widget as Material, + tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), - ); - expect(closedMaterialRect, srcMaterialRect); - expect(_getOpacity(tester, 'Open'), 0.0); - expect(_getOpacity(tester, 'Closed'), 1.0); + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataClosed, + biggerMaterial: dataPreFade, + tester: tester, + ); + expect(_getOpacity(tester, 'Open'), moreOrLessEquals(0.0)); + expect(_getOpacity(tester, 'Closed'), 1.0); - final _TrackedData dataClosed = _TrackedData( - closedMaterial, - closedMaterialRect, - ); + // Jump to the middle of the fade in. + await tester.pump(const Duration(milliseconds: 30)); // 300ms * 3/10 = 90ms + final _TrackedData dataMidFadeIn = _TrackedData( + destMaterialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == destMaterialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataPreFade, + biggerMaterial: dataMidFadeIn, + tester: tester, + ); + expect(dataMidFadeIn.material.color, isNot(dataPreFade.material.color)); + expect(_getOpacity(tester, 'Open'), lessThan(1.0)); + expect(_getOpacity(tester, 'Open'), greaterThan(0.0)); + expect(_getOpacity(tester, 'Closed'), 1.0); - // Jump to the start of the fade in. - await tester.pump(const Duration(milliseconds: 60)); // 300ms * 1/5 = 60ms - final _TrackedData dataPreFade = _TrackedData( - destMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == destMaterialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataClosed, - biggerMaterial: dataPreFade, - tester: tester, - ); - expect(_getOpacity(tester, 'Open'), moreOrLessEquals(0.0)); - expect(_getOpacity(tester, 'Closed'), 1.0); - - // Jump to the middle of the fade in. - await tester - .pump(const Duration(milliseconds: 30)); // 300ms * 3/10 = 90ms - final _TrackedData dataMidFadeIn = _TrackedData( - destMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == destMaterialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataPreFade, - biggerMaterial: dataMidFadeIn, - tester: tester, - ); - expect(dataMidFadeIn.material.color, isNot(dataPreFade.material.color)); - expect(_getOpacity(tester, 'Open'), lessThan(1.0)); - expect(_getOpacity(tester, 'Open'), greaterThan(0.0)); - expect(_getOpacity(tester, 'Closed'), 1.0); - - // Jump to the end of the fade in at 2/5 of 300ms. - await tester.pump( - const Duration(milliseconds: 30), - ); // 300ms * 2/5 = 120ms - - final _TrackedData dataPostFadeIn = _TrackedData( - destMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == destMaterialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataMidFadeIn, - biggerMaterial: dataPostFadeIn, - tester: tester, - ); - expect(_getOpacity(tester, 'Open'), moreOrLessEquals(1.0)); - expect(_getOpacity(tester, 'Closed'), 1.0); - - // Jump almost to the end of the transition. - await tester.pump(const Duration(milliseconds: 180)); - final _TrackedData dataTransitionDone = _TrackedData( - destMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == destMaterialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataMidFadeIn, - biggerMaterial: dataTransitionDone, - tester: tester, - ); - expect(_getOpacity(tester, 'Open'), 1.0); - expect(dataTransitionDone.material.color, Colors.blue); - expect(dataTransitionDone.material.elevation, 8.0); - expect(dataTransitionDone.radius, 0.0); - expect(dataTransitionDone.rect, const Rect.fromLTRB(0, 0, 800, 600)); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text('Closed'), findsNothing); // No longer in the tree. - expect(find.text('Open'), findsOneWidget); - final Element finalMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ), - ); - final _TrackedData dataOpen = _TrackedData( - finalMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == finalMaterialElement), - ), - ); - expect(dataOpen.material.color, dataTransitionDone.material.color); - expect( - dataOpen.material.elevation, dataTransitionDone.material.elevation); - expect(dataOpen.radius, dataTransitionDone.radius); - expect(dataOpen.rect, dataTransitionDone.rect); - }, - ); + // Jump to the end of the fade in at 2/5 of 300ms. + await tester.pump(const Duration(milliseconds: 30)); // 300ms * 2/5 = 120ms - testWidgets( - 'Container closes - Fade (by default)', - (WidgetTester tester) async { - const ShapeBorder shape = RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8.0)), - ); + final _TrackedData dataPostFadeIn = _TrackedData( + destMaterialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == destMaterialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataMidFadeIn, + biggerMaterial: dataPostFadeIn, + tester: tester, + ); + expect(_getOpacity(tester, 'Open'), moreOrLessEquals(1.0)); + expect(_getOpacity(tester, 'Closed'), 1.0); + + // Jump almost to the end of the transition. + await tester.pump(const Duration(milliseconds: 180)); + final _TrackedData dataTransitionDone = _TrackedData( + destMaterialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == destMaterialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataMidFadeIn, + biggerMaterial: dataTransitionDone, + tester: tester, + ); + expect(_getOpacity(tester, 'Open'), 1.0); + expect(dataTransitionDone.material.color, Colors.blue); + expect(dataTransitionDone.material.elevation, 8.0); + expect(dataTransitionDone.radius, 0.0); + expect(dataTransitionDone.rect, const Rect.fromLTRB(0, 0, 800, 600)); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text('Closed'), findsNothing); // No longer in the tree. + expect(find.text('Open'), findsOneWidget); + final Element finalMaterialElement = tester.firstElement( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ); + final _TrackedData dataOpen = _TrackedData( + finalMaterialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == finalMaterialElement), + ), + ); + expect(dataOpen.material.color, dataTransitionDone.material.color); + expect(dataOpen.material.elevation, dataTransitionDone.material.elevation); + expect(dataOpen.radius, dataTransitionDone.radius); + expect(dataOpen.rect, dataTransitionDone.rect); + }); + + testWidgets('Container closes - Fade (by default)', ( + WidgetTester tester, + ) async { + const ShapeBorder shape = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8.0)), + ); - await tester.pumpWidget(_boilerplate( + await tester.pumpWidget( + _boilerplate( child: Center( child: OpenContainer( closedColor: Colors.green, @@ -205,150 +194,140 @@ void main() { }, ), ), - )); + ), + ); - await tester.tap(find.text('Closed')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Closed')); + await tester.pumpAndSettle(); - // Open container has the expected properties. - expect(find.text('Closed'), findsNothing); - expect(find.text('Open'), findsOneWidget); - final Element initialMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ), - ); - final _TrackedData dataOpen = _TrackedData( - initialMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == initialMaterialElement), - ), - ); - expect(dataOpen.material.color, Colors.blue); - expect(dataOpen.material.elevation, 8.0); - expect(dataOpen.radius, 0.0); - expect(dataOpen.rect, const Rect.fromLTRB(0, 0, 800, 600)); + // Open container has the expected properties. + expect(find.text('Closed'), findsNothing); + expect(find.text('Open'), findsOneWidget); + final Element initialMaterialElement = tester.firstElement( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ); + final _TrackedData dataOpen = _TrackedData( + initialMaterialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == initialMaterialElement), + ), + ); + expect(dataOpen.material.color, Colors.blue); + expect(dataOpen.material.elevation, 8.0); + expect(dataOpen.radius, 0.0); + expect(dataOpen.rect, const Rect.fromLTRB(0, 0, 800, 600)); - // Close the container. - final NavigatorState navigator = tester.state(find.byType(Navigator)); - navigator.pop(); - await tester.pump(); + // Close the container. + final NavigatorState navigator = tester.state(find.byType(Navigator)); + navigator.pop(); + await tester.pump(); - expect(find.text('Closed'), findsOneWidget); - expect(find.text('Open'), findsOneWidget); - final Element materialElement = tester.firstElement( - find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ), - ); - final _TrackedData dataTransitionStart = _TrackedData( - materialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == materialElement), - ), - ); - expect(dataTransitionStart.material.color, dataOpen.material.color); - expect( - dataTransitionStart.material.elevation, dataOpen.material.elevation); - expect(dataTransitionStart.radius, dataOpen.radius); - expect(dataTransitionStart.rect, dataOpen.rect); - expect(_getOpacity(tester, 'Open'), 1.0); - - // Jump to start of fade out: 1/5 of 300. - await tester.pump(const Duration(milliseconds: 60)); // 300 * 1/5 = 60 - final _TrackedData dataPreFadeOut = _TrackedData( - materialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == materialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataPreFadeOut, - biggerMaterial: dataTransitionStart, - tester: tester, - ); - expect(_getOpacity(tester, 'Open'), moreOrLessEquals(1.0)); - expect(_getOpacity(tester, 'Closed'), 1.0); - - // Jump to the middle of the fade out. - await tester.pump(const Duration(milliseconds: 30)); // 300 * 3/10 = 90 - final _TrackedData dataMidpoint = _TrackedData( - materialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == materialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataMidpoint, - biggerMaterial: dataPreFadeOut, - tester: tester, - ); - expect(dataMidpoint.material.color, isNot(dataPreFadeOut.material.color)); - expect(_getOpacity(tester, 'Open'), lessThan(1.0)); - expect(_getOpacity(tester, 'Open'), greaterThan(0.0)); - expect(_getOpacity(tester, 'Closed'), 1.0); - - // Jump to the end of the fade out. - await tester.pump(const Duration(milliseconds: 30)); // 300 * 2/5 = 120 - final _TrackedData dataPostFadeOut = _TrackedData( - materialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == materialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataPostFadeOut, - biggerMaterial: dataMidpoint, - tester: tester, - ); - expect(_getOpacity(tester, 'Open'), moreOrLessEquals(0.0)); - expect(_getOpacity(tester, 'Closed'), 1.0); - - // Jump almost to the end of the transition. - await tester.pump(const Duration(milliseconds: 180)); - final _TrackedData dataTransitionDone = _TrackedData( - materialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == materialElement), - ), - ); - _expectMaterialPropertiesHaveAdvanced( - smallerMaterial: dataTransitionDone, - biggerMaterial: dataPostFadeOut, - tester: tester, - ); - expect(_getOpacity(tester, 'Closed'), 1.0); - expect(_getOpacity(tester, 'Open'), 0.0); - expect(dataTransitionDone.material.color, Colors.green); - expect(dataTransitionDone.material.elevation, 4.0); - expect(dataTransitionDone.radius, 8.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text('Open'), findsNothing); // No longer in the tree. - expect(find.text('Closed'), findsOneWidget); - final Element finalMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ), - ); - final _TrackedData dataClosed = _TrackedData( - finalMaterialElement.widget as Material, - tester.getRect( - find.byElementPredicate((Element e) => e == finalMaterialElement), - ), - ); - expect(dataClosed.material.color, dataTransitionDone.material.color); - expect( - dataClosed.material.elevation, - dataTransitionDone.material.elevation, - ); - expect(dataClosed.radius, dataTransitionDone.radius); - expect(dataClosed.rect, dataTransitionDone.rect); - }, - ); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Open'), findsOneWidget); + final Element materialElement = tester.firstElement( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ); + final _TrackedData dataTransitionStart = _TrackedData( + materialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == materialElement), + ), + ); + expect(dataTransitionStart.material.color, dataOpen.material.color); + expect(dataTransitionStart.material.elevation, dataOpen.material.elevation); + expect(dataTransitionStart.radius, dataOpen.radius); + expect(dataTransitionStart.rect, dataOpen.rect); + expect(_getOpacity(tester, 'Open'), 1.0); + + // Jump to start of fade out: 1/5 of 300. + await tester.pump(const Duration(milliseconds: 60)); // 300 * 1/5 = 60 + final _TrackedData dataPreFadeOut = _TrackedData( + materialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == materialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataPreFadeOut, + biggerMaterial: dataTransitionStart, + tester: tester, + ); + expect(_getOpacity(tester, 'Open'), moreOrLessEquals(1.0)); + expect(_getOpacity(tester, 'Closed'), 1.0); + + // Jump to the middle of the fade out. + await tester.pump(const Duration(milliseconds: 30)); // 300 * 3/10 = 90 + final _TrackedData dataMidpoint = _TrackedData( + materialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == materialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataMidpoint, + biggerMaterial: dataPreFadeOut, + tester: tester, + ); + expect(dataMidpoint.material.color, isNot(dataPreFadeOut.material.color)); + expect(_getOpacity(tester, 'Open'), lessThan(1.0)); + expect(_getOpacity(tester, 'Open'), greaterThan(0.0)); + expect(_getOpacity(tester, 'Closed'), 1.0); + + // Jump to the end of the fade out. + await tester.pump(const Duration(milliseconds: 30)); // 300 * 2/5 = 120 + final _TrackedData dataPostFadeOut = _TrackedData( + materialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == materialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataPostFadeOut, + biggerMaterial: dataMidpoint, + tester: tester, + ); + expect(_getOpacity(tester, 'Open'), moreOrLessEquals(0.0)); + expect(_getOpacity(tester, 'Closed'), 1.0); + + // Jump almost to the end of the transition. + await tester.pump(const Duration(milliseconds: 180)); + final _TrackedData dataTransitionDone = _TrackedData( + materialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == materialElement), + ), + ); + _expectMaterialPropertiesHaveAdvanced( + smallerMaterial: dataTransitionDone, + biggerMaterial: dataPostFadeOut, + tester: tester, + ); + expect(_getOpacity(tester, 'Closed'), 1.0); + expect(_getOpacity(tester, 'Open'), 0.0); + expect(dataTransitionDone.material.color, Colors.green); + expect(dataTransitionDone.material.elevation, 4.0); + expect(dataTransitionDone.radius, 8.0); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text('Open'), findsNothing); // No longer in the tree. + expect(find.text('Closed'), findsOneWidget); + final Element finalMaterialElement = tester.firstElement( + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), + ); + final _TrackedData dataClosed = _TrackedData( + finalMaterialElement.widget as Material, + tester.getRect( + find.byElementPredicate((Element e) => e == finalMaterialElement), + ), + ); + expect(dataClosed.material.color, dataTransitionDone.material.color); + expect( + dataClosed.material.elevation, + dataTransitionDone.material.elevation, + ); + expect(dataClosed.radius, dataTransitionDone.radius); + expect(dataClosed.rect, dataTransitionDone.rect); + }); testWidgets('Container opens - Fade through', (WidgetTester tester) async { const ShapeBorder shape = RoundedRectangleBorder( @@ -357,34 +336,33 @@ void main() { bool closedBuilderCalled = false; bool openBuilderCalled = false; - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - closedColor: Colors.green, - openColor: Colors.blue, - middleColor: Colors.red, - closedElevation: 4.0, - openElevation: 8.0, - closedShape: shape, - closedBuilder: (BuildContext context, VoidCallback _) { - closedBuilderCalled = true; - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback _) { - openBuilderCalled = true; - return const Text('Open'); - }, - transitionType: ContainerTransitionType.fadeThrough, + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + closedColor: Colors.green, + openColor: Colors.blue, + middleColor: Colors.red, + closedElevation: 4.0, + openElevation: 8.0, + closedShape: shape, + closedBuilder: (BuildContext context, VoidCallback _) { + closedBuilderCalled = true; + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback _) { + openBuilderCalled = true; + return const Text('Open'); + }, + transitionType: ContainerTransitionType.fadeThrough, + ), ), ), - )); + ); // Closed container has the expected properties. final Element srcMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ), + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); final Material srcMaterial = srcMaterialElement.widget as Material; expect(srcMaterial.color, Colors.green); @@ -406,10 +384,7 @@ void main() { // On the first frame of the animation everything still looks like before. final Element destMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ), + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); final Material closedMaterial = destMaterialElement.widget as Material; expect(closedMaterial.color, Colors.green); @@ -510,10 +485,7 @@ void main() { expect(find.text('Closed'), findsNothing); // No longer in the tree. expect(find.text('Open'), findsOneWidget); final Element finalMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ), + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); final _TrackedData dataOpen = _TrackedData( finalMaterialElement.widget as Material, @@ -532,25 +504,27 @@ void main() { borderRadius: BorderRadius.all(Radius.circular(8.0)), ); - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - closedColor: Colors.green, - openColor: Colors.blue, - middleColor: Colors.red, - closedElevation: 4.0, - openElevation: 8.0, - closedShape: shape, - closedBuilder: (BuildContext context, VoidCallback _) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback _) { - return const Text('Open'); - }, - transitionType: ContainerTransitionType.fadeThrough, + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + closedColor: Colors.green, + openColor: Colors.blue, + middleColor: Colors.red, + closedElevation: 4.0, + openElevation: 8.0, + closedShape: shape, + closedBuilder: (BuildContext context, VoidCallback _) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback _) { + return const Text('Open'); + }, + transitionType: ContainerTransitionType.fadeThrough, + ), ), ), - )); + ); await tester.tap(find.text('Closed')); await tester.pumpAndSettle(); @@ -559,10 +533,7 @@ void main() { expect(find.text('Closed'), findsNothing); expect(find.text('Open'), findsOneWidget); final Element initialMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ), + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); final _TrackedData dataOpen = _TrackedData( initialMaterialElement.widget as Material, @@ -584,10 +555,7 @@ void main() { expect(find.text('Closed'), findsOneWidget); expect(find.text('Open'), findsOneWidget); final Element materialElement = tester.firstElement( - find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ), + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); final _TrackedData dataTransitionStart = _TrackedData( materialElement.widget as Material, @@ -685,10 +653,7 @@ void main() { expect(find.text('Open'), findsNothing); // No longer in the tree. expect(find.text('Closed'), findsOneWidget); final Element finalMaterialElement = tester.firstElement( - find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ), + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); final _TrackedData dataClosed = _TrackedData( finalMaterialElement.widget as Material, @@ -705,21 +670,24 @@ void main() { expect(dataClosed.rect, dataTransitionDone.rect); }); - testWidgets('Cannot tap container if tappable=false', - (WidgetTester tester) async { - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - tappable: false, - closedBuilder: (BuildContext context, VoidCallback _) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback _) { - return const Text('Open'); - }, + testWidgets('Cannot tap container if tappable=false', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + tappable: false, + closedBuilder: (BuildContext context, VoidCallback _) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback _) { + return const Text('Open'); + }, + ), ), ), - )); + ); expect(find.text('Open'), findsNothing); expect(find.text('Closed'), findsOneWidget); @@ -731,21 +699,23 @@ void main() { testWidgets('Action callbacks work', (WidgetTester tester) async { late VoidCallback open, close; - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - tappable: false, - closedBuilder: (BuildContext context, VoidCallback action) { - open = action; - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - close = action; - return const Text('Open'); - }, + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + tappable: false, + closedBuilder: (BuildContext context, VoidCallback action) { + open = action; + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + close = action; + return const Text('Open'); + }, + ), ), ), - )); + ); expect(find.text('Open'), findsNothing); expect(find.text('Closed'), findsOneWidget); @@ -766,18 +736,20 @@ void main() { }); testWidgets('open widget keeps state', (WidgetTester tester) async { - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - closedBuilder: (BuildContext context, VoidCallback action) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const DummyStatefulWidget(); - }, + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + closedBuilder: (BuildContext context, VoidCallback action) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const DummyStatefulWidget(); + }, + ), ), ), - )); + ); await tester.tap(find.text('Closed')); await tester.pump(const Duration(milliseconds: 200)); @@ -802,19 +774,21 @@ void main() { testWidgets('closed widget keeps state', (WidgetTester tester) async { late VoidCallback open; - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - closedBuilder: (BuildContext context, VoidCallback action) { - open = action; - return const DummyStatefulWidget(); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const Text('Open'); - }, + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + closedBuilder: (BuildContext context, VoidCallback action) { + open = action; + return const DummyStatefulWidget(); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const Text('Open'); + }, + ), ), ), - )); + ); final State stateClosed = tester.state(find.byType(DummyStatefulWidget)); expect(stateClosed, isNotNull); @@ -829,10 +803,9 @@ void main() { await tester.pumpAndSettle(); expect(find.byType(DummyStatefulWidget), findsNothing); expect(find.text('Open'), findsOneWidget); - final State stateOpen = tester.state(find.byType( - DummyStatefulWidget, - skipOffstage: false, - )); + final State stateOpen = tester.state( + find.byType(DummyStatefulWidget, skipOffstage: false), + ); expect(stateOpen, same(stateOpening)); final NavigatorState navigator = tester.state(find.byType(Navigator)); @@ -844,35 +817,29 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Open'), findsNothing); - final State stateClosedAgain = - tester.state(find.byType(DummyStatefulWidget)); + final State stateClosedAgain = tester.state( + find.byType(DummyStatefulWidget), + ); expect(stateClosedAgain, same(stateClosing)); }); - testWidgets('closes to the right location when src position has changed', - (WidgetTester tester) async { + testWidgets('closes to the right location when src position has changed', ( + WidgetTester tester, + ) async { final Widget openContainer = OpenContainer( closedBuilder: (BuildContext context, VoidCallback action) { - return const SizedBox( - height: 100, - width: 100, - child: Text('Closed'), - ); + return const SizedBox(height: 100, width: 100, child: Text('Closed')); }, openBuilder: (BuildContext context, VoidCallback action) { - return GestureDetector( - onTap: action, - child: const Text('Open'), - ); + return GestureDetector(onTap: action, child: const Text('Open')); }, ); - await tester.pumpWidget(_boilerplate( - child: Align( - alignment: Alignment.topLeft, - child: openContainer, + await tester.pumpWidget( + _boilerplate( + child: Align(alignment: Alignment.topLeft, child: openContainer), ), - )); + ); final Rect originTextRect = tester.getRect(find.text('Closed')); expect(originTextRect.topLeft, Offset.zero); @@ -883,12 +850,11 @@ void main() { expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsNothing); - await tester.pumpWidget(_boilerplate( - child: Align( - alignment: Alignment.bottomLeft, - child: openContainer, + await tester.pumpWidget( + _boilerplate( + child: Align(alignment: Alignment.bottomLeft, child: openContainer), ), - )); + ); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsNothing); @@ -921,10 +887,7 @@ void main() { ); }, openBuilder: (BuildContext context, VoidCallback action) { - return GestureDetector( - onTap: action, - child: const Text('Open'), - ); + return GestureDetector(onTap: action, child: const Text('Open')); }, ), ), @@ -932,12 +895,11 @@ void main() { await tester.pumpWidget(openContainer); - final Size orignalClosedRect = tester.getSize(find - .ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ) - .first); + final Size orignalClosedRect = tester.getSize( + find + .ancestor(of: find.text('Closed'), matching: find.byType(Material)) + .first, + ); expect(orignalClosedRect, const Size(100, 100)); await tester.tap(find.text('Closed')); @@ -946,10 +908,9 @@ void main() { expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsNothing); - final _SizableContainerState containerState = tester.state(find.byType( - _SizableContainer, - skipOffstage: false, - )); + final _SizableContainerState containerState = tester.state( + find.byType(_SizableContainer, skipOffstage: false), + ); containerState.size = 200; expect(find.text('Open'), findsOneWidget); @@ -960,41 +921,42 @@ void main() { expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final Size transitionEndSize = tester.getSize(find - .ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ) - .first); + final Size transitionEndSize = tester.getSize( + find + .ancestor(of: find.text('Open'), matching: find.byType(Material)) + .first, + ); expect(transitionEndSize, const Size(200, 200)); await tester.pump(const Duration(milliseconds: 1)); expect(find.text('Open'), findsNothing); expect(find.text('Closed'), findsOneWidget); - final Size finalSize = tester.getSize(find - .ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ) - .first); + final Size finalSize = tester.getSize( + find + .ancestor(of: find.text('Closed'), matching: find.byType(Material)) + .first, + ); expect(finalSize, const Size(200, 200)); }); - testWidgets('transition is interrupted and should not jump', - (WidgetTester tester) async { - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - closedBuilder: (BuildContext context, VoidCallback action) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const Text('Open'); - }, + testWidgets('transition is interrupted and should not jump', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + closedBuilder: (BuildContext context, VoidCallback action) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const Text('Open'); + }, + ), ), ), - )); + ); await tester.tap(find.text('Closed')); await tester.pump(); @@ -1002,10 +964,9 @@ void main() { expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final Material openingMaterial = tester.firstWidget(find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - )); + final Material openingMaterial = tester.firstWidget( + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), + ); final Rect openingRect = tester.getRect( find.byWidgetPredicate((Widget w) => w == openingMaterial), ); @@ -1015,10 +976,9 @@ void main() { navigator.pop(); await tester.pump(); - final Material closingMaterial = tester.firstWidget(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - )); + final Material closingMaterial = tester.firstWidget( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ); final Rect closingRect = tester.getRect( find.byWidgetPredicate((Widget w) => w == closingMaterial), ); @@ -1030,82 +990,83 @@ void main() { }); testWidgets('navigator is not full size', (WidgetTester tester) async { - await tester.pumpWidget(Center( - child: SizedBox( - width: 300, - height: 400, - child: _boilerplate( - child: Center( - child: OpenContainer( - closedBuilder: (BuildContext context, VoidCallback action) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const Text('Open'); - }, + await tester.pumpWidget( + Center( + child: SizedBox( + width: 300, + height: 400, + child: _boilerplate( + child: Center( + child: OpenContainer( + closedBuilder: (BuildContext context, VoidCallback action) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const Text('Open'); + }, + ), ), ), ), ), - )); + ); const Rect fullNavigator = Rect.fromLTWH(250, 100, 300, 400); expect(tester.getRect(find.byType(Navigator)), fullNavigator); - final Rect materialRectClosed = tester.getRect(find - .ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ) - .first); + final Rect materialRectClosed = tester.getRect( + find + .ancestor(of: find.text('Closed'), matching: find.byType(Material)) + .first, + ); await tester.tap(find.text('Closed')); await tester.pump(); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final Rect materialRectTransitionStart = tester.getRect(find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - )); + final Rect materialRectTransitionStart = tester.getRect( + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), + ); expect(materialRectTransitionStart, materialRectClosed); await tester.pump(const Duration(milliseconds: 300)); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final Rect materialRectTransitionEnd = tester.getRect(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - )); + final Rect materialRectTransitionEnd = tester.getRect( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ); expect(materialRectTransitionEnd, fullNavigator); await tester.pumpAndSettle(); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsNothing); - final Rect materialRectOpen = tester.getRect(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - )); + final Rect materialRectOpen = tester.getRect( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ); expect(materialRectOpen, fullNavigator); }); - testWidgets('does not crash when disposed right after pop', - (WidgetTester tester) async { - await tester.pumpWidget(Center( - child: SizedBox( - width: 300, - height: 400, - child: _boilerplate( - child: Center( - child: OpenContainer( - closedBuilder: (BuildContext context, VoidCallback action) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const Text('Open'); - }, + testWidgets('does not crash when disposed right after pop', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Center( + child: SizedBox( + width: 300, + height: 400, + child: _boilerplate( + child: Center( + child: OpenContainer( + closedBuilder: (BuildContext context, VoidCallback action) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const Text('Open'); + }, + ), ), ), ), ), - )); + ); await tester.tap(find.text('Closed')); await tester.pumpAndSettle(); @@ -1120,25 +1081,27 @@ void main() { }); testWidgets('can specify a duration', (WidgetTester tester) async { - await tester.pumpWidget(Center( - child: SizedBox( - width: 300, - height: 400, - child: _boilerplate( - child: Center( - child: OpenContainer( - transitionDuration: const Duration(seconds: 2), - closedBuilder: (BuildContext context, VoidCallback action) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const Text('Open'); - }, + await tester.pumpWidget( + Center( + child: SizedBox( + width: 300, + height: 400, + child: _boilerplate( + child: Center( + child: OpenContainer( + transitionDuration: const Duration(seconds: 2), + closedBuilder: (BuildContext context, VoidCallback action) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const Text('Open'); + }, + ), ), ), ), ), - )); + ); expect(find.text('Open'), findsNothing); expect(find.text('Closed'), findsOneWidget); @@ -1168,75 +1131,82 @@ void main() { }); testWidgets('can specify an open shape', (WidgetTester tester) async { - await tester.pumpWidget(Center( - child: SizedBox( - width: 300, - height: 400, - child: _boilerplate( - child: Center( - child: OpenContainer( - closedShape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - openShape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(40), + await tester.pumpWidget( + Center( + child: SizedBox( + width: 300, + height: 400, + child: _boilerplate( + child: Center( + child: OpenContainer( + closedShape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + openShape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(40), + ), + closedBuilder: (BuildContext context, VoidCallback action) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return const Text('Open'); + }, ), - closedBuilder: (BuildContext context, VoidCallback action) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return const Text('Open'); - }, ), ), ), ), - )); + ); expect(find.text('Open'), findsNothing); expect(find.text('Closed'), findsOneWidget); - final double closedRadius = _getRadius(tester.firstWidget(find.ancestor( - of: find.text('Closed'), - matching: find.byType(Material), - ))); + final double closedRadius = _getRadius( + tester.firstWidget( + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), + ), + ); expect(closedRadius, 10.0); await tester.tap(find.text('Closed')); await tester.pump(); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final double openingRadius = _getRadius(tester.firstWidget(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ))); + final double openingRadius = _getRadius( + tester.firstWidget( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ), + ); expect(openingRadius, 10.0); await tester.pump(const Duration(milliseconds: 150)); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final double halfwayRadius = _getRadius(tester.firstWidget(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ))); + final double halfwayRadius = _getRadius( + tester.firstWidget( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ), + ); expect(halfwayRadius, greaterThan(10.0)); expect(halfwayRadius, lessThan(40.0)); await tester.pump(const Duration(milliseconds: 150)); expect(find.text('Open'), findsOneWidget); expect(find.text('Closed'), findsOneWidget); - final double openRadius = _getRadius(tester.firstWidget(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ))); + final double openRadius = _getRadius( + tester.firstWidget( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ), + ); expect(openRadius, 40.0); await tester.pump(const Duration(milliseconds: 1)); expect(find.text('Closed'), findsNothing); expect(find.text('Open'), findsOneWidget); - final double finalRadius = _getRadius(tester.firstWidget(find.ancestor( - of: find.text('Open'), - matching: find.byType(Material), - ))); + final double finalRadius = _getRadius( + tester.firstWidget( + find.ancestor(of: find.text('Open'), matching: find.byType(Material)), + ), + ); expect(finalRadius, 40.0); }); @@ -1245,23 +1215,25 @@ void main() { borderRadius: BorderRadius.all(Radius.circular(8.0)), ); - await tester.pumpWidget(_boilerplate( - child: Center( - child: OpenContainer( - closedColor: Colors.green, - openColor: Colors.blue, - closedElevation: 4.0, - openElevation: 8.0, - closedShape: shape, - closedBuilder: (BuildContext context, VoidCallback _) { - return const Text('Closed'); - }, - openBuilder: (BuildContext context, VoidCallback _) { - return const Text('Open'); - }, + await tester.pumpWidget( + _boilerplate( + child: Center( + child: OpenContainer( + closedColor: Colors.green, + openColor: Colors.blue, + closedElevation: 4.0, + openElevation: 8.0, + closedShape: shape, + closedBuilder: (BuildContext context, VoidCallback _) { + return const Text('Closed'); + }, + openBuilder: (BuildContext context, VoidCallback _) { + return const Text('Open'); + }, + ), ), ), - )); + ); expect(find.text('Closed'), findsOneWidget); expect(find.text('Open'), findsNothing); @@ -1302,206 +1274,210 @@ void main() { }); testWidgets( - 'Container partly offscreen can be opened without crash - vertical', - (WidgetTester tester) async { - final ScrollController controller = - ScrollController(initialScrollOffset: 50); - await tester.pumpWidget(Center( - child: SizedBox( - height: 200, - width: 200, - child: _boilerplate( - child: ListView.builder( - cacheExtent: 0, - controller: controller, - itemBuilder: (BuildContext context, int index) { - return OpenContainer( - closedBuilder: (BuildContext context, VoidCallback _) { - return SizedBox( - height: 100, - width: 100, - child: Text('Closed $index'), + 'Container partly offscreen can be opened without crash - vertical', + (WidgetTester tester) async { + final ScrollController controller = ScrollController( + initialScrollOffset: 50, + ); + await tester.pumpWidget( + Center( + child: SizedBox( + height: 200, + width: 200, + child: _boilerplate( + child: ListView.builder( + cacheExtent: 0, + controller: controller, + itemBuilder: (BuildContext context, int index) { + return OpenContainer( + closedBuilder: (BuildContext context, VoidCallback _) { + return SizedBox( + height: 100, + width: 100, + child: Text('Closed $index'), + ); + }, + openBuilder: (BuildContext context, VoidCallback _) { + return Text('Open $index'); + }, ); }, - openBuilder: (BuildContext context, VoidCallback _) { - return Text('Open $index'); - }, - ); - }, + ), + ), ), ), - ), - )); - - void expectClosedState() { - expect(find.text('Closed 0'), findsOneWidget); - expect(find.text('Closed 1'), findsOneWidget); - expect(find.text('Closed 2'), findsOneWidget); - expect(find.text('Closed 3'), findsNothing); - - expect(find.text('Open 0'), findsNothing); - expect(find.text('Open 1'), findsNothing); - expect(find.text('Open 2'), findsNothing); - expect(find.text('Open 3'), findsNothing); - } + ); - expectClosedState(); + void expectClosedState() { + expect(find.text('Closed 0'), findsOneWidget); + expect(find.text('Closed 1'), findsOneWidget); + expect(find.text('Closed 2'), findsOneWidget); + expect(find.text('Closed 3'), findsNothing); - // Open container that's partly visible at top. - await tester.tapAt( - tester.getBottomRight(find.text('Closed 0')) - const Offset(20, 20), - ); - await tester.pump(); - await tester.pumpAndSettle(); - expect(find.text('Closed 0'), findsNothing); - expect(find.text('Open 0'), findsOneWidget); + expect(find.text('Open 0'), findsNothing); + expect(find.text('Open 1'), findsNothing); + expect(find.text('Open 2'), findsNothing); + expect(find.text('Open 3'), findsNothing); + } - final NavigatorState navigator = tester.state(find.byType(Navigator)); - navigator.pop(); - await tester.pump(); - await tester.pumpAndSettle(); - expectClosedState(); + expectClosedState(); - // Open container that's partly visible at bottom. - await tester.tapAt( - tester.getTopLeft(find.text('Closed 2')) + const Offset(20, 20), - ); - await tester.pump(); - await tester.pumpAndSettle(); + // Open container that's partly visible at top. + await tester.tapAt( + tester.getBottomRight(find.text('Closed 0')) - const Offset(20, 20), + ); + await tester.pump(); + await tester.pumpAndSettle(); + expect(find.text('Closed 0'), findsNothing); + expect(find.text('Open 0'), findsOneWidget); - expect(find.text('Closed 2'), findsNothing); - expect(find.text('Open 2'), findsOneWidget); - }); + final NavigatorState navigator = tester.state(find.byType(Navigator)); + navigator.pop(); + await tester.pump(); + await tester.pumpAndSettle(); + expectClosedState(); + + // Open container that's partly visible at bottom. + await tester.tapAt( + tester.getTopLeft(find.text('Closed 2')) + const Offset(20, 20), + ); + await tester.pump(); + await tester.pumpAndSettle(); + + expect(find.text('Closed 2'), findsNothing); + expect(find.text('Open 2'), findsOneWidget); + }, + ); testWidgets( - 'Container partly offscreen can be opened without crash - horizontal', - (WidgetTester tester) async { - final ScrollController controller = - ScrollController(initialScrollOffset: 50); - await tester.pumpWidget(Center( - child: SizedBox( - height: 200, - width: 200, - child: _boilerplate( - child: ListView.builder( - scrollDirection: Axis.horizontal, - cacheExtent: 0, - controller: controller, - itemBuilder: (BuildContext context, int index) { - return OpenContainer( - closedBuilder: (BuildContext context, VoidCallback _) { - return SizedBox( - height: 100, - width: 100, - child: Text('Closed $index'), + 'Container partly offscreen can be opened without crash - horizontal', + (WidgetTester tester) async { + final ScrollController controller = ScrollController( + initialScrollOffset: 50, + ); + await tester.pumpWidget( + Center( + child: SizedBox( + height: 200, + width: 200, + child: _boilerplate( + child: ListView.builder( + scrollDirection: Axis.horizontal, + cacheExtent: 0, + controller: controller, + itemBuilder: (BuildContext context, int index) { + return OpenContainer( + closedBuilder: (BuildContext context, VoidCallback _) { + return SizedBox( + height: 100, + width: 100, + child: Text('Closed $index'), + ); + }, + openBuilder: (BuildContext context, VoidCallback _) { + return Text('Open $index'); + }, ); }, - openBuilder: (BuildContext context, VoidCallback _) { - return Text('Open $index'); - }, - ); - }, + ), + ), ), ), - ), - )); - - void expectClosedState() { - expect(find.text('Closed 0'), findsOneWidget); - expect(find.text('Closed 1'), findsOneWidget); - expect(find.text('Closed 2'), findsOneWidget); - expect(find.text('Closed 3'), findsNothing); - - expect(find.text('Open 0'), findsNothing); - expect(find.text('Open 1'), findsNothing); - expect(find.text('Open 2'), findsNothing); - expect(find.text('Open 3'), findsNothing); - } + ); - expectClosedState(); + void expectClosedState() { + expect(find.text('Closed 0'), findsOneWidget); + expect(find.text('Closed 1'), findsOneWidget); + expect(find.text('Closed 2'), findsOneWidget); + expect(find.text('Closed 3'), findsNothing); - // Open container that's partly visible at left edge. - await tester.tapAt( - tester.getBottomRight(find.text('Closed 0')) - const Offset(20, 20), - ); - await tester.pump(); - await tester.pumpAndSettle(); - expect(find.text('Closed 0'), findsNothing); - expect(find.text('Open 0'), findsOneWidget); + expect(find.text('Open 0'), findsNothing); + expect(find.text('Open 1'), findsNothing); + expect(find.text('Open 2'), findsNothing); + expect(find.text('Open 3'), findsNothing); + } - final NavigatorState navigator = tester.state(find.byType(Navigator)); - navigator.pop(); - await tester.pump(); - await tester.pumpAndSettle(); - expectClosedState(); + expectClosedState(); - // Open container that's partly visible at right edge. - await tester.tapAt( - tester.getTopLeft(find.text('Closed 2')) + const Offset(20, 20), - ); - await tester.pump(); - await tester.pumpAndSettle(); + // Open container that's partly visible at left edge. + await tester.tapAt( + tester.getBottomRight(find.text('Closed 0')) - const Offset(20, 20), + ); + await tester.pump(); + await tester.pumpAndSettle(); + expect(find.text('Closed 0'), findsNothing); + expect(find.text('Open 0'), findsOneWidget); - expect(find.text('Closed 2'), findsNothing); - expect(find.text('Open 2'), findsOneWidget); - }); + final NavigatorState navigator = tester.state(find.byType(Navigator)); + navigator.pop(); + await tester.pump(); + await tester.pumpAndSettle(); + expectClosedState(); + + // Open container that's partly visible at right edge. + await tester.tapAt( + tester.getTopLeft(find.text('Closed 2')) + const Offset(20, 20), + ); + await tester.pump(); + await tester.pumpAndSettle(); + + expect(find.text('Closed 2'), findsNothing); + expect(find.text('Open 2'), findsOneWidget); + }, + ); testWidgets( - 'Container can be dismissed after container widget itself is removed without crash', - (WidgetTester tester) async { - await tester.pumpWidget(_boilerplate(child: _RemoveOpenContainerExample())); + 'Container can be dismissed after container widget itself is removed without crash', + (WidgetTester tester) async { + await tester.pumpWidget( + _boilerplate(child: _RemoveOpenContainerExample()), + ); - expect(find.text('Closed'), findsOneWidget); - expect(find.text('Closed', skipOffstage: false), findsOneWidget); - expect(find.text('Open'), findsNothing); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Closed', skipOffstage: false), findsOneWidget); + expect(find.text('Open'), findsNothing); - await tester.tap(find.text('Open the container')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Open the container')); + await tester.pumpAndSettle(); - expect(find.text('Closed'), findsNothing); - expect(find.text('Closed', skipOffstage: false), findsOneWidget); - expect(find.text('Open'), findsOneWidget); + expect(find.text('Closed'), findsNothing); + expect(find.text('Closed', skipOffstage: false), findsOneWidget); + expect(find.text('Open'), findsOneWidget); - await tester.tap(find.text('Remove the container')); - await tester.pump(); + await tester.tap(find.text('Remove the container')); + await tester.pump(); - expect(find.text('Closed'), findsNothing); - expect(find.text('Closed', skipOffstage: false), findsNothing); - expect(find.text('Open'), findsOneWidget); + expect(find.text('Closed'), findsNothing); + expect(find.text('Closed', skipOffstage: false), findsNothing); + expect(find.text('Open'), findsOneWidget); - await tester.tap(find.text('Close the container')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Close the container')); + await tester.pumpAndSettle(); - expect(find.text('Closed'), findsNothing); - expect(find.text('Closed', skipOffstage: false), findsNothing); - expect(find.text('Open'), findsNothing); - expect(find.text('Container has been removed'), findsOneWidget); - }); + expect(find.text('Closed'), findsNothing); + expect(find.text('Closed', skipOffstage: false), findsNothing); + expect(find.text('Open'), findsNothing); + expect(find.text('Container has been removed'), findsOneWidget); + }, + ); - testWidgets('onClosed callback is called when container has closed', - (WidgetTester tester) async { + testWidgets('onClosed callback is called when container has closed', ( + WidgetTester tester, + ) async { bool hasClosed = false; final Widget openContainer = OpenContainer( onClosed: (dynamic _) { hasClosed = true; }, closedBuilder: (BuildContext context, VoidCallback action) { - return GestureDetector( - onTap: action, - child: const Text('Closed'), - ); + return GestureDetector(onTap: action, child: const Text('Closed')); }, openBuilder: (BuildContext context, VoidCallback action) { - return GestureDetector( - onTap: action, - child: const Text('Open'), - ); + return GestureDetector(onTap: action, child: const Text('Open')); }, ); - await tester.pumpWidget( - _boilerplate(child: openContainer), - ); + await tester.pumpWidget(_boilerplate(child: openContainer)); expect(find.text('Open'), findsNothing); expect(find.text('Closed'), findsOneWidget); @@ -1522,73 +1498,73 @@ void main() { }); testWidgets( - 'onClosed callback receives popped value when container has closed', - (WidgetTester tester) async { - bool? value = false; - final Widget openContainer = OpenContainer( - onClosed: (bool? poppedValue) { - value = poppedValue; - }, - 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'), - ); - }, - ); + 'onClosed callback receives popped value when container has closed', + (WidgetTester tester) async { + bool? value = false; + final Widget openContainer = OpenContainer( + onClosed: (bool? poppedValue) { + value = poppedValue; + }, + 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'), + ); + }, + ); - await tester.pumpWidget( - _boilerplate(child: openContainer), - ); + await tester.pumpWidget(_boilerplate(child: openContainer)); - expect(find.text('Open'), findsNothing); - expect(find.text('Closed'), findsOneWidget); - expect(value, isFalse); + expect(find.text('Open'), findsNothing); + expect(find.text('Closed'), findsOneWidget); + expect(value, isFalse); - await tester.tap(find.text('Closed')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Closed')); + await tester.pumpAndSettle(); - expect(find.text('Open'), findsOneWidget); - expect(find.text('Closed'), findsNothing); + expect(find.text('Open'), findsOneWidget); + expect(find.text('Closed'), findsNothing); - await tester.tap(find.text('Open')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); - expect(find.text('Open'), findsNothing); - expect(find.text('Closed'), findsOneWidget); - expect(value, isTrue); - }); + expect(find.text('Open'), findsNothing); + expect(find.text('Closed'), findsOneWidget); + expect(value, isTrue); + }, + ); - testWidgets('closedBuilder has anti-alias clip by default', - (WidgetTester tester) async { + testWidgets('closedBuilder has anti-alias clip by default', ( + WidgetTester tester, + ) async { final GlobalKey closedBuilderKey = GlobalKey(); final Widget openContainer = OpenContainer( closedBuilder: (BuildContext context, VoidCallback action) { return Text('Close', key: closedBuilderKey); }, - openBuilder: - (BuildContext context, CloseContainerActionCallback action) { + openBuilder: ( + BuildContext context, + CloseContainerActionCallback action, + ) { return const Text('Open'); }, ); - await tester.pumpWidget( - _boilerplate(child: openContainer), - ); + 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); @@ -1600,23 +1576,24 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return Text('Close', key: closedBuilderKey); }, - openBuilder: - (BuildContext context, CloseContainerActionCallback action) { + openBuilder: ( + BuildContext context, + CloseContainerActionCallback action, + ) { return const Text('Open'); }, clipBehavior: Clip.none, ); - await tester.pumpWidget( - _boilerplate(child: openContainer), - ); + 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); @@ -1665,124 +1642,145 @@ void main() { } testWidgets( - 'Verify that "useRootNavigator: false" uses the correct navigator', - (WidgetTester tester) async { - const Key appKey = Key('App'); - const Key nestedNavigatorKey = Key('Nested Navigator'); - - await tester.pumpWidget(createRootNavigatorTest( - appKey: appKey, - nestedNavigatorKey: nestedNavigatorKey, - useRootNavigator: false)); + 'Verify that "useRootNavigator: false" uses the correct navigator', + (WidgetTester tester) async { + const Key appKey = Key('App'); + const Key nestedNavigatorKey = Key('Nested Navigator'); + + await tester.pumpWidget( + createRootNavigatorTest( + appKey: appKey, + nestedNavigatorKey: nestedNavigatorKey, + useRootNavigator: false, + ), + ); - await tester.tap(find.text('Closed')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Closed')); + await tester.pumpAndSettle(); - expect( + expect( find.descendant(of: find.byKey(appKey), matching: find.text('Opened')), - findsOneWidget); + findsOneWidget, + ); - expect( + expect( find.descendant( - of: find.byKey(nestedNavigatorKey), matching: find.text('Opened')), - findsOneWidget); - }); - - testWidgets('Verify that "useRootNavigator: true" uses the correct navigator', - (WidgetTester tester) async { - const Key appKey = Key('App'); - const Key nestedNavigatorKey = Key('Nested Navigator'); + of: find.byKey(nestedNavigatorKey), + matching: find.text('Opened'), + ), + findsOneWidget, + ); + }, + ); - await tester.pumpWidget(createRootNavigatorTest( - appKey: appKey, - nestedNavigatorKey: nestedNavigatorKey, - useRootNavigator: true)); + testWidgets( + 'Verify that "useRootNavigator: true" uses the correct navigator', + (WidgetTester tester) async { + const Key appKey = Key('App'); + const Key nestedNavigatorKey = Key('Nested Navigator'); + + await tester.pumpWidget( + createRootNavigatorTest( + appKey: appKey, + nestedNavigatorKey: nestedNavigatorKey, + useRootNavigator: true, + ), + ); - await tester.tap(find.text('Closed')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Closed')); + await tester.pumpAndSettle(); - expect( + expect( find.descendant(of: find.byKey(appKey), matching: find.text('Opened')), - findsOneWidget); + findsOneWidget, + ); - expect( + expect( find.descendant( - of: find.byKey(nestedNavigatorKey), matching: find.text('Opened')), - findsNothing); - }); + of: find.byKey(nestedNavigatorKey), + matching: find.text('Opened'), + ), + findsNothing, + ); + }, + ); - testWidgets('Verify correct opened size when "useRootNavigator: false"', - (WidgetTester tester) async { + testWidgets('Verify correct opened size when "useRootNavigator: false"', ( + WidgetTester tester, + ) async { const Key appKey = Key('App'); const Key nestedNavigatorKey = Key('Nested Navigator'); - await tester.pumpWidget(createRootNavigatorTest( + await tester.pumpWidget( + createRootNavigatorTest( appKey: appKey, nestedNavigatorKey: nestedNavigatorKey, - useRootNavigator: false)); + useRootNavigator: false, + ), + ); await tester.tap(find.text('Closed')); await tester.pumpAndSettle(); - expect(tester.getSize(find.text('Opened')), - equals(tester.getSize(find.byKey(nestedNavigatorKey)))); + expect( + tester.getSize(find.text('Opened')), + equals(tester.getSize(find.byKey(nestedNavigatorKey))), + ); }); - testWidgets('Verify correct opened size when "useRootNavigator: true"', - (WidgetTester tester) async { + testWidgets('Verify correct opened size when "useRootNavigator: true"', ( + WidgetTester tester, + ) async { const Key appKey = Key('App'); const Key nestedNavigatorKey = Key('Nested Navigator'); - await tester.pumpWidget(createRootNavigatorTest( + await tester.pumpWidget( + createRootNavigatorTest( appKey: appKey, nestedNavigatorKey: nestedNavigatorKey, - useRootNavigator: true)); + useRootNavigator: true, + ), + ); await tester.tap(find.text('Closed')); await tester.pumpAndSettle(); - expect(tester.getSize(find.text('Opened')), - equals(tester.getSize(find.byKey(appKey)))); + expect( + tester.getSize(find.text('Opened')), + equals(tester.getSize(find.byKey(appKey))), + ); }); - testWidgets( - 'Verify routeSettings passed to Navigator', - (WidgetTester tester) async { - const RouteSettings routeSettings = RouteSettings( - name: 'route-name', - arguments: 'arguments', - ); + testWidgets('Verify routeSettings passed to Navigator', ( + WidgetTester tester, + ) async { + const RouteSettings routeSettings = RouteSettings( + name: 'route-name', + arguments: 'arguments', + ); - final Widget openContainer = OpenContainer( - routeSettings: routeSettings, - closedBuilder: (BuildContext context, VoidCallback action) { - return GestureDetector( - onTap: action, - child: const Text('Closed'), - ); - }, - openBuilder: (BuildContext context, VoidCallback action) { - return GestureDetector( - onTap: action, - child: const Text('Open'), - ); - }, - ); + final Widget openContainer = OpenContainer( + routeSettings: routeSettings, + closedBuilder: (BuildContext context, VoidCallback action) { + return GestureDetector(onTap: action, child: const Text('Closed')); + }, + openBuilder: (BuildContext context, VoidCallback action) { + return GestureDetector(onTap: action, child: const Text('Open')); + }, + ); - await tester.pumpWidget(_boilerplate(child: openContainer)); + await tester.pumpWidget(_boilerplate(child: openContainer)); - // Open the container - await tester.tap(find.text('Closed')); - await tester.pumpAndSettle(); + // Open the container + await tester.tap(find.text('Closed')); + await tester.pumpAndSettle(); - // 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')), - )!; - expect(modalRoute.settings, routeSettings); - }, - ); + // 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')))!; + expect(modalRoute.settings, routeSettings); + }); } Color _getScrimColor(WidgetTester tester) { @@ -1813,10 +1811,9 @@ void _expectMaterialPropertiesHaveAdvanced({ } double _getOpacity(WidgetTester tester, String label) { - final FadeTransition widget = tester.firstWidget(find.ancestor( - of: find.text(label), - matching: find.byType(FadeTransition), - )); + final FadeTransition widget = tester.firstWidget( + find.ancestor(of: find.text(label), matching: find.byType(FadeTransition)), + ); // Verify that the correct fade transition is retrieved (i.e. not something from a page transition). assert(widget.child is Builder && widget.child?.key is GlobalKey, '$widget'); return widget.opacity.value; @@ -1842,11 +1839,7 @@ double _getRadius(Material material) { } Widget _boilerplate({required Widget child}) { - return MaterialApp( - home: Scaffold( - body: child, - ), - ); + return MaterialApp(home: Scaffold(body: child)); } class _SizableContainer extends StatefulWidget { @@ -1879,11 +1872,7 @@ class _SizableContainerState extends State<_SizableContainer> { @override Widget build(BuildContext context) { - return SizedBox( - height: size, - width: size, - child: widget.child, - ); + return SizedBox(height: size, width: size, child: widget.child); } } @@ -1902,33 +1891,35 @@ 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( + 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')), - ], - ), - ); + child: const Text('Remove the container'), + ), + ], + ), + ); } } diff --git a/packages/animations/test/page_transition_switcher_test.dart b/packages/animations/test/page_transition_switcher_test.dart index f7a35fb2dff..bef8bc51be9 100644 --- a/packages/animations/test/page_transition_switcher_test.dart +++ b/packages/animations/test/page_transition_switcher_test.dart @@ -19,10 +19,12 @@ void main() { ), ); - Map primaryAnimation = - _getPrimaryAnimation([containerOne], tester); - Map secondaryAnimation = - _getSecondaryAnimation([containerOne], tester); + Map primaryAnimation = _getPrimaryAnimation([ + containerOne, + ], tester); + Map secondaryAnimation = _getSecondaryAnimation([ + containerOne, + ], tester); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], equals(0.0)); @@ -35,10 +37,14 @@ void main() { ); await tester.pump(const Duration(milliseconds: 40)); - primaryAnimation = - _getPrimaryAnimation([containerOne, containerTwo], tester); - secondaryAnimation = - _getSecondaryAnimation([containerOne, containerTwo], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + ], tester); // Secondary is running for outgoing widget. expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], moreOrLessEquals(0.4)); @@ -59,10 +65,16 @@ void main() { ); await tester.pump(const Duration(milliseconds: 20)); - primaryAnimation = _getPrimaryAnimation( - [containerOne, containerTwo, containerThree], tester); - secondaryAnimation = _getSecondaryAnimation( - [containerOne, containerTwo, containerThree], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], equals(0.6)); expect(primaryAnimation[containerTwo], equals(0.6)); @@ -72,8 +84,9 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('transitions in a new child in reverse.', - (WidgetTester tester) async { + testWidgets('transitions in a new child in reverse.', ( + WidgetTester tester, + ) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); @@ -86,10 +99,12 @@ void main() { ), ); - Map primaryAnimation = - _getPrimaryAnimation([containerOne], tester); - Map secondaryAnimation = - _getSecondaryAnimation([containerOne], tester); + Map primaryAnimation = _getPrimaryAnimation([ + containerOne, + ], tester); + Map secondaryAnimation = _getSecondaryAnimation([ + containerOne, + ], tester); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], equals(0.0)); @@ -103,10 +118,14 @@ void main() { ); await tester.pump(const Duration(milliseconds: 40)); - primaryAnimation = - _getPrimaryAnimation([containerOne, containerTwo], tester); - secondaryAnimation = - _getSecondaryAnimation([containerOne, containerTwo], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + ], tester); // Primary is running forward for outgoing widget. expect(primaryAnimation[containerOne], moreOrLessEquals(0.6)); expect(secondaryAnimation[containerOne], equals(0.0)); @@ -128,10 +147,16 @@ void main() { ); await tester.pump(const Duration(milliseconds: 20)); - primaryAnimation = _getPrimaryAnimation( - [containerOne, containerTwo, containerThree], tester); - secondaryAnimation = _getSecondaryAnimation( - [containerOne, containerTwo, containerThree], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); expect(primaryAnimation[containerOne], equals(0.4)); expect(secondaryAnimation[containerOne], equals(0.0)); expect(primaryAnimation[containerTwo], equals(0.8)); @@ -153,10 +178,12 @@ void main() { ), ); - Map primaryAnimation = - _getPrimaryAnimation([containerOne], tester); - Map secondaryAnimation = - _getSecondaryAnimation([containerOne], tester); + Map primaryAnimation = _getPrimaryAnimation([ + containerOne, + ], tester); + Map secondaryAnimation = _getSecondaryAnimation([ + containerOne, + ], tester); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], equals(0.0)); @@ -169,10 +196,14 @@ void main() { ); await tester.pump(const Duration(milliseconds: 40)); - primaryAnimation = - _getPrimaryAnimation([containerOne, containerTwo], tester); - secondaryAnimation = - _getSecondaryAnimation([containerOne, containerTwo], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + ], tester); expect(secondaryAnimation[containerOne], moreOrLessEquals(0.4)); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerTwo], equals(0.0)); @@ -188,10 +219,16 @@ void main() { ); await tester.pump(const Duration(milliseconds: 20)); - primaryAnimation = _getPrimaryAnimation( - [containerOne, containerTwo, containerThree], tester); - secondaryAnimation = _getSecondaryAnimation( - [containerOne, containerTwo, containerThree], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); expect(secondaryAnimation[containerOne], equals(0.6)); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerTwo], equals(0.0)); @@ -214,10 +251,12 @@ void main() { ), ); - Map primaryAnimation = - _getPrimaryAnimation([containerOne], tester); - Map secondaryAnimation = - _getSecondaryAnimation([containerOne], tester); + Map primaryAnimation = _getPrimaryAnimation([ + containerOne, + ], tester); + Map secondaryAnimation = _getSecondaryAnimation([ + containerOne, + ], tester); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], equals(0.0)); @@ -231,10 +270,14 @@ void main() { ); await tester.pump(const Duration(milliseconds: 40)); - primaryAnimation = - _getPrimaryAnimation([containerOne, containerTwo], tester); - secondaryAnimation = - _getSecondaryAnimation([containerOne, containerTwo], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + ], tester); // Primary is running in reverse for outgoing widget. expect(primaryAnimation[containerOne], moreOrLessEquals(0.6)); expect(secondaryAnimation[containerOne], equals(0.0)); @@ -261,10 +304,16 @@ void main() { // it should now be exiting underneath container three. Container three's // primary animation should be running forwards since it is entering above // container two. - primaryAnimation = _getPrimaryAnimation( - [containerOne, containerTwo, containerThree], tester); - secondaryAnimation = _getSecondaryAnimation( - [containerOne, containerTwo, containerThree], tester); + primaryAnimation = _getPrimaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + containerOne, + containerTwo, + containerThree, + ], tester); expect(primaryAnimation[containerOne], equals(0.4)); expect(secondaryAnimation[containerOne], equals(0.0)); expect(primaryAnimation[containerTwo], equals(1.0)); @@ -276,9 +325,7 @@ void main() { testWidgets('using custom layout', (WidgetTester tester) async { Widget newLayoutBuilder(List activeEntries) { - return Column( - children: activeEntries, - ); + return Column(children: activeEntries); } await tester.pumpWidget( @@ -293,8 +340,9 @@ void main() { expect(find.byType(Column), findsOneWidget); }); - testWidgets("doesn't transition in a new child of the same type.", - (WidgetTester tester) async { + testWidgets("doesn't transition in a new child of the same type.", ( + WidgetTester tester, + ) async { await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), @@ -373,8 +421,9 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets("doesn't start any animations after dispose.", - (WidgetTester tester) async { + testWidgets("doesn't start any animations after dispose.", ( + WidgetTester tester, + ) async { await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), @@ -395,8 +444,9 @@ void main() { expect(find.byType(FadeTransition), findsNWidgets(2)); expect(find.byType(ScaleTransition), findsNWidgets(2)); final FadeTransition fade = tester.firstWidget(find.byType(FadeTransition)); - final ScaleTransition scale = - tester.firstWidget(find.byType(ScaleTransition)); + final ScaleTransition scale = tester.firstWidget( + find.byType(ScaleTransition), + ); expect(fade.opacity.value, equals(0.5)); expect(scale.scale.value, equals(1.0)); @@ -405,8 +455,9 @@ void main() { expect(await tester.pumpAndSettle(), equals(1)); }); - testWidgets("doesn't reset state of the children in transitions.", - (WidgetTester tester) async { + testWidgets("doesn't reset state of the children in transitions.", ( + WidgetTester tester, + ) async { final UniqueKey statefulOne = UniqueKey(); final UniqueKey statefulTwo = UniqueKey(); final UniqueKey statefulThree = UniqueKey(); @@ -421,10 +472,12 @@ void main() { ), ); - Map primaryAnimation = - _getPrimaryAnimation([statefulOne], tester); - Map secondaryAnimation = - _getSecondaryAnimation([statefulOne], tester); + Map primaryAnimation = _getPrimaryAnimation([ + statefulOne, + ], tester); + Map secondaryAnimation = _getSecondaryAnimation([ + statefulOne, + ], tester); expect(primaryAnimation[statefulOne], equals(1.0)); expect(secondaryAnimation[statefulOne], equals(0.0)); expect(StatefulTestWidgetState.generation, equals(1)); @@ -439,10 +492,14 @@ void main() { await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(FadeTransition), findsNWidgets(2)); - primaryAnimation = - _getPrimaryAnimation([statefulOne, statefulTwo], tester); - secondaryAnimation = - _getSecondaryAnimation([statefulOne, statefulTwo], tester); + primaryAnimation = _getPrimaryAnimation([ + statefulOne, + statefulTwo, + ], tester); + secondaryAnimation = _getSecondaryAnimation([ + statefulOne, + statefulTwo, + ], tester); expect(primaryAnimation[statefulTwo], equals(0.5)); expect(secondaryAnimation[statefulTwo], equals(0.0)); expect(StatefulTestWidgetState.generation, equals(2)); @@ -461,8 +518,9 @@ void main() { expect(StatefulTestWidgetState.generation, equals(3)); }); - testWidgets('updates widgets without animating if they are isomorphic.', - (WidgetTester tester) async { + testWidgets('updates widgets without animating if they are isomorphic.', ( + WidgetTester tester, + ) async { Future pumpChild(Widget child) async { return tester.pumpWidget( Directionality( @@ -495,89 +553,101 @@ void main() { }); testWidgets( - 'updates previous child transitions if the transitionBuilder changes.', - (WidgetTester tester) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); - - // Insert three unique children so that we have some previous children. - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: PageTransitionSwitcher( - duration: const Duration(milliseconds: 100), - transitionBuilder: _transitionBuilder, - child: Container(key: containerOne, color: const Color(0xFFFF0000)), + 'updates previous child transitions if the transitionBuilder changes.', + (WidgetTester tester) async { + final UniqueKey containerOne = UniqueKey(); + final UniqueKey containerTwo = UniqueKey(); + final UniqueKey containerThree = UniqueKey(); + + // Insert three unique children so that we have some previous children. + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageTransitionSwitcher( + duration: const Duration(milliseconds: 100), + transitionBuilder: _transitionBuilder, + child: Container(key: containerOne, color: const Color(0xFFFF0000)), + ), ), - ), - ); + ); - await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: PageTransitionSwitcher( - duration: const Duration(milliseconds: 100), - transitionBuilder: _transitionBuilder, - child: Container(key: containerTwo, color: const Color(0xFF00FF00)), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageTransitionSwitcher( + duration: const Duration(milliseconds: 100), + transitionBuilder: _transitionBuilder, + child: Container(key: containerTwo, color: const Color(0xFF00FF00)), + ), ), - ), - ); + ); - await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: PageTransitionSwitcher( - duration: const Duration(milliseconds: 100), - transitionBuilder: _transitionBuilder, - child: Container(key: containerThree, color: const Color(0xFF0000FF)), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageTransitionSwitcher( + duration: const Duration(milliseconds: 100), + transitionBuilder: _transitionBuilder, + child: Container( + key: containerThree, + color: const Color(0xFF0000FF), + ), + ), ), - ), - ); + ); - await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); + + expect(find.byType(FadeTransition), findsNWidgets(3)); + expect(find.byType(ScaleTransition), findsNWidgets(3)); + expect(find.byType(SlideTransition), findsNothing); + expect(find.byType(SizeTransition), findsNothing); + + Widget newTransitionBuilder( + Widget child, + Animation primary, + Animation secondary, + ) { + return SlideTransition( + position: Tween( + begin: Offset.zero, + end: const Offset(20, 30), + ).animate(primary), + child: SizeTransition( + sizeFactor: Tween(begin: 10, end: 0.0).animate(secondary), + child: child, + ), + ); + } - expect(find.byType(FadeTransition), findsNWidgets(3)); - expect(find.byType(ScaleTransition), findsNWidgets(3)); - expect(find.byType(SlideTransition), findsNothing); - expect(find.byType(SizeTransition), findsNothing); - - Widget newTransitionBuilder( - Widget child, Animation primary, Animation secondary) { - return SlideTransition( - position: Tween(begin: Offset.zero, end: const Offset(20, 30)) - .animate(primary), - child: SizeTransition( - sizeFactor: Tween(begin: 10, end: 0.0).animate(secondary), - child: child, + // Now set a new transition builder and make sure all the previous + // transitions are replaced. + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageTransitionSwitcher( + duration: const Duration(milliseconds: 100), + transitionBuilder: newTransitionBuilder, + child: Container( + key: containerThree, + color: const Color(0x00000000), + ), + ), ), ); - } - // Now set a new transition builder and make sure all the previous - // transitions are replaced. - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: PageTransitionSwitcher( - duration: const Duration(milliseconds: 100), - transitionBuilder: newTransitionBuilder, - child: Container(key: containerThree, color: const Color(0x00000000)), - ), - ), - ); - - await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); - expect(find.byType(FadeTransition), findsNothing); - expect(find.byType(ScaleTransition), findsNothing); - expect(find.byType(SlideTransition), findsNWidgets(3)); - expect(find.byType(SizeTransition), findsNWidgets(3)); - }); + expect(find.byType(FadeTransition), findsNothing); + expect(find.byType(ScaleTransition), findsNothing); + expect(find.byType(SlideTransition), findsNWidgets(3)); + expect(find.byType(SizeTransition), findsNWidgets(3)); + }, + ); } class StatefulTestWidget extends StatefulWidget { @@ -602,7 +672,10 @@ class StatefulTestWidgetState extends State { } Widget _transitionBuilder( - Widget child, Animation primary, Animation secondary) { + Widget child, + Animation primary, + Animation secondary, +) { return ScaleTransition( scale: Tween(begin: 0.0, end: 1.0).animate(primary), child: FadeTransition( @@ -617,10 +690,7 @@ Map _getSecondaryAnimation(List keys, WidgetTester tester) { final Map result = {}; for (final Key key in keys) { final FadeTransition transition = tester.firstWidget( - find.ancestor( - of: find.byKey(key), - matching: find.byType(FadeTransition), - ), + find.ancestor(of: find.byKey(key), matching: find.byType(FadeTransition)), ); result[key] = 1.0 - transition.opacity.value; } diff --git a/packages/animations/test/shared_axis_transition_test.dart b/packages/animations/test/shared_axis_transition_test.dart index bd4c41918c9..57e1e0827f5 100644 --- a/packages/animations/test/shared_axis_transition_test.dart +++ b/packages/animations/test/shared_axis_transition_test.dart @@ -35,474 +35,471 @@ void main() { }, ); - testWidgets( - 'SharedAxisTransition runs forward', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition runs forward', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.horizontal, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.horizontal, + ), + ); - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); - expect(find.text(topRoute), findsNothing); - - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - await tester.pump(); - - // Bottom route is not offset and fully visible. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); - // Top route is offset to the right by 30.0 pixels - // and not visible yet. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 30.0, - ); - expect(_getOpacity(topRoute, tester), 0.0); - - // Jump 3/10ths of the way through the transition, bottom route - // should be be completely faded out while the top route - // is also completely faded out. - // Transition time: 300ms, 3/10 * 300ms = 90ms - await tester.pump(const Duration(milliseconds: 90)); - - // Bottom route is now invisible - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route is still invisible, but moving towards the left. - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - double? topOffset = _getTranslationOffset( + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); + expect(find.text(topRoute), findsNothing); + + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + await tester.pump(); + + // Bottom route is not offset and fully visible. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); + // Top route is offset to the right by 30.0 pixels + // and not visible yet. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( topRoute, tester, SharedAxisTransitionType.horizontal, - ); - expect(topOffset, lessThan(30.0)); - expect(topOffset, greaterThan(0.0)); - - // Jump to the middle of fading in - await tester.pump(const Duration(milliseconds: 90)); - // Bottom route is still invisible - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route is fading in - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), greaterThan(0)); - expect(_getOpacity(topRoute, tester), lessThan(1.0)); - topOffset = _getTranslationOffset( + ), + 30.0, + ); + expect(_getOpacity(topRoute, tester), 0.0); + + // Jump 3/10ths of the way through the transition, bottom route + // should be be completely faded out while the top route + // is also completely faded out. + // Transition time: 300ms, 3/10 * 300ms = 90ms + await tester.pump(const Duration(milliseconds: 90)); + + // Bottom route is now invisible + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route is still invisible, but moving towards the left. + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + double? topOffset = _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ); + expect(topOffset, lessThan(30.0)); + expect(topOffset, greaterThan(0.0)); + + // Jump to the middle of fading in + await tester.pump(const Duration(milliseconds: 90)); + // Bottom route is still invisible + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route is fading in + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), greaterThan(0)); + expect(_getOpacity(topRoute, tester), lessThan(1.0)); + topOffset = _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ); + expect(topOffset, greaterThan(0.0)); + expect(topOffset, lessThan(30.0)); + + // Jump to the end of the transition + await tester.pump(const Duration(milliseconds: 120)); + // Bottom route is not visible. + expect(find.text(bottomRoute), findsOneWidget); + + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + -30.0, + ); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route has no offset and is visible. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( topRoute, tester, SharedAxisTransitionType.horizontal, - ); - expect(topOffset, greaterThan(0.0)); - expect(topOffset, lessThan(30.0)); - - // Jump to the end of the transition - await tester.pump(const Duration(milliseconds: 120)); - // Bottom route is not visible. - expect(find.text(bottomRoute), findsOneWidget); - - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - -30.0, - ); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route has no offset and is visible. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(topRoute, tester), 1.0); + ), + 0.0, + ); + expect(_getOpacity(topRoute, tester), 1.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(bottomRoute), findsNothing); - expect(find.text(topRoute), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(bottomRoute), findsNothing); + expect(find.text(topRoute), findsOneWidget); + }); - testWidgets( - 'SharedAxisTransition runs in reverse', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition runs in reverse', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.horizontal, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.horizontal, + ), + ); - navigator.currentState!.pushNamed('/a'); - await tester.pumpAndSettle(); + navigator.currentState!.pushNamed('/a'); + await tester.pumpAndSettle(); - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(topRoute, tester), 1.0); - expect(find.text(bottomRoute), findsNothing); - - navigator.currentState!.pop(); - await tester.pump(); - - // Top route is is not offset and fully visible. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(topRoute, tester), 1.0); - // Bottom route is offset to the left and is not visible yet. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - -30.0, - ); - expect(_getOpacity(bottomRoute, tester), 0.0); - - // Jump 3/10ths of the way through the transition, bottom route - // should be be completely faded out while the top route - // is also completely faded out. - // Transition time: 300ms, 3/10 * 300ms = 90ms - await tester.pump(const Duration(milliseconds: 90)); - - // Top route is now invisible - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is still invisible, but moving towards the right. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), - moreOrLessEquals(0, epsilon: 0.005)); - double? bottomOffset = _getTranslationOffset( + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + 0.0, + ); + expect(_getOpacity(topRoute, tester), 1.0); + expect(find.text(bottomRoute), findsNothing); + + navigator.currentState!.pop(); + await tester.pump(); + + // Top route is is not offset and fully visible. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + 0.0, + ); + expect(_getOpacity(topRoute, tester), 1.0); + // Bottom route is offset to the left and is not visible yet. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( bottomRoute, tester, SharedAxisTransitionType.horizontal, - ); - expect(bottomOffset, lessThan(0.0)); - expect(bottomOffset, greaterThan(-30.0)); - - // Jump to the middle of fading in - await tester.pump(const Duration(milliseconds: 90)); - // Top route is still invisible - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is fading in - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), greaterThan(0)); - expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - bottomOffset = _getTranslationOffset( + ), + -30.0, + ); + expect(_getOpacity(bottomRoute, tester), 0.0); + + // Jump 3/10ths of the way through the transition, bottom route + // should be be completely faded out while the top route + // is also completely faded out. + // Transition time: 300ms, 3/10 * 300ms = 90ms + await tester.pump(const Duration(milliseconds: 90)); + + // Top route is now invisible + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is still invisible, but moving towards the right. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getOpacity(bottomRoute, tester), + moreOrLessEquals(0, epsilon: 0.005), + ); + double? bottomOffset = _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ); + expect(bottomOffset, lessThan(0.0)); + expect(bottomOffset, greaterThan(-30.0)); + + // Jump to the middle of fading in + await tester.pump(const Duration(milliseconds: 90)); + // Top route is still invisible + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is fading in + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), greaterThan(0)); + expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); + bottomOffset = _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ); + expect(bottomOffset, lessThan(0.0)); + expect(bottomOffset, greaterThan(-30.0)); + + // Jump to the end of the transition + await tester.pump(const Duration(milliseconds: 120)); + // Top route is not visible and is offset to the right. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + 30.0, + ); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is not offset and is visible. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( bottomRoute, tester, SharedAxisTransitionType.horizontal, - ); - expect(bottomOffset, lessThan(0.0)); - expect(bottomOffset, greaterThan(-30.0)); - - // Jump to the end of the transition - await tester.pump(const Duration(milliseconds: 120)); - // Top route is not visible and is offset to the right. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 30.0, - ); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is not offset and is visible. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(topRoute), findsNothing); - expect(find.text(bottomRoute), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(topRoute), findsNothing); + expect(find.text(bottomRoute), findsOneWidget); + }); - testWidgets( - 'SharedAxisTransition does not jump when interrupted', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition does not jump when interrupted', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.horizontal, - ), - ); - expect(find.text(bottomRoute), findsOneWidget); - expect(find.text(topRoute), findsNothing); - - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - - // Jump to halfway point of transition. - await tester.pump(const Duration(milliseconds: 150)); - // Bottom route is fully faded out. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - final double halfwayBottomOffset = _getTranslationOffset( + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.horizontal, + ), + ); + expect(find.text(bottomRoute), findsOneWidget); + expect(find.text(topRoute), findsNothing); + + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + + // Jump to halfway point of transition. + await tester.pump(const Duration(milliseconds: 150)); + // Bottom route is fully faded out. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + final double halfwayBottomOffset = _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ); + expect(halfwayBottomOffset, lessThan(0.0)); + expect(halfwayBottomOffset, greaterThan(-30.0)); + + // Top route is fading/coming in. + expect(find.text(topRoute), findsOneWidget); + final double halfwayTopOffset = _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ); + final double halfwayTopOpacity = _getOpacity(topRoute, tester); + expect(halfwayTopOffset, greaterThan(0.0)); + expect(halfwayTopOffset, lessThan(30.0)); + expect(halfwayTopOpacity, greaterThan(0.0)); + expect(halfwayTopOpacity, lessThan(1.0)); + + // Interrupt the transition with a pop. + navigator.currentState!.pop(); + await tester.pump(); + + // Nothing should change. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( bottomRoute, tester, SharedAxisTransitionType.horizontal, - ); - expect(halfwayBottomOffset, lessThan(0.0)); - expect(halfwayBottomOffset, greaterThan(-30.0)); + ), + halfwayBottomOffset, + ); + expect(_getOpacity(bottomRoute, tester), 0.0); + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + halfwayTopOffset, + ); + expect(_getOpacity(topRoute, tester), halfwayTopOpacity); - // Top route is fading/coming in. - expect(find.text(topRoute), findsOneWidget); - final double halfwayTopOffset = _getTranslationOffset( + // Jump to the 1/4 (75 ms) point of transition + await tester.pump(const Duration(milliseconds: 75)); + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + lessThan(0.0), + ); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + greaterThan(-30.0), + ); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + greaterThan(halfwayBottomOffset), + ); + expect(_getOpacity(bottomRoute, tester), greaterThan(0.0)); + expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); + + // Jump to the end. + await tester.pump(const Duration(milliseconds: 75)); + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.horizontal, + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( topRoute, tester, SharedAxisTransitionType.horizontal, - ); - final double halfwayTopOpacity = _getOpacity(topRoute, tester); - expect(halfwayTopOffset, greaterThan(0.0)); - expect(halfwayTopOffset, lessThan(30.0)); - expect(halfwayTopOpacity, greaterThan(0.0)); - expect(halfwayTopOpacity, lessThan(1.0)); - - // Interrupt the transition with a pop. - navigator.currentState!.pop(); - await tester.pump(); - - // Nothing should change. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - halfwayBottomOffset, - ); - expect(_getOpacity(bottomRoute, tester), 0.0); - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - halfwayTopOffset, - ); - expect(_getOpacity(topRoute, tester), halfwayTopOpacity); - - // Jump to the 1/4 (75 ms) point of transition - await tester.pump(const Duration(milliseconds: 75)); - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - lessThan(0.0), - ); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - greaterThan(-30.0), - ); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - greaterThan(halfwayBottomOffset), - ); - expect(_getOpacity(bottomRoute, tester), greaterThan(0.0)); - expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - - // Jump to the end. - await tester.pump(const Duration(milliseconds: 75)); - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.horizontal, - ), - 30.0, - ); - expect(_getOpacity(topRoute, tester), 0.0); + ), + 30.0, + ); + expect(_getOpacity(topRoute, tester), 0.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(topRoute), findsNothing); - expect(find.text(bottomRoute), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(topRoute), findsNothing); + expect(find.text(bottomRoute), findsOneWidget); + }); - testWidgets( - 'State is not lost when transitioning', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('State is not lost when transitioning', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - contentBuilder: (RouteSettings settings) { - return _StatefulTestWidget( - key: ValueKey(settings.name), - name: settings.name!, - ); - }, - transitionType: SharedAxisTransitionType.horizontal, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + contentBuilder: (RouteSettings settings) { + return _StatefulTestWidget( + key: ValueKey(settings.name), + name: settings.name!, + ); + }, + transitionType: SharedAxisTransitionType.horizontal, + ), + ); - final _StatefulTestWidgetState bottomState = tester.state( - find.byKey(const ValueKey(bottomRoute)), - ); - expect(bottomState.widget.name, bottomRoute); + final _StatefulTestWidgetState bottomState = tester.state( + find.byKey(const ValueKey(bottomRoute)), + ); + expect(bottomState.widget.name, bottomRoute); - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - await tester.pump(); + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + await tester.pump(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - final _StatefulTestWidgetState topState = tester.state( - find.byKey(const ValueKey(topRoute)), - ); - expect(topState.widget.name, topRoute); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + final _StatefulTestWidgetState topState = tester.state( + find.byKey(const ValueKey(topRoute)), + ); + expect(topState.widget.name, topRoute); - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey( - const ValueKey(bottomRoute), - skipOffstage: false, - )), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pumpAndSettle(); + expect( + tester.state( + find.byKey(const ValueKey(bottomRoute), skipOffstage: false), + ), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - navigator.currentState!.pop(); - await tester.pump(); + navigator.currentState!.pop(); + await tester.pump(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect(find.byKey(const ValueKey(topRoute)), findsNothing); - }, - ); + await tester.pumpAndSettle(); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect(find.byKey(const ValueKey(topRoute)), findsNothing); + }); testWidgets('default fill color', (WidgetTester tester) async { final GlobalKey navigator = GlobalKey(); @@ -520,29 +517,35 @@ 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, - defaultFillColor); + expect( + tester.widget(fillContainerFinder).color, + defaultFillColor, + ); navigator.currentState!.pushNamed(topRoute); 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, - defaultFillColor); + expect( + tester.widget(fillContainerFinder).color, + defaultFillColor, + ); }); testWidgets('custom fill color', (WidgetTester tester) async { @@ -559,29 +562,35 @@ 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, Colors.green); + tester.widget(fillContainerFinder).color, + Colors.green, + ); navigator.currentState!.pushNamed(topRoute); 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, Colors.green); + tester.widget(fillContainerFinder).color, + Colors.green, + ); }); testWidgets('should keep state', (WidgetTester tester) async { @@ -593,17 +602,19 @@ void main() { vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SharedAxisTransition( - transitionType: SharedAxisTransitionType.horizontal, - animation: animation, - secondaryAnimation: secondaryAnimation, - child: const _StatefulTestWidget(name: 'Foo'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SharedAxisTransition( + transitionType: SharedAxisTransitionType.horizontal, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: const _StatefulTestWidget(name: 'Foo'), + ), ), ), - )); + ); final State state = tester.state( find.byType(_StatefulTestWidget), ); @@ -678,476 +689,471 @@ void main() { }, ); - testWidgets( - 'SharedAxisTransition runs forward', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition runs forward', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.vertical, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.vertical, + ), + ); - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); - expect(find.text(topRoute), findsNothing); - - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - await tester.pump(); - - // Bottom route is not offset and fully visible. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); - // Top route is offset down by 30.0 pixels - // and not visible yet. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 30.0, - ); - expect(_getOpacity(topRoute, tester), 0.0); - - // Jump 3/10ths of the way through the transition, bottom route - // should be be completely faded out while the top route - // is also completely faded out. - // Transition time: 300ms, 3/10 * 300ms = 90ms - await tester.pump(const Duration(milliseconds: 90)); - - // Bottom route is now invisible - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route is still invisible, but moving up. - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - double? topOffset = _getTranslationOffset( + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); + expect(find.text(topRoute), findsNothing); + + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + await tester.pump(); + + // Bottom route is not offset and fully visible. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); + // Top route is offset down by 30.0 pixels + // and not visible yet. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( topRoute, tester, SharedAxisTransitionType.vertical, - ); - expect(topOffset, lessThan(30.0)); - expect(topOffset, greaterThan(0.0)); - - // Jump to the middle of fading in - await tester.pump(const Duration(milliseconds: 90)); - // Bottom route is still invisible - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route is fading in - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), greaterThan(0)); - expect(_getOpacity(topRoute, tester), lessThan(1.0)); - topOffset = _getTranslationOffset( + ), + 30.0, + ); + expect(_getOpacity(topRoute, tester), 0.0); + + // Jump 3/10ths of the way through the transition, bottom route + // should be be completely faded out while the top route + // is also completely faded out. + // Transition time: 300ms, 3/10 * 300ms = 90ms + await tester.pump(const Duration(milliseconds: 90)); + + // Bottom route is now invisible + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route is still invisible, but moving up. + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + double? topOffset = _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ); + expect(topOffset, lessThan(30.0)); + expect(topOffset, greaterThan(0.0)); + + // Jump to the middle of fading in + await tester.pump(const Duration(milliseconds: 90)); + // Bottom route is still invisible + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route is fading in + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), greaterThan(0)); + expect(_getOpacity(topRoute, tester), lessThan(1.0)); + topOffset = _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ); + expect(topOffset, greaterThan(0.0)); + expect(topOffset, lessThan(30.0)); + + // Jump to the end of the transition + await tester.pump(const Duration(milliseconds: 120)); + // Bottom route is not visible. + expect(find.text(bottomRoute), findsOneWidget); + + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + -30.0, + ); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route has no offset and is visible. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( topRoute, tester, SharedAxisTransitionType.vertical, - ); - expect(topOffset, greaterThan(0.0)); - expect(topOffset, lessThan(30.0)); - - // Jump to the end of the transition - await tester.pump(const Duration(milliseconds: 120)); - // Bottom route is not visible. - expect(find.text(bottomRoute), findsOneWidget); - - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - -30.0, - ); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route has no offset and is visible. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(topRoute, tester), 1.0); + ), + 0.0, + ); + expect(_getOpacity(topRoute, tester), 1.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(bottomRoute), findsNothing); - expect(find.text(topRoute), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(bottomRoute), findsNothing); + expect(find.text(topRoute), findsOneWidget); + }); - testWidgets( - 'SharedAxisTransition runs in reverse', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition runs in reverse', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.vertical, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.vertical, + ), + ); - navigator.currentState!.pushNamed('/a'); - await tester.pumpAndSettle(); + navigator.currentState!.pushNamed('/a'); + await tester.pumpAndSettle(); - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(topRoute, tester), 1.0); - expect(find.text(bottomRoute), findsNothing); - - navigator.currentState!.pop(); - await tester.pump(); - - // Top route is is not offset and fully visible. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(topRoute, tester), 1.0); - // Bottom route is offset up and is not visible yet. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - -30.0, - ); - expect(_getOpacity(bottomRoute, tester), 0.0); - - // Jump 3/10ths of the way through the transition, bottom route - // should be be completely faded out while the top route - // is also completely faded out. - // Transition time: 300ms, 3/10 * 300ms = 90ms - await tester.pump(const Duration(milliseconds: 90)); - - // Top route is now invisible - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is still invisible, but moving down. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getOpacity(bottomRoute, tester), - moreOrLessEquals(0, epsilon: 0.005), - ); - double? bottomOffset = _getTranslationOffset( + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ), + 0.0, + ); + expect(_getOpacity(topRoute, tester), 1.0); + expect(find.text(bottomRoute), findsNothing); + + navigator.currentState!.pop(); + await tester.pump(); + + // Top route is is not offset and fully visible. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ), + 0.0, + ); + expect(_getOpacity(topRoute, tester), 1.0); + // Bottom route is offset up and is not visible yet. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( bottomRoute, tester, SharedAxisTransitionType.vertical, - ); - expect(bottomOffset, lessThan(0.0)); - expect(bottomOffset, greaterThan(-30.0)); - - // Jump to the middle of fading in - await tester.pump(const Duration(milliseconds: 90)); - // Top route is still invisible - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is fading in - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), greaterThan(0)); - expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - bottomOffset = _getTranslationOffset( + ), + -30.0, + ); + expect(_getOpacity(bottomRoute, tester), 0.0); + + // Jump 3/10ths of the way through the transition, bottom route + // should be be completely faded out while the top route + // is also completely faded out. + // Transition time: 300ms, 3/10 * 300ms = 90ms + await tester.pump(const Duration(milliseconds: 90)); + + // Top route is now invisible + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is still invisible, but moving down. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getOpacity(bottomRoute, tester), + moreOrLessEquals(0, epsilon: 0.005), + ); + double? bottomOffset = _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ); + expect(bottomOffset, lessThan(0.0)); + expect(bottomOffset, greaterThan(-30.0)); + + // Jump to the middle of fading in + await tester.pump(const Duration(milliseconds: 90)); + // Top route is still invisible + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is fading in + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), greaterThan(0)); + expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); + bottomOffset = _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ); + expect(bottomOffset, lessThan(0.0)); + expect(bottomOffset, greaterThan(-30.0)); + + // Jump to the end of the transition + await tester.pump(const Duration(milliseconds: 120)); + // Top route is not visible and is offset down. + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ), + 30.0, + ); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is not offset and is visible. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( bottomRoute, tester, SharedAxisTransitionType.vertical, - ); - expect(bottomOffset, lessThan(0.0)); - expect(bottomOffset, greaterThan(-30.0)); - - // Jump to the end of the transition - await tester.pump(const Duration(milliseconds: 120)); - // Top route is not visible and is offset down. - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 30.0, - ); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is not offset and is visible. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(topRoute), findsNothing); - expect(find.text(bottomRoute), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(topRoute), findsNothing); + expect(find.text(bottomRoute), findsOneWidget); + }); - testWidgets( - 'SharedAxisTransition does not jump when interrupted', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition does not jump when interrupted', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.vertical, - ), - ); - expect(find.text(bottomRoute), findsOneWidget); - expect(find.text(topRoute), findsNothing); - - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - - // Jump to halfway point of transition. - await tester.pump(const Duration(milliseconds: 150)); - // Bottom route is fully faded out. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - final double halfwayBottomOffset = _getTranslationOffset( + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.vertical, + ), + ); + expect(find.text(bottomRoute), findsOneWidget); + expect(find.text(topRoute), findsNothing); + + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + + // Jump to halfway point of transition. + await tester.pump(const Duration(milliseconds: 150)); + // Bottom route is fully faded out. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + final double halfwayBottomOffset = _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ); + expect(halfwayBottomOffset, lessThan(0.0)); + expect(halfwayBottomOffset, greaterThan(-30.0)); + + // Top route is fading/coming in. + expect(find.text(topRoute), findsOneWidget); + final double halfwayTopOffset = _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ); + final double halfwayTopOpacity = _getOpacity(topRoute, tester); + expect(halfwayTopOffset, greaterThan(0.0)); + expect(halfwayTopOffset, lessThan(30.0)); + expect(halfwayTopOpacity, greaterThan(0.0)); + expect(halfwayTopOpacity, lessThan(1.0)); + + // Interrupt the transition with a pop. + navigator.currentState!.pop(); + await tester.pump(); + + // Nothing should change. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( bottomRoute, tester, SharedAxisTransitionType.vertical, - ); - expect(halfwayBottomOffset, lessThan(0.0)); - expect(halfwayBottomOffset, greaterThan(-30.0)); + ), + halfwayBottomOffset, + ); + expect(_getOpacity(bottomRoute, tester), 0.0); + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( + topRoute, + tester, + SharedAxisTransitionType.vertical, + ), + halfwayTopOffset, + ); + expect(_getOpacity(topRoute, tester), halfwayTopOpacity); + + // Jump to the 1/4 (75 ms) point of transition + await tester.pump(const Duration(milliseconds: 75)); + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + lessThan(0.0), + ); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + greaterThan(-30.0), + ); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + greaterThan(halfwayBottomOffset), + ); + expect(_getOpacity(bottomRoute, tester), greaterThan(0.0)); + expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - // Top route is fading/coming in. - expect(find.text(topRoute), findsOneWidget); - final double halfwayTopOffset = _getTranslationOffset( + // Jump to the end. + await tester.pump(const Duration(milliseconds: 75)); + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getTranslationOffset( + bottomRoute, + tester, + SharedAxisTransitionType.vertical, + ), + 0.0, + ); + expect(_getOpacity(bottomRoute, tester), 1.0); + expect(find.text(topRoute), findsOneWidget); + expect( + _getTranslationOffset( topRoute, tester, SharedAxisTransitionType.vertical, - ); - final double halfwayTopOpacity = _getOpacity(topRoute, tester); - expect(halfwayTopOffset, greaterThan(0.0)); - expect(halfwayTopOffset, lessThan(30.0)); - expect(halfwayTopOpacity, greaterThan(0.0)); - expect(halfwayTopOpacity, lessThan(1.0)); - - // Interrupt the transition with a pop. - navigator.currentState!.pop(); - await tester.pump(); - - // Nothing should change. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - halfwayBottomOffset, - ); - expect(_getOpacity(bottomRoute, tester), 0.0); - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - halfwayTopOffset, - ); - expect(_getOpacity(topRoute, tester), halfwayTopOpacity); - - // Jump to the 1/4 (75 ms) point of transition - await tester.pump(const Duration(milliseconds: 75)); - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - lessThan(0.0), - ); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - greaterThan(-30.0), - ); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - greaterThan(halfwayBottomOffset), - ); - expect(_getOpacity(bottomRoute, tester), greaterThan(0.0)); - expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - - // Jump to the end. - await tester.pump(const Duration(milliseconds: 75)); - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getTranslationOffset( - bottomRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 0.0, - ); - expect(_getOpacity(bottomRoute, tester), 1.0); - expect(find.text(topRoute), findsOneWidget); - expect( - _getTranslationOffset( - topRoute, - tester, - SharedAxisTransitionType.vertical, - ), - 30.0, - ); - expect(_getOpacity(topRoute, tester), 0.0); + ), + 30.0, + ); + expect(_getOpacity(topRoute, tester), 0.0); - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(topRoute), findsNothing); - expect(find.text(bottomRoute), findsOneWidget); - }, - ); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(topRoute), findsNothing); + expect(find.text(bottomRoute), findsOneWidget); + }); - testWidgets( - 'State is not lost when transitioning', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('State is not lost when transitioning', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - contentBuilder: (RouteSettings settings) { - return _StatefulTestWidget( - key: ValueKey(settings.name), - name: settings.name!, - ); - }, - transitionType: SharedAxisTransitionType.vertical, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + contentBuilder: (RouteSettings settings) { + return _StatefulTestWidget( + key: ValueKey(settings.name), + name: settings.name!, + ); + }, + transitionType: SharedAxisTransitionType.vertical, + ), + ); - final _StatefulTestWidgetState bottomState = tester.state( - find.byKey(const ValueKey(bottomRoute)), - ); - expect(bottomState.widget.name, bottomRoute); + final _StatefulTestWidgetState bottomState = tester.state( + find.byKey(const ValueKey(bottomRoute)), + ); + expect(bottomState.widget.name, bottomRoute); - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - await tester.pump(); + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + await tester.pump(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - final _StatefulTestWidgetState topState = tester.state( - find.byKey(const ValueKey(topRoute)), - ); - expect(topState.widget.name, topRoute); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + final _StatefulTestWidgetState topState = tester.state( + find.byKey(const ValueKey(topRoute)), + ); + expect(topState.widget.name, topRoute); - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey( - const ValueKey(bottomRoute), - skipOffstage: false, - )), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pumpAndSettle(); + expect( + tester.state( + find.byKey(const ValueKey(bottomRoute), skipOffstage: false), + ), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - navigator.currentState!.pop(); - await tester.pump(); + navigator.currentState!.pop(); + await tester.pump(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect(find.byKey(const ValueKey(topRoute)), findsNothing); - }, - ); + await tester.pumpAndSettle(); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect(find.byKey(const ValueKey(topRoute)), findsNothing); + }); testWidgets('default fill color', (WidgetTester tester) async { final GlobalKey navigator = GlobalKey(); @@ -1165,29 +1171,35 @@ 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, - defaultFillColor); + expect( + tester.widget(fillContainerFinder).color, + defaultFillColor, + ); navigator.currentState!.pushNamed(topRoute); 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, - defaultFillColor); + expect( + tester.widget(fillContainerFinder).color, + defaultFillColor, + ); }); testWidgets('custom fill color', (WidgetTester tester) async { @@ -1204,29 +1216,35 @@ 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, Colors.green); + tester.widget(fillContainerFinder).color, + Colors.green, + ); navigator.currentState!.pushNamed(topRoute); 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, Colors.green); + tester.widget(fillContainerFinder).color, + Colors.green, + ); }); testWidgets('should keep state', (WidgetTester tester) async { @@ -1238,17 +1256,19 @@ void main() { vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SharedAxisTransition( - transitionType: SharedAxisTransitionType.vertical, - animation: animation, - secondaryAnimation: secondaryAnimation, - child: const _StatefulTestWidget(name: 'Foo'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SharedAxisTransition( + transitionType: SharedAxisTransitionType.vertical, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: const _StatefulTestWidget(name: 'Foo'), + ), ), ), - )); + ); final State state = tester.state( find.byType(_StatefulTestWidget), ); @@ -1323,369 +1343,361 @@ void main() { }, ); - testWidgets( - 'SharedAxisTransition runs forward', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + testWidgets('SharedAxisTransition runs forward', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.scaled, - ), - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.scaled, + ), + ); - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), 1.0); - expect(_getOpacity(bottomRoute, tester), 1.0); - expect(find.text(topRoute), findsNothing); - - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - await tester.pump(); - - // Bottom route is full size and fully visible. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), 1.0); - expect(_getOpacity(bottomRoute, tester), 1.0); - // Top route is at 80% of full size and not visible yet. - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), 0.8); - expect(_getOpacity(topRoute, tester), 0.0); - - // Jump 3/10ths of the way through the transition, bottom route - // should be be completely faded out while the top route - // is also completely faded out. - // Transition time: 300ms, 3/10 * 300ms = 90ms - await tester.pump(const Duration(milliseconds: 90)); - - // Bottom route is now invisible - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route is still invisible, but scaling up. - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - double topScale = _getScale(topRoute, tester); - expect(topScale, greaterThan(0.8)); - expect(topScale, lessThan(1.0)); - - // Jump to the middle of fading in - await tester.pump(const Duration(milliseconds: 90)); - // Bottom route is still invisible - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route is fading in - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), greaterThan(0)); - expect(_getOpacity(topRoute, tester), lessThan(1.0)); - topScale = _getScale(topRoute, tester); - expect(topScale, greaterThan(0.8)); - expect(topScale, lessThan(1.0)); - - // Jump to the end of the transition - await tester.pump(const Duration(milliseconds: 120)); - // Bottom route is not visible. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), 1.1); - expect(_getOpacity(bottomRoute, tester), 0.0); - // Top route fully scaled in and visible. - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), 1.0); - expect(_getOpacity(topRoute, tester), 1.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(bottomRoute), findsNothing); - expect(find.text(topRoute), findsOneWidget); - }, - ); + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), 1.0); + expect(_getOpacity(bottomRoute, tester), 1.0); + expect(find.text(topRoute), findsNothing); - testWidgets( - 'SharedAxisTransition runs in reverse', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + await tester.pump(); - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.scaled, - ), - ); + // Bottom route is full size and fully visible. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), 1.0); + expect(_getOpacity(bottomRoute, tester), 1.0); + // Top route is at 80% of full size and not visible yet. + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), 0.8); + expect(_getOpacity(topRoute, tester), 0.0); + + // Jump 3/10ths of the way through the transition, bottom route + // should be be completely faded out while the top route + // is also completely faded out. + // Transition time: 300ms, 3/10 * 300ms = 90ms + await tester.pump(const Duration(milliseconds: 90)); + + // Bottom route is now invisible + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route is still invisible, but scaling up. + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + double topScale = _getScale(topRoute, tester); + expect(topScale, greaterThan(0.8)); + expect(topScale, lessThan(1.0)); + + // Jump to the middle of fading in + await tester.pump(const Duration(milliseconds: 90)); + // Bottom route is still invisible + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route is fading in + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), greaterThan(0)); + expect(_getOpacity(topRoute, tester), lessThan(1.0)); + topScale = _getScale(topRoute, tester); + expect(topScale, greaterThan(0.8)); + expect(topScale, lessThan(1.0)); + + // Jump to the end of the transition + await tester.pump(const Duration(milliseconds: 120)); + // Bottom route is not visible. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), 1.1); + expect(_getOpacity(bottomRoute, tester), 0.0); + // Top route fully scaled in and visible. + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), 1.0); + expect(_getOpacity(topRoute, tester), 1.0); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(bottomRoute), findsNothing); + expect(find.text(topRoute), findsOneWidget); + }); - navigator.currentState!.pushNamed(topRoute); - await tester.pumpAndSettle(); - - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), 1.0); - expect(_getOpacity(topRoute, tester), 1.0); - expect(find.text(bottomRoute), findsNothing); - - navigator.currentState!.pop(); - await tester.pump(); - - // Top route is full size and fully visible. - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), 1.0); - expect(_getOpacity(topRoute, tester), 1.0); - // Bottom route is at 110% of full size and not visible yet. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), 1.1); - expect(_getOpacity(bottomRoute, tester), 0.0); - - // Jump 3/10ths of the way through the transition, bottom route - // should be be completely faded out while the top route - // is also completely faded out. - // Transition time: 300ms, 3/10 * 300ms = 90ms - await tester.pump(const Duration(milliseconds: 90)); - - // Bottom route is now invisible - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - // Top route is still invisible, but scaling down. - expect(find.text(bottomRoute), findsOneWidget); - expect( - _getOpacity(bottomRoute, tester), - moreOrLessEquals(0, epsilon: 0.005), - ); - double bottomScale = _getScale(bottomRoute, tester); - expect(bottomScale, greaterThan(1.0)); - expect(bottomScale, lessThan(1.1)); - - // Jump to the middle of fading in - await tester.pump(const Duration(milliseconds: 90)); - // Top route is still invisible - expect(find.text(topRoute), findsOneWidget); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route is fading in - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), greaterThan(0)); - expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - bottomScale = _getScale(bottomRoute, tester); - expect(bottomScale, greaterThan(1.0)); - expect(bottomScale, lessThan(1.1)); - - // Jump to the end of the transition - await tester.pump(const Duration(milliseconds: 120)); - // Top route is not visible. - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), 0.8); - expect(_getOpacity(topRoute, tester), 0.0); - // Bottom route fully scaled in and visible. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), 1.0); - expect(_getOpacity(bottomRoute, tester), 1.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(topRoute), findsNothing); - expect(find.text(bottomRoute), findsOneWidget); - }, - ); + testWidgets('SharedAxisTransition runs in reverse', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - testWidgets( - 'SharedAxisTransition does not jump when interrupted', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.scaled, + ), + ); - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.scaled, - ), - ); - expect(find.text(bottomRoute), findsOneWidget); - expect(find.text(topRoute), findsNothing); - - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - - // Jump to halfway point of transition. - await tester.pump(const Duration(milliseconds: 150)); - // Bottom route is fully faded out. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getOpacity(bottomRoute, tester), 0.0); - final double halfwayBottomScale = _getScale(bottomRoute, tester); - expect(halfwayBottomScale, greaterThan(1.0)); - expect(halfwayBottomScale, lessThan(1.1)); - - // Top route is fading/scaling in. - expect(find.text(topRoute), findsOneWidget); - final double halfwayTopScale = _getScale(topRoute, tester); - final double halfwayTopOpacity = _getOpacity(topRoute, tester); - expect(halfwayTopScale, greaterThan(0.8)); - expect(halfwayTopScale, lessThan(1.0)); - expect(halfwayTopOpacity, greaterThan(0.0)); - expect(halfwayTopOpacity, lessThan(1.0)); - - // Interrupt the transition with a pop. - navigator.currentState!.pop(); - await tester.pump(); - - // Nothing should change. - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), halfwayBottomScale); - expect(_getOpacity(bottomRoute, tester), 0.0); - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), halfwayTopScale); - expect(_getOpacity(topRoute, tester), halfwayTopOpacity); - - // Jump to the 1/4 (75 ms) point of transition - await tester.pump(const Duration(milliseconds: 75)); - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), greaterThan(1.0)); - expect(_getScale(bottomRoute, tester), lessThan(1.1)); - expect(_getScale(bottomRoute, tester), lessThan(halfwayBottomScale)); - expect(_getOpacity(bottomRoute, tester), greaterThan(0.0)); - expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); - - // Jump to the end. - await tester.pump(const Duration(milliseconds: 75)); - expect(find.text(bottomRoute), findsOneWidget); - expect(_getScale(bottomRoute, tester), 1.0); - expect(_getOpacity(bottomRoute, tester), 1.0); - expect(find.text(topRoute), findsOneWidget); - expect(_getScale(topRoute, tester), 0.80); - expect(_getOpacity(topRoute, tester), 0.0); - - await tester.pump(const Duration(milliseconds: 1)); - expect(find.text(topRoute), findsNothing); - expect(find.text(bottomRoute), findsOneWidget); - }, - ); + navigator.currentState!.pushNamed(topRoute); + await tester.pumpAndSettle(); - testWidgets( - 'SharedAxisTransition properly disposes animation', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), 1.0); + expect(_getOpacity(topRoute, tester), 1.0); + expect(find.text(bottomRoute), findsNothing); - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.scaled, - ), - ); - expect(find.text(bottomRoute), findsOneWidget); - expect(find.text(topRoute), findsNothing); + navigator.currentState!.pop(); + await tester.pump(); + + // Top route is full size and fully visible. + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), 1.0); + expect(_getOpacity(topRoute, tester), 1.0); + // Bottom route is at 110% of full size and not visible yet. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), 1.1); + expect(_getOpacity(bottomRoute, tester), 0.0); + + // Jump 3/10ths of the way through the transition, bottom route + // should be be completely faded out while the top route + // is also completely faded out. + // Transition time: 300ms, 3/10 * 300ms = 90ms + await tester.pump(const Duration(milliseconds: 90)); + + // Bottom route is now invisible + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + // Top route is still invisible, but scaling down. + expect(find.text(bottomRoute), findsOneWidget); + expect( + _getOpacity(bottomRoute, tester), + moreOrLessEquals(0, epsilon: 0.005), + ); + double bottomScale = _getScale(bottomRoute, tester); + expect(bottomScale, greaterThan(1.0)); + expect(bottomScale, lessThan(1.1)); + + // Jump to the middle of fading in + await tester.pump(const Duration(milliseconds: 90)); + // Top route is still invisible + expect(find.text(topRoute), findsOneWidget); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route is fading in + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), greaterThan(0)); + expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); + bottomScale = _getScale(bottomRoute, tester); + expect(bottomScale, greaterThan(1.0)); + expect(bottomScale, lessThan(1.1)); + + // Jump to the end of the transition + await tester.pump(const Duration(milliseconds: 120)); + // Top route is not visible. + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), 0.8); + expect(_getOpacity(topRoute, tester), 0.0); + // Bottom route fully scaled in and visible. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), 1.0); + expect(_getOpacity(bottomRoute, tester), 1.0); - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(topRoute), findsNothing); + expect(find.text(bottomRoute), findsOneWidget); + }); - // Jump to halfway point of transition. - await tester.pump(const Duration(milliseconds: 150)); - expect(find.byType(SharedAxisTransition), findsNWidgets(2)); + testWidgets('SharedAxisTransition does not jump when interrupted', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - // Rebuild the app without the transition. - await tester.pumpWidget( - MaterialApp( - navigatorKey: navigator, - home: const Material( - child: Text('abc'), - ), - ), - ); - await tester.pump(); - // Transitions should have been disposed of. - expect(find.byType(SharedAxisTransition), findsNothing); - }, - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.scaled, + ), + ); + expect(find.text(bottomRoute), findsOneWidget); + expect(find.text(topRoute), findsNothing); - testWidgets( - 'State is not lost when transitioning', - (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); - await tester.pumpWidget( - _TestWidget( - navigatorKey: navigator, - transitionType: SharedAxisTransitionType.scaled, - contentBuilder: (RouteSettings settings) { - return _StatefulTestWidget( - key: ValueKey(settings.name), - name: settings.name!, - ); - }, - ), - ); + // Jump to halfway point of transition. + await tester.pump(const Duration(milliseconds: 150)); + // Bottom route is fully faded out. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getOpacity(bottomRoute, tester), 0.0); + final double halfwayBottomScale = _getScale(bottomRoute, tester); + expect(halfwayBottomScale, greaterThan(1.0)); + expect(halfwayBottomScale, lessThan(1.1)); + + // Top route is fading/scaling in. + expect(find.text(topRoute), findsOneWidget); + final double halfwayTopScale = _getScale(topRoute, tester); + final double halfwayTopOpacity = _getOpacity(topRoute, tester); + expect(halfwayTopScale, greaterThan(0.8)); + expect(halfwayTopScale, lessThan(1.0)); + expect(halfwayTopOpacity, greaterThan(0.0)); + expect(halfwayTopOpacity, lessThan(1.0)); + + // Interrupt the transition with a pop. + navigator.currentState!.pop(); + await tester.pump(); - final _StatefulTestWidgetState bottomState = tester.state( - find.byKey(const ValueKey(bottomRoute)), - ); - expect(bottomState.widget.name, bottomRoute); + // Nothing should change. + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), halfwayBottomScale); + expect(_getOpacity(bottomRoute, tester), 0.0); + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), halfwayTopScale); + expect(_getOpacity(topRoute, tester), halfwayTopOpacity); + + // Jump to the 1/4 (75 ms) point of transition + await tester.pump(const Duration(milliseconds: 75)); + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), greaterThan(1.0)); + expect(_getScale(bottomRoute, tester), lessThan(1.1)); + expect(_getScale(bottomRoute, tester), lessThan(halfwayBottomScale)); + expect(_getOpacity(bottomRoute, tester), greaterThan(0.0)); + expect(_getOpacity(bottomRoute, tester), lessThan(1.0)); + + // Jump to the end. + await tester.pump(const Duration(milliseconds: 75)); + expect(find.text(bottomRoute), findsOneWidget); + expect(_getScale(bottomRoute, tester), 1.0); + expect(_getOpacity(bottomRoute, tester), 1.0); + expect(find.text(topRoute), findsOneWidget); + expect(_getScale(topRoute, tester), 0.80); + expect(_getOpacity(topRoute, tester), 0.0); + + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text(topRoute), findsNothing); + expect(find.text(bottomRoute), findsOneWidget); + }); - navigator.currentState!.pushNamed(topRoute); - await tester.pump(); - await tester.pump(); + testWidgets('SharedAxisTransition properly disposes animation', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - final _StatefulTestWidgetState topState = tester.state( - find.byKey(const ValueKey(topRoute)), - ); - expect(topState.widget.name, topRoute); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.scaled, + ), + ); + expect(find.text(bottomRoute), findsOneWidget); + expect(find.text(topRoute), findsNothing); - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey( - const ValueKey(bottomRoute), - skipOffstage: false, - )), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + // Jump to halfway point of transition. + await tester.pump(const Duration(milliseconds: 150)); + expect(find.byType(SharedAxisTransition), findsNWidgets(2)); - navigator.currentState!.pop(); - await tester.pump(); + // Rebuild the app without the transition. + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + home: const Material(child: Text('abc')), + ), + ); + await tester.pump(); + // Transitions should have been disposed of. + expect(find.byType(SharedAxisTransition), findsNothing); + }); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + testWidgets('State is not lost when transitioning', ( + WidgetTester tester, + ) async { + final GlobalKey navigator = GlobalKey(); + const String bottomRoute = '/'; + const String topRoute = '/a'; - await tester.pump(const Duration(milliseconds: 150)); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect( - tester.state(find.byKey(const ValueKey(topRoute))), - topState, - ); + await tester.pumpWidget( + _TestWidget( + navigatorKey: navigator, + transitionType: SharedAxisTransitionType.scaled, + contentBuilder: (RouteSettings settings) { + return _StatefulTestWidget( + key: ValueKey(settings.name), + name: settings.name!, + ); + }, + ), + ); - await tester.pumpAndSettle(); - expect( - tester.state(find.byKey(const ValueKey(bottomRoute))), - bottomState, - ); - expect(find.byKey(const ValueKey(topRoute)), findsNothing); - }, - ); + final _StatefulTestWidgetState bottomState = tester.state( + find.byKey(const ValueKey(bottomRoute)), + ); + expect(bottomState.widget.name, bottomRoute); + + navigator.currentState!.pushNamed(topRoute); + await tester.pump(); + await tester.pump(); + + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + final _StatefulTestWidgetState topState = tester.state( + find.byKey(const ValueKey(topRoute)), + ); + expect(topState.widget.name, topRoute); + + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); + + await tester.pumpAndSettle(); + expect( + tester.state( + find.byKey(const ValueKey(bottomRoute), skipOffstage: false), + ), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); + + navigator.currentState!.pop(); + await tester.pump(); + + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); + + await tester.pump(const Duration(milliseconds: 150)); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect( + tester.state(find.byKey(const ValueKey(topRoute))), + topState, + ); + + await tester.pumpAndSettle(); + expect( + tester.state(find.byKey(const ValueKey(bottomRoute))), + bottomState, + ); + expect(find.byKey(const ValueKey(topRoute)), findsNothing); + }); testWidgets('default fill color', (WidgetTester tester) async { final GlobalKey navigator = GlobalKey(); @@ -1703,29 +1715,35 @@ 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, - defaultFillColor); + expect( + tester.widget(fillContainerFinder).color, + defaultFillColor, + ); navigator.currentState!.pushNamed(topRoute); 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, - defaultFillColor); + expect( + tester.widget(fillContainerFinder).color, + defaultFillColor, + ); }); testWidgets('custom fill color', (WidgetTester tester) async { @@ -1742,29 +1760,35 @@ 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, Colors.green); + tester.widget(fillContainerFinder).color, + Colors.green, + ); navigator.currentState!.pushNamed(topRoute); 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, Colors.green); + tester.widget(fillContainerFinder).color, + Colors.green, + ); }); testWidgets('should keep state', (WidgetTester tester) async { @@ -1776,17 +1800,19 @@ void main() { vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SharedAxisTransition( - transitionType: SharedAxisTransitionType.scaled, - animation: animation, - secondaryAnimation: secondaryAnimation, - child: const _StatefulTestWidget(name: 'Foo'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SharedAxisTransition( + transitionType: SharedAxisTransitionType.scaled, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: const _StatefulTestWidget(name: 'Foo'), + ), ), ), - )); + ); final State state = tester.state( find.byType(_StatefulTestWidget), ); @@ -1858,15 +1884,19 @@ double _getTranslationOffset( switch (transitionType) { case SharedAxisTransitionType.horizontal: - return tester.widgetList(finder).fold(0.0, - (double a, Widget widget) { + return tester.widgetList(finder).fold(0.0, ( + double a, + Widget widget, + ) { final Transform transition = widget as Transform; final Vector3 translation = transition.transform.getTranslation(); return a + translation.x; }); case SharedAxisTransitionType.vertical: - return tester.widgetList(finder).fold(0.0, - (double a, Widget widget) { + return tester.widgetList(finder).fold(0.0, ( + double a, + Widget widget, + ) { final Transform transition = widget as Transform; final Vector3 translation = transition.transform.getTranslation(); return a + translation.y; @@ -1926,9 +1956,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 221ed484d40..0051c4f7652 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.29/Dart 3.7. + ## 0.11.2 * Fixes overflowed toggles in the camera example. diff --git a/packages/camera/camera/README.md b/packages/camera/camera/README.md index 1ebac1e02f0..9f5e6e296e2 100644 --- a/packages/camera/camera/README.md +++ b/packages/camera/camera/README.md @@ -131,23 +131,26 @@ class _CameraAppState extends State { void initState() { super.initState(); controller = CameraController(_cameras[0], ResolutionPreset.max); - controller.initialize().then((_) { - if (!mounted) { - return; - } - setState(() {}); - }).catchError((Object e) { - if (e is CameraException) { - switch (e.code) { - case 'CameraAccessDenied': - // Handle access errors here. - break; - default: - // Handle other errors here. - break; - } - } - }); + controller + .initialize() + .then((_) { + if (!mounted) { + return; + } + setState(() {}); + }) + .catchError((Object e) { + if (e is CameraException) { + switch (e.code) { + case 'CameraAccessDenied': + // Handle access errors here. + break; + default: + // Handle other errors here. + break; + } + } + }); } @override @@ -161,11 +164,10 @@ class _CameraAppState extends State { if (!controller.value.isInitialized) { return Container(); } - return MaterialApp( - home: CameraPreview(controller), - ); + return MaterialApp(home: CameraPreview(controller)); } } + ``` For a more elaborate usage example see [here](https://github.com/flutter/packages/tree/main/packages/camera/camera/example). diff --git a/packages/camera/camera/example/integration_test/camera_test.dart b/packages/camera/camera/example/integration_test/camera_test.dart index d981a4e8d97..2e4cb68841f 100644 --- a/packages/camera/camera/example/integration_test/camera_test.dart +++ b/packages/camera/camera/example/integration_test/camera_test.dart @@ -33,15 +33,15 @@ 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.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + 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), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -57,7 +57,9 @@ void main() { // automatic code to fall back to smaller sizes when we need to. Returns // whether the image is exactly the desired resolution. Future testCaptureVideoResolution( - CameraController controller, ResolutionPreset preset) async { + CameraController controller, + ResolutionPreset preset, + ) async { final Size expectedSize = presetExpectedSizes[preset]!; // Take Video @@ -67,15 +69,18 @@ void main() { // Load video metadata final File videoFile = File(file.path); - final VideoPlayerController videoController = - VideoPlayerController.file(videoFile); + final VideoPlayerController videoController = VideoPlayerController.file( + videoFile, + ); await videoController.initialize(); final Size video = videoController.value.size; // Verify image dimensions are as expected expect(video, isNotNull); return assertExpectedDimensions( - expectedSize, Size(video.height, video.width)); + expectedSize, + Size(video.height, video.width), + ); } testWidgets( @@ -89,14 +94,20 @@ void main() { bool previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = - CameraController(cameraDescription, preset.key); + final CameraController controller = CameraController( + cameraDescription, + preset.key, + ); await controller.initialize(); await controller.prepareForVideoRecording(); - final bool presetExactlySupported = - await testCaptureVideoResolution(controller, preset.key); - assert(!(!previousPresetExactlySupported && presetExactlySupported), - 'The camera took higher resolution pictures at a lower resolution.'); + final bool presetExactlySupported = await testCaptureVideoResolution( + controller, + preset.key, + ); + assert( + !(!previousPresetExactlySupported && presetExactlySupported), + 'The camera took higher resolution pictures at a lower resolution.', + ); previousPresetExactlySupported = presetExactlySupported; await controller.dispose(); } @@ -188,46 +199,44 @@ void main() { expect(duration, lessThan(recordingTime - timePaused)); }, skip: !Platform.isAndroid || skipFor157181); - testWidgets( - 'Android image streaming', - (WidgetTester tester) async { - final List cameras = await availableCameras(); - if (cameras.isEmpty) { - return; - } + testWidgets('Android image streaming', (WidgetTester tester) async { + final List cameras = await availableCameras(); + if (cameras.isEmpty) { + return; + } - final CameraController controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final CameraController controller = CameraController( + cameras[0], + ResolutionPreset.low, + enableAudio: false, + ); - await controller.initialize(); - bool isDetecting = false; + await controller.initialize(); + bool isDetecting = false; - await controller.startImageStream((CameraImage image) { - if (isDetecting) { - return; - } + await controller.startImageStream((CameraImage image) { + if (isDetecting) { + return; + } - isDetecting = true; + isDetecting = true; - expectLater(image, isNotNull).whenComplete(() => isDetecting = false); - }); + expectLater(image, isNotNull).whenComplete(() => isDetecting = false); + }); - expect(controller.value.isStreamingImages, true); + expect(controller.value.isStreamingImages, true); - sleep(const Duration(milliseconds: 500)); + sleep(const Duration(milliseconds: 500)); - await controller.stopImageStream(); - await controller.dispose(); - }, - skip: !Platform.isAndroid, - ); + await controller.stopImageStream(); + await controller.dispose(); + }, skip: !Platform.isAndroid); /// Start streaming with specifying the ImageFormatGroup. - Future startStreaming(List cameras, - ImageFormatGroup? imageFormatGroup) async { + Future startStreaming( + List cameras, + ImageFormatGroup? imageFormatGroup, + ) async { final CameraController controller = CameraController( cameras.first, ResolutionPreset.low, @@ -290,29 +299,27 @@ void main() { expect(controller.description, cameras[1]); }); - testWidgets( - 'iOS image streaming with imageFormatGroup', - (WidgetTester tester) async { - final List cameras = await availableCameras(); - if (cameras.isEmpty) { - return; - } - - CameraImage image = await startStreaming(cameras, null); - expect(image, isNotNull); - expect(image.format.group, ImageFormatGroup.bgra8888); - expect(image.planes.length, 1); - - image = await startStreaming(cameras, ImageFormatGroup.yuv420); - expect(image, isNotNull); - expect(image.format.group, ImageFormatGroup.yuv420); - expect(image.planes.length, 2); + testWidgets('iOS image streaming with imageFormatGroup', ( + WidgetTester tester, + ) async { + final List cameras = await availableCameras(); + if (cameras.isEmpty) { + return; + } - image = await startStreaming(cameras, ImageFormatGroup.bgra8888); - expect(image, isNotNull); - expect(image.format.group, ImageFormatGroup.bgra8888); - expect(image.planes.length, 1); - }, - skip: !Platform.isIOS, - ); + CameraImage image = await startStreaming(cameras, null); + expect(image, isNotNull); + expect(image.format.group, ImageFormatGroup.bgra8888); + expect(image.planes.length, 1); + + image = await startStreaming(cameras, ImageFormatGroup.yuv420); + expect(image, isNotNull); + expect(image.format.group, ImageFormatGroup.yuv420); + expect(image.planes.length, 2); + + image = await startStreaming(cameras, ImageFormatGroup.bgra8888); + expect(image, isNotNull); + expect(image.format.group, ImageFormatGroup.bgra8888); + expect(image.planes.length, 1); + }, skip: !Platform.isIOS); } diff --git a/packages/camera/camera/example/lib/main.dart b/packages/camera/camera/example/lib/main.dart index a11d0f7083e..c02111f87f7 100644 --- a/packages/camera/camera/example/lib/main.dart +++ b/packages/camera/camera/example/lib/main.dart @@ -132,9 +132,7 @@ class _CameraExampleHomeState extends State @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Camera example'), - ), + appBar: AppBar(title: const Text('Camera example')), body: Column( children: [ Expanded( @@ -151,9 +149,7 @@ class _CameraExampleHomeState extends State ), child: Padding( padding: const EdgeInsets.all(1.0), - child: Center( - child: _cameraPreviewWidget(), - ), + child: Center(child: _cameraPreviewWidget()), ), ), ), @@ -162,10 +158,7 @@ class _CameraExampleHomeState extends State Padding( padding: const EdgeInsets.all(5.0), child: Row( - children: [ - _cameraTogglesRowWidget(), - _thumbnailWidget(), - ], + children: [_cameraTogglesRowWidget(), _thumbnailWidget()], ), ), ], @@ -193,15 +186,17 @@ class _CameraExampleHomeState extends State child: CameraPreview( controller!, child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onScaleStart: _handleScaleStart, - onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), - ); - }), + builder: (BuildContext context, BoxConstraints constraints) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onScaleStart: _handleScaleStart, + onScaleUpdate: _handleScaleUpdate, + onTapDown: + (TapDownDetails details) => + onViewFinderTap(details, constraints), + ); + }, + ), ), ); } @@ -217,8 +212,10 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale) - .clamp(_minAvailableZoom, _maxAvailableZoom); + _currentScale = (_baseScale * details.scale).clamp( + _minAvailableZoom, + _maxAvailableZoom, + ); await controller!.setZoomLevel(_currentScale); } @@ -270,20 +267,19 @@ 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), @@ -291,13 +287,16 @@ class _CameraExampleHomeState extends State onPressed: controller != null ? onAudioModeButtonPressed : null, ), IconButton( - icon: Icon(controller?.value.isCaptureOrientationLocked ?? false - ? Icons.screen_lock_rotation - : Icons.screen_rotation), + icon: Icon( + controller?.value.isCaptureOrientationLocked ?? false + ? Icons.screen_lock_rotation + : Icons.screen_rotation, + ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: + controller != null + ? onCaptureOrientationLockButtonPressed + : null, ), ], ), @@ -317,39 +316,47 @@ 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, ), ], ), @@ -359,14 +366,16 @@ 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( @@ -376,18 +385,18 @@ class _CameraExampleHomeState extends State color: Colors.grey.shade50, child: Column( children: [ - const Center( - child: Text('Exposure Mode'), - ), + const Center(child: Text('Exposure Mode')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, 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); @@ -398,24 +407,25 @@ 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'), ), ], ), - const Center( - child: Text('Exposure Offset'), - ), + const Center(child: Text('Exposure Offset')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ @@ -425,10 +435,11 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: _minAvailableExposureOffset == - _maxAvailableExposureOffset - ? null - : setExposureOffset, + onChanged: + _minAvailableExposureOffset == + _maxAvailableExposureOffset + ? null + : setExposureOffset, ), Text(_maxAvailableExposureOffset.toString()), ], @@ -442,14 +453,16 @@ 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( @@ -459,17 +472,16 @@ class _CameraExampleHomeState extends State color: Colors.grey.shade50, child: Column( children: [ - const Center( - child: Text('Focus Mode'), - ), + const Center(child: Text('Focus Mode')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, 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); @@ -480,9 +492,11 @@ 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'), ), ], @@ -504,43 +518,48 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.camera_alt), color: Colors.blue, - onPressed: cameraController != null && - cameraController.value.isInitialized && - !cameraController.value.isRecordingVideo - ? onTakePictureButtonPressed - : null, + onPressed: + cameraController != 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, + onPressed: + cameraController != 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), + icon: + cameraController != null && + 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, + onPressed: + cameraController != 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, + onPressed: + cameraController != null && + cameraController.value.isInitialized && + cameraController.value.isRecordingVideo + ? onStopButtonPressed + : null, ), IconButton( icon: const Icon(Icons.pause_presentation), @@ -599,8 +618,9 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of(context) - .showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -627,7 +647,8 @@ class _CameraExampleHomeState extends State } Future _initializeCameraController( - CameraDescription cameraDescription) async { + CameraDescription cameraDescription, + ) async { final CameraController cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, @@ -644,7 +665,8 @@ class _CameraExampleHomeState extends State } if (cameraController.value.hasError) { showInSnackBar( - 'Camera error ${cameraController.value.errorDescription}'); + 'Camera error ${cameraController.value.errorDescription}', + ); } }); @@ -654,19 +676,20 @@ 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), - cameraController - .getMinZoomLevel() - .then((double value) => _minAvailableZoom = value), + cameraController.getMaxZoomLevel().then( + (double value) => _maxAvailableZoom = value, + ), + cameraController.getMinZoomLevel().then( + (double value) => _minAvailableZoom = value, + ), ]); } on CameraException catch (e) { switch (e.code) { @@ -758,7 +781,8 @@ class _CameraExampleHomeState extends State } else { await cameraController.lockCaptureOrientation(); showInSnackBar( - 'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}'); + 'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}', + ); } } } on CameraException catch (e) { @@ -977,9 +1001,10 @@ 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) { @@ -1037,9 +1062,7 @@ class CameraApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - home: CameraExampleHome(), - ); + return const MaterialApp(home: CameraExampleHome()); } } diff --git a/packages/camera/camera/example/lib/readme_full_example.dart b/packages/camera/camera/example/lib/readme_full_example.dart index 0a7c418f4c5..2cf930c5e85 100644 --- a/packages/camera/camera/example/lib/readme_full_example.dart +++ b/packages/camera/camera/example/lib/readme_full_example.dart @@ -31,23 +31,26 @@ class _CameraAppState extends State { void initState() { super.initState(); controller = CameraController(_cameras[0], ResolutionPreset.max); - controller.initialize().then((_) { - if (!mounted) { - return; - } - setState(() {}); - }).catchError((Object e) { - if (e is CameraException) { - switch (e.code) { - case 'CameraAccessDenied': - // Handle access errors here. - break; - default: - // Handle other errors here. - break; - } - } - }); + controller + .initialize() + .then((_) { + if (!mounted) { + return; + } + setState(() {}); + }) + .catchError((Object e) { + if (e is CameraException) { + switch (e.code) { + case 'CameraAccessDenied': + // Handle access errors here. + break; + default: + // Handle other errors here. + break; + } + } + }); } @override @@ -61,9 +64,8 @@ class _CameraAppState extends State { if (!controller.value.isInitialized) { return Container(); } - return MaterialApp( - home: CameraPreview(controller), - ); + return MaterialApp(home: CameraPreview(controller)); } } + // #enddocregion FullAppExample diff --git a/packages/camera/camera/example/pubspec.yaml b/packages/camera/camera/example/pubspec.yaml index a6f18c4c24c..e268268e320 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: camera: diff --git a/packages/camera/camera/example/test/main_test.dart b/packages/camera/camera/example/test/main_test.dart index eb75a29f8ed..01d8d624b86 100644 --- a/packages/camera/camera/example/test/main_test.dart +++ b/packages/camera/camera/example/test/main_test.dart @@ -15,22 +15,21 @@ void main() { expect(find.byType(SnackBar), findsOneWidget); }); - testWidgets( - 'CameraDescription toggles will not overflow', - (WidgetTester tester) async { - WidgetsFlutterBinding.ensureInitialized(); - // Adds 10 fake camera descriptions. - for (int i = 0; i < 10; i++) { - cameras.add( - CameraDescription( - name: 'camera_$i', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ); - } - await tester.pumpWidget(const CameraApp()); - await tester.pumpAndSettle(); - }, - ); + testWidgets('CameraDescription toggles will not overflow', ( + WidgetTester tester, + ) async { + WidgetsFlutterBinding.ensureInitialized(); + // Adds 10 fake camera descriptions. + for (int i = 0; i < 10; i++) { + cameras.add( + CameraDescription( + name: 'camera_$i', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ); + } + await tester.pumpWidget(const CameraApp()); + await tester.pumpAndSettle(); + }); } diff --git a/packages/camera/camera/example/test_driver/integration_test.dart b/packages/camera/camera/example/test_driver/integration_test.dart index aa57599f316..7779a8e714d 100644 --- a/packages/camera/camera/example/test_driver/integration_test.dart +++ b/packages/camera/camera/example/test_driver/integration_test.dart @@ -29,14 +29,14 @@ Future main() async { 'pm', 'grant', _examplePackage, - 'android.permission.CAMERA' + 'android.permission.CAMERA', ]); Process.runSync('adb', [ 'shell', 'pm', 'grant', _examplePackage, - 'android.permission.RECORD_AUDIO' + 'android.permission.RECORD_AUDIO', ]); print('Starting test.'); final FlutterDriver driver = await FlutterDriver.connect(); @@ -51,14 +51,14 @@ Future main() async { 'pm', 'revoke', _examplePackage, - 'android.permission.CAMERA' + 'android.permission.CAMERA', ]); Process.runSync('adb', [ 'shell', 'pm', 'revoke', _examplePackage, - 'android.permission.RECORD_AUDIO' + 'android.permission.RECORD_AUDIO', ]); final Map result = jsonDecode(data) as Map; diff --git a/packages/camera/camera/lib/src/camera_controller.dart b/packages/camera/camera/lib/src/camera_controller.dart index 3f39d3202b8..0cd0fb0878f 100644 --- a/packages/camera/camera/lib/src/camera_controller.dart +++ b/packages/camera/camera/lib/src/camera_controller.dart @@ -58,21 +58,21 @@ class CameraValue { /// Creates a new camera controller state for an uninitialized controller. const CameraValue.uninitialized(CameraDescription description) - : this( - isInitialized: false, - isRecordingVideo: false, - isTakingPicture: false, - isStreamingImages: false, - isRecordingPaused: false, - flashMode: FlashMode.auto, - exposureMode: ExposureMode.auto, - exposurePointSupported: false, - focusMode: FocusMode.auto, - focusPointSupported: false, - deviceOrientation: DeviceOrientation.portraitUp, - isPreviewPaused: false, - description: description, - ); + : this( + isInitialized: false, + isRecordingVideo: false, + isTakingPicture: false, + isStreamingImages: false, + isRecordingPaused: false, + flashMode: FlashMode.auto, + exposureMode: ExposureMode.auto, + exposurePointSupported: false, + focusMode: FocusMode.auto, + focusPointSupported: false, + deviceOrientation: DeviceOrientation.portraitUp, + isPreviewPaused: false, + description: description, + ); /// True after [CameraController.initialize] has completed successfully. final bool isInitialized; @@ -187,17 +187,20 @@ class CameraValue { exposurePointSupported ?? this.exposurePointSupported, focusPointSupported: focusPointSupported ?? this.focusPointSupported, deviceOrientation: deviceOrientation ?? this.deviceOrientation, - lockedCaptureOrientation: lockedCaptureOrientation == null - ? this.lockedCaptureOrientation - : lockedCaptureOrientation.orNull, - recordingOrientation: recordingOrientation == null - ? this.recordingOrientation - : recordingOrientation.orNull, + lockedCaptureOrientation: + lockedCaptureOrientation == null + ? this.lockedCaptureOrientation + : lockedCaptureOrientation.orNull, + recordingOrientation: + recordingOrientation == null + ? this.recordingOrientation + : recordingOrientation.orNull, isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused, description: description ?? this.description, - previewPauseOrientation: previewPauseOrientation == null - ? this.previewPauseOrientation - : previewPauseOrientation.orNull, + previewPauseOrientation: + previewPauseOrientation == null + ? this.previewPauseOrientation + : previewPauseOrientation.orNull, ); } @@ -249,13 +252,14 @@ class CameraController extends ValueNotifier { int? videoBitrate, int? audioBitrate, this.imageFormatGroup, - }) : mediaSettings = MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - fps: fps, - videoBitrate: videoBitrate, - audioBitrate: audioBitrate), - super(CameraValue.uninitialized(description)); + }) : mediaSettings = MediaSettings( + resolutionPreset: resolutionPreset, + enableAudio: enableAudio, + fps: fps, + videoBitrate: videoBitrate, + audioBitrate: audioBitrate, + ), + super(CameraValue.uninitialized(description)); /// The properties of the camera device controlled by this controller. CameraDescription get description => value.description; @@ -298,7 +302,7 @@ class CameraController extends ValueNotifier { // this value is null. Future? _initializeFuture; StreamSubscription? - _deviceOrientationSubscription; + _deviceOrientationSubscription; /// Checks whether [CameraController.dispose] has completed successfully. /// @@ -336,22 +340,21 @@ class CameraController extends ValueNotifier { _deviceOrientationSubscription ??= CameraPlatform.instance .onDeviceOrientationChanged() .listen((DeviceOrientationChangedEvent event) { - value = value.copyWith( - deviceOrientation: event.orientation, - ); - }); + value = value.copyWith(deviceOrientation: event.orientation); + }); _cameraId = await CameraPlatform.instance.createCameraWithSettings( description, mediaSettings, ); - _unawaited(CameraPlatform.instance - .onCameraInitialized(_cameraId) - .first - .then((CameraInitializedEvent event) { - initializeCompleter.complete(event); - })); + _unawaited( + CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( + CameraInitializedEvent event, + ) { + initializeCompleter.complete(event); + }), + ); await CameraPlatform.instance.initializeCamera( _cameraId, @@ -361,19 +364,22 @@ class CameraController extends ValueNotifier { value = value.copyWith( isInitialized: true, description: description, - previewSize: await initializeCompleter.future - .then((CameraInitializedEvent event) => Size( - event.previewWidth, - event.previewHeight, - )), - exposureMode: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.exposureMode), - focusMode: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.focusMode), + previewSize: await initializeCompleter.future.then( + (CameraInitializedEvent event) => + Size(event.previewWidth, event.previewHeight), + ), + exposureMode: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.exposureMode, + ), + focusMode: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.focusMode, + ), exposurePointSupported: await initializeCompleter.future.then( - (CameraInitializedEvent event) => event.exposurePointSupported), - focusPointSupported: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.focusPointSupported), + (CameraInitializedEvent event) => event.exposurePointSupported, + ), + focusPointSupported: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.focusPointSupported, + ), ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -405,9 +411,11 @@ class CameraController extends ValueNotifier { try { await CameraPlatform.instance.pausePreview(_cameraId); value = value.copyWith( - isPreviewPaused: true, - previewPauseOrientation: Optional.of( - value.lockedCaptureOrientation ?? value.deviceOrientation)); + isPreviewPaused: true, + previewPauseOrientation: Optional.of( + value.lockedCaptureOrientation ?? value.deviceOrientation, + ), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -421,8 +429,9 @@ class CameraController extends ValueNotifier { try { await CameraPlatform.instance.resumePreview(_cameraId); value = value.copyWith( - isPreviewPaused: false, - previewPauseOrientation: const Optional.absent()); + isPreviewPaused: false, + previewPauseOrientation: const Optional.absent(), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -504,8 +513,8 @@ class CameraController extends ValueNotifier { _imageStreamSubscription = CameraPlatform.instance .onStreamedFrameAvailable(_cameraId) .listen((CameraImageData imageData) { - onAvailable(CameraImage.fromPlatformInterface(imageData)); - }); + onAvailable(CameraImage.fromPlatformInterface(imageData)); + }); value = value.copyWith(isStreamingImages: true); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -545,8 +554,9 @@ class CameraController extends ValueNotifier { /// /// The video is returned as a [XFile] after calling [stopVideoRecording]. /// Throws a [CameraException] if the capture fails. - Future startVideoRecording( - {onLatestImageAvailable? onAvailable}) async { + Future startVideoRecording({ + onLatestImageAvailable? onAvailable, + }) async { _throwIfNotInitialized('startVideoRecording'); if (value.isRecordingVideo) { throw CameraException( @@ -564,13 +574,16 @@ class CameraController extends ValueNotifier { try { await CameraPlatform.instance.startVideoCapturing( - VideoCaptureOptions(_cameraId, streamCallback: streamCallback)); + VideoCaptureOptions(_cameraId, streamCallback: streamCallback), + ); value = value.copyWith( - isRecordingVideo: true, - isRecordingPaused: false, - recordingOrientation: Optional.of( - value.lockedCaptureOrientation ?? value.deviceOrientation), - isStreamingImages: onAvailable != null); + isRecordingVideo: true, + isRecordingPaused: false, + recordingOrientation: Optional.of( + value.lockedCaptureOrientation ?? value.deviceOrientation, + ), + isStreamingImages: onAvailable != null, + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -593,8 +606,9 @@ class CameraController extends ValueNotifier { } try { - final XFile file = - await CameraPlatform.instance.stopVideoRecording(_cameraId); + final XFile file = await CameraPlatform.instance.stopVideoRecording( + _cameraId, + ); value = value.copyWith( isRecordingVideo: false, recordingOrientation: const Optional.absent(), @@ -715,18 +729,14 @@ class CameraController extends ValueNotifier { if (point != null && (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { throw ArgumentError( - 'The values of point should be anywhere between (0,0) and (1,1).'); + 'The values of point should be anywhere between (0,0) and (1,1).', + ); } try { await CameraPlatform.instance.setExposurePoint( _cameraId, - point == null - ? null - : Point( - point.dx, - point.dy, - ), + point == null ? null : Point(point.dx, point.dy), ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -779,8 +789,10 @@ class CameraController extends ValueNotifier { Future setExposureOffset(double offset) async { _throwIfNotInitialized('setExposureOffset'); // Check if offset is in range - final List range = await Future.wait( - >[getMinExposureOffset(), getMaxExposureOffset()]); + final List range = await Future.wait(>[ + getMinExposureOffset(), + getMaxExposureOffset(), + ]); if (offset < range[0] || offset > range[1]) { throw CameraException( 'exposureOffsetOutOfBounds', @@ -814,10 +826,14 @@ class CameraController extends ValueNotifier { Future lockCaptureOrientation([DeviceOrientation? orientation]) async { try { await CameraPlatform.instance.lockCaptureOrientation( - _cameraId, orientation ?? value.deviceOrientation); + _cameraId, + orientation ?? value.deviceOrientation, + ); value = value.copyWith( - lockedCaptureOrientation: Optional.of( - orientation ?? value.deviceOrientation)); + lockedCaptureOrientation: Optional.of( + orientation ?? value.deviceOrientation, + ), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -838,7 +854,8 @@ class CameraController extends ValueNotifier { try { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); value = value.copyWith( - lockedCaptureOrientation: const Optional.absent()); + lockedCaptureOrientation: const Optional.absent(), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -852,17 +869,13 @@ class CameraController extends ValueNotifier { if (point != null && (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { throw ArgumentError( - 'The values of point should be anywhere between (0,0) and (1,1).'); + 'The values of point should be anywhere between (0,0) and (1,1).', + ); } try { await CameraPlatform.instance.setFocusPoint( _cameraId, - point == null - ? null - : Point( - point.dx, - point.dy, - ), + point == null ? null : Point(point.dx, point.dy), ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); diff --git a/packages/camera/camera/lib/src/camera_image.dart b/packages/camera/camera/lib/src/camera_image.dart index 0e531b33dc7..e2dda4ed88c 100644 --- a/packages/camera/camera/lib/src/camera_image.dart +++ b/packages/camera/camera/lib/src/camera_image.dart @@ -15,20 +15,20 @@ import 'package:flutter/foundation.dart'; /// format of the Image. class Plane { Plane._fromPlatformInterface(CameraImagePlane plane) - : bytes = plane.bytes, - bytesPerPixel = plane.bytesPerPixel, - bytesPerRow = plane.bytesPerRow, - height = plane.height, - width = plane.width; + : bytes = plane.bytes, + bytesPerPixel = plane.bytesPerPixel, + bytesPerRow = plane.bytesPerRow, + height = plane.height, + width = plane.width; // Only used by the deprecated codepath that's kept to avoid breaking changes. // Never called by the plugin itself. Plane._fromPlatformData(Map data) - : bytes = data['bytes'] as Uint8List, - bytesPerPixel = data['bytesPerPixel'] as int?, - bytesPerRow = data['bytesPerRow'] as int, - height = data['height'] as int?, - width = data['width'] as int?; + : bytes = data['bytes'] as Uint8List, + bytesPerPixel = data['bytesPerPixel'] as int?, + bytesPerRow = data['bytesPerRow'] as int, + height = data['height'] as int?, + width = data['width'] as int?; /// Bytes representing this plane. final Uint8List bytes; @@ -55,8 +55,8 @@ class Plane { /// Describes how pixels are represented in an image. class ImageFormat { ImageFormat._fromPlatformInterface(CameraImageFormat format) - : group = format.group, - raw = format.raw; + : group = format.group, + raw = format.raw; // Only used by the deprecated codepath that's kept to avoid breaking changes. // Never called by the plugin itself. @@ -118,27 +118,33 @@ ImageFormatGroup _asImageFormatGroup(dynamic rawFormat) { class CameraImage { /// Creates a [CameraImage] from the platform interface version. CameraImage.fromPlatformInterface(CameraImageData data) - : format = ImageFormat._fromPlatformInterface(data.format), - height = data.height, - width = data.width, - planes = List.unmodifiable(data.planes.map( - (CameraImagePlane plane) => Plane._fromPlatformInterface(plane))), - lensAperture = data.lensAperture, - sensorExposureTime = data.sensorExposureTime, - sensorSensitivity = data.sensorSensitivity; + : format = ImageFormat._fromPlatformInterface(data.format), + height = data.height, + width = data.width, + planes = List.unmodifiable( + data.planes.map( + (CameraImagePlane plane) => Plane._fromPlatformInterface(plane), + ), + ), + lensAperture = data.lensAperture, + sensorExposureTime = data.sensorExposureTime, + sensorSensitivity = data.sensorSensitivity; /// Creates a [CameraImage] from method channel data. @Deprecated('Use fromPlatformInterface instead') CameraImage.fromPlatformData(Map data) - : format = ImageFormat._fromPlatformData(data['format']), - height = data['height'] as int, - width = data['width'] as int, - lensAperture = data['lensAperture'] as double?, - sensorExposureTime = data['sensorExposureTime'] as int?, - sensorSensitivity = data['sensorSensitivity'] as double?, - planes = List.unmodifiable((data['planes'] as List) - .map((dynamic planeData) => - Plane._fromPlatformData(planeData as Map))); + : format = ImageFormat._fromPlatformData(data['format']), + height = data['height'] as int, + width = data['width'] as int, + lensAperture = data['lensAperture'] as double?, + sensorExposureTime = data['sensorExposureTime'] as int?, + sensorSensitivity = data['sensorSensitivity'] as double?, + planes = List.unmodifiable( + (data['planes'] as List).map( + (dynamic planeData) => + Plane._fromPlatformData(planeData as Map), + ), + ); /// Format of the image provided. /// diff --git a/packages/camera/camera/lib/src/camera_preview.dart b/packages/camera/camera/lib/src/camera_preview.dart index 53f9034dc85..835792f00af 100644 --- a/packages/camera/camera/lib/src/camera_preview.dart +++ b/packages/camera/camera/lib/src/camera_preview.dart @@ -23,23 +23,24 @@ class CameraPreview extends StatelessWidget { Widget build(BuildContext context) { return controller.value.isInitialized ? ValueListenableBuilder( - valueListenable: controller, - builder: (BuildContext context, Object? value, Widget? child) { - return AspectRatio( - aspectRatio: _isLandscape() - ? controller.value.aspectRatio - : (1 / controller.value.aspectRatio), - child: Stack( - fit: StackFit.expand, - children: [ - _wrapInRotatedBox(child: controller.buildPreview()), - child ?? Container(), - ], - ), - ); - }, - child: child, - ) + valueListenable: controller, + builder: (BuildContext context, Object? value, Widget? child) { + return AspectRatio( + aspectRatio: + _isLandscape() + ? controller.value.aspectRatio + : (1 / controller.value.aspectRatio), + child: Stack( + fit: StackFit.expand, + children: [ + _wrapInRotatedBox(child: controller.buildPreview()), + child ?? Container(), + ], + ), + ); + }, + child: child, + ) : Container(); } @@ -48,16 +49,13 @@ class CameraPreview extends StatelessWidget { return child; } - return RotatedBox( - quarterTurns: _getQuarterTurns(), - child: child, - ); + return RotatedBox(quarterTurns: _getQuarterTurns(), child: child); } bool _isLandscape() { return [ DeviceOrientation.landscapeLeft, - DeviceOrientation.landscapeRight + DeviceOrientation.landscapeRight, ].contains(_getApplicableOrientation()); } diff --git a/packages/camera/camera/pubspec.yaml b/packages/camera/camera/pubspec.yaml index d60b7eba1df..073c8019872 100644 --- a/packages/camera/camera/pubspec.yaml +++ b/packages/camera/camera/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.11.2 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/camera/camera/test/camera_export_test.dart b/packages/camera/camera/test/camera_export_test.dart index a668c1ab650..e3383cdde2f 100644 --- a/packages/camera/camera/test/camera_export_test.dart +++ b/packages/camera/camera/test/camera_export_test.dart @@ -9,20 +9,17 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('camera', () { - test( - 'ensure camera.dart exports classes from platform interface', - () { - main_file.CameraDescription; - main_file.CameraException; - main_file.CameraLensDirection; - main_file.CameraLensType; - main_file.ExposureMode; - main_file.FlashMode; - main_file.FocusMode; - main_file.ImageFormatGroup; - main_file.ResolutionPreset; - main_file.XFile; - }, - ); + test('ensure camera.dart exports classes from platform interface', () { + main_file.CameraDescription; + main_file.CameraException; + main_file.CameraLensDirection; + main_file.CameraLensType; + main_file.ExposureMode; + main_file.FlashMode; + main_file.FocusMode; + main_file.ImageFormatGroup; + main_file.ResolutionPreset; + main_file.XFile; + }); }); } diff --git a/packages/camera/camera/test/camera_image_stream_test.dart b/packages/camera/camera/test/camera_image_stream_test.dart index fd17694e246..c2880cd0470 100644 --- a/packages/camera/camera/test/camera_image_stream_test.dart +++ b/packages/camera/camera/test/camera_image_stream_test.dart @@ -21,11 +21,13 @@ void main() { test('startImageStream() throws $CameraException when uninitialized', () { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); expect( () => cameraController.startImageStream((CameraImage image) {}), @@ -45,57 +47,74 @@ void main() { ); }); - test('startImageStream() throws $CameraException when recording videos', - () async { - final CameraController cameraController = CameraController( + test( + 'startImageStream() throws $CameraException when recording videos', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); + await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isRecordingVideo: true); + cameraController.value = cameraController.value.copyWith( + isRecordingVideo: true, + ); - expect( + expect( () => cameraController.startImageStream((CameraImage image) {}), - throwsA(isA().having( - (CameraException error) => error.description, - 'A video recording is already started.', - 'startImageStream was called while a video is being recorded.', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'A video recording is already started.', + 'startImageStream was called while a video is being recorded.', + ), + ), + ); + }, + ); test( - 'startImageStream() throws $CameraException when already streaming images', - () async { - final CameraController cameraController = CameraController( + 'startImageStream() throws $CameraException when already streaming images', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - cameraController.value = - cameraController.value.copyWith(isStreamingImages: true); - expect( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + cameraController.value = cameraController.value.copyWith( + isStreamingImages: true, + ); + expect( () => cameraController.startImageStream((CameraImage image) {}), - throwsA(isA().having( - (CameraException error) => error.description, - 'A camera has started streaming images.', - 'startImageStream was called while a camera was streaming images.', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'A camera has started streaming images.', + 'startImageStream was called while a camera was streaming images.', + ), + ), + ); + }, + ); test('startImageStream() calls CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.startImageStream((CameraImage image) {}); @@ -103,17 +122,19 @@ void main() { expect(mockPlatform.streamCallLog, [ 'supportsImageStreaming', 'onStreamedFrameAvailable', - 'listen' + 'listen', ]); }); test('stopImageStream() throws $CameraException when uninitialized', () { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); expect( cameraController.stopImageStream, @@ -133,32 +154,41 @@ void main() { ); }); - test('stopImageStream() throws $CameraException when not streaming images', - () async { - final CameraController cameraController = CameraController( + test( + 'stopImageStream() throws $CameraException when not streaming images', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - expect( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + expect( cameraController.stopImageStream, - throwsA(isA().having( - (CameraException error) => error.description, - 'No camera is streaming images', - 'stopImageStream was called when no camera is streaming images.', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'No camera is streaming images', + 'stopImageStream was called when no camera is streaming images.', + ), + ), + ); + }, + ); test('stopImageStream() intended behaviour', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.startImageStream((CameraImage image) {}); await cameraController.stopImageStream(); @@ -168,35 +198,41 @@ void main() { 'onStreamedFrameAvailable', 'listen', 'supportsImageStreaming', - 'cancel' + 'cancel', ]); }); test('startVideoRecording() can stream images', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.startVideoRecording( - onAvailable: (CameraImage image) {}); + onAvailable: (CameraImage image) {}, + ); expect( - mockPlatform.streamCallLog.contains('startVideoCapturing with stream'), - isTrue); + mockPlatform.streamCallLog.contains('startVideoCapturing with stream'), + isTrue, + ); }); test('startVideoRecording() by default does not stream', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); @@ -212,8 +248,10 @@ class MockStreamingCameraPlatform extends MockCameraPlatform { StreamController? _streamController; @override - Stream onStreamedFrameAvailable(int cameraId, - {CameraImageStreamOptions? options}) { + Stream onStreamedFrameAvailable( + int cameraId, { + CameraImageStreamOptions? options, + }) { streamCallLog.add('onStreamedFrameAvailable'); _streamController = StreamController( onListen: _onFrameStreamListen, diff --git a/packages/camera/camera/test/camera_image_test.dart b/packages/camera/camera/test/camera_image_test.dart index 04bfd146a9c..1ae711d054a 100644 --- a/packages/camera/camera/test/camera_image_test.dart +++ b/packages/camera/camera/test/camera_image_test.dart @@ -48,12 +48,16 @@ void main() { expect(image.planes.length, originalImage.planes.length); for (int i = 0; i < image.planes.length; i++) { expect( - image.planes[i].bytes.length, originalImage.planes[i].bytes.length); + image.planes[i].bytes.length, + originalImage.planes[i].bytes.length, + ); for (int j = 0; j < image.planes[i].bytes.length; j++) { expect(image.planes[i].bytes[j], originalImage.planes[i].bytes[j]); } expect( - image.planes[i].bytesPerPixel, originalImage.planes[i].bytesPerPixel); + image.planes[i].bytesPerPixel, + originalImage.planes[i].bytesPerPixel, + ); expect(image.planes[i].bytesPerRow, originalImage.planes[i].bytesPerRow); expect(image.planes[i].width, originalImage.planes[i].width); expect(image.planes[i].height, originalImage.planes[i].height); @@ -63,24 +67,25 @@ void main() { group('legacy constructors', () { test('$CameraImage can be created', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImage cameraImage = - CameraImage.fromPlatformData({ - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImage cameraImage = CameraImage.fromPlatformData( + { + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.yuv420); @@ -90,118 +95,123 @@ void main() { test('$CameraImage has ImageFormatGroup.yuv420 for iOS', () { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final CameraImage cameraImage = - CameraImage.fromPlatformData({ - 'format': 875704438, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImage cameraImage = CameraImage.fromPlatformData( + { + 'format': 875704438, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('$CameraImage has ImageFormatGroup.yuv420 for Android', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImage cameraImage = - CameraImage.fromPlatformData({ - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImage cameraImage = CameraImage.fromPlatformData( + { + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('$CameraImage has ImageFormatGroup.nv21 for android', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImage cameraImage = - CameraImage.fromPlatformData({ - 'format': 17, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImage cameraImage = CameraImage.fromPlatformData( + { + 'format': 17, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.nv21); }); test('$CameraImage has ImageFormatGroup.bgra8888 for iOS', () { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final CameraImage cameraImage = - CameraImage.fromPlatformData({ - 'format': 1111970369, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImage cameraImage = CameraImage.fromPlatformData( + { + 'format': 1111970369, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.bgra8888); }); test('$CameraImage has ImageFormatGroup.unknown', () { - final CameraImage cameraImage = - CameraImage.fromPlatformData({ - 'format': null, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImage cameraImage = CameraImage.fromPlatformData( + { + 'format': null, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.unknown); }); }); diff --git a/packages/camera/camera/test/camera_preview_test.dart b/packages/camera/camera/test/camera_preview_test.dart index 73359e455ad..ff296bec5ad 100644 --- a/packages/camera/camera/test/camera_preview_test.dart +++ b/packages/camera/camera/test/camera_preview_test.dart @@ -15,7 +15,10 @@ class FakeController extends ValueNotifier FakeController() : super(const CameraValue.uninitialized(fakeDescription)); static const CameraDescription fakeDescription = CameraDescription( - name: '', lensDirection: CameraLensDirection.back, sensorOrientation: 0); + name: '', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ); @override Future dispose() async { @@ -71,12 +74,12 @@ class FakeController extends ValueNotifier @override MediaSettings get mediaSettings => const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ); + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ); @override Future resumeVideoRecording() async {} @@ -106,8 +109,9 @@ class FakeController extends ValueNotifier Future startImageStream(onLatestImageAvailable onAvailable) async {} @override - Future startVideoRecording( - {onLatestImageAvailable? onAvailable}) async {} + Future startVideoRecording({ + onLatestImageAvailable? onAvailable, + }) async {} @override Future stopImageStream() async {} @@ -140,439 +144,460 @@ class FakeController extends ValueNotifier void main() { group('RotatedBox (Android only)', () { testWidgets( - 'when recording in DeviceOrientaiton.portraitUp, rotatedBox should not be rotated', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when recording in DeviceOrientaiton.portraitUp, rotatedBox should not be rotated', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitDown, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.portraitUp), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.portraitUp, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 0); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 0); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when recording in DeviceOrientaiton.landscapeRight, rotatedBox should be rotated by one clockwise quarter turn', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when recording in DeviceOrientaiton.landscapeRight, rotatedBox should be rotated by one clockwise quarter turn', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), + DeviceOrientation.landscapeLeft, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeRight), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeRight, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 1); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 1); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when recording in DeviceOrientaiton.portraitDown, rotatedBox should be rotated by two clockwise quarter turns', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when recording in DeviceOrientaiton.portraitDown, rotatedBox should be rotated by two clockwise quarter turns', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.portraitDown), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.portraitDown, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 2); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 2); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when recording in DeviceOrientaiton.landscapeLeft, rotatedBox should be rotated by three clockwise quarter turns', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when recording in DeviceOrientaiton.landscapeLeft, rotatedBox should be rotated by three clockwise quarter turns', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 3); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 3); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation locked in DeviceOrientaiton.portaitUp, rotatedBox should not be rotated', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation locked in DeviceOrientaiton.portaitUp, rotatedBox should not be rotated', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitDown, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.portraitUp), + DeviceOrientation.portraitUp, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 0); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 0); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation locked in DeviceOrientaiton.landscapeRight, rotatedBox should be rotated by one clockwise quarter turn', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation locked in DeviceOrientaiton.landscapeRight, rotatedBox should be rotated by one clockwise quarter turn', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitDown, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 1); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 1); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation locked in DeviceOrientaiton.portraitDown, rotatedBox should be rotated by two clockwise quarter turns', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation locked in DeviceOrientaiton.portraitDown, rotatedBox should be rotated by two clockwise quarter turns', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.portraitDown), + DeviceOrientation.portraitDown, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 2); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 2); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation locked in DeviceOrientaiton.landscapeRight, rotatedBox should be rotated by three clockwise quarter turns', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation locked in DeviceOrientaiton.landscapeRight, rotatedBox should be rotated by three clockwise quarter turns', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 1); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 1); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation not locked, not recording, and device orientation is portrait up, rotatedBox should not be rotated', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation not locked, not recording, and device orientation is portrait up, rotatedBox should not be rotated', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 0); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 0); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation not locked, not recording, and device orientation is landscape right, rotatedBox should be rotated by one clockwise quarter turn', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation not locked, not recording, and device orientation is landscape right, rotatedBox should be rotated by one clockwise quarter turn', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.landscapeRight, recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 1); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 1); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation not locked, not recording, and device orientation is portrait down, rotatedBox should be rotated by two clockwise quarter turns', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation not locked, not recording, and device orientation is portrait down, rotatedBox should be rotated by two clockwise quarter turns', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitDown, recordingOrientation: const Optional.fromNullable( - DeviceOrientation.landscapeLeft), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + DeviceOrientation.landscapeLeft, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 2); + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 2); - debugDefaultTargetPlatformOverride = null; - }); + debugDefaultTargetPlatformOverride = null; + }, + ); testWidgets( - 'when orientation not locked, not recording, and device orientation is landscape left, rotatedBox should be rotated by three clockwise quarter turns', - ( - WidgetTester tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.android; + 'when orientation not locked, not recording, and device orientation is landscape left, rotatedBox should be rotated by three clockwise quarter turns', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); - addTearDown(controller.dispose); + final FakeController controller = FakeController(); + addTearDown(controller.dispose); - controller.value = controller.value.copyWith( + controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.landscapeLeft, recordingOrientation: const Optional.fromNullable( - DeviceOrientation.portraitDown), - previewSize: const Size(480, 640) // preview size irrelevant to test - ); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), - ); - expect(find.byType(RotatedBox), findsOneWidget); - - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.quarterTurns, 3); - - debugDefaultTargetPlatformOverride = null; - }); + DeviceOrientation.portraitDown, + ), + previewSize: const Size(480, 640), // preview size irrelevant to test + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CameraPreview(controller), + ), + ); + expect(find.byType(RotatedBox), findsOneWidget); + + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.quarterTurns, 3); + + debugDefaultTargetPlatformOverride = null; + }, + ); }, skip: kIsWeb); - testWidgets('when not on Android there should not be a rotated box', - (WidgetTester tester) async { + testWidgets('when not on Android there should not be a rotated box', ( + WidgetTester tester, + ) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; final FakeController controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( - isInitialized: true, - previewSize: const Size(480, 640) // preview size irrelevant to test - ); + isInitialized: true, + previewSize: const Size(480, 640), // preview size irrelevant to test + ); await tester.pumpWidget( Directionality( diff --git a/packages/camera/camera/test/camera_test.dart b/packages/camera/camera/test/camera_test.dart index 0c6a319397e..118cce3f80f 100644 --- a/packages/camera/camera/test/camera_test.dart +++ b/packages/camera/camera/test/camera_test.dart @@ -15,15 +15,17 @@ import 'package:mockito/mockito.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; List get mockAvailableCameras => [ - const CameraDescription( - name: 'camBack', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - const CameraDescription( - name: 'camFront', - lensDirection: CameraLensDirection.front, - sensorOrientation: 180), - ]; + const CameraDescription( + name: 'camBack', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + const CameraDescription( + name: 'camFront', + lensDirection: CameraLensDirection.front, + sensorOrientation: 180, + ), +]; int get mockInitializeCamera => 13; @@ -56,32 +58,33 @@ void main() { WidgetsFlutterBinding.ensureInitialized(); group('camera', () { - test('debugCheckIsDisposed should not throw assertion error when disposed', - () { - const MockCameraDescription description = MockCameraDescription(); - final CameraController controller = CameraController( - description, - ResolutionPreset.low, - ); + test( + 'debugCheckIsDisposed should not throw assertion error when disposed', + () { + const MockCameraDescription description = MockCameraDescription(); + final CameraController controller = CameraController( + description, + ResolutionPreset.low, + ); - controller.dispose(); + controller.dispose(); - expect(controller.debugCheckIsDisposed, returnsNormally); - }); + expect(controller.debugCheckIsDisposed, returnsNormally); + }, + ); - test('debugCheckIsDisposed should throw assertion error when not disposed', - () { - const MockCameraDescription description = MockCameraDescription(); - final CameraController controller = CameraController( - description, - ResolutionPreset.low, - ); + test( + 'debugCheckIsDisposed should throw assertion error when not disposed', + () { + const MockCameraDescription description = MockCameraDescription(); + final CameraController controller = CameraController( + description, + ResolutionPreset.low, + ); - expect( - () => controller.debugCheckIsDisposed(), - throwsAssertionError, - ); - }); + expect(() => controller.debugCheckIsDisposed(), throwsAssertionError); + }, + ); test('availableCameras() has camera', () async { CameraPlatform.instance = MockCameraPlatform(); @@ -99,11 +102,13 @@ void main() { test('Can be initialized', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); expect(cameraController.value.aspectRatio, 1); @@ -114,9 +119,10 @@ void main() { test('can be initialized with media settings', () async { final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), ResolutionPreset.low, fps: 15, videoBitrate: 200000, @@ -137,11 +143,13 @@ void main() { test('default constructor initializes media settings', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); expect(cameraController.resolutionPreset, ResolutionPreset.max); @@ -153,11 +161,13 @@ void main() { test('can be disposed', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); expect(cameraController.value.aspectRatio, 1); @@ -171,11 +181,13 @@ void main() { test('initialize() throws CameraException when disposed', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); expect(cameraController.value.aspectRatio, 1); @@ -187,53 +199,106 @@ void main() { verify(CameraPlatform.instance.dispose(13)).called(1); expect( - cameraController.initialize, - throwsA(isA().having( + cameraController.initialize, + throwsA( + isA().having( (CameraException error) => error.description, 'Error description', 'initialize was called on a disposed CameraController', - ))); + ), + ), + ); }); - test('initialize() throws $CameraException on $PlatformException ', - () async { - final CameraController cameraController = CameraController( + test( + 'initialize() throws $CameraException on $PlatformException ', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - mockPlatformException = true; + mockPlatformException = true; - expect( + expect( cameraController.initialize, - throwsA(isA().having( - (CameraException error) => error.description, - 'foo', - 'bar', - ))); - mockPlatformException = false; - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'foo', + 'bar', + ), + ), + ); + mockPlatformException = false; + }, + ); test('initialize() sets imageFormat', () async { debugDefaultTargetPlatformOverride = TargetPlatform.android; final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), ResolutionPreset.max, imageFormatGroup: ImageFormatGroup.yuv420, ); await cameraController.initialize(); - verify(CameraPlatform.instance - .initializeCamera(13, imageFormatGroup: ImageFormatGroup.yuv420)) - .called(1); + verify( + CameraPlatform.instance.initializeCamera( + 13, + imageFormatGroup: ImageFormatGroup.yuv420, + ), + ).called(1); }); - test('setDescription waits for initialize before calling dispose', - () async { + test( + 'setDescription waits for initialize before calling dispose', + () async { + final CameraController cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + imageFormatGroup: ImageFormatGroup.bgra8888, + ); + + final Completer initializeCompleter = Completer(); + when( + CameraPlatform.instance.initializeCamera( + mockInitializeCamera, + imageFormatGroup: ImageFormatGroup.bgra8888, + ), + ).thenAnswer((_) => initializeCompleter.future); + + unawaited(cameraController.initialize()); + + final Future setDescriptionFuture = cameraController + .setDescription( + const CameraDescription( + name: 'cam2', + lensDirection: CameraLensDirection.front, + sensorOrientation: 90, + ), + ); + verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera)); + + initializeCompleter.complete(); + + await setDescriptionFuture; + verify(CameraPlatform.instance.dispose(mockInitializeCamera)); + }, + ); + + test('prepareForVideoRecording() calls $CameraPlatform ', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', @@ -241,40 +306,7 @@ void main() { sensorOrientation: 90, ), ResolutionPreset.max, - imageFormatGroup: ImageFormatGroup.bgra8888, - ); - - final Completer initializeCompleter = Completer(); - when(CameraPlatform.instance.initializeCamera( - mockInitializeCamera, - imageFormatGroup: ImageFormatGroup.bgra8888, - )).thenAnswer( - (_) => initializeCompleter.future, ); - - unawaited(cameraController.initialize()); - - final Future setDescriptionFuture = cameraController.setDescription( - const CameraDescription( - name: 'cam2', - lensDirection: CameraLensDirection.front, - sensorOrientation: 90), - ); - verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera)); - - initializeCompleter.complete(); - - await setDescriptionFuture; - verify(CameraPlatform.instance.dispose(mockInitializeCamera)); - }); - - test('prepareForVideoRecording() calls $CameraPlatform ', () async { - final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); await cameraController.initialize(); await cameraController.prepareForVideoRecording(); @@ -284,11 +316,13 @@ void main() { test('takePicture() throws $CameraException when uninitialized ', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); expect( cameraController.takePicture(), throwsA( @@ -307,144 +341,179 @@ void main() { ); }); - test('takePicture() throws $CameraException when takePicture is true', - () async { - final CameraController cameraController = CameraController( + test( + 'takePicture() throws $CameraException when takePicture is true', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isTakingPicture: true); - expect( + cameraController.value = cameraController.value.copyWith( + isTakingPicture: true, + ); + expect( cameraController.takePicture(), - throwsA(isA().having( - (CameraException error) => error.description, - 'Previous capture has not returned yet.', - 'takePicture was called before the previous capture returned.', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'Previous capture has not returned yet.', + 'takePicture was called before the previous capture returned.', + ), + ), + ); + }, + ); test('takePicture() returns $XFile', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); final XFile xFile = await cameraController.takePicture(); expect(xFile.path, mockTakePicture.path); }); - test('takePicture() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'takePicture() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - mockPlatformException = true; - expect( + mockPlatformException = true; + expect( cameraController.takePicture(), - throwsA(isA().having( - (CameraException error) => error.description, - 'foo', - 'bar', - ))); - mockPlatformException = false; - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'foo', + 'bar', + ), + ), + ); + mockPlatformException = false; + }, + ); - test('startVideoRecording() throws $CameraException when uninitialized', - () async { - final CameraController cameraController = CameraController( + test( + 'startVideoRecording() throws $CameraException when uninitialized', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - expect( - cameraController.startVideoRecording(), - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) - .having( - (CameraException error) => error.description, - 'description', - 'startVideoRecording() was called on an uninitialized CameraController.', - ), - ), - ); - }); - test('startVideoRecording() throws $CameraException when recording videos', - () async { - final CameraController cameraController = CameraController( + expect( + cameraController.startVideoRecording(), + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'Uninitialized CameraController', + ) + .having( + (CameraException error) => error.description, + 'description', + 'startVideoRecording() was called on an uninitialized CameraController.', + ), + ), + ); + }, + ); + test( + 'startVideoRecording() throws $CameraException when recording videos', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); + await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isRecordingVideo: true); + cameraController.value = cameraController.value.copyWith( + isRecordingVideo: true, + ); - expect( + expect( cameraController.startVideoRecording(), - throwsA(isA().having( - (CameraException error) => error.description, - 'A video recording is already started.', - 'startVideoRecording was called when a recording is already started.', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'A video recording is already started.', + 'startVideoRecording was called when a recording is already started.', + ), + ), + ); + }, + ); - test('getMaxZoomLevel() throws $CameraException when uninitialized', - () async { - final CameraController cameraController = CameraController( + test( + 'getMaxZoomLevel() throws $CameraException when uninitialized', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - expect( - cameraController.getMaxZoomLevel, - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) - .having( - (CameraException error) => error.description, - 'description', - 'getMaxZoomLevel() was called on an uninitialized CameraController.', - ), - ), - ); - }); + expect( + cameraController.getMaxZoomLevel, + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'Uninitialized CameraController', + ) + .having( + (CameraException error) => error.description, + 'description', + 'getMaxZoomLevel() was called on an uninitialized CameraController.', + ), + ), + ); + }, + ); test('getMaxZoomLevel() throws $CameraException when disposed', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.dispose(); @@ -468,58 +537,105 @@ void main() { }); test( - 'getMaxZoomLevel() throws $CameraException when a platform exception occured.', - () async { - final CameraController cameraController = CameraController( + 'getMaxZoomLevel() throws $CameraException when a platform exception occured.', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); - when(CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera)) - .thenThrow(CameraException( - 'TEST_ERROR', - 'This is a test error messge', - )); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error messge'), + ); - expect( + expect( cameraController.getMaxZoomLevel, - throwsA(isA() - .having( - (CameraException error) => error.code, 'code', 'TEST_ERROR') - .having( - (CameraException error) => error.description, - 'description', - 'This is a test error messge', - ))); - }); + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'TEST_ERROR', + ) + .having( + (CameraException error) => error.description, + 'description', + 'This is a test error messge', + ), + ), + ); + }, + ); test('getMaxZoomLevel() returns max zoom level.', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera)) - .thenAnswer((_) => Future.value(42.0)); + when( + CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera), + ).thenAnswer((_) => Future.value(42.0)); final double maxZoomLevel = await cameraController.getMaxZoomLevel(); expect(maxZoomLevel, 42.0); }); - test('getMinZoomLevel() throws $CameraException when uninitialized', - () async { - final CameraController cameraController = CameraController( + test( + 'getMinZoomLevel() throws $CameraException when uninitialized', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + expect( + cameraController.getMinZoomLevel, + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'Uninitialized CameraController', + ) + .having( + (CameraException error) => error.description, + 'description', + 'getMinZoomLevel() was called on an uninitialized CameraController.', + ), + ), + ); + }, + ); + + test('getMinZoomLevel() throws $CameraException when disposed', () async { + final CameraController cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + await cameraController.initialize(); + await cameraController.dispose(); expect( cameraController.getMinZoomLevel, @@ -528,86 +644,69 @@ void main() { .having( (CameraException error) => error.code, 'code', - 'Uninitialized CameraController', + 'Disposed CameraController', ) .having( (CameraException error) => error.description, 'description', - 'getMinZoomLevel() was called on an uninitialized CameraController.', + 'getMinZoomLevel() was called on a disposed CameraController.', ), ), ); }); - test('getMinZoomLevel() throws $CameraException when disposed', () async { - final CameraController cameraController = CameraController( + test( + 'getMinZoomLevel() throws $CameraException when a platform exception occured.', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - - await cameraController.initialize(); - await cameraController.dispose(); - - expect( - cameraController.getMinZoomLevel, - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'Disposed CameraController', - ) - .having( - (CameraException error) => error.description, - 'description', - 'getMinZoomLevel() was called on a disposed CameraController.', - ), - ), - ); - }); - - test( - 'getMinZoomLevel() throws $CameraException when a platform exception occured.', - () async { - final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); - when(CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera)) - .thenThrow(CameraException( - 'TEST_ERROR', - 'This is a test error messge', - )); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error messge'), + ); - expect( + expect( cameraController.getMinZoomLevel, - throwsA(isA() - .having( - (CameraException error) => error.code, 'code', 'TEST_ERROR') - .having( - (CameraException error) => error.description, - 'description', - 'This is a test error messge', - ))); - }); + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'TEST_ERROR', + ) + .having( + (CameraException error) => error.description, + 'description', + 'This is a test error messge', + ), + ), + ); + }, + ); test('getMinZoomLevel() returns max zoom level.', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera)) - .thenAnswer((_) => Future.value(42.0)); + when( + CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera), + ).thenAnswer((_) => Future.value(42.0)); final double maxZoomLevel = await cameraController.getMinZoomLevel(); expect(maxZoomLevel, 42.0); @@ -615,11 +714,13 @@ void main() { test('setZoomLevel() throws $CameraException when uninitialized', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); expect( () => cameraController.setZoomLevel(42.0), @@ -641,11 +742,13 @@ void main() { test('setZoomLevel() throws $CameraException when disposed', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.dispose(); @@ -669,492 +772,658 @@ void main() { }); test( - 'setZoomLevel() throws $CameraException when a platform exception occured.', - () async { - final CameraController cameraController = CameraController( + 'setZoomLevel() throws $CameraException when a platform exception occured.', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); - when(CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0)) - .thenThrow(CameraException( - 'TEST_ERROR', - 'This is a test error messge', - )); + await cameraController.initialize(); + when( + CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error messge'), + ); - expect( + expect( () => cameraController.setZoomLevel(42), - throwsA(isA() - .having( - (CameraException error) => error.code, 'code', 'TEST_ERROR') - .having( - (CameraException error) => error.description, - 'description', - 'This is a test error messge', - ))); + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'TEST_ERROR', + ) + .having( + (CameraException error) => error.description, + 'description', + 'This is a test error messge', + ), + ), + ); - reset(CameraPlatform.instance); - }); + reset(CameraPlatform.instance); + }, + ); test( - 'setZoomLevel() completes and calls method channel with correct value.', - () async { - final CameraController cameraController = CameraController( + 'setZoomLevel() completes and calls method channel with correct value.', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); - await cameraController.setZoomLevel(42.0); + await cameraController.initialize(); + await cameraController.setZoomLevel(42.0); - verify(CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0)) - .called(1); - }); + verify( + CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0), + ).called(1); + }, + ); test('setFlashMode() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.setFlashMode(FlashMode.always); - verify(CameraPlatform.instance - .setFlashMode(cameraController.cameraId, FlashMode.always)) - .called(1); + verify( + CameraPlatform.instance.setFlashMode( + cameraController.cameraId, + FlashMode.always, + ), + ).called(1); }); - test('setFlashMode() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'setFlashMode() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - when(CameraPlatform.instance - .setFlashMode(cameraController.cameraId, FlashMode.always)) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setFlashMode( + cameraController.cameraId, + FlashMode.always, + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.setFlashMode(FlashMode.always), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('setExposureMode() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.setExposureMode(ExposureMode.auto); - verify(CameraPlatform.instance - .setExposureMode(cameraController.cameraId, ExposureMode.auto)) - .called(1); + verify( + CameraPlatform.instance.setExposureMode( + cameraController.cameraId, + ExposureMode.auto, + ), + ).called(1); }); - test('setExposureMode() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'setExposureMode() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - when(CameraPlatform.instance - .setExposureMode(cameraController.cameraId, ExposureMode.auto)) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setExposureMode( + cameraController.cameraId, + ExposureMode.auto, + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.setExposureMode(ExposureMode.auto), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('setExposurePoint() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.setExposurePoint(const Offset(0.5, 0.5)); - verify(CameraPlatform.instance.setExposurePoint( - cameraController.cameraId, const Point(0.5, 0.5))) - .called(1); + verify( + CameraPlatform.instance.setExposurePoint( + cameraController.cameraId, + const Point(0.5, 0.5), + ), + ).called(1); }); - test('setExposurePoint() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'setExposurePoint() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - when(CameraPlatform.instance.setExposurePoint( - cameraController.cameraId, const Point(0.5, 0.5))) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setExposurePoint( + cameraController.cameraId, + const Point(0.5, 0.5), + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.setExposurePoint(const Offset(0.5, 0.5)), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('getMinExposureOffset() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .thenAnswer((_) => Future.value(0.0)); + when( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).thenAnswer((_) => Future.value(0.0)); await cameraController.getMinExposureOffset(); - verify(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .called(1); + verify( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).called(1); }); - test('getMinExposureOffset() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'getMinExposureOffset() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - when(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .thenThrow( - CameraException( - 'TEST_ERROR', - 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getMinExposureOffset( + cameraController.cameraId, + ), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error message'), + ); - expect( + expect( cameraController.getMinExposureOffset(), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('getMaxExposureOffset() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .thenAnswer((_) => Future.value(1.0)); + when( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).thenAnswer((_) => Future.value(1.0)); await cameraController.getMaxExposureOffset(); - verify(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .called(1); + verify( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).called(1); }); - test('getMaxExposureOffset() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'getMaxExposureOffset() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - when(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .thenThrow( - CameraException( - 'TEST_ERROR', - 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getMaxExposureOffset( + cameraController.cameraId, + ), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error message'), + ); - expect( + expect( cameraController.getMaxExposureOffset(), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('getExposureOffsetStepSize() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .thenAnswer((_) => Future.value(0.0)); + when( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).thenAnswer((_) => Future.value(0.0)); await cameraController.getExposureOffsetStepSize(); - verify(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .called(1); + verify( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).called(1); }); test( - 'getExposureOffsetStepSize() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + 'getExposureOffsetStepSize() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - - when(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .thenThrow( - CameraException( - 'TEST_ERROR', - 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error message'), + ); - expect( + expect( cameraController.getExposureOffsetStepSize(), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('setExposureOffset() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => -1.0); - when(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => 2.0); - when(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .thenAnswer((_) async => 1.0); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 1.0)) - .thenAnswer((_) async => 1.0); + when( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => -1.0); + when( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => 2.0); + when( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).thenAnswer((_) async => 1.0); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 1.0, + ), + ).thenAnswer((_) async => 1.0); await cameraController.setExposureOffset(1.0); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 1.0)) - .called(1); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 1.0, + ), + ).called(1); }); - test('setExposureOffset() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'setExposureOffset() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - when(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => -1.0); - when(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => 2.0); - when(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .thenAnswer((_) async => 1.0); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 1.0)) - .thenThrow( - CameraException( - 'TEST_ERROR', - 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMinExposureOffset( + cameraController.cameraId, + ), + ).thenAnswer((_) async => -1.0); + when( + CameraPlatform.instance.getMaxExposureOffset( + cameraController.cameraId, + ), + ).thenAnswer((_) async => 2.0); + when( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).thenAnswer((_) async => 1.0); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 1.0, + ), + ).thenThrow( + CameraException('TEST_ERROR', 'This is a test error message'), + ); - expect( + expect( cameraController.setExposureOffset(1.0), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test( - 'setExposureOffset() throws $CameraException when offset is out of bounds', - () async { - final CameraController cameraController = CameraController( + 'setExposureOffset() throws $CameraException when offset is out of bounds', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - when(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => -1.0); - when(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => 2.0); - when(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .thenAnswer((_) async => 1.0); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.0)) - .thenAnswer((_) async => 0.0); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -1.0)) - .thenAnswer((_) async => 0.0); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 2.0)) - .thenAnswer((_) async => 0.0); - - expect( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMinExposureOffset( + cameraController.cameraId, + ), + ).thenAnswer((_) async => -1.0); + when( + CameraPlatform.instance.getMaxExposureOffset( + cameraController.cameraId, + ), + ).thenAnswer((_) async => 2.0); + when( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).thenAnswer((_) async => 1.0); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.0, + ), + ).thenAnswer((_) async => 0.0); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -1.0, + ), + ).thenAnswer((_) async => 0.0); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 2.0, + ), + ).thenAnswer((_) async => 0.0); + + expect( cameraController.setExposureOffset(3.0), - throwsA(isA().having( - (CameraException error) => error.description, - 'exposureOffsetOutOfBounds', - 'The provided exposure offset was outside the supported range for this device.', - ))); - expect( + throwsA( + isA().having( + (CameraException error) => error.description, + 'exposureOffsetOutOfBounds', + 'The provided exposure offset was outside the supported range for this device.', + ), + ), + ); + expect( cameraController.setExposureOffset(-2.0), - throwsA(isA().having( - (CameraException error) => error.description, - 'exposureOffsetOutOfBounds', - 'The provided exposure offset was outside the supported range for this device.', - ))); - - await cameraController.setExposureOffset(0.0); - await cameraController.setExposureOffset(-1.0); - await cameraController.setExposureOffset(2.0); - - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.0)) - .called(1); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -1.0)) - .called(1); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 2.0)) - .called(1); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'exposureOffsetOutOfBounds', + 'The provided exposure offset was outside the supported range for this device.', + ), + ), + ); + + await cameraController.setExposureOffset(0.0); + await cameraController.setExposureOffset(-1.0); + await cameraController.setExposureOffset(2.0); + + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.0, + ), + ).called(1); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -1.0, + ), + ).called(1); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 2.0, + ), + ).called(1); + }, + ); test('setExposureOffset() rounds offset to nearest step', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - when(CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => -1.2); - when(CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId)) - .thenAnswer((_) async => 1.2); - when(CameraPlatform.instance - .getExposureOffsetStepSize(cameraController.cameraId)) - .thenAnswer((_) async => 0.4); - - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -1.2)) - .thenAnswer((_) async => -1.2); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -0.8)) - .thenAnswer((_) async => -0.8); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -0.4)) - .thenAnswer((_) async => -0.4); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.0)) - .thenAnswer((_) async => 0.0); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.4)) - .thenAnswer((_) async => 0.4); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.8)) - .thenAnswer((_) async => 0.8); - when(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 1.2)) - .thenAnswer((_) async => 1.2); + when( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => -1.2); + when( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => 1.2); + when( + CameraPlatform.instance.getExposureOffsetStepSize( + cameraController.cameraId, + ), + ).thenAnswer((_) async => 0.4); + + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -1.2, + ), + ).thenAnswer((_) async => -1.2); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -0.8, + ), + ).thenAnswer((_) async => -0.8); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -0.4, + ), + ).thenAnswer((_) async => -0.4); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.0, + ), + ).thenAnswer((_) async => 0.0); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.4, + ), + ).thenAnswer((_) async => 0.4); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.8, + ), + ).thenAnswer((_) async => 0.8); + when( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 1.2, + ), + ).thenAnswer((_) async => 1.2); await cameraController.setExposureOffset(1.2); await cameraController.setExposureOffset(-1.2); @@ -1173,274 +1442,371 @@ void main() { await cameraController.setExposureOffset(-0.6); await cameraController.setExposureOffset(-0.7); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.8)) - .called(2); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -0.8)) - .called(2); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.0)) - .called(2); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, 0.4)) - .called(4); - verify(CameraPlatform.instance - .setExposureOffset(cameraController.cameraId, -0.4)) - .called(4); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.8, + ), + ).called(2); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -0.8, + ), + ).called(2); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.0, + ), + ).called(2); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + 0.4, + ), + ).called(4); + verify( + CameraPlatform.instance.setExposureOffset( + cameraController.cameraId, + -0.4, + ), + ).called(4); }); test('pausePreview() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - cameraController.value = cameraController.value - .copyWith(deviceOrientation: DeviceOrientation.portraitUp); + cameraController.value = cameraController.value.copyWith( + deviceOrientation: DeviceOrientation.portraitUp, + ); await cameraController.pausePreview(); - verify(CameraPlatform.instance.pausePreview(cameraController.cameraId)) - .called(1); + verify( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ).called(1); expect(cameraController.value.isPreviewPaused, equals(true)); - expect(cameraController.value.previewPauseOrientation, - DeviceOrientation.portraitUp); + expect( + cameraController.value.previewPauseOrientation, + DeviceOrientation.portraitUp, + ); }); - test('pausePreview() does not call $CameraPlatform when already paused', - () async { - final CameraController cameraController = CameraController( + test( + 'pausePreview() does not call $CameraPlatform when already paused', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isPreviewPaused: true); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: true, + ); - await cameraController.pausePreview(); + await cameraController.pausePreview(); - verifyNever( - CameraPlatform.instance.pausePreview(cameraController.cameraId)); - expect(cameraController.value.isPreviewPaused, equals(true)); - }); + verifyNever( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ); + expect(cameraController.value.isPreviewPaused, equals(true)); + }, + ); test( - 'pausePreview() sets previewPauseOrientation according to locked orientation', - () async { - final CameraController cameraController = CameraController( + 'pausePreview() sets previewPauseOrientation according to locked orientation', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( isPreviewPaused: false, deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: - Optional.of(DeviceOrientation.landscapeRight)); + lockedCaptureOrientation: Optional.of( + DeviceOrientation.landscapeRight, + ), + ); - await cameraController.pausePreview(); + await cameraController.pausePreview(); - expect(cameraController.value.deviceOrientation, - equals(DeviceOrientation.portraitUp)); - expect(cameraController.value.previewPauseOrientation, - equals(DeviceOrientation.landscapeRight)); - }); + expect( + cameraController.value.deviceOrientation, + equals(DeviceOrientation.portraitUp), + ); + expect( + cameraController.value.previewPauseOrientation, + equals(DeviceOrientation.landscapeRight), + ); + }, + ); - test('pausePreview() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'pausePreview() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - when(CameraPlatform.instance.pausePreview(cameraController.cameraId)) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.pausePreview(), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('resumePreview() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isPreviewPaused: true); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: true, + ); await cameraController.resumePreview(); - verify(CameraPlatform.instance.resumePreview(cameraController.cameraId)) - .called(1); + verify( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ).called(1); expect(cameraController.value.isPreviewPaused, equals(false)); }); - test('resumePreview() does not call $CameraPlatform when not paused', - () async { - final CameraController cameraController = CameraController( + test( + 'resumePreview() does not call $CameraPlatform when not paused', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isPreviewPaused: false); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: false, + ); - await cameraController.resumePreview(); + await cameraController.resumePreview(); - verifyNever( - CameraPlatform.instance.resumePreview(cameraController.cameraId)); - expect(cameraController.value.isPreviewPaused, equals(false)); - }); + verifyNever( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ); + expect(cameraController.value.isPreviewPaused, equals(false)); + }, + ); - test('resumePreview() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + test( + 'resumePreview() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - cameraController.value = - cameraController.value.copyWith(isPreviewPaused: true); - when(CameraPlatform.instance.resumePreview(cameraController.cameraId)) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: true, + ); + when( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.resumePreview(), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('lockCaptureOrientation() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.lockCaptureOrientation(); - expect(cameraController.value.lockedCaptureOrientation, - equals(DeviceOrientation.portraitUp)); - await cameraController - .lockCaptureOrientation(DeviceOrientation.landscapeRight); - expect(cameraController.value.lockedCaptureOrientation, - equals(DeviceOrientation.landscapeRight)); - - verify(CameraPlatform.instance.lockCaptureOrientation( - cameraController.cameraId, DeviceOrientation.portraitUp)) - .called(1); - verify(CameraPlatform.instance.lockCaptureOrientation( - cameraController.cameraId, DeviceOrientation.landscapeRight)) - .called(1); + expect( + cameraController.value.lockedCaptureOrientation, + equals(DeviceOrientation.portraitUp), + ); + await cameraController.lockCaptureOrientation( + DeviceOrientation.landscapeRight, + ); + expect( + cameraController.value.lockedCaptureOrientation, + equals(DeviceOrientation.landscapeRight), + ); + + verify( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.portraitUp, + ), + ).called(1); + verify( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.landscapeRight, + ), + ).called(1); }); test( - 'lockCaptureOrientation() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + 'lockCaptureOrientation() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - when(CameraPlatform.instance.lockCaptureOrientation( - cameraController.cameraId, DeviceOrientation.portraitUp)) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.portraitUp, + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); test('unlockCaptureOrientation() calls $CameraPlatform', () async { final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); await cameraController.initialize(); await cameraController.unlockCaptureOrientation(); expect(cameraController.value.lockedCaptureOrientation, equals(null)); - verify(CameraPlatform.instance - .unlockCaptureOrientation(cameraController.cameraId)) - .called(1); + verify( + CameraPlatform.instance.unlockCaptureOrientation( + cameraController.cameraId, + ), + ).called(1); }); test( - 'unlockCaptureOrientation() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( + 'unlockCaptureOrientation() throws $CameraException on $PlatformException', + () async { + final CameraController cameraController = CameraController( const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90), - ResolutionPreset.max); - await cameraController.initialize(); - when(CameraPlatform.instance - .unlockCaptureOrientation(cameraController.cameraId)) - .thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.unlockCaptureOrientation( + cameraController.cameraId, + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); - expect( + expect( cameraController.unlockCaptureOrientation(), - throwsA(isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ))); - }); + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); }); } @@ -1451,14 +1817,13 @@ class MockCameraPlatform extends Mock Future initializeCamera( int? cameraId, { ImageFormatGroup? imageFormatGroup = ImageFormatGroup.unknown, - }) async => - super.noSuchMethod(Invocation.method( - #initializeCamera, - [cameraId], - { - #imageFormatGroup: imageFormatGroup, - }, - )); + }) async => super.noSuchMethod( + Invocation.method( + #initializeCamera, + [cameraId], + {#imageFormatGroup: imageFormatGroup}, + ), + ); @override Future dispose(int? cameraId) async { @@ -1471,7 +1836,9 @@ class MockCameraPlatform extends Mock @override Future createCameraWithSettings( - CameraDescription cameraDescription, MediaSettings? mediaSettings) => + CameraDescription cameraDescription, + MediaSettings? mediaSettings, + ) => mockPlatformException ? throw PlatformException(code: 'foo', message: 'bar') : Future.value(mockInitializeCamera); @@ -1481,8 +1848,7 @@ class MockCameraPlatform extends Mock CameraDescription description, ResolutionPreset? resolutionPreset, { bool enableAudio = false, - }) => - createCameraWithSettings(description, null); + }) => createCameraWithSettings(description, null); @override Stream onCameraInitialized(int cameraId) => @@ -1499,12 +1865,14 @@ class MockCameraPlatform extends Mock @override Stream onDeviceOrientationChanged() => Stream.value( - mockOnDeviceOrientationChangedEvent); + mockOnDeviceOrientationChangedEvent, + ); @override - Future takePicture(int cameraId) => mockPlatformException - ? throw PlatformException(code: 'foo', message: 'bar') - : Future.value(mockTakePicture); + Future takePicture(int cameraId) => + mockPlatformException + ? throw PlatformException(code: 'foo', message: 'bar') + : Future.value(mockTakePicture); @override Future prepareForVideoRecording() async => @@ -1526,92 +1894,111 @@ class MockCameraPlatform extends Mock @override Future lockCaptureOrientation( - int? cameraId, DeviceOrientation? orientation) async => - super.noSuchMethod(Invocation.method( - #lockCaptureOrientation, [cameraId, orientation])); + int? cameraId, + DeviceOrientation? orientation, + ) async => super.noSuchMethod( + Invocation.method(#lockCaptureOrientation, [ + cameraId, + orientation, + ]), + ); @override Future unlockCaptureOrientation(int? cameraId) async => super.noSuchMethod( - Invocation.method(#unlockCaptureOrientation, [cameraId])); + Invocation.method(#unlockCaptureOrientation, [cameraId]), + ); @override Future pausePreview(int? cameraId) async => super.noSuchMethod(Invocation.method(#pausePreview, [cameraId])); @override - Future resumePreview(int? cameraId) async => super - .noSuchMethod(Invocation.method(#resumePreview, [cameraId])); + Future resumePreview(int? cameraId) async => super.noSuchMethod( + Invocation.method(#resumePreview, [cameraId]), + ); @override - Future getMaxZoomLevel(int? cameraId) async => super.noSuchMethod( - Invocation.method(#getMaxZoomLevel, [cameraId]), - returnValue: Future.value(1.0), - ) as Future; + Future getMaxZoomLevel(int? cameraId) async => + super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, [cameraId]), + returnValue: Future.value(1.0), + ) + as Future; @override - Future getMinZoomLevel(int? cameraId) async => super.noSuchMethod( - Invocation.method(#getMinZoomLevel, [cameraId]), - returnValue: Future.value(0.0), - ) as Future; + Future getMinZoomLevel(int? cameraId) async => + super.noSuchMethod( + Invocation.method(#getMinZoomLevel, [cameraId]), + returnValue: Future.value(0.0), + ) + as Future; @override Future setZoomLevel(int? cameraId, double? zoom) async => super.noSuchMethod( - Invocation.method(#setZoomLevel, [cameraId, zoom])); + Invocation.method(#setZoomLevel, [cameraId, zoom]), + ); @override Future setFlashMode(int? cameraId, FlashMode? mode) async => super.noSuchMethod( - Invocation.method(#setFlashMode, [cameraId, mode])); + Invocation.method(#setFlashMode, [cameraId, mode]), + ); @override Future setExposureMode(int? cameraId, ExposureMode? mode) async => super.noSuchMethod( - Invocation.method(#setExposureMode, [cameraId, mode])); + Invocation.method(#setExposureMode, [cameraId, mode]), + ); @override Future setExposurePoint(int? cameraId, Point? point) async => super.noSuchMethod( - Invocation.method(#setExposurePoint, [cameraId, point])); + Invocation.method(#setExposurePoint, [cameraId, point]), + ); @override Future getMinExposureOffset(int? cameraId) async => super.noSuchMethod( - Invocation.method(#getMinExposureOffset, [cameraId]), - returnValue: Future.value(0.0), - ) as Future; + Invocation.method(#getMinExposureOffset, [cameraId]), + returnValue: Future.value(0.0), + ) + as Future; @override Future getMaxExposureOffset(int? cameraId) async => super.noSuchMethod( - Invocation.method(#getMaxExposureOffset, [cameraId]), - returnValue: Future.value(1.0), - ) as Future; + Invocation.method(#getMaxExposureOffset, [cameraId]), + returnValue: Future.value(1.0), + ) + as Future; @override Future getExposureOffsetStepSize(int? cameraId) async => super.noSuchMethod( - Invocation.method(#getExposureOffsetStepSize, [cameraId]), - returnValue: Future.value(1.0), - ) as Future; + Invocation.method(#getExposureOffsetStepSize, [cameraId]), + returnValue: Future.value(1.0), + ) + as Future; @override Future setExposureOffset(int? cameraId, double? offset) async => super.noSuchMethod( - Invocation.method(#setExposureOffset, [cameraId, offset]), - returnValue: Future.value(1.0), - ) as Future; + Invocation.method(#setExposureOffset, [cameraId, offset]), + returnValue: Future.value(1.0), + ) + as Future; } class MockCameraDescription extends CameraDescription { /// Creates a new camera description with the given properties. const MockCameraDescription() - : super( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ); + : super( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ); @override CameraLensDirection get lensDirection => CameraLensDirection.back; diff --git a/packages/camera/camera/test/camera_value_test.dart b/packages/camera/camera/test/camera_value_test.dart index 2c5ff71dcee..2ee73935d5a 100644 --- a/packages/camera/camera/test/camera_value_test.dart +++ b/packages/camera/camera/test/camera_value_test.dart @@ -43,15 +43,18 @@ void main() { expect(cameraValue.exposurePointSupported, true); expect(cameraValue.deviceOrientation, DeviceOrientation.portraitUp); expect( - cameraValue.lockedCaptureOrientation, DeviceOrientation.portraitUp); + cameraValue.lockedCaptureOrientation, + DeviceOrientation.portraitUp, + ); expect(cameraValue.recordingOrientation, DeviceOrientation.portraitUp); expect(cameraValue.isPreviewPaused, false); expect(cameraValue.previewPauseOrientation, DeviceOrientation.portraitUp); }); test('Can be created as uninitialized', () { - const CameraValue cameraValue = - CameraValue.uninitialized(FakeController.fakeDescription); + const CameraValue cameraValue = CameraValue.uninitialized( + FakeController.fakeDescription, + ); expect(cameraValue, isA()); expect(cameraValue.isInitialized, isFalse); @@ -73,8 +76,9 @@ void main() { }); test('Can be copied with isInitialized', () { - const CameraValue cv = - CameraValue.uninitialized(FakeController.fakeDescription); + const CameraValue cv = CameraValue.uninitialized( + FakeController.fakeDescription, + ); final CameraValue cameraValue = cv.copyWith(isInitialized: true); expect(cameraValue, isA()); @@ -97,17 +101,21 @@ void main() { }); test('Has aspectRatio after setting size', () { - const CameraValue cv = - CameraValue.uninitialized(FakeController.fakeDescription); - final CameraValue cameraValue = - cv.copyWith(isInitialized: true, previewSize: const Size(20, 10)); + const CameraValue cv = CameraValue.uninitialized( + FakeController.fakeDescription, + ); + final CameraValue cameraValue = cv.copyWith( + isInitialized: true, + previewSize: const Size(20, 10), + ); expect(cameraValue.aspectRatio, 2.0); }); test('hasError is true after setting errorDescription', () { - const CameraValue cv = - CameraValue.uninitialized(FakeController.fakeDescription); + const CameraValue cv = CameraValue.uninitialized( + FakeController.fakeDescription, + ); final CameraValue cameraValue = cv.copyWith(errorDescription: 'error'); expect(cameraValue.hasError, isTrue); @@ -115,12 +123,14 @@ void main() { }); test('Recording paused is false when not recording', () { - const CameraValue cv = - CameraValue.uninitialized(FakeController.fakeDescription); + const CameraValue cv = CameraValue.uninitialized( + FakeController.fakeDescription, + ); final CameraValue cameraValue = cv.copyWith( - isInitialized: true, - isRecordingVideo: false, - isRecordingPaused: true); + isInitialized: true, + isRecordingVideo: false, + isRecordingPaused: true, + ); expect(cameraValue.isRecordingPaused, isFalse); }); @@ -147,21 +157,22 @@ void main() { ); expect( - cameraValue.toString(), - 'CameraValue(isRecordingVideo: false, isInitialized: false, ' - 'errorDescription: null, previewSize: Size(10.0, 10.0), ' - 'isStreamingImages: false, flashMode: FlashMode.auto, ' - 'exposureMode: ExposureMode.auto, focusMode: FocusMode.auto, ' - 'exposurePointSupported: true, focusPointSupported: true, ' - 'deviceOrientation: DeviceOrientation.portraitUp, ' - 'lockedCaptureOrientation: DeviceOrientation.portraitUp, ' - 'recordingOrientation: DeviceOrientation.portraitUp, ' - 'isPreviewPaused: true, ' - 'previewPausedOrientation: DeviceOrientation.portraitUp, ' - // CameraDescription.toString is defined in the platform interface - // package, so don't assert a specific value for it, only that - // whatever it returns is inserted as expected. - 'description: ${FakeController.fakeDescription})'); + cameraValue.toString(), + 'CameraValue(isRecordingVideo: false, isInitialized: false, ' + 'errorDescription: null, previewSize: Size(10.0, 10.0), ' + 'isStreamingImages: false, flashMode: FlashMode.auto, ' + 'exposureMode: ExposureMode.auto, focusMode: FocusMode.auto, ' + 'exposurePointSupported: true, focusPointSupported: true, ' + 'deviceOrientation: DeviceOrientation.portraitUp, ' + 'lockedCaptureOrientation: DeviceOrientation.portraitUp, ' + 'recordingOrientation: DeviceOrientation.portraitUp, ' + 'isPreviewPaused: true, ' + 'previewPausedOrientation: DeviceOrientation.portraitUp, ' + // CameraDescription.toString is defined in the platform interface + // package, so don't assert a specific value for it, only that + // whatever it returns is inserted as expected. + 'description: ${FakeController.fakeDescription})', + ); }); }); } diff --git a/packages/camera/camera_android/CHANGELOG.md b/packages/camera/camera_android/CHANGELOG.md index 572080a2cb7..c150cd658ea 100644 --- a/packages/camera/camera_android/CHANGELOG.md +++ b/packages/camera/camera_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.10.10+5 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/camera/camera_android/example/integration_test/camera_test.dart b/packages/camera/camera_android/example/integration_test/camera_test.dart index 2ff36722ef1..24c00b8a0d2 100644 --- a/packages/camera/camera_android/example/integration_test/camera_test.dart +++ b/packages/camera/camera_android/example/integration_test/camera_test.dart @@ -30,13 +30,13 @@ void main() { final Map presetExpectedSizes = { - ResolutionPreset.low: const Size(240, 320), - ResolutionPreset.medium: const Size(480, 720), - ResolutionPreset.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + ResolutionPreset.low: const Size(240, 320), + ResolutionPreset.medium: const Size(480, 720), + ResolutionPreset.high: const Size(720, 1280), + ResolutionPreset.veryHigh: const Size(1080, 1920), + ResolutionPreset.ultraHigh: const Size(2160, 3840), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -52,7 +52,9 @@ void main() { // automatic code to fall back to smaller sizes when we need to. Returns // whether the image is exactly the desired resolution. Future testCaptureVideoResolution( - CameraController controller, ResolutionPreset preset) async { + CameraController controller, + ResolutionPreset preset, + ) async { final Size expectedSize = presetExpectedSizes[preset]!; // Take Video @@ -62,15 +64,18 @@ void main() { // Load video metadata final File videoFile = File(file.path); - final VideoPlayerController videoController = - VideoPlayerController.file(videoFile); + final VideoPlayerController videoController = VideoPlayerController.file( + videoFile, + ); await videoController.initialize(); final Size video = videoController.value.size; // Verify image dimensions are as expected expect(video, isNotNull); return assertExpectedDimensions( - expectedSize, Size(video.height, video.width)); + expectedSize, + Size(video.height, video.width), + ); } testWidgets( @@ -86,14 +91,19 @@ void main() { for (final MapEntry preset in presetExpectedSizes.entries) { final CameraController controller = CameraController( - cameraDescription, - mediaSettings: MediaSettings(resolutionPreset: preset.key)); + cameraDescription, + mediaSettings: MediaSettings(resolutionPreset: preset.key), + ); await controller.initialize(); await controller.prepareForVideoRecording(); - final bool presetExactlySupported = - await testCaptureVideoResolution(controller, preset.key); - assert(!(!previousPresetExactlySupported && presetExactlySupported), - 'The camera took higher resolution pictures at a lower resolution.'); + final bool presetExactlySupported = await testCaptureVideoResolution( + controller, + preset.key, + ); + assert( + !(!previousPresetExactlySupported && presetExactlySupported), + 'The camera took higher resolution pictures at a lower resolution.', + ); previousPresetExactlySupported = presetExactlySupported; await controller.dispose(); } @@ -175,9 +185,9 @@ void main() { } catch (err) { expect(err, isA()); expect( - (err as PlatformException).message, - equals( - 'Device does not support switching the camera while recording')); + (err as PlatformException).message, + equals('Device does not support switching the camera while recording'), + ); failed = true; } @@ -205,55 +215,50 @@ void main() { expect(controller.description, cameras[1]); }); - testWidgets( - 'image streaming', - (WidgetTester tester) async { - final List cameras = - await CameraPlatform.instance.availableCameras(); - if (cameras.isEmpty) { - return; - } + testWidgets('image streaming', (WidgetTester tester) async { + final List cameras = + await CameraPlatform.instance.availableCameras(); + if (cameras.isEmpty) { + return; + } - final CameraController controller = CameraController(cameras[0]); + final CameraController controller = CameraController(cameras[0]); - await controller.initialize(); - bool isDetecting = false; + await controller.initialize(); + bool isDetecting = false; - await controller.startImageStream((CameraImageData image) { - if (isDetecting) { - return; - } + await controller.startImageStream((CameraImageData image) { + if (isDetecting) { + return; + } - isDetecting = true; + isDetecting = true; - expectLater(image, isNotNull).whenComplete(() => isDetecting = false); - }); + expectLater(image, isNotNull).whenComplete(() => isDetecting = false); + }); - expect(controller.value.isStreamingImages, true); + expect(controller.value.isStreamingImages, true); - sleep(const Duration(milliseconds: 500)); + sleep(const Duration(milliseconds: 500)); - await controller.stopImageStream(); - await controller.dispose(); - }, - ); + await controller.stopImageStream(); + await controller.dispose(); + }); - testWidgets( - 'recording with image stream', - (WidgetTester tester) async { - final List cameras = - await CameraPlatform.instance.availableCameras(); - if (cameras.isEmpty) { - return; - } + testWidgets('recording with image stream', (WidgetTester tester) async { + final List cameras = + await CameraPlatform.instance.availableCameras(); + if (cameras.isEmpty) { + return; + } - final CameraController controller = CameraController(cameras[0]); + final CameraController controller = CameraController(cameras[0]); - await controller.initialize(); - bool isDetecting = false; + await controller.initialize(); + bool isDetecting = false; - await controller.startVideoRecording( - streamCallback: (CameraImageData image) { + await controller.startVideoRecording( + streamCallback: (CameraImageData image) { if (isDetecting) { return; } @@ -261,21 +266,21 @@ void main() { isDetecting = true; expectLater(image, isNotNull); - }); + }, + ); - expect(controller.value.isStreamingImages, true); + expect(controller.value.isStreamingImages, true); - // Stopping recording before anything is recorded will throw, per - // https://developer.android.com/reference/android/media/MediaRecorder.html#stop() - // so delay long enough to ensure that some data is recorded. - await Future.delayed(const Duration(seconds: 2)); + // Stopping recording before anything is recorded will throw, per + // https://developer.android.com/reference/android/media/MediaRecorder.html#stop() + // so delay long enough to ensure that some data is recorded. + await Future.delayed(const Duration(seconds: 2)); - await controller.stopVideoRecording(); - await controller.dispose(); + await controller.stopVideoRecording(); + await controller.dispose(); - expect(controller.value.isStreamingImages, false); - }, - ); + expect(controller.value.isStreamingImages, false); + }); group('Camera settings', () { Future getCamera() async { @@ -316,7 +321,9 @@ void main() { final CameraController controller = CameraController( cameraDescription, mediaSettings: MediaSettings( - resolutionPreset: ResolutionPreset.medium, fps: fps), + resolutionPreset: ResolutionPreset.medium, + fps: fps, + ), ); await startRecording(controller); @@ -347,8 +354,9 @@ void main() { final CameraController controller = CameraController( cameraDescription, mediaSettings: MediaSettings( - resolutionPreset: ResolutionPreset.medium, - videoBitrate: videoBitrate), + resolutionPreset: ResolutionPreset.medium, + videoBitrate: videoBitrate, + ), ); await startRecording(controller); diff --git a/packages/camera/camera_android/example/lib/camera_controller.dart b/packages/camera/camera_android/example/lib/camera_controller.dart index 17308a4e0de..6eb6b753e0e 100644 --- a/packages/camera/camera_android/example/lib/camera_controller.dart +++ b/packages/camera/camera_android/example/lib/camera_controller.dart @@ -33,19 +33,19 @@ class CameraValue { /// Creates a new camera controller state for an uninitialized controller. const CameraValue.uninitialized(CameraDescription description) - : this( - isInitialized: false, - isRecordingVideo: false, - isTakingPicture: false, - isStreamingImages: false, - isRecordingPaused: false, - flashMode: FlashMode.auto, - exposureMode: ExposureMode.auto, - focusMode: FocusMode.auto, - deviceOrientation: DeviceOrientation.portraitUp, - isPreviewPaused: false, - description: description, - ); + : this( + isInitialized: false, + isRecordingVideo: false, + isTakingPicture: false, + isStreamingImages: false, + isRecordingPaused: false, + flashMode: FlashMode.auto, + exposureMode: ExposureMode.auto, + focusMode: FocusMode.auto, + deviceOrientation: DeviceOrientation.portraitUp, + isPreviewPaused: false, + description: description, + ); /// True after [CameraController.initialize] has completed successfully. final bool isInitialized; @@ -131,17 +131,20 @@ class CameraValue { exposureMode: exposureMode ?? this.exposureMode, focusMode: focusMode ?? this.focusMode, deviceOrientation: deviceOrientation ?? this.deviceOrientation, - lockedCaptureOrientation: lockedCaptureOrientation == null - ? this.lockedCaptureOrientation - : lockedCaptureOrientation.orNull, - recordingOrientation: recordingOrientation == null - ? this.recordingOrientation - : recordingOrientation.orNull, + lockedCaptureOrientation: + lockedCaptureOrientation == null + ? this.lockedCaptureOrientation + : lockedCaptureOrientation.orNull, + recordingOrientation: + recordingOrientation == null + ? this.recordingOrientation + : recordingOrientation.orNull, isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused, description: description ?? this.description, - previewPauseOrientation: previewPauseOrientation == null - ? this.previewPauseOrientation - : previewPauseOrientation.orNull, + previewPauseOrientation: + previewPauseOrientation == null + ? this.previewPauseOrientation + : previewPauseOrientation.orNull, ); } @@ -173,11 +176,12 @@ class CameraController extends ValueNotifier { /// Creates a new camera controller in an uninitialized state. CameraController( CameraDescription cameraDescription, { - MediaSettings mediaSettings = - const MediaSettings(resolutionPreset: ResolutionPreset.medium), + MediaSettings mediaSettings = const MediaSettings( + resolutionPreset: ResolutionPreset.medium, + ), this.imageFormatGroup, - }) : _mediaSettings = mediaSettings, - super(CameraValue.uninitialized(cameraDescription)); + }) : _mediaSettings = mediaSettings, + super(CameraValue.uninitialized(cameraDescription)); /// final MediaSettings _mediaSettings; @@ -196,7 +200,7 @@ class CameraController extends ValueNotifier { StreamSubscription? _imageStreamSubscription; FutureOr? _initCalled; StreamSubscription? - _deviceOrientationSubscription; + _deviceOrientationSubscription; /// The camera identifier with which the controller is associated. int get cameraId => _cameraId; @@ -211,22 +215,21 @@ class CameraController extends ValueNotifier { _deviceOrientationSubscription = CameraPlatform.instance .onDeviceOrientationChanged() .listen((DeviceOrientationChangedEvent event) { - value = value.copyWith( - deviceOrientation: event.orientation, - ); - }); + value = value.copyWith(deviceOrientation: event.orientation); + }); _cameraId = await CameraPlatform.instance.createCameraWithSettings( description, _mediaSettings, ); - unawaited(CameraPlatform.instance - .onCameraInitialized(_cameraId) - .first - .then((CameraInitializedEvent event) { - initializeCompleter.complete(event); - })); + unawaited( + CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( + CameraInitializedEvent event, + ) { + initializeCompleter.complete(event); + }), + ); await CameraPlatform.instance.initializeCamera( _cameraId, @@ -236,19 +239,22 @@ class CameraController extends ValueNotifier { value = value.copyWith( isInitialized: true, description: description, - previewSize: await initializeCompleter.future - .then((CameraInitializedEvent event) => Size( - event.previewWidth, - event.previewHeight, - )), - exposureMode: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.exposureMode), - focusMode: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.focusMode), - exposurePointSupported: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.exposurePointSupported), - focusPointSupported: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.focusPointSupported), + previewSize: await initializeCompleter.future.then( + (CameraInitializedEvent event) => + Size(event.previewWidth, event.previewHeight), + ), + exposureMode: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.exposureMode, + ), + focusMode: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.focusMode, + ), + exposurePointSupported: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.exposurePointSupported, + ), + focusPointSupported: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.focusPointSupported, + ), ); _initCalled = true; @@ -263,17 +269,20 @@ class CameraController extends ValueNotifier { Future pausePreview() async { await CameraPlatform.instance.pausePreview(_cameraId); value = value.copyWith( - isPreviewPaused: true, - previewPauseOrientation: Optional.of( - value.lockedCaptureOrientation ?? value.deviceOrientation)); + isPreviewPaused: true, + previewPauseOrientation: Optional.of( + value.lockedCaptureOrientation ?? value.deviceOrientation, + ), + ); } /// Resumes the current camera preview Future resumePreview() async { await CameraPlatform.instance.resumePreview(_cameraId); value = value.copyWith( - isPreviewPaused: false, - previewPauseOrientation: const Optional.absent()); + isPreviewPaused: false, + previewPauseOrientation: const Optional.absent(), + ); } /// Sets the description of the camera. @@ -298,12 +307,13 @@ class CameraController extends ValueNotifier { /// Start streaming images from platform camera. Future startImageStream( - void Function(CameraImageData image) onAvailable) async { + void Function(CameraImageData image) onAvailable, + ) async { _imageStreamSubscription = CameraPlatform.instance .onStreamedFrameAvailable(_cameraId) .listen((CameraImageData imageData) { - onAvailable(imageData); - }); + onAvailable(imageData); + }); value = value.copyWith(isStreamingImages: true); } @@ -318,16 +328,20 @@ class CameraController extends ValueNotifier { /// /// The video is returned as a [XFile] after calling [stopVideoRecording]. /// Throws a [CameraException] if the capture fails. - Future startVideoRecording( - {void Function(CameraImageData image)? streamCallback}) async { + Future startVideoRecording({ + void Function(CameraImageData image)? streamCallback, + }) async { await CameraPlatform.instance.startVideoCapturing( - VideoCaptureOptions(_cameraId, streamCallback: streamCallback)); + VideoCaptureOptions(_cameraId, streamCallback: streamCallback), + ); value = value.copyWith( - isRecordingVideo: true, - isRecordingPaused: false, - isStreamingImages: streamCallback != null, - recordingOrientation: Optional.of( - value.lockedCaptureOrientation ?? value.deviceOrientation)); + isRecordingVideo: true, + isRecordingPaused: false, + isStreamingImages: streamCallback != null, + recordingOrientation: Optional.of( + value.lockedCaptureOrientation ?? value.deviceOrientation, + ), + ); } /// Stops the video recording and returns the file where it was saved. @@ -338,8 +352,9 @@ class CameraController extends ValueNotifier { await stopImageStream(); } - final XFile file = - await CameraPlatform.instance.stopVideoRecording(_cameraId); + final XFile file = await CameraPlatform.instance.stopVideoRecording( + _cameraId, + ); value = value.copyWith( isRecordingVideo: false, isRecordingPaused: false, @@ -386,12 +401,12 @@ class CameraController extends ValueNotifier { // Check if offset is in range final List range = await Future.wait(>[ CameraPlatform.instance.getMinExposureOffset(_cameraId), - CameraPlatform.instance.getMaxExposureOffset(_cameraId) + CameraPlatform.instance.getMaxExposureOffset(_cameraId), ]); // Round to the closest step if needed - final double stepSize = - await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); + final double stepSize = await CameraPlatform.instance + .getExposureOffsetStepSize(_cameraId); if (stepSize > 0) { final double inv = 1.0 / stepSize; double roundedOffset = (offset * inv).roundToDouble() / inv; @@ -410,18 +425,23 @@ class CameraController extends ValueNotifier { /// /// If [orientation] is omitted, the current device orientation is used. Future lockCaptureOrientation() async { - await CameraPlatform.instance - .lockCaptureOrientation(_cameraId, value.deviceOrientation); + await CameraPlatform.instance.lockCaptureOrientation( + _cameraId, + value.deviceOrientation, + ); value = value.copyWith( - lockedCaptureOrientation: - Optional.of(value.deviceOrientation)); + lockedCaptureOrientation: Optional.of( + value.deviceOrientation, + ), + ); } /// Unlocks the capture orientation. Future unlockCaptureOrientation() async { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); value = value.copyWith( - lockedCaptureOrientation: const Optional.absent()); + lockedCaptureOrientation: const Optional.absent(), + ); } /// Sets the focus mode for taking pictures. diff --git a/packages/camera/camera_android/example/lib/camera_preview.dart b/packages/camera/camera_android/example/lib/camera_preview.dart index 4fbdb3a2b06..11a5e92b633 100644 --- a/packages/camera/camera_android/example/lib/camera_preview.dart +++ b/packages/camera/camera_android/example/lib/camera_preview.dart @@ -23,26 +23,25 @@ class CameraPreview extends StatelessWidget { Widget build(BuildContext context) { return controller.value.isInitialized ? ValueListenableBuilder( - valueListenable: controller, - builder: (BuildContext context, Object? value, Widget? child) { - final double cameraAspectRatio = - controller.value.previewSize!.width / - controller.value.previewSize!.height; - return AspectRatio( - aspectRatio: _isLandscape() - ? cameraAspectRatio - : (1 / cameraAspectRatio), - child: Stack( - fit: StackFit.expand, - children: [ - _wrapInRotatedBox(child: controller.buildPreview()), - child ?? Container(), - ], - ), - ); - }, - child: child, - ) + valueListenable: controller, + builder: (BuildContext context, Object? value, Widget? child) { + final double cameraAspectRatio = + controller.value.previewSize!.width / + controller.value.previewSize!.height; + return AspectRatio( + aspectRatio: + _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio), + child: Stack( + fit: StackFit.expand, + children: [ + _wrapInRotatedBox(child: controller.buildPreview()), + child ?? Container(), + ], + ), + ); + }, + child: child, + ) : Container(); } @@ -51,16 +50,13 @@ class CameraPreview extends StatelessWidget { return child; } - return RotatedBox( - quarterTurns: _getQuarterTurns(), - child: child, - ); + return RotatedBox(quarterTurns: _getQuarterTurns(), child: child); } bool _isLandscape() { return [ DeviceOrientation.landscapeLeft, - DeviceOrientation.landscapeRight + DeviceOrientation.landscapeRight, ].contains(_getApplicableOrientation()); } diff --git a/packages/camera/camera_android/example/lib/main.dart b/packages/camera/camera_android/example/lib/main.dart index 47c40c7d20d..e8bd4e77179 100644 --- a/packages/camera/camera_android/example/lib/main.dart +++ b/packages/camera/camera_android/example/lib/main.dart @@ -130,9 +130,7 @@ class _CameraExampleHomeState extends State @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Camera example'), - ), + appBar: AppBar(title: const Text('Camera example')), body: Column( children: [ Expanded( @@ -149,9 +147,7 @@ class _CameraExampleHomeState extends State ), child: Padding( padding: const EdgeInsets.all(1.0), - child: Center( - child: _cameraPreviewWidget(), - ), + child: Center(child: _cameraPreviewWidget()), ), ), ), @@ -160,10 +156,7 @@ class _CameraExampleHomeState extends State Padding( padding: const EdgeInsets.all(5.0), child: Row( - children: [ - _cameraTogglesRowWidget(), - _thumbnailWidget(), - ], + children: [_cameraTogglesRowWidget(), _thumbnailWidget()], ), ), ], @@ -191,15 +184,17 @@ class _CameraExampleHomeState extends State child: CameraPreview( controller!, child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onScaleStart: _handleScaleStart, - onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), - ); - }), + builder: (BuildContext context, BoxConstraints constraints) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onScaleStart: _handleScaleStart, + onScaleUpdate: _handleScaleUpdate, + onTapDown: + (TapDownDetails details) => + onViewFinderTap(details, constraints), + ); + }, + ), ), ); } @@ -215,11 +210,15 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale) - .clamp(_minAvailableZoom, _maxAvailableZoom); + _currentScale = (_baseScale * details.scale).clamp( + _minAvailableZoom, + _maxAvailableZoom, + ); - await CameraPlatform.instance - .setZoomLevel(controller!.cameraId, _currentScale); + await CameraPlatform.instance.setZoomLevel( + controller!.cameraId, + _currentScale, + ); } /// Display the thumbnail of the captured image or video. @@ -238,8 +237,9 @@ class _CameraExampleHomeState extends State SizedBox( width: 64.0, height: 64.0, - child: (localVideoController == null) - ? ( + child: + (localVideoController == null) + ? ( // The captured image on the web contains a network-accessible URL // pointing to a location within the browser. It may be displayed // either with Image.network or Image.memory after loading the image @@ -247,16 +247,18 @@ class _CameraExampleHomeState extends State kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path))) - : Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.pink)), - child: Center( - child: AspectRatio( + : Container( + decoration: BoxDecoration( + border: Border.all(color: Colors.pink), + ), + child: Center( + child: AspectRatio( aspectRatio: localVideoController.value.aspectRatio, - child: VideoPlayer(localVideoController)), + child: VideoPlayer(localVideoController), + ), + ), ), - ), ), ], ), @@ -279,20 +281,19 @@ 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), @@ -300,13 +301,16 @@ class _CameraExampleHomeState extends State onPressed: controller != null ? onAudioModeButtonPressed : null, ), IconButton( - icon: Icon(controller?.value.isCaptureOrientationLocked ?? false - ? Icons.screen_lock_rotation - : Icons.screen_rotation), + icon: Icon( + controller?.value.isCaptureOrientationLocked ?? false + ? Icons.screen_lock_rotation + : Icons.screen_rotation, + ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: + controller != null + ? onCaptureOrientationLockButtonPressed + : null, ), ], ), @@ -326,39 +330,47 @@ 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, ), ], ), @@ -368,14 +380,16 @@ 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( @@ -385,22 +399,24 @@ class _CameraExampleHomeState extends State color: Colors.grey.shade50, child: Column( children: [ - const Center( - child: Text('Exposure Mode'), - ), + const Center(child: Text('Exposure Mode')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( style: styleAuto, - onPressed: controller != null - ? () => - onSetExposureModeButtonPressed(ExposureMode.auto) - : null, + onPressed: + controller != null + ? () => onSetExposureModeButtonPressed( + ExposureMode.auto, + ) + : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance - .setExposurePoint(controller!.cameraId, null); + CameraPlatform.instance.setExposurePoint( + controller!.cameraId, + null, + ); showInSnackBar('Resetting exposure point'); } }, @@ -408,24 +424,25 @@ 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'), ), ], ), - const Center( - child: Text('Exposure Offset'), - ), + const Center(child: Text('Exposure Offset')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ @@ -435,10 +452,11 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: _minAvailableExposureOffset == - _maxAvailableExposureOffset - ? null - : setExposureOffset, + onChanged: + _minAvailableExposureOffset == + _maxAvailableExposureOffset + ? null + : setExposureOffset, ), Text(_maxAvailableExposureOffset.toString()), ], @@ -452,14 +470,16 @@ 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( @@ -469,21 +489,22 @@ class _CameraExampleHomeState extends State color: Colors.grey.shade50, child: Column( children: [ - const Center( - child: Text('Focus Mode'), - ), + const Center(child: Text('Focus Mode')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( style: styleAuto, - onPressed: controller != null - ? () => onSetFocusModeButtonPressed(FocusMode.auto) - : null, + onPressed: + controller != null + ? () => onSetFocusModeButtonPressed(FocusMode.auto) + : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance - .setFocusPoint(controller!.cameraId, null); + CameraPlatform.instance.setFocusPoint( + controller!.cameraId, + null, + ); } showInSnackBar('Resetting focus point'); }, @@ -491,9 +512,11 @@ 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'), ), ], @@ -515,44 +538,49 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.camera_alt), color: Colors.blue, - onPressed: cameraController != null && - cameraController.value.isInitialized && - !cameraController.value.isRecordingVideo - ? onTakePictureButtonPressed - : null, + onPressed: + cameraController != 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, + onPressed: + cameraController != null && + cameraController.value.isInitialized && + !cameraController.value.isRecordingVideo + ? onVideoRecordButtonPressed + : null, ), IconButton( - icon: cameraController != null && - (!cameraController.value.isRecordingVideo || - cameraController.value.isRecordingPaused) - ? const Icon(Icons.play_arrow) - : const Icon(Icons.pause), + icon: + cameraController != null && + (!cameraController.value.isRecordingVideo || + 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, + onPressed: + cameraController != 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, + onPressed: + cameraController != null && + cameraController.value.isInitialized && + cameraController.value.isRecordingVideo + ? onStopButtonPressed + : null, ), IconButton( icon: const Icon(Icons.pause_presentation), @@ -606,8 +634,9 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of(context) - .showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -634,7 +663,8 @@ class _CameraExampleHomeState extends State } Future _initializeCameraController( - CameraDescription cameraDescription) async { + CameraDescription cameraDescription, + ) async { final CameraController cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( @@ -660,14 +690,13 @@ class _CameraExampleHomeState extends State // The exposure mode is currently not supported on the web. ...!kIsWeb ? >[ - CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId) - .then( - (double value) => _minAvailableExposureOffset = value), - CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId) - .then((double value) => _maxAvailableExposureOffset = value) - ] + CameraPlatform.instance + .getMinExposureOffset(cameraController.cameraId) + .then((double value) => _minAvailableExposureOffset = value), + CameraPlatform.instance + .getMaxExposureOffset(cameraController.cameraId) + .then((double value) => _maxAvailableExposureOffset = value), + ] : >[], CameraPlatform.instance .getMaxZoomLevel(cameraController.cameraId) @@ -769,7 +798,8 @@ class _CameraExampleHomeState extends State } else { await cameraController.lockCaptureOrientation(); showInSnackBar( - 'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}'); + 'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}', + ); } } } on CameraException catch (e) { @@ -988,9 +1018,10 @@ 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) { @@ -1048,9 +1079,7 @@ class CameraApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - home: CameraExampleHome(), - ); + return const MaterialApp(home: CameraExampleHome()); } } diff --git a/packages/camera/camera_android/example/pubspec.yaml b/packages/camera/camera_android/example/pubspec.yaml index 43ebd555322..8a362e8c5e1 100644 --- a/packages/camera/camera_android/example/pubspec.yaml +++ b/packages/camera/camera_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the camera plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: camera_android: diff --git a/packages/camera/camera_android/example/test_driver/integration_test.dart b/packages/camera/camera_android/example/test_driver/integration_test.dart index aa57599f316..7779a8e714d 100644 --- a/packages/camera/camera_android/example/test_driver/integration_test.dart +++ b/packages/camera/camera_android/example/test_driver/integration_test.dart @@ -29,14 +29,14 @@ Future main() async { 'pm', 'grant', _examplePackage, - 'android.permission.CAMERA' + 'android.permission.CAMERA', ]); Process.runSync('adb', [ 'shell', 'pm', 'grant', _examplePackage, - 'android.permission.RECORD_AUDIO' + 'android.permission.RECORD_AUDIO', ]); print('Starting test.'); final FlutterDriver driver = await FlutterDriver.connect(); @@ -51,14 +51,14 @@ Future main() async { 'pm', 'revoke', _examplePackage, - 'android.permission.CAMERA' + 'android.permission.CAMERA', ]); Process.runSync('adb', [ 'shell', 'pm', 'revoke', _examplePackage, - 'android.permission.RECORD_AUDIO' + 'android.permission.RECORD_AUDIO', ]); final Map result = jsonDecode(data) as Map; diff --git a/packages/camera/camera_android/lib/src/android_camera.dart b/packages/camera/camera_android/lib/src/android_camera.dart index 61695771616..19c5b0f8f18 100644 --- a/packages/camera/camera_android/lib/src/android_camera.dart +++ b/packages/camera/camera_android/lib/src/android_camera.dart @@ -18,7 +18,7 @@ import 'utils.dart'; class AndroidCamera extends CameraPlatform { /// Creates a new [CameraPlatform] instance. AndroidCamera({@visibleForTesting CameraApi? hostApi}) - : _hostApi = hostApi ?? CameraApi(); + : _hostApi = hostApi ?? CameraApi(); /// Registers this class as the default instance of [CameraPlatform]. static void registerWith() { @@ -60,22 +60,25 @@ class AndroidCamera extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => - cameraEventStreamController.stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => cameraEventStreamController + .stream + .where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { try { final List cameraDescriptions = await _hostApi.getAvailableCameras(); - return cameraDescriptions - .map((PlatformCameraDescription cameraDescription) { + return cameraDescriptions.map(( + PlatformCameraDescription cameraDescription, + ) { return CameraDescription( - name: cameraDescription.name, - lensDirection: cameraLensDirectionFromPlatform( - cameraDescription.lensDirection), - sensorOrientation: cameraDescription.sensorOrientation); + name: cameraDescription.name, + lensDirection: cameraLensDirectionFromPlatform( + cameraDescription.lensDirection, + ), + sensorOrientation: cameraDescription.sensorOrientation, + ); }).toList(); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -87,13 +90,10 @@ class AndroidCamera extends CameraPlatform { CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, - }) => - createCameraWithSettings( - cameraDescription, - MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - )); + }) => createCameraWithSettings( + cameraDescription, + MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio), + ); @override Future createCameraWithSettings( @@ -102,7 +102,9 @@ class AndroidCamera extends CameraPlatform { ) async { try { return await _hostApi.create( - cameraDescription.name, mediaSettingsToPlatform(mediaSettings)); + cameraDescription.name, + mediaSettingsToPlatform(mediaSettings), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -113,16 +115,18 @@ class AndroidCamera extends CameraPlatform { int cameraId, { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) async { - hostCameraHandlers.putIfAbsent(cameraId, - () => HostCameraMessageHandler(cameraId, cameraEventStreamController)); + hostCameraHandlers.putIfAbsent( + cameraId, + () => HostCameraMessageHandler(cameraId, cameraEventStreamController), + ); final Completer completer = Completer(); - unawaited(onCameraInitialized(cameraId) - .first - .then((CameraInitializedEvent value) { - completer.complete(); - })); + unawaited( + onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) { + completer.complete(); + }), + ); try { await _hostApi.initialize(imageFormatGroupToPlatform(imageFormatGroup)); @@ -135,8 +139,9 @@ class AndroidCamera extends CameraPlatform { @override Future dispose(int cameraId) async { - final HostCameraMessageHandler? handler = - hostCameraHandlers.remove(cameraId); + final HostCameraMessageHandler? handler = hostCameraHandlers.remove( + cameraId, + ); handler?.dispose(); await _hostApi.dispose(); @@ -178,8 +183,9 @@ class AndroidCamera extends CameraPlatform { int cameraId, DeviceOrientation orientation, ) async { - await _hostApi - .lockCaptureOrientation(deviceOrientationToPlatform(orientation)); + await _hostApi.lockCaptureOrientation( + deviceOrientationToPlatform(orientation), + ); } @override @@ -198,8 +204,10 @@ class AndroidCamera extends CameraPlatform { Future prepareForVideoRecording() async {} @override - Future startVideoRecording(int cameraId, - {Duration? maxVideoDuration}) async { + Future startVideoRecording( + int cameraId, { + Duration? maxVideoDuration, + }) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -232,14 +240,17 @@ class AndroidCamera extends CameraPlatform { bool supportsImageStreaming() => true; @override - Stream onStreamedFrameAvailable(int cameraId, - {CameraImageStreamOptions? options}) { + Stream onStreamedFrameAvailable( + int cameraId, { + CameraImageStreamOptions? options, + }) { _installStreamController(onListen: _onFrameStreamListen); return _frameStreamController!.stream; } - StreamController _installStreamController( - {void Function()? onListen}) { + StreamController _installStreamController({ + void Function()? onListen, + }) { _frameStreamController = StreamController( onListen: onListen ?? () {}, onPause: _onFrameStreamPauseResume, @@ -259,13 +270,16 @@ class AndroidCamera extends CameraPlatform { } void _startStreamListener() { - const EventChannel cameraEventChannel = - EventChannel('plugins.flutter.io/camera_android/imageStream'); - _platformImageStreamSubscription = - cameraEventChannel.receiveBroadcastStream().listen((dynamic imageData) { - _frameStreamController! - .add(cameraImageFromPlatformData(imageData as Map)); - }); + const EventChannel cameraEventChannel = EventChannel( + 'plugins.flutter.io/camera_android/imageStream', + ); + _platformImageStreamSubscription = cameraEventChannel + .receiveBroadcastStream() + .listen((dynamic imageData) { + _frameStreamController!.add( + cameraImageFromPlatformData(imageData as Map), + ); + }); } FutureOr _onFrameStreamCancel() async { @@ -276,8 +290,10 @@ class AndroidCamera extends CameraPlatform { } void _onFrameStreamPauseResume() { - throw CameraException('InvalidCall', - 'Pause and resume are not supported for onStreamedFrameAvailable'); + throw CameraException( + 'InvalidCall', + 'Pause and resume are not supported for onStreamedFrameAvailable', + ); } @override @@ -359,7 +375,8 @@ class AndroidCamera extends CameraPlatform { @override Future setDescriptionWhileRecording( - CameraDescription description) async { + CameraDescription description, + ) async { await _hostApi.setDescriptionWhileRecording(description.name); } @@ -382,8 +399,9 @@ class HostDeviceMessageHandler implements CameraGlobalEventApi { StreamController.broadcast(); @override void deviceOrientationChanged(PlatformDeviceOrientation orientation) { - deviceEventStreamController.add(DeviceOrientationChangedEvent( - deviceOrientationFromPlatform(orientation))); + deviceEventStreamController.add( + DeviceOrientationChangedEvent(deviceOrientationFromPlatform(orientation)), + ); } } @@ -412,14 +430,17 @@ class HostCameraMessageHandler implements CameraEventApi { @override void initialized(PlatformCameraState initialState) { - cameraEventStreamController.add(CameraInitializedEvent( + cameraEventStreamController.add( + CameraInitializedEvent( cameraId, initialState.previewSize.width, initialState.previewSize.height, exposureModeFromPlatform(initialState.exposureMode), initialState.exposurePointSupported, focusModeFromPlatform(initialState.focusMode), - initialState.focusPointSupported)); + initialState.focusPointSupported, + ), + ); } @override diff --git a/packages/camera/camera_android/lib/src/messages.g.dart b/packages/camera/camera_android/lib/src/messages.g.dart index 81e21a01da3..babb6fc14d4 100644 --- a/packages/camera/camera_android/lib/src/messages.g.dart +++ b/packages/camera/camera_android/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -30,11 +33,7 @@ List wrapResponse( } /// Pigeon equivalent of [CameraLensDirection]. -enum PlatformCameraLensDirection { - front, - back, - external, -} +enum PlatformCameraLensDirection { front, back, external } /// Pigeon equivalent of [DeviceOrientation]. enum PlatformDeviceOrientation { @@ -45,26 +44,13 @@ enum PlatformDeviceOrientation { } /// Pigeon equivalent of [ExposureMode]. -enum PlatformExposureMode { - auto, - locked, -} +enum PlatformExposureMode { auto, locked } /// Pigeon equivalent of [FocusMode]. -enum PlatformFocusMode { - auto, - locked, -} +enum PlatformFocusMode { auto, locked } /// Pigeon equivalent of [ResolutionPreset]. -enum PlatformResolutionPreset { - low, - medium, - high, - veryHigh, - ultraHigh, - max, -} +enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } /// Pigeon equivalent of [ImageFormatGroup]. enum PlatformImageFormatGroup { @@ -75,12 +61,7 @@ enum PlatformImageFormatGroup { } /// Pigeon equivalent of [FlashMode]. -enum PlatformFlashMode { - off, - auto, - always, - torch, -} +enum PlatformFlashMode { off, auto, always, torch } /// Pigeon equivalent of [CameraDescription]. class PlatformCameraDescription { @@ -97,11 +78,7 @@ class PlatformCameraDescription { int sensorOrientation; Object encode() { - return [ - name, - lensDirection, - sensorOrientation, - ]; + return [name, lensDirection, sensorOrientation]; } static PlatformCameraDescription decode(Object result) { @@ -158,20 +135,14 @@ class PlatformCameraState { /// Pigeon equivalent of [Size]. class PlatformSize { - PlatformSize({ - required this.width, - required this.height, - }); + PlatformSize({required this.width, required this.height}); double width; double height; Object encode() { - return [ - width, - height, - ]; + return [width, height]; } static PlatformSize decode(Object result) { @@ -185,28 +156,19 @@ class PlatformSize { /// Pigeon equivalent of [Point]. class PlatformPoint { - PlatformPoint({ - required this.x, - required this.y, - }); + PlatformPoint({required this.x, required this.y}); double x; double y; Object encode() { - return [ - x, - y, - ]; + return [x, y]; } static PlatformPoint decode(Object result) { result as List; - return PlatformPoint( - x: result[0]! as double, - y: result[1]! as double, - ); + return PlatformPoint(x: result[0]! as double, y: result[1]! as double); } } @@ -345,11 +307,12 @@ class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - CameraApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + CameraApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -362,10 +325,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -389,17 +352,20 @@ class CameraApi { /// Creates a new camera with the given name and settings and returns its ID. Future create( - String cameraName, PlatformMediaSettings mediaSettings) async { + String cameraName, + PlatformMediaSettings mediaSettings, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.create$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([cameraName, mediaSettings]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([cameraName, mediaSettings]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -424,10 +390,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.initialize$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([imageFormat]) as List?; if (pigeonVar_replyList == null) { @@ -449,10 +415,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.dispose$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -470,15 +436,16 @@ class CameraApi { /// Locks the camera with the given ID to the given orientation. Future lockCaptureOrientation( - PlatformDeviceOrientation orientation) async { + PlatformDeviceOrientation orientation, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([orientation]) as List?; if (pigeonVar_replyList == null) { @@ -500,10 +467,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.unlockCaptureOrientation$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -526,10 +493,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.takePicture$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -556,10 +523,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([enableStream]) as List?; if (pigeonVar_replyList == null) { @@ -582,10 +549,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -612,10 +579,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.pauseVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -637,10 +604,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.resumeVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -662,10 +629,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.startImageStream$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -687,10 +654,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.stopImageStream$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -712,10 +679,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setFlashMode$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([flashMode]) as List?; if (pigeonVar_replyList == null) { @@ -737,10 +704,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setExposureMode$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([exposureMode]) as List?; if (pigeonVar_replyList == null) { @@ -764,10 +731,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setExposurePoint$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([point]) as List?; if (pigeonVar_replyList == null) { @@ -789,10 +756,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.getMinExposureOffset$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -819,10 +786,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.getMaxExposureOffset$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -849,10 +816,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.getExposureOffsetStepSize$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -880,10 +847,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setExposureOffset$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([offset]) as List?; if (pigeonVar_replyList == null) { @@ -910,10 +877,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setFocusMode$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([focusMode]) as List?; if (pigeonVar_replyList == null) { @@ -937,10 +904,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setFocusPoint$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([point]) as List?; if (pigeonVar_replyList == null) { @@ -962,10 +929,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.getMaxZoomLevel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -992,10 +959,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.getMinZoomLevel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1022,10 +989,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setZoomLevel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([zoom]) as List?; if (pigeonVar_replyList == null) { @@ -1047,10 +1014,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.pausePreview$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1072,10 +1039,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.resumePreview$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1099,10 +1066,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_android.CameraApi.setDescriptionWhileRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([description]) as List?; if (pigeonVar_replyList == null) { @@ -1134,23 +1101,27 @@ abstract class CameraGlobalEventApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged was null.', + ); final List args = (message as List?)!; final PlatformDeviceOrientation? arg_orientation = (args[0] as PlatformDeviceOrientation?); - assert(arg_orientation != null, - 'Argument for dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged was null, expected non-null PlatformDeviceOrientation.'); + assert( + arg_orientation != null, + 'Argument for dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged was null, expected non-null PlatformDeviceOrientation.', + ); try { api.deviceOrientationChanged(arg_orientation!); return wrapResponse(empty: true); @@ -1158,7 +1129,8 @@ abstract class CameraGlobalEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1187,23 +1159,27 @@ abstract class CameraEventApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_android.CameraEventApi.initialized$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_android.CameraEventApi.initialized$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null.', + ); final List args = (message as List?)!; final PlatformCameraState? arg_initialState = (args[0] as PlatformCameraState?); - assert(arg_initialState != null, - 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null, expected non-null PlatformCameraState.'); + assert( + arg_initialState != null, + 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null, expected non-null PlatformCameraState.', + ); try { api.initialized(arg_initialState!); return wrapResponse(empty: true); @@ -1211,28 +1187,33 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_android.CameraEventApi.error$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_android.CameraEventApi.error$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.error was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.error was null.', + ); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.error was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.error was null, expected non-null String.', + ); try { api.error(arg_message!); return wrapResponse(empty: true); @@ -1240,18 +1221,19 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_android.CameraEventApi.closed$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_android.CameraEventApi.closed$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -1263,7 +1245,8 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/camera/camera_android/lib/src/type_conversion.dart b/packages/camera/camera_android/lib/src/type_conversion.dart index b4f0e42ea0a..4c3c540a0a6 100644 --- a/packages/camera/camera_android/lib/src/type_conversion.dart +++ b/packages/camera/camera_android/lib/src/type_conversion.dart @@ -10,16 +10,20 @@ import 'package:camera_platform_interface/camera_platform_interface.dart'; /// [CameraImageData]. CameraImageData cameraImageFromPlatformData(Map data) { return CameraImageData( - format: _cameraImageFormatFromPlatformData(data['format']), - height: data['height'] as int, - width: data['width'] as int, - lensAperture: data['lensAperture'] as double?, - sensorExposureTime: data['sensorExposureTime'] as int?, - sensorSensitivity: data['sensorSensitivity'] as double?, - planes: List.unmodifiable( - (data['planes'] as List).map( - (dynamic planeData) => _cameraImagePlaneFromPlatformData( - planeData as Map)))); + format: _cameraImageFormatFromPlatformData(data['format']), + height: data['height'] as int, + width: data['width'] as int, + lensAperture: data['lensAperture'] as double?, + sensorExposureTime: data['sensorExposureTime'] as int?, + sensorSensitivity: data['sensorSensitivity'] as double?, + planes: List.unmodifiable( + (data['planes'] as List).map( + (dynamic planeData) => _cameraImagePlaneFromPlatformData( + planeData as Map, + ), + ), + ), + ); } CameraImageFormat _cameraImageFormatFromPlatformData(dynamic data) { @@ -41,9 +45,10 @@ ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) { CameraImagePlane _cameraImagePlaneFromPlatformData(Map data) { return CameraImagePlane( - bytes: data['bytes'] as Uint8List, - bytesPerPixel: data['bytesPerPixel'] as int?, - bytesPerRow: data['bytesPerRow'] as int, - height: data['height'] as int?, - width: data['width'] as int?); + bytes: data['bytes'] as Uint8List, + bytesPerPixel: data['bytesPerPixel'] as int?, + bytesPerRow: data['bytesPerRow'] as int, + height: data['height'] as int?, + width: data['width'] as int?, + ); } diff --git a/packages/camera/camera_android/lib/src/utils.dart b/packages/camera/camera_android/lib/src/utils.dart index 1b3d2809e2c..3091e3c0396 100644 --- a/packages/camera/camera_android/lib/src/utils.dart +++ b/packages/camera/camera_android/lib/src/utils.dart @@ -11,28 +11,27 @@ import 'messages.g.dart'; /// Converts a [PlatformCameraLensDirection] to [CameraLensDirection]. CameraLensDirection cameraLensDirectionFromPlatform( - PlatformCameraLensDirection direction) => - switch (direction) { - PlatformCameraLensDirection.front => CameraLensDirection.front, - PlatformCameraLensDirection.back => CameraLensDirection.back, - PlatformCameraLensDirection.external => CameraLensDirection.external, - }; + PlatformCameraLensDirection direction, +) => switch (direction) { + PlatformCameraLensDirection.front => CameraLensDirection.front, + PlatformCameraLensDirection.back => CameraLensDirection.back, + PlatformCameraLensDirection.external => CameraLensDirection.external, +}; /// Converts a [PlatformDeviceOrientation] to [DeviceOrientation]. DeviceOrientation deviceOrientationFromPlatform( - PlatformDeviceOrientation orientation) => - switch (orientation) { - PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp, - PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown, - PlatformDeviceOrientation.landscapeLeft => - DeviceOrientation.landscapeLeft, - PlatformDeviceOrientation.landscapeRight => - DeviceOrientation.landscapeRight, - }; + PlatformDeviceOrientation orientation, +) => switch (orientation) { + PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp, + PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown, + PlatformDeviceOrientation.landscapeLeft => DeviceOrientation.landscapeLeft, + PlatformDeviceOrientation.landscapeRight => DeviceOrientation.landscapeRight, +}; /// Converts a [DeviceOrientation] to [PlatformDeviceOrientation]. PlatformDeviceOrientation deviceOrientationToPlatform( - DeviceOrientation orientation) { + DeviceOrientation orientation, +) { switch (orientation) { case DeviceOrientation.portraitUp: return PlatformDeviceOrientation.portraitUp; @@ -106,12 +105,12 @@ PlatformResolutionPreset resolutionPresetToPlatform(ResolutionPreset? preset) => /// Converts a [MediaSettings] to [PlatformMediaSettings]. PlatformMediaSettings mediaSettingsToPlatform(MediaSettings? settings) => PlatformMediaSettings( - resolutionPreset: - resolutionPresetToPlatform(settings?.resolutionPreset), - enableAudio: settings?.enableAudio ?? false, - videoBitrate: settings?.videoBitrate, - audioBitrate: settings?.audioBitrate, - fps: settings?.fps); + resolutionPreset: resolutionPresetToPlatform(settings?.resolutionPreset), + enableAudio: settings?.enableAudio ?? false, + videoBitrate: settings?.videoBitrate, + audioBitrate: settings?.audioBitrate, + fps: settings?.fps, + ); /// Converts an [ImageFormatGroup] to [PlatformImageFormatGroup]. /// diff --git a/packages/camera/camera_android/pigeons/messages.dart b/packages/camera/camera_android/pigeons/messages.dart index 6031ac3d5a3..5a59c2c0d29 100644 --- a/packages/camera/camera_android/pigeons/messages.dart +++ b/packages/camera/camera_android/pigeons/messages.dart @@ -3,26 +3,24 @@ // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - javaOptions: JavaOptions(package: 'io.flutter.plugins.camera'), - javaOut: 'android/src/main/java/io/flutter/plugins/camera/Messages.java', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + javaOptions: JavaOptions(package: 'io.flutter.plugins.camera'), + javaOut: 'android/src/main/java/io/flutter/plugins/camera/Messages.java', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Pigeon equivalent of [CameraLensDirection]. -enum PlatformCameraLensDirection { - front, - back, - external, -} +enum PlatformCameraLensDirection { front, back, external } /// Pigeon equivalent of [CameraDescription]. class PlatformCameraDescription { - PlatformCameraDescription( - {required this.name, - required this.lensDirection, - required this.sensorOrientation}); + PlatformCameraDescription({ + required this.name, + required this.lensDirection, + required this.sensorOrientation, + }); final String name; final PlatformCameraLensDirection lensDirection; @@ -38,25 +36,20 @@ enum PlatformDeviceOrientation { } /// Pigeon equivalent of [ExposureMode]. -enum PlatformExposureMode { - auto, - locked, -} +enum PlatformExposureMode { auto, locked } /// Pigeon equivalent of [FocusMode]. -enum PlatformFocusMode { - auto, - locked, -} +enum PlatformFocusMode { auto, locked } /// Data needed for [CameraInitializedEvent]. class PlatformCameraState { - PlatformCameraState( - {required this.previewSize, - required this.exposureMode, - required this.focusMode, - required this.exposurePointSupported, - required this.focusPointSupported}); + PlatformCameraState({ + required this.previewSize, + required this.exposureMode, + required this.focusMode, + required this.exposurePointSupported, + required this.focusPointSupported, + }); final PlatformSize previewSize; final PlatformExposureMode exposureMode; @@ -82,23 +75,17 @@ class PlatformPoint { } /// Pigeon equivalent of [ResolutionPreset]. -enum PlatformResolutionPreset { - low, - medium, - high, - veryHigh, - ultraHigh, - max, -} +enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } /// Pigeon equivalent of [MediaSettings]. class PlatformMediaSettings { - PlatformMediaSettings( - {required this.resolutionPreset, - required this.enableAudio, - this.fps, - this.videoBitrate, - this.audioBitrate}); + PlatformMediaSettings({ + required this.resolutionPreset, + required this.enableAudio, + this.fps, + this.videoBitrate, + this.audioBitrate, + }); final PlatformResolutionPreset resolutionPreset; final int? fps; final int? videoBitrate; @@ -115,12 +102,7 @@ enum PlatformImageFormatGroup { } /// Pigeon equivalent of [FlashMode]. -enum PlatformFlashMode { - off, - auto, - always, - torch, -} +enum PlatformFlashMode { off, auto, always, torch } /// Handles calls from Dart to the native side. @HostApi() diff --git a/packages/camera/camera_android/pubspec.yaml b/packages/camera/camera_android/pubspec.yaml index dc58455ec7e..a9c4a7d27af 100644 --- a/packages/camera/camera_android/pubspec.yaml +++ b/packages/camera/camera_android/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.10+5 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/camera/camera_android/test/android_camera_test.dart b/packages/camera/camera_android/test/android_camera_test.dart index e2897b1e579..248ff3174c7 100644 --- a/packages/camera/camera_android/test/android_camera_test.dart +++ b/packages/camera/camera_android/test/android_camera_test.dart @@ -35,13 +35,17 @@ void main() { // have been initialized. While registerWith could initialize them, that // could slow down startup, so instead the handler should be set up lazily. final ByteData? response = await TestDefaultBinaryMessengerBinding - .instance.defaultBinaryMessenger + .instance + .defaultBinaryMessenger .handlePlatformMessage( - AndroidCamera.deviceEventChannelName, - const StandardMethodCodec().encodeMethodCall(const MethodCall( - 'orientation_changed', - {'orientation': 'portraitDown'})), - (ByteData? data) {}); + AndroidCamera.deviceEventChannelName, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('orientation_changed', { + 'orientation': 'portraitDown', + }), + ), + (ByteData? data) {}, + ); expect(response, null); }); @@ -54,18 +58,26 @@ void main() { test('Should send creation data and receive back a camera id', () async { // Arrange final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); - when(mockCameraApi.create( + when( + mockCameraApi.create( 'Test', - argThat(predicate((PlatformMediaSettings settings) => - settings.resolutionPreset == PlatformResolutionPreset.high && - !settings.enableAudio)))).thenAnswer((_) async => 1); + argThat( + predicate( + (PlatformMediaSettings settings) => + settings.resolutionPreset == PlatformResolutionPreset.high && + !settings.enableAudio, + ), + ), + ), + ).thenAnswer((_) async => 1); // Act final int cameraId = await camera.createCamera( const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0), + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), ResolutionPreset.high, ); @@ -74,76 +86,110 @@ void main() { }); test( - 'Should send creation data and receive back a camera id using createCameraWithSettings', - () async { - // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); - when(mockCameraApi.create( - 'Test', - argThat(predicate((PlatformMediaSettings settings) => - settings.resolutionPreset == PlatformResolutionPreset.low && - !settings.enableAudio && - settings.fps == 15 && - settings.videoBitrate == 200000 && - settings.audioBitrate == 32000)))).thenAnswer((_) async => 1); + 'Should send creation data and receive back a camera id using createCameraWithSettings', + () async { + // Arrange + final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + when( + mockCameraApi.create( + 'Test', + argThat( + predicate( + (PlatformMediaSettings settings) => + settings.resolutionPreset == PlatformResolutionPreset.low && + !settings.enableAudio && + settings.fps == 15 && + settings.videoBitrate == 200000 && + settings.audioBitrate == 32000, + ), + ), + ), + ).thenAnswer((_) async => 1); - // Act - final int cameraId = await camera.createCameraWithSettings( - const CameraDescription( + // Act + final int cameraId = await camera.createCameraWithSettings( + const CameraDescription( name: 'Test', lensDirection: CameraLensDirection.back, - sensorOrientation: 0), - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - ), - ); + sensorOrientation: 0, + ), + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + ), + ); - // Assert - expect(cameraId, 1); - }); + // Assert + expect(cameraId, 1); + }, + ); - test('Should throw CameraException when create throws a PlatformException', - () { - // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); - when(mockCameraApi.create( - 'Test', - argThat(predicate((PlatformMediaSettings settings) => - settings.resolutionPreset == PlatformResolutionPreset.high && - !settings.enableAudio)))).thenThrow(CameraException( - 'TESTING_ERROR_CODE', 'Mock error message used during testing.')); + test( + 'Should throw CameraException when create throws a PlatformException', + () { + // Arrange + final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + when( + mockCameraApi.create( + 'Test', + argThat( + predicate( + (PlatformMediaSettings settings) => + settings.resolutionPreset == + PlatformResolutionPreset.high && + !settings.enableAudio, + ), + ), + ), + ).thenThrow( + CameraException( + 'TESTING_ERROR_CODE', + 'Mock error message used during testing.', + ), + ); - // Act - expect( - () => camera.createCamera( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + // Act + expect( + () => camera.createCamera( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), + ResolutionPreset.high, ), - ResolutionPreset.high, - ), - throwsA( - isA() - .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') - .having((CameraException e) => e.description, 'description', - 'Mock error message used during testing.'), - ), - ); - }); + throwsA( + isA() + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }, + ); test( 'Should throw CameraException when initialize throws a PlatformException', () { // Arrange final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); - when(mockCameraApi.initialize(PlatformImageFormatGroup.yuv420)) - .thenThrow(CameraException('TESTING_ERROR_CODE', - 'Mock error message used during testing.')); + when( + mockCameraApi.initialize(PlatformImageFormatGroup.yuv420), + ).thenThrow( + CameraException( + 'TESTING_ERROR_CODE', + 'Mock error message used during testing.', + ), + ); // Act expect( @@ -151,7 +197,10 @@ void main() { throwsA( isA() .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) .having( (CameraException e) => e.description, 'description', @@ -165,11 +214,18 @@ void main() { test('Should send initialization data', () async { // Arrange final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); - when(mockCameraApi.create( + when( + mockCameraApi.create( 'Test', - argThat(predicate((PlatformMediaSettings settings) => - settings.resolutionPreset == PlatformResolutionPreset.high && - !settings.enableAudio)))).thenAnswer((_) async => 1); + argThat( + predicate( + (PlatformMediaSettings settings) => + settings.resolutionPreset == PlatformResolutionPreset.high && + !settings.enableAudio, + ), + ), + ), + ).thenAnswer((_) async => 1); final int cameraId = await camera.createCamera( const CameraDescription( @@ -182,31 +238,41 @@ void main() { // Act final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; // Assert expect(cameraId, 1); - verify(mockCameraApi.initialize(PlatformImageFormatGroup.yuv420)) - .called(1); + verify( + mockCameraApi.initialize(PlatformImageFormatGroup.yuv420), + ).called(1); }); test('Should send a disposal call on dispose', () async { // Arrange final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); - when(mockCameraApi.create( + when( + mockCameraApi.create( 'Test', - argThat(predicate((PlatformMediaSettings settings) => - settings.resolutionPreset == PlatformResolutionPreset.high && - !settings.enableAudio)))).thenAnswer((_) async => 1); + argThat( + predicate( + (PlatformMediaSettings settings) => + settings.resolutionPreset == PlatformResolutionPreset.high && + !settings.enableAudio, + ), + ), + ), + ).thenAnswer((_) async => 1); final int cameraId = await camera.createCamera( const CameraDescription( name: 'Test', @@ -216,15 +282,17 @@ void main() { ResolutionPreset.high, ); final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; // Act @@ -252,22 +320,24 @@ void main() { ResolutionPreset.high, ); final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; }); test('Should receive initialized event', () async { // Act - final Stream eventStream = - camera.onCameraInitialized(cameraId); + final Stream eventStream = camera + .onCameraInitialized(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -282,12 +352,15 @@ void main() { FocusMode.auto, true, ); - camera.hostCameraHandlers[cameraId]!.initialized(PlatformCameraState( + camera.hostCameraHandlers[cameraId]!.initialized( + PlatformCameraState( previewSize: previewSize, exposureMode: PlatformExposureMode.auto, focusMode: PlatformFocusMode.auto, exposurePointSupported: true, - focusPointSupported: true)); + focusPointSupported: true, + ), + ); // Assert expect(await streamQueue.next, event); @@ -298,8 +371,9 @@ void main() { test('Should receive camera closing events', () async { // Act - final Stream eventStream = - camera.onCameraClosing(cameraId); + final Stream eventStream = camera.onCameraClosing( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -320,14 +394,17 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = - camera.onCameraError(cameraId); + final Stream errorStream = camera.onCameraError( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(errorStream); // Emit test events - final CameraErrorEvent event = - CameraErrorEvent(cameraId, 'Error Description'); + final CameraErrorEvent event = CameraErrorEvent( + cameraId, + 'Error Description', + ); for (int i = 0; i < 3; i++) { camera.hostCameraHandlers[cameraId]!.error('Error Description'); } @@ -349,11 +426,13 @@ void main() { StreamQueue(eventStream); // Emit test events - const DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); for (int i = 0; i < 3; i++) { - camera.hostHandler - .deviceOrientationChanged(PlatformDeviceOrientation.portraitUp); + camera.hostHandler.deviceOrientationChanged( + PlatformDeviceOrientation.portraitUp, + ); } // Assert @@ -397,65 +476,83 @@ void main() { await initializeFuture; }); - test('Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final List returnData = - [ - PlatformCameraDescription( - name: 'Test 1', - lensDirection: PlatformCameraLensDirection.front, - sensorOrientation: 1), - PlatformCameraDescription( - name: 'Test 2', - lensDirection: PlatformCameraLensDirection.back, - sensorOrientation: 2), - ]; - when(mockCameraApi.getAvailableCameras()) - .thenAnswer((_) async => returnData); - - // Act - final List cameras = await camera.availableCameras(); + test( + 'Should fetch CameraDescription instances for available cameras', + () async { + // Arrange + final List returnData = + [ + PlatformCameraDescription( + name: 'Test 1', + lensDirection: PlatformCameraLensDirection.front, + sensorOrientation: 1, + ), + PlatformCameraDescription( + name: 'Test 2', + lensDirection: PlatformCameraLensDirection.back, + sensorOrientation: 2, + ), + ]; + when( + mockCameraApi.getAvailableCameras(), + ).thenAnswer((_) async => returnData); - // Assert - expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { - final PlatformCameraDescription platformCameraDescription = - returnData[i]; - final CameraDescription cameraDescription = CameraDescription( + // Act + final List cameras = await camera.availableCameras(); + + // Assert + expect(cameras.length, returnData.length); + for (int i = 0; i < returnData.length; i++) { + final PlatformCameraDescription platformCameraDescription = + returnData[i]; + final CameraDescription cameraDescription = CameraDescription( name: platformCameraDescription.name, lensDirection: cameraLensDirectionFromPlatform( - platformCameraDescription.lensDirection), - sensorOrientation: platformCameraDescription.sensorOrientation); - expect(cameras[i], cameraDescription); - } - }); + platformCameraDescription.lensDirection, + ), + sensorOrientation: platformCameraDescription.sensorOrientation, + ); + expect(cameras[i], cameraDescription); + } + }, + ); test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - // Arrange - when(mockCameraApi.getAvailableCameras()).thenThrow(PlatformException( - code: 'TESTING_ERROR_CODE', - message: 'Mock error message used during testing.')); - - // Act - expect( - camera.availableCameras, - throwsA( - isA() - .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') - .having((CameraException e) => e.description, 'description', - 'Mock error message used during testing.'), - ), - ); - }); + 'Should throw CameraException when availableCameras throws a PlatformException', + () { + // Arrange + when(mockCameraApi.getAvailableCameras()).thenThrow( + PlatformException( + code: 'TESTING_ERROR_CODE', + message: 'Mock error message used during testing.', + ), + ); + + // Act + expect( + camera.availableCameras, + throwsA( + isA() + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }, + ); test('Should take a picture and return an XFile instance', () async { // Arrange - when(mockCameraApi.takePicture()) - .thenAnswer((_) async => '/test/path.jpg'); + when( + mockCameraApi.takePicture(), + ).thenAnswer((_) async => '/test/path.jpg'); // Act final XFile file = await camera.takePicture(cameraId); @@ -474,23 +571,27 @@ void main() { }); test( - 'Should pass enableStream if callback is passed when starting recording a video', - () async { - // Arrange - // Act - await camera.startVideoCapturing( - VideoCaptureOptions(cameraId, - streamCallback: (CameraImageData imageData) {}), - ); + 'Should pass enableStream if callback is passed when starting recording a video', + () async { + // Arrange + // Act + await camera.startVideoCapturing( + VideoCaptureOptions( + cameraId, + streamCallback: (CameraImageData imageData) {}, + ), + ); - // Assert - verify(mockCameraApi.startVideoRecording(true)).called(1); - }); + // Assert + verify(mockCameraApi.startVideoRecording(true)).called(1); + }, + ); test('Should stop a video recording and return the file', () async { // Arrange - when(mockCameraApi.stopVideoRecording()) - .thenAnswer((_) async => '/test/path.mp4'); + when( + mockCameraApi.stopVideoRecording(), + ).thenAnswer((_) async => '/test/path.mp4'); // Act final XFile file = await camera.stopVideoRecording(cameraId); @@ -520,17 +621,18 @@ void main() { test('Should set the description while recording', () async { // Arrange const CameraDescription camera2Description = CameraDescription( - name: 'Test2', - lensDirection: CameraLensDirection.front, - sensorOrientation: 0); + name: 'Test2', + lensDirection: CameraLensDirection.front, + sensorOrientation: 0, + ); // Act await camera.setDescriptionWhileRecording(camera2Description); // Assert - verify(mockCameraApi - .setDescriptionWhileRecording(camera2Description.name)) - .called(1); + verify( + mockCameraApi.setDescriptionWhileRecording(camera2Description.name), + ).called(1); }); test('Should set the flash mode', () async { @@ -555,10 +657,12 @@ void main() { await camera.setExposureMode(cameraId, ExposureMode.locked); // Assert - verify(mockCameraApi.setExposureMode(PlatformExposureMode.auto)) - .called(1); - verify(mockCameraApi.setExposureMode(PlatformExposureMode.locked)) - .called(1); + verify( + mockCameraApi.setExposureMode(PlatformExposureMode.auto), + ).called(1); + verify( + mockCameraApi.setExposureMode(PlatformExposureMode.locked), + ).called(1); }); test('Should set the exposure point', () async { @@ -568,9 +672,15 @@ void main() { await camera.setExposurePoint(cameraId, null); // Assert - verify(mockCameraApi.setExposurePoint(argThat(predicate( - (PlatformPoint point) => point.x == 0.4 && point.y == 0.5)))) - .called(1); + verify( + mockCameraApi.setExposurePoint( + argThat( + predicate( + (PlatformPoint point) => point.x == 0.4 && point.y == 0.5, + ), + ), + ), + ).called(1); verify(mockCameraApi.setExposurePoint(null)).called(1); }); @@ -579,8 +689,9 @@ void main() { when(mockCameraApi.getMinExposureOffset()).thenAnswer((_) async => 2.0); // Act - final double minExposureOffset = - await camera.getMinExposureOffset(cameraId); + final double minExposureOffset = await camera.getMinExposureOffset( + cameraId, + ); // Assert expect(minExposureOffset, 2.0); @@ -591,8 +702,9 @@ void main() { when(mockCameraApi.getMaxExposureOffset()).thenAnswer((_) async => 2.0); // Act - final double maxExposureOffset = - await camera.getMaxExposureOffset(cameraId); + final double maxExposureOffset = await camera.getMaxExposureOffset( + cameraId, + ); // Assert expect(maxExposureOffset, 2.0); @@ -600,8 +712,9 @@ void main() { test('Should get the exposure offset step size', () async { // Arrange - when(mockCameraApi.getExposureOffsetStepSize()) - .thenAnswer((_) async => 0.25); + when( + mockCameraApi.getExposureOffsetStepSize(), + ).thenAnswer((_) async => 0.25); // Act final double stepSize = await camera.getExposureOffsetStepSize(cameraId); @@ -672,31 +785,44 @@ void main() { verify(mockCameraApi.setZoomLevel(2.0)).called(1); }); - test('Should throw CameraException when illegal zoom level is supplied', - () async { - // Arrange - when(mockCameraApi.setZoomLevel(-1.0)).thenThrow( - PlatformException(code: 'ZOOM_ERROR', message: 'Illegal zoom error')); + test( + 'Should throw CameraException when illegal zoom level is supplied', + () async { + // Arrange + when(mockCameraApi.setZoomLevel(-1.0)).thenThrow( + PlatformException(code: 'ZOOM_ERROR', message: 'Illegal zoom error'), + ); - // Act & assert - expect( + // Act & assert + expect( () => camera.setZoomLevel(cameraId, -1.0), - throwsA(isA() - .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') - .having((CameraException e) => e.description, 'description', - 'Illegal zoom error'))); - }); + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') + .having( + (CameraException e) => e.description, + 'description', + 'Illegal zoom error', + ), + ), + ); + }, + ); test('Should lock the capture orientation', () async { // Arrange // Act await camera.lockCaptureOrientation( - cameraId, DeviceOrientation.portraitUp); + cameraId, + DeviceOrientation.portraitUp, + ); // Assert - verify(mockCameraApi - .lockCaptureOrientation(PlatformDeviceOrientation.portraitUp)) - .called(1); + verify( + mockCameraApi.lockCaptureOrientation( + PlatformDeviceOrientation.portraitUp, + ), + ).called(1); }); test('Should unlock the capture orientation', () async { diff --git a/packages/camera/camera_android/test/android_camera_test.mocks.dart b/packages/camera/camera_android/test/android_camera_test.mocks.dart index 6be1c98ad57..53cd6e9489a 100644 --- a/packages/camera/camera_android/test/android_camera_test.mocks.dart +++ b/packages/camera/camera_android/test/android_camera_test.mocks.dart @@ -27,31 +27,33 @@ import 'package:mockito/src/dummies.dart' as _i3; /// See the documentation for Mockito's code generation for more information. class MockCameraApi extends _i1.Mock implements _i2.CameraApi { @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override _i4.Future> getAvailableCameras() => (super.noSuchMethod( - Invocation.method( - #getAvailableCameras, - [], - ), - returnValue: _i4.Future>.value( - <_i2.PlatformCameraDescription>[]), - returnValueForMissingStub: - _i4.Future>.value( - <_i2.PlatformCameraDescription>[]), - ) as _i4.Future>); + Invocation.method(#getAvailableCameras, []), + returnValue: _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + returnValueForMissingStub: + _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + ) + as _i4.Future>); @override _i4.Future create( @@ -59,310 +61,259 @@ class MockCameraApi extends _i1.Mock implements _i2.CameraApi { _i2.PlatformMediaSettings? mediaSettings, ) => (super.noSuchMethod( - Invocation.method( - #create, - [ - cameraName, - mediaSettings, - ], - ), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) as _i4.Future); + Invocation.method(#create, [cameraName, mediaSettings]), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) + as _i4.Future); @override _i4.Future initialize(_i2.PlatformImageFormatGroup? imageFormat) => (super.noSuchMethod( - Invocation.method( - #initialize, - [imageFormat], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#initialize, [imageFormat]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future dispose() => + (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future lockCaptureOrientation( - _i2.PlatformDeviceOrientation? orientation) => + _i2.PlatformDeviceOrientation? orientation, + ) => (super.noSuchMethod( - Invocation.method( - #lockCaptureOrientation, - [orientation], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#lockCaptureOrientation, [orientation]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future unlockCaptureOrientation() => (super.noSuchMethod( - Invocation.method( - #unlockCaptureOrientation, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future unlockCaptureOrientation() => + (super.noSuchMethod( + Invocation.method(#unlockCaptureOrientation, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future takePicture() => (super.noSuchMethod( - Invocation.method( - #takePicture, - [], - ), - returnValue: _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #takePicture, - [], - ), - )), - returnValueForMissingStub: - _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #takePicture, - [], - ), - )), - ) as _i4.Future); + _i4.Future takePicture() => + (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + ) + as _i4.Future); @override _i4.Future startVideoRecording(bool? enableStream) => (super.noSuchMethod( - Invocation.method( - #startVideoRecording, - [enableStream], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#startVideoRecording, [enableStream]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future stopVideoRecording() => (super.noSuchMethod( - Invocation.method( - #stopVideoRecording, - [], - ), - returnValue: _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #stopVideoRecording, - [], - ), - )), - returnValueForMissingStub: - _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #stopVideoRecording, - [], - ), - )), - ) as _i4.Future); + _i4.Future stopVideoRecording() => + (super.noSuchMethod( + Invocation.method(#stopVideoRecording, []), + returnValue: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#stopVideoRecording, []), + ), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#stopVideoRecording, []), + ), + ), + ) + as _i4.Future); @override - _i4.Future pauseVideoRecording() => (super.noSuchMethod( - Invocation.method( - #pauseVideoRecording, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future pauseVideoRecording() => + (super.noSuchMethod( + Invocation.method(#pauseVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future resumeVideoRecording() => (super.noSuchMethod( - Invocation.method( - #resumeVideoRecording, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future resumeVideoRecording() => + (super.noSuchMethod( + Invocation.method(#resumeVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future startImageStream() => (super.noSuchMethod( - Invocation.method( - #startImageStream, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future startImageStream() => + (super.noSuchMethod( + Invocation.method(#startImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future stopImageStream() => (super.noSuchMethod( - Invocation.method( - #stopImageStream, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future stopImageStream() => + (super.noSuchMethod( + Invocation.method(#stopImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setFlashMode(_i2.PlatformFlashMode? flashMode) => (super.noSuchMethod( - Invocation.method( - #setFlashMode, - [flashMode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFlashMode, [flashMode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setExposureMode(_i2.PlatformExposureMode? exposureMode) => (super.noSuchMethod( - Invocation.method( - #setExposureMode, - [exposureMode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setExposureMode, [exposureMode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setExposurePoint(_i2.PlatformPoint? point) => (super.noSuchMethod( - Invocation.method( - #setExposurePoint, - [point], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setExposurePoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future getMinExposureOffset() => (super.noSuchMethod( - Invocation.method( - #getMinExposureOffset, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMinExposureOffset() => + (super.noSuchMethod( + Invocation.method(#getMinExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future getMaxExposureOffset() => (super.noSuchMethod( - Invocation.method( - #getMaxExposureOffset, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMaxExposureOffset() => + (super.noSuchMethod( + Invocation.method(#getMaxExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future getExposureOffsetStepSize() => (super.noSuchMethod( - Invocation.method( - #getExposureOffsetStepSize, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getExposureOffsetStepSize() => + (super.noSuchMethod( + Invocation.method(#getExposureOffsetStepSize, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future setExposureOffset(double? offset) => (super.noSuchMethod( - Invocation.method( - #setExposureOffset, - [offset], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future setExposureOffset(double? offset) => + (super.noSuchMethod( + Invocation.method(#setExposureOffset, [offset]), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override _i4.Future setFocusMode(_i2.PlatformFocusMode? focusMode) => (super.noSuchMethod( - Invocation.method( - #setFocusMode, - [focusMode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFocusMode, [focusMode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setFocusPoint(_i2.PlatformPoint? point) => (super.noSuchMethod( - Invocation.method( - #setFocusPoint, - [point], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFocusPoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future getMaxZoomLevel() => (super.noSuchMethod( - Invocation.method( - #getMaxZoomLevel, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMaxZoomLevel() => + (super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future getMinZoomLevel() => (super.noSuchMethod( - Invocation.method( - #getMinZoomLevel, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMinZoomLevel() => + (super.noSuchMethod( + Invocation.method(#getMinZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future setZoomLevel(double? zoom) => (super.noSuchMethod( - Invocation.method( - #setZoomLevel, - [zoom], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setZoomLevel(double? zoom) => + (super.noSuchMethod( + Invocation.method(#setZoomLevel, [zoom]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future pausePreview() => (super.noSuchMethod( - Invocation.method( - #pausePreview, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future pausePreview() => + (super.noSuchMethod( + Invocation.method(#pausePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future resumePreview() => (super.noSuchMethod( - Invocation.method( - #resumePreview, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future resumePreview() => + (super.noSuchMethod( + Invocation.method(#resumePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setDescriptionWhileRecording(String? description) => (super.noSuchMethod( - Invocation.method( - #setDescriptionWhileRecording, - [description], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setDescriptionWhileRecording, [description]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/camera/camera_android/test/method_channel_mock.dart b/packages/camera/camera_android/test/method_channel_mock.dart index a7362d0e049..2822682432a 100644 --- a/packages/camera/camera_android/test/method_channel_mock.dart +++ b/packages/camera/camera_android/test/method_channel_mock.dart @@ -24,8 +24,10 @@ class MethodChannelMock { log.add(methodCall); if (!methods.containsKey(methodCall.method)) { - throw MissingPluginException('No implementation found for method ' - '${methodCall.method} on channel ${methodChannel.name}'); + throw MissingPluginException( + 'No implementation found for method ' + '${methodCall.method} on channel ${methodChannel.name}', + ); } return Future.delayed(delay ?? Duration.zero, () { diff --git a/packages/camera/camera_android/test/type_conversion_test.dart b/packages/camera/camera_android/test/type_conversion_test.dart index 076b5773346..a4b4281b6dd 100644 --- a/packages/camera/camera_android/test/type_conversion_test.dart +++ b/packages/camera/camera_android/test/type_conversion_test.dart @@ -10,24 +10,25 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 1, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 1, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.unknown); @@ -35,46 +36,48 @@ void main() { }); test('CameraImageData has ImageFormatGroup.yuv420', () { - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('CameraImageData has ImageFormatGroup.nv21', () { - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 17, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 17, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.nv21); }); } diff --git a/packages/camera/camera_android/test/utils_test.dart b/packages/camera/camera_android/test/utils_test.dart index ebcac58d2c6..f13517c78b2 100644 --- a/packages/camera/camera_android/test/utils_test.dart +++ b/packages/camera/camera_android/test/utils_test.dart @@ -11,44 +11,51 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('Utility methods', () { test( - 'Should return CameraLensDirection when valid value is supplied when parsing camera lens direction', - () { + 'Should return CameraLensDirection when valid value is supplied when parsing camera lens direction', + () { + expect( + cameraLensDirectionFromPlatform(PlatformCameraLensDirection.back), + CameraLensDirection.back, + ); + expect( + cameraLensDirectionFromPlatform(PlatformCameraLensDirection.front), + CameraLensDirection.front, + ); + expect( + cameraLensDirectionFromPlatform(PlatformCameraLensDirection.external), + CameraLensDirection.external, + ); + }, + ); + + test('deviceOrientationFromPlatform() should convert correctly', () { expect( - cameraLensDirectionFromPlatform(PlatformCameraLensDirection.back), - CameraLensDirection.back, + deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitUp), + DeviceOrientation.portraitUp, ); expect( - cameraLensDirectionFromPlatform(PlatformCameraLensDirection.front), - CameraLensDirection.front, + deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitDown), + DeviceOrientation.portraitDown, ); expect( - cameraLensDirectionFromPlatform(PlatformCameraLensDirection.external), - CameraLensDirection.external, + deviceOrientationFromPlatform(PlatformDeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, ); - }); - - test('deviceOrientationFromPlatform() should convert correctly', () { - expect( - deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitUp), - DeviceOrientation.portraitUp); - expect( - deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitDown), - DeviceOrientation.portraitDown); expect( - deviceOrientationFromPlatform( - PlatformDeviceOrientation.landscapeRight), - DeviceOrientation.landscapeRight); - expect( - deviceOrientationFromPlatform( - PlatformDeviceOrientation.landscapeLeft), - DeviceOrientation.landscapeLeft); + deviceOrientationFromPlatform(PlatformDeviceOrientation.landscapeLeft), + DeviceOrientation.landscapeLeft, + ); }); test('exposureModeFromPlatform() should convert correctly', () { - expect(exposureModeFromPlatform(PlatformExposureMode.auto), - ExposureMode.auto); - expect(exposureModeFromPlatform(PlatformExposureMode.locked), - ExposureMode.locked); + expect( + exposureModeFromPlatform(PlatformExposureMode.auto), + ExposureMode.auto, + ); + expect( + exposureModeFromPlatform(PlatformExposureMode.locked), + ExposureMode.locked, + ); }); test('focusModeFromPlatform() should convert correctly', () { diff --git a/packages/camera/camera_avfoundation/CHANGELOG.md b/packages/camera/camera_avfoundation/CHANGELOG.md index c37b5a7f628..821d6d9894d 100644 --- a/packages/camera/camera_avfoundation/CHANGELOG.md +++ b/packages/camera/camera_avfoundation/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.9.21+1 * Migrates `startImageStream` and `setUpCaptureSessionForAudioIfNeeded` methods to Swift. diff --git a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart index c8fded8ad23..47dcdf8e68d 100644 --- a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart +++ b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart @@ -32,13 +32,13 @@ void main() { final Map presetExpectedSizes = { - ResolutionPreset.low: const Size(288, 352), - ResolutionPreset.medium: const Size(480, 640), - ResolutionPreset.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + ResolutionPreset.low: const Size(288, 352), + ResolutionPreset.medium: const Size(480, 640), + ResolutionPreset.high: const Size(720, 1280), + ResolutionPreset.veryHigh: const Size(1080, 1920), + ResolutionPreset.ultraHigh: const Size(2160, 3840), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -54,7 +54,9 @@ void main() { // automatic code to fall back to smaller sizes when we need to. Returns // whether the image is exactly the desired resolution. Future testCaptureImageResolution( - CameraController controller, ResolutionPreset preset) async { + CameraController controller, + ResolutionPreset preset, + ) async { final Size expectedSize = presetExpectedSizes[preset]!; // Take Picture @@ -67,11 +69,14 @@ void main() { // Verify image dimensions are as expected expect(image, isNotNull); return assertExpectedDimensions( - expectedSize, Size(image.height.toDouble(), image.width.toDouble())); + expectedSize, + Size(image.height.toDouble(), image.width.toDouble()), + ); } - testWidgets('Capture specific image resolutions', - (WidgetTester tester) async { + testWidgets('Capture specific image resolutions', ( + WidgetTester tester, + ) async { final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { @@ -81,13 +86,19 @@ void main() { bool previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = - CameraController(cameraDescription, preset.key); + final CameraController controller = CameraController( + cameraDescription, + preset.key, + ); await controller.initialize(); - final bool presetExactlySupported = - await testCaptureImageResolution(controller, preset.key); - assert(!(!previousPresetExactlySupported && presetExactlySupported), - 'The camera took higher resolution pictures at a lower resolution.'); + final bool presetExactlySupported = await testCaptureImageResolution( + controller, + preset.key, + ); + assert( + !(!previousPresetExactlySupported && presetExactlySupported), + 'The camera took higher resolution pictures at a lower resolution.', + ); previousPresetExactlySupported = presetExactlySupported; await controller.dispose(); } @@ -98,7 +109,9 @@ void main() { // automatic code to fall back to smaller sizes when we need to. Returns // whether the image is exactly the desired resolution. Future testCaptureVideoResolution( - CameraController controller, ResolutionPreset preset) async { + CameraController controller, + ResolutionPreset preset, + ) async { final Size expectedSize = presetExpectedSizes[preset]!; // Take Video @@ -108,19 +121,23 @@ void main() { // Load video metadata final File videoFile = File(file.path); - final VideoPlayerController videoController = - VideoPlayerController.file(videoFile); + final VideoPlayerController videoController = VideoPlayerController.file( + videoFile, + ); await videoController.initialize(); final Size video = videoController.value.size; // Verify image dimensions are as expected expect(video, isNotNull); return assertExpectedDimensions( - expectedSize, Size(video.height, video.width)); + expectedSize, + Size(video.height, video.width), + ); } - testWidgets('Capture specific video resolutions', - (WidgetTester tester) async { + testWidgets('Capture specific video resolutions', ( + WidgetTester tester, + ) async { final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { @@ -130,14 +147,20 @@ void main() { bool previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = - CameraController(cameraDescription, preset.key); + final CameraController controller = CameraController( + cameraDescription, + preset.key, + ); await controller.initialize(); await controller.prepareForVideoRecording(); - final bool presetExactlySupported = - await testCaptureVideoResolution(controller, preset.key); - assert(!(!previousPresetExactlySupported && presetExactlySupported), - 'The camera took higher resolution pictures at a lower resolution.'); + final bool presetExactlySupported = await testCaptureVideoResolution( + controller, + preset.key, + ); + assert( + !(!previousPresetExactlySupported && presetExactlySupported), + 'The camera took higher resolution pictures at a lower resolution.', + ); previousPresetExactlySupported = presetExactlySupported; await controller.dispose(); } @@ -240,8 +263,10 @@ void main() { }); /// Start streaming with specifying the ImageFormatGroup. - Future startStreaming(List cameras, - ImageFormatGroup? imageFormatGroup) async { + Future startStreaming( + List cameras, + ImageFormatGroup? imageFormatGroup, + ) async { final CameraController controller = CameraController( cameras.first, ResolutionPreset.low, @@ -265,31 +290,30 @@ void main() { return completer.future; } - testWidgets( - 'image streaming with imageFormatGroup', - (WidgetTester tester) async { - final List cameras = - await CameraPlatform.instance.availableCameras(); - if (cameras.isEmpty) { - return; - } + testWidgets('image streaming with imageFormatGroup', ( + WidgetTester tester, + ) async { + final List cameras = + await CameraPlatform.instance.availableCameras(); + if (cameras.isEmpty) { + return; + } - CameraImageData image = await startStreaming(cameras, null); - expect(image, isNotNull); - expect(image.format.group, ImageFormatGroup.bgra8888); - expect(image.planes.length, 1); + CameraImageData image = await startStreaming(cameras, null); + expect(image, isNotNull); + expect(image.format.group, ImageFormatGroup.bgra8888); + expect(image.planes.length, 1); - image = await startStreaming(cameras, ImageFormatGroup.yuv420); - expect(image, isNotNull); - expect(image.format.group, ImageFormatGroup.yuv420); - expect(image.planes.length, 2); + image = await startStreaming(cameras, ImageFormatGroup.yuv420); + expect(image, isNotNull); + expect(image.format.group, ImageFormatGroup.yuv420); + expect(image.planes.length, 2); - image = await startStreaming(cameras, ImageFormatGroup.bgra8888); - expect(image, isNotNull); - expect(image.format.group, ImageFormatGroup.bgra8888); - expect(image.planes.length, 1); - }, - ); + image = await startStreaming(cameras, ImageFormatGroup.bgra8888); + expect(image, isNotNull); + expect(image.format.group, ImageFormatGroup.bgra8888); + expect(image.planes.length, 1); + }); testWidgets('Recording with video streaming', (WidgetTester tester) async { final List cameras = @@ -308,11 +332,12 @@ void main() { await controller.prepareForVideoRecording(); final Completer completer = Completer(); await controller.startVideoRecording( - streamCallback: (CameraImageData image) { - if (!completer.isCompleted) { - completer.complete(image); - } - }); + streamCallback: (CameraImageData image) { + if (!completer.isCompleted) { + completer.complete(image); + } + }, + ); sleep(const Duration(milliseconds: 500)); await controller.stopVideoRecording(); await controller.dispose(); @@ -321,8 +346,9 @@ void main() { }); // Test fileFormat is respected when taking a picture. - testWidgets('Capture specific image output formats', - (WidgetTester tester) async { + testWidgets('Capture specific image output formats', ( + WidgetTester tester, + ) async { final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { @@ -330,8 +356,10 @@ void main() { } for (final CameraDescription cameraDescription in cameras) { for (final ImageFileFormat fileFormat in ImageFileFormat.values) { - final CameraController controller = - CameraController(cameraDescription, ResolutionPreset.low); + final CameraController controller = CameraController( + cameraDescription, + ResolutionPreset.low, + ); await controller.initialize(); await controller.setImageFileFormat(fileFormat); final XFile file = await controller.takePicture(); @@ -375,8 +403,11 @@ void main() { } for (int n = 0; n < lengths.length - 1; n++) { - expect(lengths[n], lessThan(lengths[n + 1]), - reason: 'incrementing fps should increment file size'); + expect( + lengths[n], + lessThan(lengths[n + 1]), + reason: 'incrementing fps should increment file size', + ); } }); @@ -414,8 +445,11 @@ void main() { } for (int n = 0; n < lengths.length - 1; n++) { - expect(lengths[n], lessThan(lengths[n + 1]), - reason: 'incrementing video bitrate should increment file size'); + expect( + lengths[n], + lessThan(lengths[n + 1]), + reason: 'incrementing video bitrate should increment file size', + ); } }); @@ -433,11 +467,12 @@ void main() { final CameraController controller = CameraController.withSettings( cameras.first, mediaSettings: MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 5, - videoBitrate: 32000, - audioBitrate: audioBitrate, - enableAudio: true), + resolutionPreset: ResolutionPreset.low, + fps: 5, + videoBitrate: 32000, + audioBitrate: audioBitrate, + enableAudio: true, + ), ); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -458,8 +493,11 @@ void main() { } for (int n = 0; n < lengths.length - 1; n++) { - expect(lengths[n], lessThan(lengths[n + 1]), - reason: 'incrementing audio bitrate should increment file size'); + expect( + lengths[n], + lessThan(lengths[n + 1]), + reason: 'incrementing audio bitrate should increment file size', + ); } }); }); diff --git a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart index 05867cf6dd0..13d3c2f441b 100644 --- a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart +++ b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart @@ -33,19 +33,19 @@ class CameraValue { /// Creates a new camera controller state for an uninitialized controller. const CameraValue.uninitialized(CameraDescription description) - : this( - isInitialized: false, - isRecordingVideo: false, - isTakingPicture: false, - isStreamingImages: false, - isRecordingPaused: false, - flashMode: FlashMode.auto, - exposureMode: ExposureMode.auto, - focusMode: FocusMode.auto, - deviceOrientation: DeviceOrientation.portraitUp, - isPreviewPaused: false, - description: description, - ); + : this( + isInitialized: false, + isRecordingVideo: false, + isTakingPicture: false, + isStreamingImages: false, + isRecordingPaused: false, + flashMode: FlashMode.auto, + exposureMode: ExposureMode.auto, + focusMode: FocusMode.auto, + deviceOrientation: DeviceOrientation.portraitUp, + isPreviewPaused: false, + description: description, + ); /// True after [CameraController.initialize] has completed successfully. final bool isInitialized; @@ -131,17 +131,20 @@ class CameraValue { exposureMode: exposureMode ?? this.exposureMode, focusMode: focusMode ?? this.focusMode, deviceOrientation: deviceOrientation ?? this.deviceOrientation, - lockedCaptureOrientation: lockedCaptureOrientation == null - ? this.lockedCaptureOrientation - : lockedCaptureOrientation.orNull, - recordingOrientation: recordingOrientation == null - ? this.recordingOrientation - : recordingOrientation.orNull, + lockedCaptureOrientation: + lockedCaptureOrientation == null + ? this.lockedCaptureOrientation + : lockedCaptureOrientation.orNull, + recordingOrientation: + recordingOrientation == null + ? this.recordingOrientation + : recordingOrientation.orNull, isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused, description: description ?? this.description, - previewPauseOrientation: previewPauseOrientation == null - ? this.previewPauseOrientation - : previewPauseOrientation.orNull, + previewPauseOrientation: + previewPauseOrientation == null + ? this.previewPauseOrientation + : previewPauseOrientation.orNull, ); } @@ -176,24 +179,25 @@ class CameraController extends ValueNotifier { ResolutionPreset resolutionPreset, { bool enableAudio = true, ImageFormatGroup? imageFormatGroup, - }) => - CameraController.withSettings( - cameraDescription, - mediaSettings: MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - ), - imageFormatGroup: imageFormatGroup, - ); + }) => CameraController.withSettings( + cameraDescription, + mediaSettings: MediaSettings( + resolutionPreset: resolutionPreset, + enableAudio: enableAudio, + ), + imageFormatGroup: imageFormatGroup, + ); /// Creates a new camera controller in an uninitialized state, using specified media settings like FPS and bitrate. CameraController.withSettings( CameraDescription cameraDescription, { required this.mediaSettings, this.imageFormatGroup, - }) : assert(mediaSettings.resolutionPreset != null, - 'resolutionPreset should be provided in CameraController.withSettings'), - super(CameraValue.uninitialized(cameraDescription)); + }) : assert( + mediaSettings.resolutionPreset != null, + 'resolutionPreset should be provided in CameraController.withSettings', + ), + super(CameraValue.uninitialized(cameraDescription)); /// The properties of the camera device controlled by this controller. CameraDescription get description => value.description; @@ -212,7 +216,7 @@ class CameraController extends ValueNotifier { StreamSubscription? _imageStreamSubscription; FutureOr? _initCalled; StreamSubscription? - _deviceOrientationSubscription; + _deviceOrientationSubscription; /// The camera identifier with which the controller is associated. int get cameraId => _cameraId; @@ -227,22 +231,21 @@ class CameraController extends ValueNotifier { _deviceOrientationSubscription = CameraPlatform.instance .onDeviceOrientationChanged() .listen((DeviceOrientationChangedEvent event) { - value = value.copyWith( - deviceOrientation: event.orientation, - ); - }); + value = value.copyWith(deviceOrientation: event.orientation); + }); _cameraId = await CameraPlatform.instance.createCameraWithSettings( description, mediaSettings, ); - unawaited(CameraPlatform.instance - .onCameraInitialized(_cameraId) - .first - .then((CameraInitializedEvent event) { - initializeCompleter.complete(event); - })); + unawaited( + CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( + CameraInitializedEvent event, + ) { + initializeCompleter.complete(event); + }), + ); await CameraPlatform.instance.initializeCamera( _cameraId, @@ -252,19 +255,22 @@ class CameraController extends ValueNotifier { value = value.copyWith( isInitialized: true, description: description, - previewSize: await initializeCompleter.future - .then((CameraInitializedEvent event) => Size( - event.previewWidth, - event.previewHeight, - )), - exposureMode: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.exposureMode), - focusMode: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.focusMode), - exposurePointSupported: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.exposurePointSupported), - focusPointSupported: await initializeCompleter.future - .then((CameraInitializedEvent event) => event.focusPointSupported), + previewSize: await initializeCompleter.future.then( + (CameraInitializedEvent event) => + Size(event.previewWidth, event.previewHeight), + ), + exposureMode: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.exposureMode, + ), + focusMode: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.focusMode, + ), + exposurePointSupported: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.exposurePointSupported, + ), + focusPointSupported: await initializeCompleter.future.then( + (CameraInitializedEvent event) => event.focusPointSupported, + ), ); _initCalled = true; @@ -279,17 +285,20 @@ class CameraController extends ValueNotifier { Future pausePreview() async { await CameraPlatform.instance.pausePreview(_cameraId); value = value.copyWith( - isPreviewPaused: true, - previewPauseOrientation: Optional.of( - value.lockedCaptureOrientation ?? value.deviceOrientation)); + isPreviewPaused: true, + previewPauseOrientation: Optional.of( + value.lockedCaptureOrientation ?? value.deviceOrientation, + ), + ); } /// Resumes the current camera preview Future resumePreview() async { await CameraPlatform.instance.resumePreview(_cameraId); value = value.copyWith( - isPreviewPaused: false, - previewPauseOrientation: const Optional.absent()); + isPreviewPaused: false, + previewPauseOrientation: const Optional.absent(), + ); } /// Sets the description of the camera @@ -314,12 +323,13 @@ class CameraController extends ValueNotifier { /// Start streaming images from platform camera. Future startImageStream( - void Function(CameraImageData image) onAvailable) async { + void Function(CameraImageData image) onAvailable, + ) async { _imageStreamSubscription = CameraPlatform.instance .onStreamedFrameAvailable(_cameraId) .listen((CameraImageData imageData) { - onAvailable(imageData); - }); + onAvailable(imageData); + }); value = value.copyWith(isStreamingImages: true); } @@ -334,16 +344,20 @@ class CameraController extends ValueNotifier { /// /// The video is returned as a [XFile] after calling [stopVideoRecording]. /// Throws a [CameraException] if the capture fails. - Future startVideoRecording( - {void Function(CameraImageData image)? streamCallback}) async { + Future startVideoRecording({ + void Function(CameraImageData image)? streamCallback, + }) async { await CameraPlatform.instance.startVideoCapturing( - VideoCaptureOptions(_cameraId, streamCallback: streamCallback)); + VideoCaptureOptions(_cameraId, streamCallback: streamCallback), + ); value = value.copyWith( - isRecordingVideo: true, - isRecordingPaused: false, - isStreamingImages: streamCallback != null, - recordingOrientation: Optional.of( - value.lockedCaptureOrientation ?? value.deviceOrientation)); + isRecordingVideo: true, + isRecordingPaused: false, + isStreamingImages: streamCallback != null, + recordingOrientation: Optional.of( + value.lockedCaptureOrientation ?? value.deviceOrientation, + ), + ); } /// Stops the video recording and returns the file where it was saved. @@ -354,8 +368,9 @@ class CameraController extends ValueNotifier { await stopImageStream(); } - final XFile file = - await CameraPlatform.instance.stopVideoRecording(_cameraId); + final XFile file = await CameraPlatform.instance.stopVideoRecording( + _cameraId, + ); value = value.copyWith( isRecordingVideo: false, recordingOrientation: const Optional.absent(), @@ -401,12 +416,12 @@ class CameraController extends ValueNotifier { // Check if offset is in range final List range = await Future.wait(>[ CameraPlatform.instance.getMinExposureOffset(_cameraId), - CameraPlatform.instance.getMaxExposureOffset(_cameraId) + CameraPlatform.instance.getMaxExposureOffset(_cameraId), ]); // Round to the closest step if needed - final double stepSize = - await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); + final double stepSize = await CameraPlatform.instance + .getExposureOffsetStepSize(_cameraId); if (stepSize > 0) { final double inv = 1.0 / stepSize; double roundedOffset = (offset * inv).roundToDouble() / inv; @@ -425,18 +440,23 @@ class CameraController extends ValueNotifier { /// /// If [orientation] is omitted, the current device orientation is used. Future lockCaptureOrientation() async { - await CameraPlatform.instance - .lockCaptureOrientation(_cameraId, value.deviceOrientation); + await CameraPlatform.instance.lockCaptureOrientation( + _cameraId, + value.deviceOrientation, + ); value = value.copyWith( - lockedCaptureOrientation: - Optional.of(value.deviceOrientation)); + lockedCaptureOrientation: Optional.of( + value.deviceOrientation, + ), + ); } /// Unlocks the capture orientation. Future unlockCaptureOrientation() async { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); value = value.copyWith( - lockedCaptureOrientation: const Optional.absent()); + lockedCaptureOrientation: const Optional.absent(), + ); } /// Sets the focus mode for taking pictures. diff --git a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart index 4fbdb3a2b06..11a5e92b633 100644 --- a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart +++ b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart @@ -23,26 +23,25 @@ class CameraPreview extends StatelessWidget { Widget build(BuildContext context) { return controller.value.isInitialized ? ValueListenableBuilder( - valueListenable: controller, - builder: (BuildContext context, Object? value, Widget? child) { - final double cameraAspectRatio = - controller.value.previewSize!.width / - controller.value.previewSize!.height; - return AspectRatio( - aspectRatio: _isLandscape() - ? cameraAspectRatio - : (1 / cameraAspectRatio), - child: Stack( - fit: StackFit.expand, - children: [ - _wrapInRotatedBox(child: controller.buildPreview()), - child ?? Container(), - ], - ), - ); - }, - child: child, - ) + valueListenable: controller, + builder: (BuildContext context, Object? value, Widget? child) { + final double cameraAspectRatio = + controller.value.previewSize!.width / + controller.value.previewSize!.height; + return AspectRatio( + aspectRatio: + _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio), + child: Stack( + fit: StackFit.expand, + children: [ + _wrapInRotatedBox(child: controller.buildPreview()), + child ?? Container(), + ], + ), + ); + }, + child: child, + ) : Container(); } @@ -51,16 +50,13 @@ class CameraPreview extends StatelessWidget { return child; } - return RotatedBox( - quarterTurns: _getQuarterTurns(), - child: child, - ); + return RotatedBox(quarterTurns: _getQuarterTurns(), child: child); } bool _isLandscape() { return [ DeviceOrientation.landscapeLeft, - DeviceOrientation.landscapeRight + DeviceOrientation.landscapeRight, ].contains(_getApplicableOrientation()); } diff --git a/packages/camera/camera_avfoundation/example/lib/main.dart b/packages/camera/camera_avfoundation/example/lib/main.dart index f0ebf7b7865..64d6e922383 100644 --- a/packages/camera/camera_avfoundation/example/lib/main.dart +++ b/packages/camera/camera_avfoundation/example/lib/main.dart @@ -130,9 +130,7 @@ class _CameraExampleHomeState extends State @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Camera example'), - ), + appBar: AppBar(title: const Text('Camera example')), body: Column( children: [ Expanded( @@ -149,9 +147,7 @@ class _CameraExampleHomeState extends State ), child: Padding( padding: const EdgeInsets.all(1.0), - child: Center( - child: _cameraPreviewWidget(), - ), + child: Center(child: _cameraPreviewWidget()), ), ), ), @@ -160,10 +156,7 @@ class _CameraExampleHomeState extends State Padding( padding: const EdgeInsets.all(5.0), child: Row( - children: [ - _cameraTogglesRowWidget(), - _thumbnailWidget(), - ], + children: [_cameraTogglesRowWidget(), _thumbnailWidget()], ), ), ], @@ -191,15 +184,17 @@ class _CameraExampleHomeState extends State child: CameraPreview( controller!, child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onScaleStart: _handleScaleStart, - onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), - ); - }), + builder: (BuildContext context, BoxConstraints constraints) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onScaleStart: _handleScaleStart, + onScaleUpdate: _handleScaleUpdate, + onTapDown: + (TapDownDetails details) => + onViewFinderTap(details, constraints), + ); + }, + ), ), ); } @@ -215,11 +210,15 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale) - .clamp(_minAvailableZoom, _maxAvailableZoom); + _currentScale = (_baseScale * details.scale).clamp( + _minAvailableZoom, + _maxAvailableZoom, + ); - await CameraPlatform.instance - .setZoomLevel(controller!.cameraId, _currentScale); + await CameraPlatform.instance.setZoomLevel( + controller!.cameraId, + _currentScale, + ); } /// Display the thumbnail of the captured image or video. @@ -238,8 +237,9 @@ class _CameraExampleHomeState extends State SizedBox( width: 64.0, height: 64.0, - child: (localVideoController == null) - ? ( + child: + (localVideoController == null) + ? ( // The captured image on the web contains a network-accessible URL // pointing to a location within the browser. It may be displayed // either with Image.network or Image.memory after loading the image @@ -247,16 +247,18 @@ class _CameraExampleHomeState extends State kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path))) - : Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.pink)), - child: Center( - child: AspectRatio( + : Container( + decoration: BoxDecoration( + border: Border.all(color: Colors.pink), + ), + child: Center( + child: AspectRatio( aspectRatio: localVideoController.value.aspectRatio, - child: VideoPlayer(localVideoController)), + child: VideoPlayer(localVideoController), + ), + ), ), - ), ), ], ), @@ -279,20 +281,19 @@ 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), @@ -300,13 +301,16 @@ class _CameraExampleHomeState extends State onPressed: controller != null ? onAudioModeButtonPressed : null, ), IconButton( - icon: Icon(controller?.value.isCaptureOrientationLocked ?? false - ? Icons.screen_lock_rotation - : Icons.screen_rotation), + icon: Icon( + controller?.value.isCaptureOrientationLocked ?? false + ? Icons.screen_lock_rotation + : Icons.screen_rotation, + ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: + controller != null + ? onCaptureOrientationLockButtonPressed + : null, ), ], ), @@ -326,39 +330,47 @@ 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, ), ], ), @@ -368,14 +380,16 @@ 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( @@ -385,22 +399,24 @@ class _CameraExampleHomeState extends State color: Colors.grey.shade50, child: Column( children: [ - const Center( - child: Text('Exposure Mode'), - ), + const Center(child: Text('Exposure Mode')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( style: styleAuto, - onPressed: controller != null - ? () => - onSetExposureModeButtonPressed(ExposureMode.auto) - : null, + onPressed: + controller != null + ? () => onSetExposureModeButtonPressed( + ExposureMode.auto, + ) + : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance - .setExposurePoint(controller!.cameraId, null); + CameraPlatform.instance.setExposurePoint( + controller!.cameraId, + null, + ); showInSnackBar('Resetting exposure point'); } }, @@ -408,24 +424,25 @@ 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'), ), ], ), - const Center( - child: Text('Exposure Offset'), - ), + const Center(child: Text('Exposure Offset')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ @@ -435,10 +452,11 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: _minAvailableExposureOffset == - _maxAvailableExposureOffset - ? null - : setExposureOffset, + onChanged: + _minAvailableExposureOffset == + _maxAvailableExposureOffset + ? null + : setExposureOffset, ), Text(_maxAvailableExposureOffset.toString()), ], @@ -452,14 +470,16 @@ 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( @@ -469,21 +489,22 @@ class _CameraExampleHomeState extends State color: Colors.grey.shade50, child: Column( children: [ - const Center( - child: Text('Focus Mode'), - ), + const Center(child: Text('Focus Mode')), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( style: styleAuto, - onPressed: controller != null - ? () => onSetFocusModeButtonPressed(FocusMode.auto) - : null, + onPressed: + controller != null + ? () => onSetFocusModeButtonPressed(FocusMode.auto) + : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance - .setFocusPoint(controller!.cameraId, null); + CameraPlatform.instance.setFocusPoint( + controller!.cameraId, + null, + ); } showInSnackBar('Resetting focus point'); }, @@ -491,9 +512,11 @@ 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'), ), ], @@ -515,44 +538,49 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.camera_alt), color: Colors.blue, - onPressed: cameraController != null && - cameraController.value.isInitialized && - !cameraController.value.isRecordingVideo - ? onTakePictureButtonPressed - : null, + onPressed: + cameraController != 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, + onPressed: + cameraController != null && + cameraController.value.isInitialized && + !cameraController.value.isRecordingVideo + ? onVideoRecordButtonPressed + : null, ), IconButton( - icon: cameraController != null && - (!cameraController.value.isRecordingVideo || - cameraController.value.isRecordingPaused) - ? const Icon(Icons.play_arrow) - : const Icon(Icons.pause), + icon: + cameraController != null && + (!cameraController.value.isRecordingVideo || + 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, + onPressed: + cameraController != 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, + onPressed: + cameraController != null && + cameraController.value.isInitialized && + cameraController.value.isRecordingVideo + ? onStopButtonPressed + : null, ), IconButton( icon: const Icon(Icons.pause_presentation), @@ -593,9 +621,10 @@ class _CameraExampleHomeState extends State title: Icon(getCameraLensIcon(cameraDescription.lensDirection)), groupValue: controller?.description, value: cameraDescription, - onChanged: (controller?.value.isRecordingVideo ?? false) - ? null - : onChanged, + onChanged: + (controller?.value.isRecordingVideo ?? false) + ? null + : onChanged, ), ), ); @@ -608,8 +637,9 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of(context) - .showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -636,7 +666,8 @@ class _CameraExampleHomeState extends State } Future _initializeCameraController( - CameraDescription cameraDescription) async { + CameraDescription cameraDescription, + ) async { final CameraController cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, @@ -659,14 +690,13 @@ class _CameraExampleHomeState extends State // The exposure mode is currently not supported on the web. ...!kIsWeb ? >[ - CameraPlatform.instance - .getMinExposureOffset(cameraController.cameraId) - .then( - (double value) => _minAvailableExposureOffset = value), - CameraPlatform.instance - .getMaxExposureOffset(cameraController.cameraId) - .then((double value) => _maxAvailableExposureOffset = value) - ] + CameraPlatform.instance + .getMinExposureOffset(cameraController.cameraId) + .then((double value) => _minAvailableExposureOffset = value), + CameraPlatform.instance + .getMaxExposureOffset(cameraController.cameraId) + .then((double value) => _maxAvailableExposureOffset = value), + ] : >[], CameraPlatform.instance .getMaxZoomLevel(cameraController.cameraId) @@ -768,7 +798,8 @@ class _CameraExampleHomeState extends State } else { await cameraController.lockCaptureOrientation(); showInSnackBar( - 'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}'); + 'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}', + ); } } } on CameraException catch (e) { @@ -987,9 +1018,10 @@ 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) { @@ -1047,9 +1079,7 @@ class CameraApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - home: CameraExampleHome(), - ); + return const MaterialApp(home: CameraExampleHome()); } } diff --git a/packages/camera/camera_avfoundation/example/pubspec.yaml b/packages/camera/camera_avfoundation/example/pubspec.yaml index 924c6224451..17da1138058 100644 --- a/packages/camera/camera_avfoundation/example/pubspec.yaml +++ b/packages/camera/camera_avfoundation/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the camera plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: camera_avfoundation: diff --git a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart index 3e48a5e17d6..129dda5f7fc 100644 --- a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart +++ b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart @@ -19,7 +19,7 @@ import 'utils.dart'; class AVFoundationCamera extends CameraPlatform { /// Creates a new AVFoundation-based [CameraPlatform] implementation instance. AVFoundationCamera({@visibleForTesting CameraApi? api}) - : _hostApi = api ?? CameraApi(); + : _hostApi = api ?? CameraApi(); /// Registers this class as the default instance of [CameraPlatform]. static void registerWith() { @@ -60,9 +60,9 @@ class AVFoundationCamera extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => - cameraEventStreamController.stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => cameraEventStreamController + .stream + .where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { @@ -80,13 +80,10 @@ class AVFoundationCamera extends CameraPlatform { CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, - }) => - createCameraWithSettings( - cameraDescription, - MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - )); + }) => createCameraWithSettings( + cameraDescription, + MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio), + ); @override Future createCameraWithSettings( @@ -95,15 +92,17 @@ class AVFoundationCamera extends CameraPlatform { ) async { try { return await _hostApi.create( - cameraDescription.name, - PlatformMediaSettings( - resolutionPreset: - _pigeonResolutionPreset(mediaSettings?.resolutionPreset), - framesPerSecond: mediaSettings?.fps, - videoBitrate: mediaSettings?.videoBitrate, - audioBitrate: mediaSettings?.audioBitrate, - enableAudio: mediaSettings?.enableAudio ?? true, - )); + cameraDescription.name, + PlatformMediaSettings( + resolutionPreset: _pigeonResolutionPreset( + mediaSettings?.resolutionPreset, + ), + framesPerSecond: mediaSettings?.fps, + videoBitrate: mediaSettings?.videoBitrate, + audioBitrate: mediaSettings?.audioBitrate, + enableAudio: mediaSettings?.enableAudio ?? true, + ), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -114,24 +113,23 @@ class AVFoundationCamera extends CameraPlatform { int cameraId, { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) async { - hostCameraHandlers.putIfAbsent(cameraId, - () => HostCameraMessageHandler(cameraId, cameraEventStreamController)); + hostCameraHandlers.putIfAbsent( + cameraId, + () => HostCameraMessageHandler(cameraId, cameraEventStreamController), + ); final Completer completer = Completer(); - unawaited(onCameraInitialized(cameraId) - .first - .then((CameraInitializedEvent value) { - completer.complete(); - })); + unawaited( + onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) { + completer.complete(); + }), + ); try { await _hostApi.initialize(cameraId, _pigeonImageFormat(imageFormatGroup)); } on PlatformException catch (e, s) { - completer.completeError( - CameraException(e.code, e.message), - s, - ); + completer.completeError(CameraException(e.code, e.message), s); } return completer.future; @@ -139,8 +137,9 @@ class AVFoundationCamera extends CameraPlatform { @override Future dispose(int cameraId) async { - final HostCameraMessageHandler? handler = - hostCameraHandlers.remove(cameraId); + final HostCameraMessageHandler? handler = hostCameraHandlers.remove( + cameraId, + ); handler?.dispose(); await _hostApi.dispose(cameraId); @@ -182,8 +181,9 @@ class AVFoundationCamera extends CameraPlatform { int cameraId, DeviceOrientation orientation, ) async { - await _hostApi - .lockCaptureOrientation(serializeDeviceOrientation(orientation)); + await _hostApi.lockCaptureOrientation( + serializeDeviceOrientation(orientation), + ); } @override @@ -203,8 +203,10 @@ class AVFoundationCamera extends CameraPlatform { } @override - Future startVideoRecording(int cameraId, - {Duration? maxVideoDuration}) async { + Future startVideoRecording( + int cameraId, { + Duration? maxVideoDuration, + }) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -241,15 +243,19 @@ class AVFoundationCamera extends CameraPlatform { bool supportsImageStreaming() => true; @override - Stream onStreamedFrameAvailable(int cameraId, - {CameraImageStreamOptions? options}) { - _frameStreamController = - _createStreamController(onListen: _onFrameStreamListen); + Stream onStreamedFrameAvailable( + int cameraId, { + CameraImageStreamOptions? options, + }) { + _frameStreamController = _createStreamController( + onListen: _onFrameStreamListen, + ); return _frameStreamController!.stream; } - StreamController _createStreamController( - {void Function()? onListen}) { + StreamController _createStreamController({ + void Function()? onListen, + }) { return StreamController( onListen: onListen ?? () {}, onPause: _onFrameStreamPauseResume, @@ -268,18 +274,21 @@ class AVFoundationCamera extends CameraPlatform { } void _startStreamListener() { - const EventChannel cameraEventChannel = - EventChannel('plugins.flutter.io/camera_avfoundation/imageStream'); - _platformImageStreamSubscription = - cameraEventChannel.receiveBroadcastStream().listen((dynamic imageData) { - try { - _hostApi.receivedImageStreamData(); - } on PlatformException catch (e) { - throw CameraException(e.code, e.message); - } - _frameStreamController! - .add(cameraImageFromPlatformData(imageData as Map)); - }); + const EventChannel cameraEventChannel = EventChannel( + 'plugins.flutter.io/camera_avfoundation/imageStream', + ); + _platformImageStreamSubscription = cameraEventChannel + .receiveBroadcastStream() + .listen((dynamic imageData) { + try { + _hostApi.receivedImageStreamData(); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + _frameStreamController!.add( + cameraImageFromPlatformData(imageData as Map), + ); + }); } FutureOr _onFrameStreamCancel() async { @@ -290,8 +299,10 @@ class AVFoundationCamera extends CameraPlatform { } void _onFrameStreamPauseResume() { - throw CameraException('InvalidCall', - 'Pause and resume are not supported for onStreamedFrameAvailable'); + throw CameraException( + 'InvalidCall', + 'Pause and resume are not supported for onStreamedFrameAvailable', + ); } @override @@ -381,7 +392,8 @@ class AVFoundationCamera extends CameraPlatform { @override Future setDescriptionWhileRecording( - CameraDescription description) async { + CameraDescription description, + ) async { await _hostApi.updateDescriptionWhileRecording(description.name); } @@ -452,7 +464,8 @@ class AVFoundationCamera extends CameraPlatform { /// Returns a [ResolutionPreset]'s Pigeon representation. PlatformResolutionPreset _pigeonResolutionPreset( - ResolutionPreset? resolutionPreset) { + ResolutionPreset? resolutionPreset, + ) { if (resolutionPreset == null) { // Provide a default if one isn't provided, since the native side needs // to set something. @@ -552,8 +565,9 @@ class HostDeviceMessageHandler implements CameraGlobalEventApi { @override void deviceOrientationChanged(PlatformDeviceOrientation orientation) { - deviceEventStreamController.add(DeviceOrientationChangedEvent( - deviceOrientationFromPlatform(orientation))); + deviceEventStreamController.add( + DeviceOrientationChangedEvent(deviceOrientationFromPlatform(orientation)), + ); } } @@ -585,14 +599,16 @@ class HostCameraMessageHandler implements CameraEventApi { @override void initialized(PlatformCameraState initialState) { - streamController.add(CameraInitializedEvent( - cameraId, - initialState.previewSize.width, - initialState.previewSize.height, - exposureModeFromPlatform(initialState.exposureMode), - initialState.exposurePointSupported, - focusModeFromPlatform(initialState.focusMode), - initialState.focusPointSupported, - )); + streamController.add( + CameraInitializedEvent( + cameraId, + initialState.previewSize.width, + initialState.previewSize.height, + exposureModeFromPlatform(initialState.exposureMode), + initialState.exposurePointSupported, + focusModeFromPlatform(initialState.focusMode), + initialState.focusPointSupported, + ), + ); } } diff --git a/packages/camera/camera_avfoundation/lib/src/messages.g.dart b/packages/camera/camera_avfoundation/lib/src/messages.g.dart index 535f03e34c2..540bfeecf64 100644 --- a/packages/camera/camera_avfoundation/lib/src/messages.g.dart +++ b/packages/camera/camera_avfoundation/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -47,48 +50,21 @@ enum PlatformDeviceOrientation { landscapeRight, } -enum PlatformExposureMode { - auto, - locked, -} +enum PlatformExposureMode { auto, locked } -enum PlatformFlashMode { - off, - auto, - always, - torch, -} +enum PlatformFlashMode { off, auto, always, torch } -enum PlatformFocusMode { - auto, - locked, -} +enum PlatformFocusMode { auto, locked } /// Pigeon version of ImageFileFormat. -enum PlatformImageFileFormat { - jpeg, - heif, -} +enum PlatformImageFileFormat { jpeg, heif } -enum PlatformImageFormatGroup { - bgra8888, - yuv420, -} +enum PlatformImageFormatGroup { bgra8888, yuv420 } -enum PlatformResolutionPreset { - low, - medium, - high, - veryHigh, - ultraHigh, - max, -} +enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } class PlatformCameraDescription { - PlatformCameraDescription({ - required this.name, - required this.lensDirection, - }); + PlatformCameraDescription({required this.name, required this.lensDirection}); /// The name of the camera device. String name; @@ -97,10 +73,7 @@ class PlatformCameraDescription { PlatformCameraLensDirection lensDirection; Object encode() { - return [ - name, - lensDirection, - ]; + return [name, lensDirection]; } static PlatformCameraDescription decode(Object result) { @@ -200,46 +173,31 @@ class PlatformMediaSettings { } class PlatformPoint { - PlatformPoint({ - required this.x, - required this.y, - }); + PlatformPoint({required this.x, required this.y}); double x; double y; Object encode() { - return [ - x, - y, - ]; + return [x, y]; } static PlatformPoint decode(Object result) { result as List; - return PlatformPoint( - x: result[0]! as double, - y: result[1]! as double, - ); + return PlatformPoint(x: result[0]! as double, y: result[1]! as double); } } class PlatformSize { - PlatformSize({ - required this.width, - required this.height, - }); + PlatformSize({required this.width, required this.height}); double width; double height; Object encode() { - return [ - width, - height, - ]; + return [width, height]; } static PlatformSize decode(Object result) { @@ -349,11 +307,12 @@ class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - CameraApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + CameraApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -366,10 +325,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -397,12 +356,13 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.create$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([cameraName, settings]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([cameraName, settings]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -423,17 +383,20 @@ class CameraApi { /// Initializes the camera with the given ID. Future initialize( - int cameraId, PlatformImageFormatGroup imageFormat) async { + int cameraId, + PlatformImageFormatGroup imageFormat, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.initialize$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([cameraId, imageFormat]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([cameraId, imageFormat]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -453,10 +416,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.startImageStream$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -478,10 +441,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.stopImageStream$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -506,10 +469,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.receivedImageStreamData$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -532,10 +495,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.dispose$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -553,15 +516,16 @@ class CameraApi { /// Locks the camera capture to the current device orientation. Future lockCaptureOrientation( - PlatformDeviceOrientation orientation) async { + PlatformDeviceOrientation orientation, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([orientation]) as List?; if (pigeonVar_replyList == null) { @@ -584,10 +548,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.unlockCaptureOrientation$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -610,10 +574,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.takePicture$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -640,10 +604,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.prepareForVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -666,10 +630,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([enableStream]) as List?; if (pigeonVar_replyList == null) { @@ -691,10 +655,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -721,10 +685,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.pauseVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -746,10 +710,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.resumeVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -771,10 +735,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setFlashMode$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([mode]) as List?; if (pigeonVar_replyList == null) { @@ -796,10 +760,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureMode$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([mode]) as List?; if (pigeonVar_replyList == null) { @@ -823,10 +787,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposurePoint$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([point]) as List?; if (pigeonVar_replyList == null) { @@ -848,10 +812,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinExposureOffset$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -878,10 +842,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxExposureOffset$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -908,10 +872,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureOffset$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([offset]) as List?; if (pigeonVar_replyList == null) { @@ -933,10 +897,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusMode$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([mode]) as List?; if (pigeonVar_replyList == null) { @@ -960,10 +924,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusPoint$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([point]) as List?; if (pigeonVar_replyList == null) { @@ -985,10 +949,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinZoomLevel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1015,10 +979,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxZoomLevel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1045,10 +1009,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setZoomLevel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([zoom]) as List?; if (pigeonVar_replyList == null) { @@ -1070,10 +1034,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.pausePreview$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1095,10 +1059,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.resumePreview$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -1122,10 +1086,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.updateDescriptionWhileRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraName]) as List?; if (pigeonVar_replyList == null) { @@ -1147,10 +1111,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setImageFileFormat$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([format]) as List?; if (pigeonVar_replyList == null) { @@ -1182,23 +1146,27 @@ abstract class CameraGlobalEventApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged was null.', + ); final List args = (message as List?)!; final PlatformDeviceOrientation? arg_orientation = (args[0] as PlatformDeviceOrientation?); - assert(arg_orientation != null, - 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged was null, expected non-null PlatformDeviceOrientation.'); + assert( + arg_orientation != null, + 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged was null, expected non-null PlatformDeviceOrientation.', + ); try { api.deviceOrientationChanged(arg_orientation!); return wrapResponse(empty: true); @@ -1206,7 +1174,8 @@ abstract class CameraGlobalEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1237,23 +1206,27 @@ abstract class CameraEventApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null.', + ); final List args = (message as List?)!; final PlatformCameraState? arg_initialState = (args[0] as PlatformCameraState?); - assert(arg_initialState != null, - 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null, expected non-null PlatformCameraState.'); + assert( + arg_initialState != null, + 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null, expected non-null PlatformCameraState.', + ); try { api.initialized(arg_initialState!); return wrapResponse(empty: true); @@ -1261,28 +1234,33 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error was null.', + ); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error was null, expected non-null String.', + ); try { api.error(arg_message!); return wrapResponse(empty: true); @@ -1290,7 +1268,8 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart index 58a4e1518e1..8deae74dc51 100644 --- a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart +++ b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart @@ -10,16 +10,20 @@ import 'package:camera_platform_interface/camera_platform_interface.dart'; /// [CameraImageData]. CameraImageData cameraImageFromPlatformData(Map data) { return CameraImageData( - format: _cameraImageFormatFromPlatformData(data['format']), - height: data['height'] as int, - width: data['width'] as int, - lensAperture: data['lensAperture'] as double?, - sensorExposureTime: data['sensorExposureTime'] as int?, - sensorSensitivity: data['sensorSensitivity'] as double?, - planes: List.unmodifiable( - (data['planes'] as List).map( - (dynamic planeData) => _cameraImagePlaneFromPlatformData( - planeData as Map)))); + format: _cameraImageFormatFromPlatformData(data['format']), + height: data['height'] as int, + width: data['width'] as int, + lensAperture: data['lensAperture'] as double?, + sensorExposureTime: data['sensorExposureTime'] as int?, + sensorSensitivity: data['sensorSensitivity'] as double?, + planes: List.unmodifiable( + (data['planes'] as List).map( + (dynamic planeData) => _cameraImagePlaneFromPlatformData( + planeData as Map, + ), + ), + ), + ); } CameraImageFormat _cameraImageFormatFromPlatformData(dynamic data) { @@ -40,9 +44,10 @@ ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) { CameraImagePlane _cameraImagePlaneFromPlatformData(Map data) { return CameraImagePlane( - bytes: data['bytes'] as Uint8List, - bytesPerPixel: data['bytesPerPixel'] as int?, - bytesPerRow: data['bytesPerRow'] as int, - height: data['height'] as int?, - width: data['width'] as int?); + bytes: data['bytes'] as Uint8List, + bytesPerPixel: data['bytesPerPixel'] as int?, + bytesPerRow: data['bytesPerRow'] as int, + height: data['height'] as int?, + width: data['width'] as int?, + ); } diff --git a/packages/camera/camera_avfoundation/lib/src/utils.dart b/packages/camera/camera_avfoundation/lib/src/utils.dart index 3fd7f59a891..e84a6d25930 100644 --- a/packages/camera/camera_avfoundation/lib/src/utils.dart +++ b/packages/camera/camera_avfoundation/lib/src/utils.dart @@ -9,16 +9,19 @@ import 'messages.g.dart'; /// Creates a [CameraDescription] from a Pigeon [PlatformCameraDescription]. CameraDescription cameraDescriptionFromPlatform( - PlatformCameraDescription camera) { + PlatformCameraDescription camera, +) { return CameraDescription( - name: camera.name, - lensDirection: cameraLensDirectionFromPlatform(camera.lensDirection), - sensorOrientation: 90); + name: camera.name, + lensDirection: cameraLensDirectionFromPlatform(camera.lensDirection), + sensorOrientation: 90, + ); } /// Converts a Pigeon [PlatformCameraLensDirection] to a [CameraLensDirection]. CameraLensDirection cameraLensDirectionFromPlatform( - PlatformCameraLensDirection direction) { + PlatformCameraLensDirection direction, +) { return switch (direction) { PlatformCameraLensDirection.front => CameraLensDirection.front, PlatformCameraLensDirection.back => CameraLensDirection.back, @@ -28,7 +31,8 @@ CameraLensDirection cameraLensDirectionFromPlatform( /// Convents the given device orientation to Pigeon. PlatformDeviceOrientation serializeDeviceOrientation( - DeviceOrientation orientation) { + DeviceOrientation orientation, +) { switch (orientation) { case DeviceOrientation.portraitUp: return PlatformDeviceOrientation.portraitUp; @@ -50,7 +54,8 @@ PlatformDeviceOrientation serializeDeviceOrientation( /// Converts a Pigeon [PlatformDeviceOrientation] to a [DeviceOrientation]. DeviceOrientation deviceOrientationFromPlatform( - PlatformDeviceOrientation orientation) { + PlatformDeviceOrientation orientation, +) { return switch (orientation) { PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp, PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown, diff --git a/packages/camera/camera_avfoundation/pigeons/messages.dart b/packages/camera/camera_avfoundation/pigeons/messages.dart index cc004b70ad3..4b4ccffe1a9 100644 --- a/packages/camera/camera_avfoundation/pigeons/messages.dart +++ b/packages/camera/camera_avfoundation/pigeons/messages.dart @@ -4,19 +4,20 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - objcHeaderOut: - 'ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/messages.g.h', - objcSourceOut: - 'ios/camera_avfoundation/Sources/camera_avfoundation_objc/messages.g.m', - objcOptions: ObjcOptions( - prefix: 'FCP', - headerIncludePath: './include/camera_avfoundation/messages.g.h', +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + objcHeaderOut: + 'ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/messages.g.h', + objcSourceOut: + 'ios/camera_avfoundation/Sources/camera_avfoundation_objc/messages.g.m', + objcOptions: ObjcOptions( + prefix: 'FCP', + headerIncludePath: './include/camera_avfoundation/messages.g.h', + ), + copyrightHeader: 'pigeons/copyright.txt', ), - copyrightHeader: 'pigeons/copyright.txt', -)) - +) // Pigeon version of CameraLensDirection. enum PlatformCameraLensDirection { /// Front facing camera (a user looking at the screen is seen by the camera). @@ -38,53 +39,26 @@ enum PlatformDeviceOrientation { } // Pigeon version of ExposureMode. -enum PlatformExposureMode { - auto, - locked, -} +enum PlatformExposureMode { auto, locked } // Pigeon version of FlashMode. -enum PlatformFlashMode { - off, - auto, - always, - torch, -} +enum PlatformFlashMode { off, auto, always, torch } // Pigeon version of FocusMode. -enum PlatformFocusMode { - auto, - locked, -} +enum PlatformFocusMode { auto, locked } /// Pigeon version of ImageFileFormat. -enum PlatformImageFileFormat { - jpeg, - heif, -} +enum PlatformImageFileFormat { jpeg, heif } // Pigeon version of the subset of ImageFormatGroup supported on iOS. -enum PlatformImageFormatGroup { - bgra8888, - yuv420, -} +enum PlatformImageFormatGroup { bgra8888, yuv420 } // Pigeon version of ResolutionPreset. -enum PlatformResolutionPreset { - low, - medium, - high, - veryHigh, - ultraHigh, - max, -} +enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } // Pigeon version of CameraDescription. class PlatformCameraDescription { - PlatformCameraDescription({ - required this.name, - required this.lensDirection, - }); + PlatformCameraDescription({required this.name, required this.lensDirection}); /// The name of the camera device. final String name; diff --git a/packages/camera/camera_avfoundation/pubspec.yaml b/packages/camera/camera_avfoundation/pubspec.yaml index ba90f6ab57c..44384801553 100644 --- a/packages/camera/camera_avfoundation/pubspec.yaml +++ b/packages/camera/camera_avfoundation/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.9.21+1 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart index 1e8ad7def5d..648320fe24a 100644 --- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart +++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart @@ -38,15 +38,17 @@ void main() { // Act final int cameraId = await camera.createCamera( const CameraDescription( - name: cameraName, - lensDirection: CameraLensDirection.back, - sensorOrientation: 0), + name: cameraName, + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), ResolutionPreset.high, ); // Assert - final VerificationResult verification = - verify(mockApi.create(captureAny, captureAny)); + final VerificationResult verification = verify( + mockApi.create(captureAny, captureAny), + ); expect(verification.captured[0], cameraName); final PlatformMediaSettings? settings = verification.captured[1] as PlatformMediaSettings?; @@ -56,76 +58,88 @@ void main() { }); test( - 'Should send creation data and receive back a camera id using createCameraWithSettings', - () async { - // Arrange - final MockCameraApi mockApi = MockCameraApi(); - when(mockApi.create(any, any)).thenAnswer((_) async => 1); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); - const String cameraName = 'Test'; - const int fps = 15; - const int videoBitrate = 200000; - const int audioBitrate = 32000; + 'Should send creation data and receive back a camera id using createCameraWithSettings', + () async { + // Arrange + final MockCameraApi mockApi = MockCameraApi(); + when(mockApi.create(any, any)).thenAnswer((_) async => 1); + final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); + const String cameraName = 'Test'; + const int fps = 15; + const int videoBitrate = 200000; + const int audioBitrate = 32000; - // Act - final int cameraId = await camera.createCameraWithSettings( - const CameraDescription( + // Act + final int cameraId = await camera.createCameraWithSettings( + const CameraDescription( name: cameraName, lensDirection: CameraLensDirection.back, - sensorOrientation: 0), - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: fps, - videoBitrate: videoBitrate, - audioBitrate: audioBitrate, - enableAudio: true, - ), - ); + sensorOrientation: 0, + ), + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: fps, + videoBitrate: videoBitrate, + audioBitrate: audioBitrate, + enableAudio: true, + ), + ); - // Assert - final VerificationResult verification = - verify(mockApi.create(captureAny, captureAny)); - expect(verification.captured[0], cameraName); - final PlatformMediaSettings? settings = - verification.captured[1] as PlatformMediaSettings?; - expect(settings, isNotNull); - expect(settings?.resolutionPreset, PlatformResolutionPreset.low); - expect(settings?.framesPerSecond, fps); - expect(settings?.videoBitrate, videoBitrate); - expect(settings?.audioBitrate, audioBitrate); - expect(settings?.enableAudio, true); - expect(cameraId, 1); - }); + // Assert + final VerificationResult verification = verify( + mockApi.create(captureAny, captureAny), + ); + expect(verification.captured[0], cameraName); + final PlatformMediaSettings? settings = + verification.captured[1] as PlatformMediaSettings?; + expect(settings, isNotNull); + expect(settings?.resolutionPreset, PlatformResolutionPreset.low); + expect(settings?.framesPerSecond, fps); + expect(settings?.videoBitrate, videoBitrate); + expect(settings?.audioBitrate, audioBitrate); + expect(settings?.enableAudio, true); + expect(cameraId, 1); + }, + ); - test('Should throw CameraException when create throws a PlatformException', - () { - // Arrange - const String exceptionCode = 'TESTING_ERROR_CODE'; - const String exceptionMessage = 'Mock error message used during testing.'; - final MockCameraApi mockApi = MockCameraApi(); - when(mockApi.create(any, any)).thenAnswer((_) async { - throw PlatformException(code: exceptionCode, message: exceptionMessage); - }); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); + test( + 'Should throw CameraException when create throws a PlatformException', + () { + // Arrange + const String exceptionCode = 'TESTING_ERROR_CODE'; + const String exceptionMessage = + 'Mock error message used during testing.'; + final MockCameraApi mockApi = MockCameraApi(); + when(mockApi.create(any, any)).thenAnswer((_) async { + throw PlatformException( + code: exceptionCode, + message: exceptionMessage, + ); + }); + final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); - // Act - expect( - () => camera.createCamera( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + // Act + expect( + () => camera.createCamera( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), + ResolutionPreset.high, ), - ResolutionPreset.high, - ), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', exceptionCode) - .having((CameraException e) => e.description, 'description', - exceptionMessage), - ), - ); - }); + throwsA( + isA() + .having((CameraException e) => e.code, 'code', exceptionCode) + .having( + (CameraException e) => e.description, + 'description', + exceptionMessage, + ), + ), + ); + }, + ); test( 'Should throw CameraException when initialize throws a PlatformException', @@ -137,7 +151,9 @@ void main() { final MockCameraApi mockApi = MockCameraApi(); when(mockApi.initialize(any, any)).thenAnswer((_) async { throw PlatformException( - code: exceptionCode, message: exceptionMessage); + code: exceptionCode, + message: exceptionMessage, + ); }); final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); @@ -147,7 +163,10 @@ void main() { throwsA( isA() .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) .having( (CameraException e) => e.description, 'description', @@ -173,20 +192,23 @@ void main() { // Act final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; // Assert - final VerificationResult verification = - verify(mockApi.initialize(captureAny, captureAny)); + final VerificationResult verification = verify( + mockApi.initialize(captureAny, captureAny), + ); expect(verification.captured[0], cameraId); // The default when unspecified should be bgra8888. expect(verification.captured[1], PlatformImageFormatGroup.bgra8888); @@ -205,23 +227,26 @@ void main() { ResolutionPreset.high, ); final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; // Act await camera.dispose(cameraId); // Assert - final VerificationResult verification = - verify(mockApi.dispose(captureAny)); + final VerificationResult verification = verify( + mockApi.dispose(captureAny), + ); expect(verification.captured[0], cameraId); }); }); @@ -242,22 +267,24 @@ void main() { ResolutionPreset.high, ); final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; }); test('Should receive initialized event', () async { // Act - final Stream eventStream = - camera.onCameraInitialized(cameraId); + final Stream eventStream = camera + .onCameraInitialized(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -272,13 +299,15 @@ void main() { FocusMode.auto, true, ); - camera.hostCameraHandlers[cameraId]!.initialized(PlatformCameraState( - previewSize: previewSize, - exposureMode: PlatformExposureMode.auto, - focusMode: PlatformFocusMode.auto, - exposurePointSupported: true, - focusPointSupported: true, - )); + camera.hostCameraHandlers[cameraId]!.initialized( + PlatformCameraState( + previewSize: previewSize, + exposureMode: PlatformExposureMode.auto, + focusMode: PlatformFocusMode.auto, + exposurePointSupported: true, + focusPointSupported: true, + ), + ); // Assert expect(await streamQueue.next, event); @@ -289,8 +318,9 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = - camera.onCameraError(cameraId); + final Stream errorStream = camera.onCameraError( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(errorStream); @@ -318,11 +348,13 @@ void main() { StreamQueue(eventStream); // Emit test events - const DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); for (int i = 0; i < 3; i++) { - camera.hostHandler - .deviceOrientationChanged(PlatformDeviceOrientation.portraitUp); + camera.hostHandler.deviceOrientationChanged( + PlatformDeviceOrientation.portraitUp, + ); } // Assert @@ -367,47 +399,60 @@ void main() { await initializeFuture; }); - test('Should fetch CameraDescription instances for available cameras', - () async { - final List returnData = - [ - PlatformCameraDescription( - name: 'Test 1', lensDirection: PlatformCameraLensDirection.front), - PlatformCameraDescription( - name: 'Test 2', lensDirection: PlatformCameraLensDirection.back), - ]; - when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); - - final List cameras = await camera.availableCameras(); - - expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { - expect(cameras[i].name, returnData[i].name); - expect(cameras[i].lensDirection, - cameraLensDirectionFromPlatform(returnData[i].lensDirection)); - // This value isn't provided by the platform, so is hard-coded to 90. - expect(cameras[i].sensorOrientation, 90); - } - }); + test( + 'Should fetch CameraDescription instances for available cameras', + () async { + final List returnData = + [ + PlatformCameraDescription( + name: 'Test 1', + lensDirection: PlatformCameraLensDirection.front, + ), + PlatformCameraDescription( + name: 'Test 2', + lensDirection: PlatformCameraLensDirection.back, + ), + ]; + when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); + + final List cameras = await camera.availableCameras(); + + expect(cameras.length, returnData.length); + for (int i = 0; i < returnData.length; i++) { + expect(cameras[i].name, returnData[i].name); + expect( + cameras[i].lensDirection, + cameraLensDirectionFromPlatform(returnData[i].lensDirection), + ); + // This value isn't provided by the platform, so is hard-coded to 90. + expect(cameras[i].sensorOrientation, 90); + } + }, + ); test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - const String code = 'TESTING_ERROR_CODE'; - const String message = 'Mock error message used during testing.'; - when(mockApi.getAvailableCameras()).thenAnswer( - (_) async => throw PlatformException(code: code, message: message)); - - expect( - camera.availableCameras, - throwsA( - isA() - .having((CameraException e) => e.code, 'code', code) - .having( - (CameraException e) => e.description, 'description', message), - ), - ); - }); + 'Should throw CameraException when availableCameras throws a PlatformException', + () { + const String code = 'TESTING_ERROR_CODE'; + const String message = 'Mock error message used during testing.'; + when(mockApi.getAvailableCameras()).thenAnswer( + (_) async => throw PlatformException(code: code, message: message), + ); + + expect( + camera.availableCameras, + throwsA( + isA() + .having((CameraException e) => e.code, 'code', code) + .having( + (CameraException e) => e.description, + 'description', + message, + ), + ), + ); + }, + ); test('Should take a picture and return an XFile instance', () async { const String stubPath = '/test/path.jpg'; @@ -431,13 +476,18 @@ void main() { }); test( - 'Should pass enableStream if callback is passed when starting recording a video', - () async { - await camera.startVideoCapturing(VideoCaptureOptions(cameraId, - streamCallback: (CameraImageData imageData) {})); + 'Should pass enableStream if callback is passed when starting recording a video', + () async { + await camera.startVideoCapturing( + VideoCaptureOptions( + cameraId, + streamCallback: (CameraImageData imageData) {}, + ), + ); - verify(mockApi.startVideoRecording(true)); - }); + verify(mockApi.startVideoRecording(true)); + }, + ); test('Should stop a video recording and return the file', () async { const String stubPath = '/test/path.mp4'; @@ -462,9 +512,10 @@ void main() { test('Should set the description while recording', () async { const CameraDescription camera2Description = CameraDescription( - name: 'Test2', - lensDirection: CameraLensDirection.front, - sensorOrientation: 0); + name: 'Test2', + lensDirection: CameraLensDirection.front, + sensorOrientation: 0, + ); await camera.setDescriptionWhileRecording(camera2Description); @@ -511,8 +562,9 @@ void main() { const Point point = Point(0.4, 0.6); await camera.setExposurePoint(cameraId, point); - final VerificationResult verification = - verify(mockApi.setExposurePoint(captureAny)); + final VerificationResult verification = verify( + mockApi.setExposurePoint(captureAny), + ); final PlatformPoint? passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint?.x, point.x); @@ -522,8 +574,9 @@ void main() { test('Should set the exposure point to null for reset', () async { await camera.setExposurePoint(cameraId, null); - final VerificationResult verification = - verify(mockApi.setExposurePoint(captureAny)); + final VerificationResult verification = verify( + mockApi.setExposurePoint(captureAny), + ); final PlatformPoint? passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint, null); @@ -531,22 +584,26 @@ void main() { test('Should get the min exposure offset', () async { const double stubMinOffset = 2.0; - when(mockApi.getMinExposureOffset()) - .thenAnswer((_) async => stubMinOffset); + when( + mockApi.getMinExposureOffset(), + ).thenAnswer((_) async => stubMinOffset); - final double minExposureOffset = - await camera.getMinExposureOffset(cameraId); + final double minExposureOffset = await camera.getMinExposureOffset( + cameraId, + ); expect(minExposureOffset, stubMinOffset); }); test('Should get the max exposure offset', () async { const double stubMaxOffset = 2.0; - when(mockApi.getMaxExposureOffset()) - .thenAnswer((_) async => stubMaxOffset); + when( + mockApi.getMaxExposureOffset(), + ).thenAnswer((_) async => stubMaxOffset); - final double maxExposureOffset = - await camera.getMaxExposureOffset(cameraId); + final double maxExposureOffset = await camera.getMaxExposureOffset( + cameraId, + ); expect(maxExposureOffset, stubMaxOffset); }); @@ -582,8 +639,9 @@ void main() { const Point point = Point(0.4, 0.6); await camera.setFocusPoint(cameraId, point); - final VerificationResult verification = - verify(mockApi.setFocusPoint(captureAny)); + final VerificationResult verification = verify( + mockApi.setFocusPoint(captureAny), + ); final PlatformPoint? passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint?.x, point.x); @@ -593,8 +651,9 @@ void main() { test('Should set the focus point to null for reset', () async { await camera.setFocusPoint(cameraId, null); - final VerificationResult verification = - verify(mockApi.setFocusPoint(captureAny)); + final VerificationResult verification = verify( + mockApi.setFocusPoint(captureAny), + ); final PlatformPoint? passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint, null); @@ -633,27 +692,39 @@ void main() { verify(mockApi.setZoomLevel(zoom)); }); - test('Should throw CameraException when illegal zoom level is supplied', - () async { - const String code = 'ZOOM_ERROR'; - const String message = 'Illegal zoom error'; - when(mockApi.setZoomLevel(any)).thenAnswer( - (_) async => throw PlatformException(code: code, message: message)); + test( + 'Should throw CameraException when illegal zoom level is supplied', + () async { + const String code = 'ZOOM_ERROR'; + const String message = 'Illegal zoom error'; + when(mockApi.setZoomLevel(any)).thenAnswer( + (_) async => throw PlatformException(code: code, message: message), + ); - expect( + expect( () => camera.setZoomLevel(cameraId, -1.0), - throwsA(isA() - .having((CameraException e) => e.code, 'code', code) - .having((CameraException e) => e.description, 'description', - message))); - }); + throwsA( + isA() + .having((CameraException e) => e.code, 'code', code) + .having( + (CameraException e) => e.description, + 'description', + message, + ), + ), + ); + }, + ); test('Should lock the capture orientation', () async { await camera.lockCaptureOrientation( - cameraId, DeviceOrientation.portraitUp); + cameraId, + DeviceOrientation.portraitUp, + ); verify( - mockApi.lockCaptureOrientation(PlatformDeviceOrientation.portraitUp)); + mockApi.lockCaptureOrientation(PlatformDeviceOrientation.portraitUp), + ); }); test('Should unlock the capture orientation', () async { diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart index b1118578a16..0d09546d2ae 100644 --- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart +++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart @@ -27,31 +27,33 @@ import 'package:mockito/src/dummies.dart' as _i3; /// See the documentation for Mockito's code generation for more information. class MockCameraApi extends _i1.Mock implements _i2.CameraApi { @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override _i4.Future> getAvailableCameras() => (super.noSuchMethod( - Invocation.method( - #getAvailableCameras, - [], - ), - returnValue: _i4.Future>.value( - <_i2.PlatformCameraDescription>[]), - returnValueForMissingStub: - _i4.Future>.value( - <_i2.PlatformCameraDescription>[]), - ) as _i4.Future>); + Invocation.method(#getAvailableCameras, []), + returnValue: _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + returnValueForMissingStub: + _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + ) + as _i4.Future>); @override _i4.Future create( @@ -59,16 +61,11 @@ class MockCameraApi extends _i1.Mock implements _i2.CameraApi { _i2.PlatformMediaSettings? settings, ) => (super.noSuchMethod( - Invocation.method( - #create, - [ - cameraName, - settings, - ], - ), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) as _i4.Future); + Invocation.method(#create, [cameraName, settings]), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) + as _i4.Future); @override _i4.Future initialize( @@ -76,320 +73,268 @@ class MockCameraApi extends _i1.Mock implements _i2.CameraApi { _i2.PlatformImageFormatGroup? imageFormat, ) => (super.noSuchMethod( - Invocation.method( - #initialize, - [ - cameraId, - imageFormat, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#initialize, [cameraId, imageFormat]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future startImageStream() => (super.noSuchMethod( - Invocation.method( - #startImageStream, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future startImageStream() => + (super.noSuchMethod( + Invocation.method(#startImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future stopImageStream() => (super.noSuchMethod( - Invocation.method( - #stopImageStream, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future stopImageStream() => + (super.noSuchMethod( + Invocation.method(#stopImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future receivedImageStreamData() => (super.noSuchMethod( - Invocation.method( - #receivedImageStreamData, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future receivedImageStreamData() => + (super.noSuchMethod( + Invocation.method(#receivedImageStreamData, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future dispose(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #dispose, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future dispose(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#dispose, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future lockCaptureOrientation( - _i2.PlatformDeviceOrientation? orientation) => + _i2.PlatformDeviceOrientation? orientation, + ) => (super.noSuchMethod( - Invocation.method( - #lockCaptureOrientation, - [orientation], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#lockCaptureOrientation, [orientation]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future unlockCaptureOrientation() => (super.noSuchMethod( - Invocation.method( - #unlockCaptureOrientation, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future unlockCaptureOrientation() => + (super.noSuchMethod( + Invocation.method(#unlockCaptureOrientation, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future takePicture() => (super.noSuchMethod( - Invocation.method( - #takePicture, - [], - ), - returnValue: _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #takePicture, - [], - ), - )), - returnValueForMissingStub: - _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #takePicture, - [], - ), - )), - ) as _i4.Future); + _i4.Future takePicture() => + (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + ) + as _i4.Future); @override - _i4.Future prepareForVideoRecording() => (super.noSuchMethod( - Invocation.method( - #prepareForVideoRecording, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future prepareForVideoRecording() => + (super.noSuchMethod( + Invocation.method(#prepareForVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future startVideoRecording(bool? enableStream) => (super.noSuchMethod( - Invocation.method( - #startVideoRecording, - [enableStream], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#startVideoRecording, [enableStream]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future stopVideoRecording() => (super.noSuchMethod( - Invocation.method( - #stopVideoRecording, - [], - ), - returnValue: _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #stopVideoRecording, - [], - ), - )), - returnValueForMissingStub: - _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #stopVideoRecording, - [], - ), - )), - ) as _i4.Future); + _i4.Future stopVideoRecording() => + (super.noSuchMethod( + Invocation.method(#stopVideoRecording, []), + returnValue: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#stopVideoRecording, []), + ), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#stopVideoRecording, []), + ), + ), + ) + as _i4.Future); @override - _i4.Future pauseVideoRecording() => (super.noSuchMethod( - Invocation.method( - #pauseVideoRecording, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future pauseVideoRecording() => + (super.noSuchMethod( + Invocation.method(#pauseVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future resumeVideoRecording() => (super.noSuchMethod( - Invocation.method( - #resumeVideoRecording, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future resumeVideoRecording() => + (super.noSuchMethod( + Invocation.method(#resumeVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setFlashMode(_i2.PlatformFlashMode? mode) => (super.noSuchMethod( - Invocation.method( - #setFlashMode, - [mode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFlashMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setExposureMode(_i2.PlatformExposureMode? mode) => (super.noSuchMethod( - Invocation.method( - #setExposureMode, - [mode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setExposureMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setExposurePoint(_i2.PlatformPoint? point) => (super.noSuchMethod( - Invocation.method( - #setExposurePoint, - [point], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setExposurePoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future getMinExposureOffset() => (super.noSuchMethod( - Invocation.method( - #getMinExposureOffset, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMinExposureOffset() => + (super.noSuchMethod( + Invocation.method(#getMinExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future getMaxExposureOffset() => (super.noSuchMethod( - Invocation.method( - #getMaxExposureOffset, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMaxExposureOffset() => + (super.noSuchMethod( + Invocation.method(#getMaxExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future setExposureOffset(double? offset) => (super.noSuchMethod( - Invocation.method( - #setExposureOffset, - [offset], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setExposureOffset(double? offset) => + (super.noSuchMethod( + Invocation.method(#setExposureOffset, [offset]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setFocusMode(_i2.PlatformFocusMode? mode) => (super.noSuchMethod( - Invocation.method( - #setFocusMode, - [mode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFocusMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setFocusPoint(_i2.PlatformPoint? point) => (super.noSuchMethod( - Invocation.method( - #setFocusPoint, - [point], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFocusPoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future getMinZoomLevel() => (super.noSuchMethod( - Invocation.method( - #getMinZoomLevel, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMinZoomLevel() => + (super.noSuchMethod( + Invocation.method(#getMinZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future getMaxZoomLevel() => (super.noSuchMethod( - Invocation.method( - #getMaxZoomLevel, - [], - ), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) as _i4.Future); + _i4.Future getMaxZoomLevel() => + (super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) + as _i4.Future); @override - _i4.Future setZoomLevel(double? zoom) => (super.noSuchMethod( - Invocation.method( - #setZoomLevel, - [zoom], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setZoomLevel(double? zoom) => + (super.noSuchMethod( + Invocation.method(#setZoomLevel, [zoom]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future pausePreview() => (super.noSuchMethod( - Invocation.method( - #pausePreview, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future pausePreview() => + (super.noSuchMethod( + Invocation.method(#pausePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future resumePreview() => (super.noSuchMethod( - Invocation.method( - #resumePreview, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future resumePreview() => + (super.noSuchMethod( + Invocation.method(#resumePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future updateDescriptionWhileRecording(String? cameraName) => (super.noSuchMethod( - Invocation.method( - #updateDescriptionWhileRecording, - [cameraName], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#updateDescriptionWhileRecording, [cameraName]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setImageFileFormat(_i2.PlatformImageFileFormat? format) => (super.noSuchMethod( - Invocation.method( - #setImageFileFormat, - [format], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setImageFileFormat, [format]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/camera/camera_avfoundation/test/type_conversion_test.dart b/packages/camera/camera_avfoundation/test/type_conversion_test.dart index b59628065cd..a4af96210bd 100644 --- a/packages/camera/camera_avfoundation/test/type_conversion_test.dart +++ b/packages/camera/camera_avfoundation/test/type_conversion_test.dart @@ -10,24 +10,25 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 1, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 1, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.unknown); @@ -35,24 +36,25 @@ void main() { }); test('CameraImageData has ImageFormatGroup.yuv420', () { - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 875704438, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 875704438, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); } diff --git a/packages/camera/camera_avfoundation/test/utils_test.dart b/packages/camera/camera_avfoundation/test/utils_test.dart index 0e45e39c9e2..24d2a507dc5 100644 --- a/packages/camera/camera_avfoundation/test/utils_test.dart +++ b/packages/camera/camera_avfoundation/test/utils_test.dart @@ -26,31 +26,41 @@ void main() { }); test('serializeDeviceOrientation() should serialize correctly', () { - expect(serializeDeviceOrientation(DeviceOrientation.portraitUp), - PlatformDeviceOrientation.portraitUp); - expect(serializeDeviceOrientation(DeviceOrientation.portraitDown), - PlatformDeviceOrientation.portraitDown); - expect(serializeDeviceOrientation(DeviceOrientation.landscapeRight), - PlatformDeviceOrientation.landscapeRight); - expect(serializeDeviceOrientation(DeviceOrientation.landscapeLeft), - PlatformDeviceOrientation.landscapeLeft); + expect( + serializeDeviceOrientation(DeviceOrientation.portraitUp), + PlatformDeviceOrientation.portraitUp, + ); + expect( + serializeDeviceOrientation(DeviceOrientation.portraitDown), + PlatformDeviceOrientation.portraitDown, + ); + expect( + serializeDeviceOrientation(DeviceOrientation.landscapeRight), + PlatformDeviceOrientation.landscapeRight, + ); + expect( + serializeDeviceOrientation(DeviceOrientation.landscapeLeft), + PlatformDeviceOrientation.landscapeLeft, + ); }); test('deviceOrientationFromPlatform() should convert correctly', () { expect( - deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitUp), - DeviceOrientation.portraitUp); + deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitUp), + DeviceOrientation.portraitUp, + ); expect( - deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitDown), - DeviceOrientation.portraitDown); + deviceOrientationFromPlatform(PlatformDeviceOrientation.portraitDown), + DeviceOrientation.portraitDown, + ); expect( - deviceOrientationFromPlatform( - PlatformDeviceOrientation.landscapeRight), - DeviceOrientation.landscapeRight); + deviceOrientationFromPlatform(PlatformDeviceOrientation.landscapeRight), + DeviceOrientation.landscapeRight, + ); expect( - deviceOrientationFromPlatform( - PlatformDeviceOrientation.landscapeLeft), - DeviceOrientation.landscapeLeft); + deviceOrientationFromPlatform(PlatformDeviceOrientation.landscapeLeft), + DeviceOrientation.landscapeLeft, + ); }); }); } diff --git a/packages/camera/camera_platform_interface/CHANGELOG.md b/packages/camera/camera_platform_interface/CHANGELOG.md index 8177ba43310..9e26946eca0 100644 --- a/packages/camera/camera_platform_interface/CHANGELOG.md +++ b/packages/camera/camera_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.10.0 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 1c76c341d9b..52bf3102893 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 @@ -63,14 +63,14 @@ class CameraInitializedEvent extends CameraEvent { /// Converts the supplied [Map] to an instance of the [CameraInitializedEvent] /// class. CameraInitializedEvent.fromJson(Map json) - : previewWidth = json['previewWidth']! as double, - previewHeight = json['previewHeight']! as double, - exposureMode = deserializeExposureMode(json['exposureMode']! as String), - exposurePointSupported = - (json['exposurePointSupported'] as bool?) ?? false, - focusMode = deserializeFocusMode(json['focusMode']! as String), - focusPointSupported = (json['focusPointSupported'] as bool?) ?? false, - super(json['cameraId']! as int); + : previewWidth = json['previewWidth']! as double, + previewHeight = json['previewHeight']! as double, + exposureMode = deserializeExposureMode(json['exposureMode']! as String), + exposurePointSupported = + (json['exposurePointSupported'] as bool?) ?? false, + focusMode = deserializeFocusMode(json['focusMode']! as String), + focusPointSupported = (json['focusPointSupported'] as bool?) ?? false, + super(json['cameraId']! as int); /// The width of the preview in pixels. final double previewWidth; @@ -93,14 +93,14 @@ class CameraInitializedEvent extends CameraEvent { /// Converts the [CameraInitializedEvent] instance into a [Map] instance that /// can be serialized to JSON. Map toJson() => { - 'cameraId': cameraId, - 'previewWidth': previewWidth, - 'previewHeight': previewHeight, - 'exposureMode': serializeExposureMode(exposureMode), - 'exposurePointSupported': exposurePointSupported, - 'focusMode': serializeFocusMode(focusMode), - 'focusPointSupported': focusPointSupported, - }; + 'cameraId': cameraId, + 'previewWidth': previewWidth, + 'previewHeight': previewHeight, + 'exposureMode': serializeExposureMode(exposureMode), + 'exposurePointSupported': exposurePointSupported, + 'focusMode': serializeFocusMode(focusMode), + 'focusPointSupported': focusPointSupported, + }; @override bool operator ==(Object other) => @@ -117,14 +117,14 @@ class CameraInitializedEvent extends CameraEvent { @override int get hashCode => Object.hash( - super.hashCode, - previewWidth, - previewHeight, - exposureMode, - exposurePointSupported, - focusMode, - focusPointSupported, - ); + super.hashCode, + previewWidth, + previewHeight, + exposureMode, + exposurePointSupported, + focusMode, + focusPointSupported, + ); } /// An event fired when the resolution preset of the camera has changed. @@ -143,9 +143,9 @@ class CameraResolutionChangedEvent extends CameraEvent { /// Converts the supplied [Map] to an instance of the /// [CameraResolutionChangedEvent] class. CameraResolutionChangedEvent.fromJson(Map json) - : captureWidth = json['captureWidth']! as double, - captureHeight = json['captureHeight']! as double, - super(json['cameraId']! as int); + : captureWidth = json['captureWidth']! as double, + captureHeight = json['captureHeight']! as double, + super(json['cameraId']! as int); /// The capture width in pixels. final double captureWidth; @@ -156,10 +156,10 @@ class CameraResolutionChangedEvent extends CameraEvent { /// Converts the [CameraResolutionChangedEvent] instance into a [Map] instance /// that can be serialized to JSON. Map toJson() => { - 'cameraId': cameraId, - 'captureWidth': captureWidth, - 'captureHeight': captureHeight, - }; + 'cameraId': cameraId, + 'captureWidth': captureWidth, + 'captureHeight': captureHeight, + }; @override bool operator ==(Object other) => @@ -183,13 +183,11 @@ class CameraClosingEvent extends CameraEvent { /// Converts the supplied [Map] to an instance of the [CameraClosingEvent] /// class. CameraClosingEvent.fromJson(Map json) - : super(json['cameraId']! as int); + : super(json['cameraId']! as int); /// Converts the [CameraClosingEvent] instance into a [Map] instance that can /// be serialized to JSON. - Map toJson() => { - 'cameraId': cameraId, - }; + Map toJson() => {'cameraId': cameraId}; @override bool operator ==(Object other) => @@ -216,8 +214,8 @@ class CameraErrorEvent extends CameraEvent { /// Converts the supplied [Map] to an instance of the [CameraErrorEvent] /// class. CameraErrorEvent.fromJson(Map json) - : description = json['description']! as String, - super(json['cameraId']! as int); + : description = json['description']! as String, + super(json['cameraId']! as int); /// Description of the error. final String description; @@ -225,9 +223,9 @@ class CameraErrorEvent extends CameraEvent { /// Converts the [CameraErrorEvent] instance into a [Map] instance that can be /// serialized to JSON. Map toJson() => { - 'cameraId': cameraId, - 'description': description, - }; + 'cameraId': cameraId, + 'description': description, + }; @override bool operator ==(Object other) => @@ -253,11 +251,12 @@ class VideoRecordedEvent extends CameraEvent { /// Converts the supplied [Map] to an instance of the [VideoRecordedEvent] /// class. VideoRecordedEvent.fromJson(Map json) - : file = XFile(json['path']! as String), - maxVideoDuration = json['maxVideoDuration'] != null - ? Duration(milliseconds: json['maxVideoDuration'] as int) - : null, - super(json['cameraId']! as int); + : file = XFile(json['path']! as String), + maxVideoDuration = + json['maxVideoDuration'] != null + ? Duration(milliseconds: json['maxVideoDuration'] as int) + : null, + super(json['cameraId']! as int); /// XFile of the recorded video. final XFile file; @@ -268,10 +267,10 @@ class VideoRecordedEvent extends CameraEvent { /// Converts the [VideoRecordedEvent] instance into a [Map] instance that can be /// serialized to JSON. Map toJson() => { - 'cameraId': cameraId, - 'path': file.path, - 'maxVideoDuration': maxVideoDuration?.inMilliseconds - }; + 'cameraId': cameraId, + 'path': file.path, + 'maxVideoDuration': maxVideoDuration?.inMilliseconds, + }; @override bool operator ==(Object other) => diff --git a/packages/camera/camera_platform_interface/lib/src/events/device_event.dart b/packages/camera/camera_platform_interface/lib/src/events/device_event.dart index 65a378f16f1..a5d9ecb831e 100644 --- a/packages/camera/camera_platform_interface/lib/src/events/device_event.dart +++ b/packages/camera/camera_platform_interface/lib/src/events/device_event.dart @@ -34,8 +34,9 @@ class DeviceOrientationChangedEvent extends DeviceEvent { /// Converts the supplied [Map] to an instance of the [DeviceOrientationChangedEvent] /// class. DeviceOrientationChangedEvent.fromJson(Map json) - : orientation = - deserializeDeviceOrientation(json['orientation']! as String); + : orientation = deserializeDeviceOrientation( + json['orientation']! as String, + ); /// The new orientation of the device final DeviceOrientation orientation; @@ -43,8 +44,8 @@ class DeviceOrientationChangedEvent extends DeviceEvent { /// Converts the [DeviceOrientationChangedEvent] instance into a [Map] instance that /// can be serialized to JSON. Map toJson() => { - 'orientation': serializeDeviceOrientation(orientation), - }; + 'orientation': serializeDeviceOrientation(orientation), + }; @override bool operator ==(Object other) => 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 e38df486533..bbe070cdc1b 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 @@ -20,10 +20,12 @@ const MethodChannel _channel = MethodChannel('plugins.flutter.io/camera'); class MethodChannelCamera extends CameraPlatform { /// Construct a new method channel camera instance. MethodChannelCamera() { - const MethodChannel channel = - MethodChannel('flutter.io/cameraPlugin/device'); + const MethodChannel channel = MethodChannel( + 'flutter.io/cameraPlugin/device', + ); channel.setMethodCallHandler( - (MethodCall call) => handleDeviceMethodCall(call)); + (MethodCall call) => handleDeviceMethodCall(call), + ); } final Map _channels = {}; @@ -56,9 +58,9 @@ class MethodChannelCamera extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => - cameraEventStreamController.stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => cameraEventStreamController + .stream + .where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { @@ -73,8 +75,9 @@ class MethodChannelCamera extends CameraPlatform { return cameras.map((Map camera) { return CameraDescription( name: camera['name']! as String, - lensDirection: - parseCameraLensDirection(camera['lensFacing']! as String), + lensDirection: parseCameraLensDirection( + camera['lensFacing']! as String, + ), sensorOrientation: camera['sensorOrientation']! as int, ); }).toList(); @@ -88,11 +91,10 @@ class MethodChannelCamera extends CameraPlatform { CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, - }) async => - createCameraWithSettings( - cameraDescription, - MediaSettings( - resolutionPreset: resolutionPreset, enableAudio: enableAudio)); + }) async => createCameraWithSettings( + cameraDescription, + MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio), + ); @override Future createCameraWithSettings( @@ -103,15 +105,18 @@ class MethodChannelCamera extends CameraPlatform { final ResolutionPreset? resolutionPreset = mediaSettings.resolutionPreset; final Map? reply = await _channel .invokeMapMethod('create', { - 'cameraName': cameraDescription.name, - 'resolutionPreset': resolutionPreset != null - ? _serializeResolutionPreset(mediaSettings.resolutionPreset!) - : null, - 'fps': mediaSettings.fps, - 'videoBitrate': mediaSettings.videoBitrate, - 'audioBitrate': mediaSettings.audioBitrate, - 'enableAudio': mediaSettings.enableAudio, - }); + 'cameraName': cameraDescription.name, + 'resolutionPreset': + resolutionPreset != null + ? _serializeResolutionPreset( + mediaSettings.resolutionPreset!, + ) + : null, + 'fps': mediaSettings.fps, + 'videoBitrate': mediaSettings.videoBitrate, + 'audioBitrate': mediaSettings.audioBitrate, + 'enableAudio': mediaSettings.enableAudio, + }); return reply!['cameraId']! as int; } on PlatformException catch (e) { @@ -125,10 +130,12 @@ class MethodChannelCamera extends CameraPlatform { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) { _channels.putIfAbsent(cameraId, () { - final MethodChannel channel = - MethodChannel('flutter.io/cameraPlugin/camera$cameraId'); + final MethodChannel channel = MethodChannel( + 'flutter.io/cameraPlugin/camera$cameraId', + ); channel.setMethodCallHandler( - (MethodCall call) => handleCameraMethodCall(call, cameraId)); + (MethodCall call) => handleCameraMethodCall(call, cameraId), + ); return channel; }); @@ -138,28 +145,27 @@ class MethodChannelCamera extends CameraPlatform { completer.complete(); }); - _channel.invokeMapMethod( - 'initialize', - { - 'cameraId': cameraId, - 'imageFormatGroup': imageFormatGroup.name(), - }, - ).catchError( - // TODO(srawlins): This should return a value of the future's type. This - // will fail upcoming analysis checks with - // https://github.com/flutter/flutter/issues/105750. - // ignore: body_might_complete_normally_catch_error - (Object error, StackTrace stackTrace) { - if (error is! PlatformException) { - // ignore: only_throw_errors - throw error; - } - completer.completeError( - CameraException(error.code, error.message), - stackTrace, + _channel + .invokeMapMethod('initialize', { + 'cameraId': cameraId, + 'imageFormatGroup': imageFormatGroup.name(), + }) + .catchError( + // TODO(srawlins): This should return a value of the future's type. This + // will fail upcoming analysis checks with + // https://github.com/flutter/flutter/issues/105750. + // ignore: body_might_complete_normally_catch_error + (Object error, StackTrace stackTrace) { + if (error is! PlatformException) { + // ignore: only_throw_errors + throw error; + } + completer.completeError( + CameraException(error.code, error.message), + stackTrace, + ); + }, ); - }, - ); return completer.future; } @@ -172,10 +178,9 @@ class MethodChannelCamera extends CameraPlatform { _channels.remove(cameraId); } - await _channel.invokeMethod( - 'dispose', - {'cameraId': cameraId}, - ); + await _channel.invokeMethod('dispose', { + 'cameraId': cameraId, + }); } @override @@ -218,7 +223,7 @@ class MethodChannelCamera extends CameraPlatform { 'lockCaptureOrientation', { 'cameraId': cameraId, - 'orientation': serializeDeviceOrientation(orientation) + 'orientation': serializeDeviceOrientation(orientation), }, ); } @@ -253,22 +258,22 @@ class MethodChannelCamera extends CameraPlatform { _channel.invokeMethod('prepareForVideoRecording'); @override - Future startVideoRecording(int cameraId, - {Duration? maxVideoDuration}) async { + Future startVideoRecording( + int cameraId, { + Duration? maxVideoDuration, + }) async { return startVideoCapturing( - VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration)); + VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration), + ); } @override Future startVideoCapturing(VideoCaptureOptions options) async { - await _channel.invokeMethod( - 'startVideoRecording', - { - 'cameraId': options.cameraId, - 'maxVideoDuration': options.maxDuration?.inMilliseconds, - 'enableStream': options.streamCallback != null, - }, - ); + await _channel.invokeMethod('startVideoRecording', { + 'cameraId': options.cameraId, + 'maxVideoDuration': options.maxDuration?.inMilliseconds, + 'enableStream': options.streamCallback != null, + }); if (options.streamCallback != null) { _installStreamController().stream.listen(options.streamCallback); @@ -295,26 +300,28 @@ class MethodChannelCamera extends CameraPlatform { @override Future pauseVideoRecording(int cameraId) => _channel.invokeMethod( - 'pauseVideoRecording', - {'cameraId': cameraId}, - ); + 'pauseVideoRecording', + {'cameraId': cameraId}, + ); @override Future resumeVideoRecording(int cameraId) => - _channel.invokeMethod( - 'resumeVideoRecording', - {'cameraId': cameraId}, - ); + _channel.invokeMethod('resumeVideoRecording', { + 'cameraId': cameraId, + }); @override - Stream onStreamedFrameAvailable(int cameraId, - {CameraImageStreamOptions? options}) { + Stream onStreamedFrameAvailable( + int cameraId, { + CameraImageStreamOptions? options, + }) { _installStreamController(onListen: _onFrameStreamListen); return _frameStreamController!.stream; } - StreamController _installStreamController( - {void Function()? onListen}) { + StreamController _installStreamController({ + void Function()? onListen, + }) { _frameStreamController = StreamController( onListen: onListen ?? () {}, onPause: _onFrameStreamPauseResume, @@ -334,20 +341,23 @@ class MethodChannelCamera extends CameraPlatform { } void _startStreamListener() { - const EventChannel cameraEventChannel = - EventChannel('plugins.flutter.io/camera/imageStream'); - _platformImageStreamSubscription = - cameraEventChannel.receiveBroadcastStream().listen((dynamic imageData) { - if (defaultTargetPlatform == TargetPlatform.iOS) { - try { - _channel.invokeMethod('receivedImageStreamData'); - } on PlatformException catch (e) { - throw CameraException(e.code, e.message); - } - } - _frameStreamController! - .add(cameraImageFromPlatformData(imageData as Map)); - }); + const EventChannel cameraEventChannel = EventChannel( + 'plugins.flutter.io/camera/imageStream', + ); + _platformImageStreamSubscription = cameraEventChannel + .receiveBroadcastStream() + .listen((dynamic imageData) { + if (defaultTargetPlatform == TargetPlatform.iOS) { + try { + _channel.invokeMethod('receivedImageStreamData'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + _frameStreamController!.add( + cameraImageFromPlatformData(imageData as Map), + ); + }); } FutureOr _onFrameStreamCancel() async { @@ -358,44 +368,37 @@ class MethodChannelCamera extends CameraPlatform { } void _onFrameStreamPauseResume() { - throw CameraException('InvalidCall', - 'Pause and resume are not supported for onStreamedFrameAvailable'); + throw CameraException( + 'InvalidCall', + 'Pause and resume are not supported for onStreamedFrameAvailable', + ); } @override Future setFlashMode(int cameraId, FlashMode mode) => - _channel.invokeMethod( - 'setFlashMode', - { - 'cameraId': cameraId, - 'mode': _serializeFlashMode(mode), - }, - ); + _channel.invokeMethod('setFlashMode', { + 'cameraId': cameraId, + 'mode': _serializeFlashMode(mode), + }); @override Future setExposureMode(int cameraId, ExposureMode mode) => - _channel.invokeMethod( - 'setExposureMode', - { - 'cameraId': cameraId, - 'mode': serializeExposureMode(mode), - }, - ); + _channel.invokeMethod('setExposureMode', { + 'cameraId': cameraId, + 'mode': serializeExposureMode(mode), + }); @override Future setExposurePoint(int cameraId, Point? point) { assert(point == null || point.x >= 0 && point.x <= 1); assert(point == null || point.y >= 0 && point.y <= 1); - return _channel.invokeMethod( - 'setExposurePoint', - { - 'cameraId': cameraId, - 'reset': point == null, - 'x': point?.x, - 'y': point?.y, - }, - ); + return _channel.invokeMethod('setExposurePoint', { + 'cameraId': cameraId, + 'reset': point == null, + 'x': point?.x, + 'y': point?.y, + }); } @override @@ -432,10 +435,7 @@ class MethodChannelCamera extends CameraPlatform { Future setExposureOffset(int cameraId, double offset) async { final double? appliedOffset = await _channel.invokeMethod( 'setExposureOffset', - { - 'cameraId': cameraId, - 'offset': offset, - }, + {'cameraId': cameraId, 'offset': offset}, ); return appliedOffset!; @@ -443,28 +443,22 @@ class MethodChannelCamera extends CameraPlatform { @override Future setFocusMode(int cameraId, FocusMode mode) => - _channel.invokeMethod( - 'setFocusMode', - { - 'cameraId': cameraId, - 'mode': serializeFocusMode(mode), - }, - ); + _channel.invokeMethod('setFocusMode', { + 'cameraId': cameraId, + 'mode': serializeFocusMode(mode), + }); @override Future setFocusPoint(int cameraId, Point? point) { assert(point == null || point.x >= 0 && point.x <= 1); assert(point == null || point.y >= 0 && point.y <= 1); - return _channel.invokeMethod( - 'setFocusPoint', - { - 'cameraId': cameraId, - 'reset': point == null, - 'x': point?.x, - 'y': point?.y, - }, - ); + return _channel.invokeMethod('setFocusPoint', { + 'cameraId': cameraId, + 'reset': point == null, + 'x': point?.x, + 'y': point?.y, + }); } @override @@ -490,13 +484,10 @@ class MethodChannelCamera extends CameraPlatform { @override Future setZoomLevel(int cameraId, double zoom) async { try { - await _channel.invokeMethod( - 'setZoomLevel', - { - 'cameraId': cameraId, - 'zoom': zoom, - }, - ); + await _channel.invokeMethod('setZoomLevel', { + 'cameraId': cameraId, + 'zoom': zoom, + }); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -504,40 +495,34 @@ class MethodChannelCamera extends CameraPlatform { @override Future pausePreview(int cameraId) async { - await _channel.invokeMethod( - 'pausePreview', - {'cameraId': cameraId}, - ); + await _channel.invokeMethod('pausePreview', { + 'cameraId': cameraId, + }); } @override Future resumePreview(int cameraId) async { - await _channel.invokeMethod( - 'resumePreview', - {'cameraId': cameraId}, - ); + await _channel.invokeMethod('resumePreview', { + 'cameraId': cameraId, + }); } @override Future setDescriptionWhileRecording( - CameraDescription description) async { + CameraDescription description, + ) async { await _channel.invokeMethod( 'setDescriptionWhileRecording', - { - 'cameraName': description.name, - }, + {'cameraName': description.name}, ); } @override Future setImageFileFormat(int cameraId, ImageFileFormat format) { - return _channel.invokeMethod( - 'setImageFileFormat', - { - 'cameraId': cameraId, - 'fileFormat': format.name, - }, - ); + return _channel.invokeMethod('setImageFileFormat', { + 'cameraId': cameraId, + 'fileFormat': format.name, + }); } @override @@ -585,8 +570,11 @@ class MethodChannelCamera extends CameraPlatform { switch (call.method) { case 'orientation_changed': final Map arguments = _getArgumentDictionary(call); - deviceEventStreamController.add(DeviceOrientationChangedEvent( - deserializeDeviceOrientation(arguments['orientation']! as String))); + deviceEventStreamController.add( + DeviceOrientationChangedEvent( + deserializeDeviceOrientation(arguments['orientation']! as String), + ), + ); default: throw MissingPluginException(); } @@ -601,41 +589,44 @@ class MethodChannelCamera extends CameraPlatform { switch (call.method) { case 'initialized': final Map arguments = _getArgumentDictionary(call); - cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - arguments['previewWidth']! as double, - arguments['previewHeight']! as double, - deserializeExposureMode(arguments['exposureMode']! as String), - arguments['exposurePointSupported']! as bool, - deserializeFocusMode(arguments['focusMode']! as String), - arguments['focusPointSupported']! as bool, - )); + cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + arguments['previewWidth']! as double, + arguments['previewHeight']! as double, + deserializeExposureMode(arguments['exposureMode']! as String), + arguments['exposurePointSupported']! as bool, + deserializeFocusMode(arguments['focusMode']! as String), + arguments['focusPointSupported']! as bool, + ), + ); case 'resolution_changed': final Map arguments = _getArgumentDictionary(call); - cameraEventStreamController.add(CameraResolutionChangedEvent( - cameraId, - arguments['captureWidth']! as double, - arguments['captureHeight']! as double, - )); + cameraEventStreamController.add( + CameraResolutionChangedEvent( + cameraId, + arguments['captureWidth']! as double, + arguments['captureHeight']! as double, + ), + ); case 'camera_closing': - cameraEventStreamController.add(CameraClosingEvent( - cameraId, - )); + cameraEventStreamController.add(CameraClosingEvent(cameraId)); case 'video_recorded': final Map arguments = _getArgumentDictionary(call); - cameraEventStreamController.add(VideoRecordedEvent( - cameraId, - XFile(arguments['path']! as String), - arguments['maxVideoDuration'] != null - ? Duration(milliseconds: arguments['maxVideoDuration']! as int) - : null, - )); + cameraEventStreamController.add( + VideoRecordedEvent( + cameraId, + XFile(arguments['path']! as String), + arguments['maxVideoDuration'] != null + ? Duration(milliseconds: arguments['maxVideoDuration']! as int) + : null, + ), + ); case 'error': final Map arguments = _getArgumentDictionary(call); - cameraEventStreamController.add(CameraErrorEvent( - cameraId, - arguments['description']! as String, - )); + cameraEventStreamController.add( + CameraErrorEvent(cameraId, arguments['description']! as String), + ); default: throw MissingPluginException(); } diff --git a/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart b/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart index b0f649a4e0d..95f872a3ef2 100644 --- a/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart +++ b/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart @@ -10,16 +10,20 @@ import '../types/types.dart'; /// [CameraImageData]. CameraImageData cameraImageFromPlatformData(Map data) { return CameraImageData( - format: _cameraImageFormatFromPlatformData(data['format']), - height: data['height'] as int, - width: data['width'] as int, - lensAperture: data['lensAperture'] as double?, - sensorExposureTime: data['sensorExposureTime'] as int?, - sensorSensitivity: data['sensorSensitivity'] as double?, - planes: List.unmodifiable( - (data['planes'] as List).map( - (dynamic planeData) => _cameraImagePlaneFromPlatformData( - planeData as Map)))); + format: _cameraImageFormatFromPlatformData(data['format']), + height: data['height'] as int, + width: data['width'] as int, + lensAperture: data['lensAperture'] as double?, + sensorExposureTime: data['sensorExposureTime'] as int?, + sensorSensitivity: data['sensorSensitivity'] as double?, + planes: List.unmodifiable( + (data['planes'] as List).map( + (dynamic planeData) => _cameraImagePlaneFromPlatformData( + planeData as Map, + ), + ), + ), + ); } CameraImageFormat _cameraImageFormatFromPlatformData(dynamic data) { @@ -51,9 +55,10 @@ ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) { CameraImagePlane _cameraImagePlaneFromPlatformData(Map data) { return CameraImagePlane( - bytes: data['bytes'] as Uint8List, - bytesPerPixel: data['bytesPerPixel'] as int?, - bytesPerRow: data['bytesPerRow'] as int, - height: data['height'] as int?, - width: data['width'] as int?); + bytes: data['bytes'] as Uint8List, + bytesPerPixel: data['bytesPerPixel'] as int?, + bytesPerRow: data['bytesPerRow'] as int, + height: data['height'] as int?, + width: data['width'] as int?, + ); } diff --git a/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart b/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart index 78228c63693..f5959a74689 100644 --- a/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart +++ b/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart @@ -114,12 +114,15 @@ abstract class CameraPlatform extends PlatformInterface { /// - Should support all 4 orientations. Stream onDeviceOrientationChanged() { throw UnimplementedError( - 'onDeviceOrientationChanged() is not implemented.'); + 'onDeviceOrientationChanged() is not implemented.', + ); } /// Locks the capture orientation. Future lockCaptureOrientation( - int cameraId, DeviceOrientation orientation) { + int cameraId, + DeviceOrientation orientation, + ) { throw UnimplementedError('lockCaptureOrientation() is not implemented.'); } @@ -144,7 +147,8 @@ abstract class CameraPlatform extends PlatformInterface { Future startVideoRecording( int cameraId, { @Deprecated( - 'This parameter is unused, and will be ignored on all platforms') + 'This parameter is unused, and will be ignored on all platforms', + ) Duration? maxVideoDuration, }) { throw UnimplementedError('startVideoRecording() is not implemented.'); @@ -186,8 +190,10 @@ abstract class CameraPlatform extends PlatformInterface { /// // TODO(bmparr): Add options to control streaming settings (e.g., // resolution and FPS). - Stream onStreamedFrameAvailable(int cameraId, - {CameraImageStreamOptions? options}) { + Stream onStreamedFrameAvailable( + int cameraId, { + CameraImageStreamOptions? options, + }) { throw UnimplementedError('onStreamedFrameAvailable() is not implemented.'); } @@ -288,7 +294,8 @@ abstract class CameraPlatform extends PlatformInterface { /// Sets the active camera while recording. Future setDescriptionWhileRecording(CameraDescription description) { throw UnimplementedError( - 'setDescriptionWhileRecording() is not implemented.'); + 'setDescriptionWhileRecording() is not implemented.', + ); } /// Returns a widget showing a live camera preview. diff --git a/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart b/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart index 95e29fad7d7..071b1ef2081 100644 --- a/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart +++ b/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart @@ -19,11 +19,15 @@ class MediaSettings { this.videoBitrate, this.audioBitrate, this.enableAudio = false, - }) : assert(fps == null || fps > 0, 'fps must be null or greater than zero'), - assert(videoBitrate == null || videoBitrate > 0, - 'videoBitrate must be null or greater than zero'), - assert(audioBitrate == null || audioBitrate > 0, - 'audioBitrate must be null or greater than zero'); + }) : assert(fps == null || fps > 0, 'fps must be null or greater than zero'), + assert( + videoBitrate == null || videoBitrate > 0, + 'videoBitrate must be null or greater than zero', + ), + assert( + audioBitrate == null || audioBitrate > 0, + 'audioBitrate must be null or greater than zero', + ); /// [ResolutionPreset] affect the quality of video recording and image capture. final ResolutionPreset? resolutionPreset; @@ -58,12 +62,12 @@ class MediaSettings { @override int get hashCode => Object.hash( - resolutionPreset, - fps, - videoBitrate, - audioBitrate, - enableAudio, - ); + resolutionPreset, + fps, + videoBitrate, + audioBitrate, + enableAudio, + ); @override String toString() { diff --git a/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart b/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart index 66ee5357d30..e5b32103e79 100644 --- a/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart +++ b/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart @@ -13,14 +13,15 @@ class VideoCaptureOptions { const VideoCaptureOptions( this.cameraId, { @Deprecated( - 'This parameter is unused, and will be ignored on all platforms') + 'This parameter is unused, and will be ignored on all platforms', + ) this.maxDuration, this.streamCallback, this.streamOptions, }) : assert( - streamOptions == null || streamCallback != null, - 'Must specify streamCallback if providing streamOptions.', - ); + streamOptions == null || streamCallback != null, + 'Must specify streamCallback if providing streamOptions.', + ); /// The ID of the camera to use for capturing. final int cameraId; diff --git a/packages/camera/camera_platform_interface/pubspec.yaml b/packages/camera/camera_platform_interface/pubspec.yaml index 1142aa4d7f2..8ea2589400b 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.10.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: cross_file: ^0.3.1 diff --git a/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart b/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart index 83e9f314b1f..88f28f776a0 100644 --- a/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart +++ b/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart @@ -33,490 +33,513 @@ void main() { }); test( - 'Default implementation of availableCameras() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - - // Act & Assert - expect( - () => cameraPlatform.availableCameras(), - throwsUnimplementedError, - ); - }); + 'Default implementation of availableCameras() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + + // Act & Assert + expect( + () => cameraPlatform.availableCameras(), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of onCameraInitialized() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of onCameraInitialized() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraInitialized(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.onCameraInitialized(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of onResolutionChanged() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of onResolutionChanged() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraResolutionChanged(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.onCameraResolutionChanged(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of onCameraClosing() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of onCameraClosing() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraClosing(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.onCameraClosing(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of onCameraError() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of onCameraError() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraError(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect(() => cameraPlatform.onCameraError(1), throwsUnimplementedError); + }, + ); test( - 'Default implementation of onDeviceOrientationChanged() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of onDeviceOrientationChanged() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onDeviceOrientationChanged(), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.onDeviceOrientationChanged(), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of lockCaptureOrientation() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of lockCaptureOrientation() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.lockCaptureOrientation( - 1, DeviceOrientation.portraitUp), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.lockCaptureOrientation( + 1, + DeviceOrientation.portraitUp, + ), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of unlockCaptureOrientation() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of unlockCaptureOrientation() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.unlockCaptureOrientation(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.unlockCaptureOrientation(1), + throwsUnimplementedError, + ); + }, + ); - test('Default implementation of dispose() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + test( + 'Default implementation of dispose() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.dispose(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect(() => cameraPlatform.dispose(1), throwsUnimplementedError); + }, + ); test( - 'Default implementation of createCamera() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of createCamera() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.createCamera( - const CameraDescription( - name: 'back', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + // Act & Assert + expect( + () => cameraPlatform.createCamera( + const CameraDescription( + name: 'back', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), + ResolutionPreset.low, ), - ResolutionPreset.low, - ), - throwsUnimplementedError, - ); - }); + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of createCameraWithSettings() should call createCamera() passing parameters', - () { - // Arrange - const CameraDescription cameraDescription = CameraDescription( - name: 'back', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ); - - const MediaSettings mediaSettings = MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ); + 'Default implementation of createCameraWithSettings() should call createCamera() passing parameters', + () { + // Arrange + const CameraDescription cameraDescription = CameraDescription( + name: 'back', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ); - bool createCameraCalled = false; + const MediaSettings mediaSettings = MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ); - final OverriddenCameraPlatform cameraPlatform = OverriddenCameraPlatform(( - CameraDescription cameraDescriptionArg, - ResolutionPreset? resolutionPresetArg, - bool enableAudioArg, - ) { - expect( - cameraDescriptionArg, + bool createCameraCalled = false; + + final OverriddenCameraPlatform cameraPlatform = + OverriddenCameraPlatform(( + CameraDescription cameraDescriptionArg, + ResolutionPreset? resolutionPresetArg, + bool enableAudioArg, + ) { + expect( + cameraDescriptionArg, + cameraDescription, + reason: 'should pass camera description', + ); + expect( + resolutionPresetArg, + mediaSettings.resolutionPreset, + reason: 'should pass resolution preset', + ); + expect( + enableAudioArg, + mediaSettings.enableAudio, + reason: 'should pass enableAudio', + ); + + createCameraCalled = true; + }); + + // Act & Assert + cameraPlatform.createCameraWithSettings( cameraDescription, - reason: 'should pass camera description', - ); - expect( - resolutionPresetArg, - mediaSettings.resolutionPreset, - reason: 'should pass resolution preset', - ); - expect( - enableAudioArg, - mediaSettings.enableAudio, - reason: 'should pass enableAudio', + mediaSettings, ); - createCameraCalled = true; - }); - - // Act & Assert - cameraPlatform.createCameraWithSettings( - cameraDescription, - mediaSettings, - ); - - expect(createCameraCalled, isTrue, + expect( + createCameraCalled, + isTrue, reason: - 'default implementation of createCameraWithSettings should call createCamera passing parameters'); - }); + 'default implementation of createCameraWithSettings should call createCamera passing parameters', + ); + }, + ); test( - 'Default implementation of initializeCamera() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of initializeCamera() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.initializeCamera(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.initializeCamera(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of pauseVideoRecording() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of pauseVideoRecording() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.pauseVideoRecording(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.pauseVideoRecording(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of prepareForVideoRecording() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of prepareForVideoRecording() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.prepareForVideoRecording(), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.prepareForVideoRecording(), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of resumeVideoRecording() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of resumeVideoRecording() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.resumeVideoRecording(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.resumeVideoRecording(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setFlashMode() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setFlashMode() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setFlashMode(1, FlashMode.auto), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setFlashMode(1, FlashMode.auto), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setExposureMode() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setExposureMode() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setExposureMode(1, ExposureMode.auto), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setExposureMode(1, ExposureMode.auto), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setExposurePoint() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setExposurePoint() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setExposurePoint(1, null), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setExposurePoint(1, null), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of getMinExposureOffset() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of getMinExposureOffset() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMinExposureOffset(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.getMinExposureOffset(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of getMaxExposureOffset() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of getMaxExposureOffset() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMaxExposureOffset(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.getMaxExposureOffset(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of getExposureOffsetStepSize() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of getExposureOffsetStepSize() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getExposureOffsetStepSize(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.getExposureOffsetStepSize(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setExposureOffset() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setExposureOffset() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setExposureOffset(1, 2.0), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setExposureOffset(1, 2.0), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setFocusMode() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setFocusMode() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setFocusMode(1, FocusMode.auto), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setFocusMode(1, FocusMode.auto), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setFocusPoint() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setFocusPoint() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setFocusPoint(1, null), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setFocusPoint(1, null), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of startVideoRecording() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of startVideoRecording() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.startVideoRecording(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.startVideoRecording(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of stopVideoRecording() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of stopVideoRecording() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.stopVideoRecording(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.stopVideoRecording(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of takePicture() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of takePicture() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.takePicture(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect(() => cameraPlatform.takePicture(1), throwsUnimplementedError); + }, + ); test( - 'Default implementation of getMaxZoomLevel() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of getMaxZoomLevel() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMaxZoomLevel(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.getMaxZoomLevel(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of getMinZoomLevel() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of getMinZoomLevel() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMinZoomLevel(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.getMinZoomLevel(1), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setZoomLevel() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of setZoomLevel() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setZoomLevel(1, 1.0), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => cameraPlatform.setZoomLevel(1, 1.0), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of pausePreview() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of pausePreview() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.pausePreview(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect(() => cameraPlatform.pausePreview(1), throwsUnimplementedError); + }, + ); test( - 'Default implementation of resumePreview() should throw unimplemented error', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of resumePreview() should throw unimplemented error', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.resumePreview(1), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect(() => cameraPlatform.resumePreview(1), throwsUnimplementedError); + }, + ); test( - 'Default implementation of supportsImageStreaming() should return false', - () { - // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + 'Default implementation of supportsImageStreaming() should return false', + () { + // Arrange + final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - cameraPlatform.supportsImageStreaming(), - false, - ); - }); + // Act & Assert + expect(cameraPlatform.supportsImageStreaming(), false); + }, + ); }); group('exports', () { test('CameraDescription is exported', () { const CameraDescription( - name: 'abc-123', - sensorOrientation: 1, - lensDirection: CameraLensDirection.external); + name: 'abc-123', + sensorOrientation: 1, + lensDirection: CameraLensDirection.external, + ); }); test('CameraException is exported', () { @@ -572,12 +595,15 @@ class OverriddenCameraPlatform extends CameraPlatform { CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, bool enableAudio, - ) _onCreateCameraCalled; + ) + _onCreateCameraCalled; @override Future createCamera( - CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, - {bool enableAudio = false}) { + CameraDescription cameraDescription, + ResolutionPreset? resolutionPreset, { + bool enableAudio = false, + }) { _onCreateCameraCalled(cameraDescription, resolutionPreset, enableAudio); return Future.value(0); } diff --git a/packages/camera/camera_platform_interface/test/events/camera_event_test.dart b/packages/camera/camera_platform_interface/test/events/camera_event_test.dart index cb1e34845b3..d242847fbbc 100644 --- a/packages/camera/camera_platform_interface/test/events/camera_event_test.dart +++ b/packages/camera/camera_platform_interface/test/events/camera_event_test.dart @@ -11,7 +11,14 @@ void main() { group('CameraInitializedEvent tests', () { test('Constructor should initialize all properties', () { const CameraInitializedEvent event = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); expect(event.cameraId, 1); expect(event.previewWidth, 1024); @@ -25,14 +32,14 @@ void main() { test('fromJson should initialize all properties', () { final CameraInitializedEvent event = CameraInitializedEvent.fromJson(const { - 'cameraId': 1, - 'previewWidth': 1024.0, - 'previewHeight': 640.0, - 'exposureMode': 'auto', - 'exposurePointSupported': true, - 'focusMode': 'auto', - 'focusPointSupported': true, - }); + 'cameraId': 1, + 'previewWidth': 1024.0, + 'previewHeight': 640.0, + 'exposureMode': 'auto', + 'exposurePointSupported': true, + 'focusMode': 'auto', + 'focusPointSupported': true, + }); expect(event.cameraId, 1); expect(event.previewWidth, 1024); @@ -45,7 +52,14 @@ void main() { test('toJson should return a map with all fields', () { const CameraInitializedEvent event = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); final Map jsonMap = event.toJson(); @@ -61,88 +75,210 @@ void main() { test('equals should return true if objects are the same', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); expect(firstEvent == secondEvent, true); }); test('equals should return false if cameraId is different', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 2, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 2, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); expect(firstEvent == secondEvent, false); }); test('equals should return false if previewWidth is different', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 2048, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 2048, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); expect(firstEvent == secondEvent, false); }); test('equals should return false if previewHeight is different', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 1024, 980, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 980, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); expect(firstEvent == secondEvent, false); }); test('equals should return false if exposureMode is different', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.locked, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.locked, + true, + FocusMode.auto, + true, + ); expect(firstEvent == secondEvent, false); }); - test('equals should return false if exposurePointSupported is different', - () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, false, FocusMode.auto, true); - - expect(firstEvent == secondEvent, false); - }); + test( + 'equals should return false if exposurePointSupported is different', + () { + const CameraInitializedEvent firstEvent = CameraInitializedEvent( + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); + const CameraInitializedEvent secondEvent = CameraInitializedEvent( + 1, + 1024, + 640, + ExposureMode.auto, + false, + FocusMode.auto, + true, + ); + + expect(firstEvent == secondEvent, false); + }, + ); test('equals should return false if focusMode is different', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.locked, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.locked, + true, + ); expect(firstEvent == secondEvent, false); }); test('equals should return false if focusPointSupported is different', () { const CameraInitializedEvent firstEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); const CameraInitializedEvent secondEvent = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, false); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + false, + ); expect(firstEvent == secondEvent, false); }); test('hashCode should match hashCode of all properties', () { const CameraInitializedEvent event = CameraInitializedEvent( - 1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true); + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); final int expectedHashCode = Object.hash( - event.cameraId.hashCode, - event.previewWidth, - event.previewHeight, - event.exposureMode, - event.exposurePointSupported, - event.focusMode, - event.focusPointSupported); + event.cameraId.hashCode, + event.previewWidth, + event.previewHeight, + event.exposureMode, + event.exposurePointSupported, + event.focusMode, + event.focusPointSupported, + ); expect(event.hashCode, expectedHashCode); }); @@ -150,8 +286,11 @@ void main() { group('CameraResolutionChangesEvent tests', () { test('Constructor should initialize all properties', () { - const CameraResolutionChangedEvent event = - CameraResolutionChangedEvent(1, 1024, 640); + const CameraResolutionChangedEvent event = CameraResolutionChangedEvent( + 1, + 1024, + 640, + ); expect(event.cameraId, 1); expect(event.captureWidth, 1024); @@ -161,10 +300,10 @@ void main() { test('fromJson should initialize all properties', () { final CameraResolutionChangedEvent event = CameraResolutionChangedEvent.fromJson(const { - 'cameraId': 1, - 'captureWidth': 1024.0, - 'captureHeight': 640.0, - }); + 'cameraId': 1, + 'captureWidth': 1024.0, + 'captureHeight': 640.0, + }); expect(event.cameraId, 1); expect(event.captureWidth, 1024); @@ -172,8 +311,11 @@ void main() { }); test('toJson should return a map with all fields', () { - const CameraResolutionChangedEvent event = - CameraResolutionChangedEvent(1, 1024, 640); + const CameraResolutionChangedEvent event = CameraResolutionChangedEvent( + 1, + 1024, + 640, + ); final Map jsonMap = event.toJson(); @@ -220,8 +362,11 @@ void main() { }); test('hashCode should match hashCode of all properties', () { - const CameraResolutionChangedEvent event = - CameraResolutionChangedEvent(1, 1024, 640); + const CameraResolutionChangedEvent event = CameraResolutionChangedEvent( + 1, + 1024, + 640, + ); final int expectedHashCode = Object.hash( event.cameraId.hashCode, event.captureWidth, @@ -240,10 +385,9 @@ void main() { }); test('fromJson should initialize all properties', () { - final CameraClosingEvent event = - CameraClosingEvent.fromJson(const { - 'cameraId': 1, - }); + final CameraClosingEvent event = CameraClosingEvent.fromJson( + const {'cameraId': 1}, + ); expect(event.cameraId, 1); }); @@ -289,7 +433,8 @@ void main() { test('fromJson should initialize all properties', () { final CameraErrorEvent event = CameraErrorEvent.fromJson( - const {'cameraId': 1, 'description': 'Error'}); + const {'cameraId': 1, 'description': 'Error'}, + ); expect(event.cameraId, 1); expect(event.description, 'Error'); @@ -328,8 +473,10 @@ void main() { test('hashCode should match hashCode of all properties', () { const CameraErrorEvent event = CameraErrorEvent(1, 'Error'); - final int expectedHashCode = - Object.hash(event.cameraId.hashCode, event.description); + final int expectedHashCode = Object.hash( + event.cameraId.hashCode, + event.description, + ); expect(event.hashCode, expectedHashCode); }); diff --git a/packages/camera/camera_platform_interface/test/events/device_event_test.dart b/packages/camera/camera_platform_interface/test/events/device_event_test.dart index 11f786c0df4..58fd9efd2e0 100644 --- a/packages/camera/camera_platform_interface/test/events/device_event_test.dart +++ b/packages/camera/camera_platform_interface/test/events/device_event_test.dart @@ -11,8 +11,9 @@ void main() { group('DeviceOrientationChangedEvent tests', () { test('Constructor should initialize all properties', () { - const DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); expect(event.orientation, DeviceOrientation.portraitUp); }); @@ -20,15 +21,16 @@ void main() { test('fromJson should initialize all properties', () { final DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent.fromJson(const { - 'orientation': 'portraitUp', - }); + 'orientation': 'portraitUp', + }); expect(event.orientation, DeviceOrientation.portraitUp); }); test('toJson should return a map with all fields', () { - const DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); final Map jsonMap = event.toJson(); @@ -55,8 +57,9 @@ void main() { }); test('hashCode should match hashCode of all properties', () { - const DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); final int expectedHashCode = event.orientation.hashCode; expect(event.hashCode, expectedHashCode); 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 063633255c9..d921038b02d 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 @@ -23,21 +23,23 @@ void main() { test('Should send creation data and receive back a camera id', () async { // Arrange final MethodChannelMock cameraMockChannel = MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'create': { - 'cameraId': 1, - 'imageFormatGroup': 'unknown', - } - }); + channelName: 'plugins.flutter.io/camera', + methods: { + 'create': { + 'cameraId': 1, + 'imageFormatGroup': 'unknown', + }, + }, + ); final MethodChannelCamera camera = MethodChannelCamera(); // Act final int cameraId = await camera.createCameraWithSettings( const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0), + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), const MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 15, @@ -56,7 +58,7 @@ void main() { 'fps': 15, 'videoBitrate': 200000, 'audioBitrate': 32000, - 'enableAudio': false + 'enableAudio': false, }, ), ]); @@ -64,84 +66,100 @@ void main() { }); test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - MethodChannelMock( + 'Should throw CameraException when create throws a PlatformException', + () { + // Arrange + MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'create': PlatformException( code: 'TESTING_ERROR_CODE', message: 'Mock error message used during testing.', - ) - }); - final MethodChannelCamera camera = MethodChannelCamera(); + ), + }, + ); + final MethodChannelCamera camera = MethodChannelCamera(); - // Act - expect( - () => camera.createCameraWithSettings( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + // Act + expect( + () => camera.createCameraWithSettings( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ), ), - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, + throwsA( + isA() + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), ), - ), - throwsA( - isA() - .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') - .having((CameraException e) => e.description, 'description', - 'Mock error message used during testing.'), - ), - ); - }); + ); + }, + ); test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - MethodChannelMock( + 'Should throw CameraException when create throws a PlatformException', + () { + // Arrange + MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'create': PlatformException( code: 'TESTING_ERROR_CODE', message: 'Mock error message used during testing.', - ) - }); - final MethodChannelCamera camera = MethodChannelCamera(); + ), + }, + ); + final MethodChannelCamera camera = MethodChannelCamera(); - // Act - expect( - () => camera.createCameraWithSettings( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + // Act + expect( + () => camera.createCameraWithSettings( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ), ), - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, + throwsA( + isA() + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), ), - ), - throwsA( - isA() - .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') - .having((CameraException e) => e.description, 'description', - 'Mock error message used during testing.'), - ), - ); - }); + ); + }, + ); test( 'Should throw CameraException when initialize throws a PlatformException', @@ -153,7 +171,7 @@ void main() { 'initialize': PlatformException( code: 'TESTING_ERROR_CODE', message: 'Mock error message used during testing.', - ) + ), }, ); final MethodChannelCamera camera = MethodChannelCamera(); @@ -163,8 +181,11 @@ void main() { () => camera.initializeCamera(0), throwsA( isA() - .having((CameraException e) => e.code, 'code', - 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) .having( (CameraException e) => e.description, 'description', @@ -178,14 +199,15 @@ void main() { test('Should send initialization data', () async { // Arrange final MethodChannelMock cameraMockChannel = MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'create': { - 'cameraId': 1, - 'imageFormatGroup': 'unknown', - }, - 'initialize': null - }); + channelName: 'plugins.flutter.io/camera', + methods: { + 'create': { + 'cameraId': 1, + 'imageFormatGroup': 'unknown', + }, + 'initialize': null, + }, + ); final MethodChannelCamera camera = MethodChannelCamera(); final int cameraId = await camera.createCameraWithSettings( const CameraDescription( @@ -204,15 +226,17 @@ void main() { // Act final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; // Assert @@ -232,12 +256,13 @@ void main() { test('Should send a disposal call on dispose', () async { // Arrange final MethodChannelMock cameraMockChannel = MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'create': {'cameraId': 1}, - 'initialize': null, - 'dispose': {'cameraId': 1} - }); + channelName: 'plugins.flutter.io/camera', + methods: { + 'create': {'cameraId': 1}, + 'initialize': null, + 'dispose': {'cameraId': 1}, + }, + ); final MethodChannelCamera camera = MethodChannelCamera(); final int cameraId = await camera.createCameraWithSettings( @@ -255,15 +280,17 @@ void main() { ), ); final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; // Act @@ -274,10 +301,7 @@ void main() { expect(cameraMockChannel.log, [ anything, anything, - isMethodCall( - 'dispose', - arguments: {'cameraId': 1}, - ), + isMethodCall('dispose', arguments: {'cameraId': 1}), ]); }); }); @@ -290,7 +314,7 @@ void main() { channelName: 'plugins.flutter.io/camera', methods: { 'create': {'cameraId': 1}, - 'initialize': null + 'initialize': null, }, ); camera = MethodChannelCamera(); @@ -309,22 +333,24 @@ void main() { ), ); final Future initializeFuture = camera.initializeCamera(cameraId); - camera.cameraEventStreamController.add(CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - )); + camera.cameraEventStreamController.add( + CameraInitializedEvent( + cameraId, + 1920, + 1080, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ), + ); await initializeFuture; }); test('Should receive initialized event', () async { // Act - final Stream eventStream = - camera.onCameraInitialized(cameraId); + final Stream eventStream = camera + .onCameraInitialized(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -339,7 +365,9 @@ void main() { true, ); await camera.handleCameraMethodCall( - MethodCall('initialized', event.toJson()), cameraId); + MethodCall('initialized', event.toJson()), + cameraId, + ); // Assert expect(await streamQueue.next, event); @@ -350,8 +378,8 @@ void main() { test('Should receive resolution changes', () async { // Act - final Stream resolutionStream = - camera.onCameraResolutionChanged(cameraId); + final Stream resolutionStream = camera + .onCameraResolutionChanged(cameraId); final StreamQueue streamQueue = StreamQueue(resolutionStream); @@ -361,13 +389,21 @@ void main() { final CameraResolutionChangedEvent uhdEvent = CameraResolutionChangedEvent(cameraId, 3840, 2160); await camera.handleCameraMethodCall( - MethodCall('resolution_changed', fhdEvent.toJson()), cameraId); + MethodCall('resolution_changed', fhdEvent.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('resolution_changed', uhdEvent.toJson()), cameraId); + MethodCall('resolution_changed', uhdEvent.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('resolution_changed', fhdEvent.toJson()), cameraId); + MethodCall('resolution_changed', fhdEvent.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('resolution_changed', uhdEvent.toJson()), cameraId); + MethodCall('resolution_changed', uhdEvent.toJson()), + cameraId, + ); // Assert expect(await streamQueue.next, fhdEvent); @@ -381,19 +417,26 @@ void main() { test('Should receive camera closing events', () async { // Act - final Stream eventStream = - camera.onCameraClosing(cameraId); + final Stream eventStream = camera.onCameraClosing( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(eventStream); // Emit test events final CameraClosingEvent event = CameraClosingEvent(cameraId); await camera.handleCameraMethodCall( - MethodCall('camera_closing', event.toJson()), cameraId); + MethodCall('camera_closing', event.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('camera_closing', event.toJson()), cameraId); + MethodCall('camera_closing', event.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('camera_closing', event.toJson()), cameraId); + MethodCall('camera_closing', event.toJson()), + cameraId, + ); // Assert expect(await streamQueue.next, event); @@ -406,20 +449,29 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = - camera.onCameraError(cameraId); + final Stream errorStream = camera.onCameraError( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(errorStream); // Emit test events - final CameraErrorEvent event = - CameraErrorEvent(cameraId, 'Error Description'); + final CameraErrorEvent event = CameraErrorEvent( + cameraId, + 'Error Description', + ); await camera.handleCameraMethodCall( - MethodCall('error', event.toJson()), cameraId); + MethodCall('error', event.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('error', event.toJson()), cameraId); + MethodCall('error', event.toJson()), + cameraId, + ); await camera.handleCameraMethodCall( - MethodCall('error', event.toJson()), cameraId); + MethodCall('error', event.toJson()), + cameraId, + ); // Assert expect(await streamQueue.next, event); @@ -441,11 +493,14 @@ void main() { const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); await camera.handleDeviceMethodCall( - MethodCall('orientation_changed', event.toJson())); + MethodCall('orientation_changed', event.toJson()), + ); await camera.handleDeviceMethodCall( - MethodCall('orientation_changed', event.toJson())); + MethodCall('orientation_changed', event.toJson()), + ); await camera.handleDeviceMethodCall( - MethodCall('orientation_changed', event.toJson())); + MethodCall('orientation_changed', event.toJson()), + ); // Assert expect(await streamQueue.next, event); @@ -466,7 +521,7 @@ void main() { channelName: 'plugins.flutter.io/camera', methods: { 'create': {'cameraId': 1}, - 'initialize': null + 'initialize': null, }, ); camera = MethodChannelCamera(); @@ -499,87 +554,102 @@ void main() { await initializeFuture; }); - test('Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final List returnData = [ - { - 'name': 'Test 1', - 'lensFacing': 'front', - 'sensorOrientation': 1 - }, - { - 'name': 'Test 2', - 'lensFacing': 'back', - 'sensorOrientation': 2 - } - ]; - final MethodChannelMock channel = MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: {'availableCameras': returnData}, - ); - - // Act - final List cameras = await camera.availableCameras(); - - // Assert - expect(channel.log, [ - isMethodCall('availableCameras', arguments: null), - ]); - expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { - final Map typedData = - (returnData[i] as Map).cast(); - final CameraDescription cameraDescription = CameraDescription( - name: typedData['name']! as String, - lensDirection: - parseCameraLensDirection(typedData['lensFacing']! as String), - sensorOrientation: typedData['sensorOrientation']! as int, + test( + 'Should fetch CameraDescription instances for available cameras', + () async { + // Arrange + final List returnData = [ + { + 'name': 'Test 1', + 'lensFacing': 'front', + 'sensorOrientation': 1, + }, + { + 'name': 'Test 2', + 'lensFacing': 'back', + 'sensorOrientation': 2, + }, + ]; + final MethodChannelMock channel = MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: {'availableCameras': returnData}, ); - expect(cameras[i], cameraDescription); - } - }); + + // Act + final List cameras = + await camera.availableCameras(); + + // Assert + expect(channel.log, [ + isMethodCall('availableCameras', arguments: null), + ]); + expect(cameras.length, returnData.length); + for (int i = 0; i < returnData.length; i++) { + final Map typedData = + (returnData[i] as Map) + .cast(); + final CameraDescription cameraDescription = CameraDescription( + name: typedData['name']! as String, + lensDirection: parseCameraLensDirection( + typedData['lensFacing']! as String, + ), + sensorOrientation: typedData['sensorOrientation']! as int, + ); + expect(cameras[i], cameraDescription); + } + }, + ); test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - // Arrange - MethodChannelMock( + 'Should throw CameraException when availableCameras throws a PlatformException', + () { + // Arrange + MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'availableCameras': PlatformException( code: 'TESTING_ERROR_CODE', message: 'Mock error message used during testing.', - ) - }); + ), + }, + ); - // Act - expect( - camera.availableCameras, - throwsA( - isA() - .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') - .having((CameraException e) => e.description, 'description', - 'Mock error message used during testing.'), - ), - ); - }); + // Act + expect( + camera.availableCameras, + throwsA( + isA() + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }, + ); test('Should take a picture and return an XFile instance', () async { // Arrange final MethodChannelMock channel = MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: {'takePicture': '/test/path.jpg'}); + channelName: 'plugins.flutter.io/camera', + methods: {'takePicture': '/test/path.jpg'}, + ); // Act final XFile file = await camera.takePicture(cameraId); // Assert expect(channel.log, [ - isMethodCall('takePicture', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'takePicture', + arguments: {'cameraId': cameraId}, + ), ]); expect(file.path, '/test/path.jpg'); }); @@ -612,11 +682,14 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('startVideoRecording', arguments: { - 'cameraId': cameraId, - 'maxVideoDuration': null, - 'enableStream': false, - }), + isMethodCall( + 'startVideoRecording', + arguments: { + 'cameraId': cameraId, + 'maxVideoDuration': null, + 'enableStream': false, + }, + ), ]); }); @@ -629,17 +702,18 @@ void main() { // Act const CameraDescription cameraDescription = CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0); + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ); await camera.setDescriptionWhileRecording(cameraDescription); // Assert expect(channel.log, [ - isMethodCall('setDescriptionWhileRecording', - arguments: { - 'cameraName': cameraDescription.name - }), + isMethodCall( + 'setDescriptionWhileRecording', + arguments: {'cameraName': cameraDescription.name}, + ), ]); }); @@ -655,9 +729,10 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('stopVideoRecording', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'stopVideoRecording', + arguments: {'cameraId': cameraId}, + ), ]); expect(file.path, '/test/path.mp4'); }); @@ -674,9 +749,10 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('pauseVideoRecording', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'pauseVideoRecording', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -692,9 +768,10 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('resumeVideoRecording', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'resumeVideoRecording', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -713,22 +790,25 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setFlashMode', arguments: { - 'cameraId': cameraId, - 'mode': 'torch' - }), - isMethodCall('setFlashMode', arguments: { - 'cameraId': cameraId, - 'mode': 'always' - }), - isMethodCall('setFlashMode', arguments: { - 'cameraId': cameraId, - 'mode': 'auto' - }), - isMethodCall('setFlashMode', arguments: { - 'cameraId': cameraId, - 'mode': 'off' - }), + isMethodCall( + 'setFlashMode', + arguments: {'cameraId': cameraId, 'mode': 'torch'}, + ), + isMethodCall( + 'setFlashMode', + arguments: { + 'cameraId': cameraId, + 'mode': 'always', + }, + ), + isMethodCall( + 'setFlashMode', + arguments: {'cameraId': cameraId, 'mode': 'auto'}, + ), + isMethodCall( + 'setFlashMode', + arguments: {'cameraId': cameraId, 'mode': 'off'}, + ), ]); }); @@ -745,14 +825,17 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setExposureMode', arguments: { - 'cameraId': cameraId, - 'mode': 'auto' - }), - isMethodCall('setExposureMode', arguments: { - 'cameraId': cameraId, - 'mode': 'locked' - }), + isMethodCall( + 'setExposureMode', + arguments: {'cameraId': cameraId, 'mode': 'auto'}, + ), + isMethodCall( + 'setExposureMode', + arguments: { + 'cameraId': cameraId, + 'mode': 'locked', + }, + ), ]); }); @@ -769,18 +852,24 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setExposurePoint', arguments: { - 'cameraId': cameraId, - 'x': 0.5, - 'y': 0.5, - 'reset': false - }), - isMethodCall('setExposurePoint', arguments: { - 'cameraId': cameraId, - 'x': null, - 'y': null, - 'reset': true - }), + isMethodCall( + 'setExposurePoint', + arguments: { + 'cameraId': cameraId, + 'x': 0.5, + 'y': 0.5, + 'reset': false, + }, + ), + isMethodCall( + 'setExposurePoint', + arguments: { + 'cameraId': cameraId, + 'x': null, + 'y': null, + 'reset': true, + }, + ), ]); }); @@ -792,15 +881,17 @@ void main() { ); // Act - final double minExposureOffset = - await camera.getMinExposureOffset(cameraId); + final double minExposureOffset = await camera.getMinExposureOffset( + cameraId, + ); // Assert expect(minExposureOffset, 2.0); expect(channel.log, [ - isMethodCall('getMinExposureOffset', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'getMinExposureOffset', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -812,15 +903,17 @@ void main() { ); // Act - final double maxExposureOffset = - await camera.getMaxExposureOffset(cameraId); + final double maxExposureOffset = await camera.getMaxExposureOffset( + cameraId, + ); // Assert expect(maxExposureOffset, 2.0); expect(channel.log, [ - isMethodCall('getMaxExposureOffset', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'getMaxExposureOffset', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -832,16 +925,17 @@ void main() { ); // Act - final double stepSize = - await camera.getExposureOffsetStepSize(cameraId); + final double stepSize = await camera.getExposureOffsetStepSize( + cameraId, + ); // Assert expect(stepSize, 0.25); expect(channel.log, [ - isMethodCall('getExposureOffsetStepSize', - arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'getExposureOffsetStepSize', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -853,16 +947,18 @@ void main() { ); // Act - final double actualOffset = - await camera.setExposureOffset(cameraId, 0.5); + final double actualOffset = await camera.setExposureOffset( + cameraId, + 0.5, + ); // Assert expect(actualOffset, 0.6); expect(channel.log, [ - isMethodCall('setExposureOffset', arguments: { - 'cameraId': cameraId, - 'offset': 0.5, - }), + isMethodCall( + 'setExposureOffset', + arguments: {'cameraId': cameraId, 'offset': 0.5}, + ), ]); }); @@ -879,14 +975,17 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setFocusMode', arguments: { - 'cameraId': cameraId, - 'mode': 'auto' - }), - isMethodCall('setFocusMode', arguments: { - 'cameraId': cameraId, - 'mode': 'locked' - }), + isMethodCall( + 'setFocusMode', + arguments: {'cameraId': cameraId, 'mode': 'auto'}, + ), + isMethodCall( + 'setFocusMode', + arguments: { + 'cameraId': cameraId, + 'mode': 'locked', + }, + ), ]); }); @@ -903,18 +1002,24 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setFocusPoint', arguments: { - 'cameraId': cameraId, - 'x': 0.5, - 'y': 0.5, - 'reset': false - }), - isMethodCall('setFocusPoint', arguments: { - 'cameraId': cameraId, - 'x': null, - 'y': null, - 'reset': true - }), + isMethodCall( + 'setFocusPoint', + arguments: { + 'cameraId': cameraId, + 'x': 0.5, + 'y': 0.5, + 'reset': false, + }, + ), + isMethodCall( + 'setFocusPoint', + arguments: { + 'cameraId': cameraId, + 'x': null, + 'y': null, + 'reset': true, + }, + ), ]); }); @@ -927,15 +1032,20 @@ void main() { expect((widget as Texture).textureId, cameraId); }); - test('Should throw MissingPluginException when handling unknown method', - () { - final MethodChannelCamera camera = MethodChannelCamera(); + test( + 'Should throw MissingPluginException when handling unknown method', + () { + final MethodChannelCamera camera = MethodChannelCamera(); - expect( + expect( () => camera.handleCameraMethodCall( - const MethodCall('unknown_method'), 1), - throwsA(isA())); - }); + const MethodCall('unknown_method'), + 1, + ), + throwsA(isA()), + ); + }, + ); test('Should get the max zoom level', () async { // Arrange @@ -950,9 +1060,10 @@ void main() { // Assert expect(maxZoomLevel, 10.0); expect(channel.log, [ - isMethodCall('getMaxZoomLevel', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'getMaxZoomLevel', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -969,9 +1080,10 @@ void main() { // Assert expect(maxZoomLevel, 1.0); expect(channel.log, [ - isMethodCall('getMinZoomLevel', arguments: { - 'cameraId': cameraId, - }), + isMethodCall( + 'getMinZoomLevel', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -987,32 +1099,42 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setZoomLevel', - arguments: {'cameraId': cameraId, 'zoom': 2.0}), + isMethodCall( + 'setZoomLevel', + arguments: {'cameraId': cameraId, 'zoom': 2.0}, + ), ]); }); - test('Should throw CameraException when illegal zoom level is supplied', - () async { - // Arrange - MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'setZoomLevel': PlatformException( - code: 'ZOOM_ERROR', - message: 'Illegal zoom error', - ) - }, - ); + test( + 'Should throw CameraException when illegal zoom level is supplied', + () async { + // Arrange + MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: { + 'setZoomLevel': PlatformException( + code: 'ZOOM_ERROR', + message: 'Illegal zoom error', + ), + }, + ); - // Act & assert - expect( + // Act & assert + expect( () => camera.setZoomLevel(cameraId, -1.0), - throwsA(isA() - .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') - .having((CameraException e) => e.description, 'description', - 'Illegal zoom error'))); - }); + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') + .having( + (CameraException e) => e.description, + 'description', + 'Illegal zoom error', + ), + ), + ); + }, + ); test('Should lock the capture orientation', () async { // Arrange @@ -1023,14 +1145,19 @@ void main() { // Act await camera.lockCaptureOrientation( - cameraId, DeviceOrientation.portraitUp); + cameraId, + DeviceOrientation.portraitUp, + ); // Assert expect(channel.log, [ - isMethodCall('lockCaptureOrientation', arguments: { - 'cameraId': cameraId, - 'orientation': 'portraitUp' - }), + isMethodCall( + 'lockCaptureOrientation', + arguments: { + 'cameraId': cameraId, + 'orientation': 'portraitUp', + }, + ), ]); }); @@ -1046,8 +1173,10 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('unlockCaptureOrientation', - arguments: {'cameraId': cameraId}), + isMethodCall( + 'unlockCaptureOrientation', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -1063,8 +1192,10 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('pausePreview', - arguments: {'cameraId': cameraId}), + isMethodCall( + 'pausePreview', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -1080,8 +1211,10 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('resumePreview', - arguments: {'cameraId': cameraId}), + isMethodCall( + 'resumePreview', + arguments: {'cameraId': cameraId}, + ), ]); }); @@ -1143,10 +1276,13 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setImageFileFormat', arguments: { - 'cameraId': cameraId, - 'fileFormat': 'heif', - }), + isMethodCall( + 'setImageFileFormat', + arguments: { + 'cameraId': cameraId, + 'fileFormat': 'heif', + }, + ), ]); }); @@ -1154,9 +1290,7 @@ void main() { // Arrange final MethodChannelMock channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', - methods: { - 'setImageFileFormat': 'jpeg', - }, + methods: {'setImageFileFormat': 'jpeg'}, ); // Act @@ -1164,10 +1298,13 @@ void main() { // Assert expect(channel.log, [ - isMethodCall('setImageFileFormat', arguments: { - 'cameraId': cameraId, - 'fileFormat': 'jpeg', - }), + isMethodCall( + 'setImageFileFormat', + arguments: { + 'cameraId': cameraId, + 'fileFormat': 'jpeg', + }, + ), ]); }); }); diff --git a/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart b/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart index b52a85a22bb..402be4c3c2c 100644 --- a/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart +++ b/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart @@ -9,24 +9,25 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.yuv420); @@ -36,48 +37,50 @@ void main() { test('CameraImageData has ImageFormatGroup.yuv420 for iOS', () { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 875704438, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 875704438, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('CameraImageData has ImageFormatGroup.yuv420 for Android', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImageData cameraImage = - cameraImageFromPlatformData({ - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4 - } - ] - }); + final CameraImageData cameraImage = cameraImageFromPlatformData( + { + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }, + ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); } diff --git a/packages/camera/camera_platform_interface/test/types/camera_description_test.dart b/packages/camera/camera_platform_interface/test/types/camera_description_test.dart index effd36951fc..d67b73c777a 100644 --- a/packages/camera/camera_platform_interface/test/types/camera_description_test.dart +++ b/packages/camera/camera_platform_interface/test/types/camera_description_test.dart @@ -107,19 +107,24 @@ void main() { expect(firstDescription == secondDescription, true); }); - test('hashCode should match hashCode of all equality-tested properties', - () { - const CameraDescription description = CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.front, - sensorOrientation: 0, - lensType: CameraLensType.ultraWide, - ); - final int expectedHashCode = Object.hash( - description.name, description.lensDirection, description.lensType); - - expect(description.hashCode, expectedHashCode); - }); + test( + 'hashCode should match hashCode of all equality-tested properties', + () { + const CameraDescription description = CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.front, + sensorOrientation: 0, + lensType: CameraLensType.ultraWide, + ); + final int expectedHashCode = Object.hash( + description.name, + description.lensDirection, + description.lensType, + ); + + expect(description.hashCode, expectedHashCode); + }, + ); test('toString should return correct string representation', () { const CameraDescription description = CameraDescription( diff --git a/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart b/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart index 8795932bf05..71956785a54 100644 --- a/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart +++ b/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart @@ -18,11 +18,12 @@ void main() { sensorSensitivity: 92.0, planes: [ CameraImagePlane( - bytes: Uint8List.fromList([1, 2, 3, 4]), - bytesPerRow: 4, - bytesPerPixel: 2, - height: 100, - width: 200) + bytes: Uint8List.fromList([1, 2, 3, 4]), + bytesPerRow: 4, + bytesPerPixel: 2, + height: 100, + width: 200, + ), ], ); expect(cameraImage.format.group, ImageFormatGroup.jpeg); diff --git a/packages/camera/camera_platform_interface/test/types/media_settings_test.dart b/packages/camera/camera_platform_interface/test/types/media_settings_test.dart index 242a153107b..a74dab48348 100644 --- a/packages/camera/camera_platform_interface/test/types/media_settings_test.dart +++ b/packages/camera/camera_platform_interface/test/types/media_settings_test.dart @@ -9,41 +9,45 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test( - 'MediaSettings non-parametrized constructor should have correct initial values', - () { - const MediaSettings settingsWithNoParameters = MediaSettings(); + 'MediaSettings non-parametrized constructor should have correct initial values', + () { + const MediaSettings settingsWithNoParameters = MediaSettings(); - expect( - settingsWithNoParameters.resolutionPreset, - isNull, - reason: - 'MediaSettings constructor should have null default resolutionPreset', - ); + expect( + settingsWithNoParameters.resolutionPreset, + isNull, + reason: + 'MediaSettings constructor should have null default resolutionPreset', + ); - expect( - settingsWithNoParameters.fps, - isNull, - reason: 'MediaSettings constructor should have null default fps', - ); + expect( + settingsWithNoParameters.fps, + isNull, + reason: 'MediaSettings constructor should have null default fps', + ); - expect( - settingsWithNoParameters.videoBitrate, - isNull, - reason: 'MediaSettings constructor should have null default videoBitrate', - ); + expect( + settingsWithNoParameters.videoBitrate, + isNull, + reason: + 'MediaSettings constructor should have null default videoBitrate', + ); - expect( - settingsWithNoParameters.audioBitrate, - isNull, - reason: 'MediaSettings constructor should have null default audioBitrate', - ); + expect( + settingsWithNoParameters.audioBitrate, + isNull, + reason: + 'MediaSettings constructor should have null default audioBitrate', + ); - expect( - settingsWithNoParameters.enableAudio, - isFalse, - reason: 'MediaSettings constructor should have false default enableAudio', - ); - }); + expect( + settingsWithNoParameters.enableAudio, + isFalse, + reason: + 'MediaSettings constructor should have false default enableAudio', + ); + }, + ); test('MediaSettings fps should hold parameters', () { const MediaSettings settings = MediaSettings( @@ -194,10 +198,7 @@ void main() { enableAudio: enableAudio1, ); - expect( - settings1 == sameSettings, - isTrue, - ); + expect(settings1 == sameSettings, isTrue); }); test('Identical objects should be equal', () { diff --git a/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart b/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart index a7362d0e049..2822682432a 100644 --- a/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart +++ b/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart @@ -24,8 +24,10 @@ class MethodChannelMock { log.add(methodCall); if (!methods.containsKey(methodCall.method)) { - throw MissingPluginException('No implementation found for method ' - '${methodCall.method} on channel ${methodChannel.name}'); + throw MissingPluginException( + 'No implementation found for method ' + '${methodCall.method} on channel ${methodChannel.name}', + ); } return Future.delayed(delay ?? Duration.zero, () { diff --git a/packages/camera/camera_platform_interface/test/utils/utils_test.dart b/packages/camera/camera_platform_interface/test/utils/utils_test.dart index 0e4171d73aa..a46e86ff2fa 100644 --- a/packages/camera/camera_platform_interface/test/utils/utils_test.dart +++ b/packages/camera/camera_platform_interface/test/utils/utils_test.dart @@ -10,51 +10,63 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('Utility methods', () { test( - 'Should return CameraLensDirection when valid value is supplied when parsing camera lens direction', - () { + 'Should return CameraLensDirection when valid value is supplied when parsing camera lens direction', + () { + expect(parseCameraLensDirection('back'), CameraLensDirection.back); + expect(parseCameraLensDirection('front'), CameraLensDirection.front); + expect( + parseCameraLensDirection('external'), + CameraLensDirection.external, + ); + }, + ); + + test( + 'Should throw ArgumentException when invalid value is supplied when parsing camera lens direction', + () { + expect( + () => parseCameraLensDirection('test'), + throwsA(isArgumentError), + ); + }, + ); + + test('serializeDeviceOrientation() should serialize correctly', () { expect( - parseCameraLensDirection('back'), - CameraLensDirection.back, + serializeDeviceOrientation(DeviceOrientation.portraitUp), + 'portraitUp', ); expect( - parseCameraLensDirection('front'), - CameraLensDirection.front, + serializeDeviceOrientation(DeviceOrientation.portraitDown), + 'portraitDown', ); expect( - parseCameraLensDirection('external'), - CameraLensDirection.external, + serializeDeviceOrientation(DeviceOrientation.landscapeRight), + 'landscapeRight', ); - }); - - test( - 'Should throw ArgumentException when invalid value is supplied when parsing camera lens direction', - () { expect( - () => parseCameraLensDirection('test'), - throwsA(isArgumentError), + serializeDeviceOrientation(DeviceOrientation.landscapeLeft), + 'landscapeLeft', ); }); - test('serializeDeviceOrientation() should serialize correctly', () { - expect(serializeDeviceOrientation(DeviceOrientation.portraitUp), - 'portraitUp'); - expect(serializeDeviceOrientation(DeviceOrientation.portraitDown), - 'portraitDown'); - expect(serializeDeviceOrientation(DeviceOrientation.landscapeRight), - 'landscapeRight'); - expect(serializeDeviceOrientation(DeviceOrientation.landscapeLeft), - 'landscapeLeft'); - }); - test('deserializeDeviceOrientation() should deserialize correctly', () { - expect(deserializeDeviceOrientation('portraitUp'), - DeviceOrientation.portraitUp); - expect(deserializeDeviceOrientation('portraitDown'), - DeviceOrientation.portraitDown); - expect(deserializeDeviceOrientation('landscapeRight'), - DeviceOrientation.landscapeRight); - expect(deserializeDeviceOrientation('landscapeLeft'), - DeviceOrientation.landscapeLeft); + expect( + deserializeDeviceOrientation('portraitUp'), + DeviceOrientation.portraitUp, + ); + expect( + deserializeDeviceOrientation('portraitDown'), + DeviceOrientation.portraitDown, + ); + expect( + deserializeDeviceOrientation('landscapeRight'), + DeviceOrientation.landscapeRight, + ); + expect( + deserializeDeviceOrientation('landscapeLeft'), + DeviceOrientation.landscapeLeft, + ); }); }); } diff --git a/packages/camera/camera_web/CHANGELOG.md b/packages/camera/camera_web/CHANGELOG.md index 13170494c45..0bfdbd06124 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 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 fab60f12405..f9271a26244 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 @@ -45,8 +45,9 @@ void main() { } } - testWidgets('Camera allows to control video bitrate', - (WidgetTester tester) async { + testWidgets('Camera allows to control video bitrate', ( + WidgetTester tester, + ) async { //const String supportedVideoType = 'video/webm'; const String supportedVideoType = 'video/webm;codecs="vp9,opus"'; bool isVideoTypeSupported(String type) => type == supportedVideoType; @@ -65,49 +66,39 @@ 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(); final MockCameraService cameraService = MockCameraService(); - CameraPlatform.instance = CameraPlugin( - cameraService: cameraService, - )..window = window; + CameraPlatform.instance = CameraPlugin(cameraService: cameraService) + ..window = window; final CameraOptions options = CameraOptions( audio: const AudioConstraints(), video: VideoConstraints( - width: VideoSizeConstraint( - ideal: videoSize.width.toInt(), - ), - height: VideoSizeConstraint( - ideal: videoSize.height.toInt(), - ), + width: VideoSizeConstraint(ideal: videoSize.width.toInt()), + height: VideoSizeConstraint(ideal: videoSize.height.toInt()), ), ); final int cameraId = videoBitrate; when( - cameraService.getMediaStreamForOptions( - options, - cameraId: cameraId, - ), + cameraService.getMediaStreamForOptions(options, cameraId: cameraId), ).thenAnswer((_) async => canvasElement.captureStream()); final Camera camera = Camera( - textureId: cameraId, - cameraService: cameraService, - options: options, - recorderOptions: ( - audioBitrate: null, - videoBitrate: videoBitrate, - )) - ..isVideoTypeSupported = isVideoTypeSupported; + textureId: cameraId, + cameraService: cameraService, + options: options, + recorderOptions: (audioBitrate: null, videoBitrate: videoBitrate), + )..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); diff --git a/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart b/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart index 4adb5cc4046..97a3d706517 100644 --- a/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart @@ -25,10 +25,7 @@ void main() { }); testWidgets('notFound', (WidgetTester tester) async { - expect( - CameraErrorCode.notFound.toString(), - equals('cameraNotFound'), - ); + expect(CameraErrorCode.notFound.toString(), equals('cameraNotFound')); }); testWidgets('notReadable', (WidgetTester tester) async { @@ -53,24 +50,15 @@ void main() { }); testWidgets('type', (WidgetTester tester) async { - expect( - CameraErrorCode.type.toString(), - equals('cameraType'), - ); + expect(CameraErrorCode.type.toString(), equals('cameraType')); }); testWidgets('abort', (WidgetTester tester) async { - expect( - CameraErrorCode.abort.toString(), - equals('cameraAbort'), - ); + expect(CameraErrorCode.abort.toString(), equals('cameraAbort')); }); testWidgets('security', (WidgetTester tester) async { - expect( - CameraErrorCode.security.toString(), - equals('cameraSecurity'), - ); + expect(CameraErrorCode.security.toString(), equals('cameraSecurity')); }); testWidgets('missingMetadata', (WidgetTester tester) async { @@ -123,10 +111,7 @@ void main() { }); testWidgets('unknown', (WidgetTester tester) async { - expect( - CameraErrorCode.unknown.toString(), - equals('cameraUnknown'), - ); + expect(CameraErrorCode.unknown.toString(), equals('cameraUnknown')); }); group('fromMediaError', () { @@ -134,7 +119,9 @@ void main() { expect( CameraErrorCode.fromMediaError( createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_ABORTED)) as MediaError, + FakeMediaError(MediaError.MEDIA_ERR_ABORTED), + ) + as MediaError, ).toString(), equals('mediaErrorAborted'), ); @@ -144,7 +131,9 @@ void main() { expect( CameraErrorCode.fromMediaError( createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_NETWORK)) as MediaError, + FakeMediaError(MediaError.MEDIA_ERR_NETWORK), + ) + as MediaError, ).toString(), equals('mediaErrorNetwork'), ); @@ -154,18 +143,22 @@ void main() { expect( CameraErrorCode.fromMediaError( createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_DECODE)) as MediaError, + FakeMediaError(MediaError.MEDIA_ERR_DECODE), + ) + as MediaError, ).toString(), equals('mediaErrorDecode'), ); }); - testWidgets('with source not supported error code', - (WidgetTester tester) async { + testWidgets('with source not supported error code', ( + WidgetTester tester, + ) async { expect( CameraErrorCode.fromMediaError( createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED)) + FakeMediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED), + ) as MediaError, ).toString(), equals('mediaErrorSourceNotSupported'), diff --git a/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart b/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart index fa4547726ce..2ecd44f5fbd 100644 --- a/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart @@ -13,15 +13,9 @@ void main() { group('CameraMetadata', () { testWidgets('supports value equality', (WidgetTester tester) async { expect( - const CameraMetadata( - deviceId: 'deviceId', - facingMode: 'environment', - ), + const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment'), equals( - const CameraMetadata( - deviceId: 'deviceId', - facingMode: 'environment', - ), + const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment'), ), ); }); diff --git a/packages/camera/camera_web/example/integration_test/camera_options_test.dart b/packages/camera/camera_web/example/integration_test/camera_options_test.dart index 66f4a6bd1eb..c1236993a89 100644 --- a/packages/camera/camera_web/example/integration_test/camera_options_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_options_test.dart @@ -36,10 +36,16 @@ void main() { audio: const AudioConstraints(), video: VideoConstraints( facingMode: FacingModeConstraint(CameraType.environment), - width: - const VideoSizeConstraint(minimum: 10, ideal: 15, maximum: 20), - height: - const VideoSizeConstraint(minimum: 15, ideal: 20, maximum: 25), + width: const VideoSizeConstraint( + minimum: 10, + ideal: 15, + maximum: 20, + ), + height: const VideoSizeConstraint( + minimum: 15, + ideal: 20, + maximum: 25, + ), deviceId: 'deviceId', ), ), @@ -49,9 +55,15 @@ void main() { video: VideoConstraints( facingMode: FacingModeConstraint(CameraType.environment), width: const VideoSizeConstraint( - minimum: 10, ideal: 15, maximum: 20), + minimum: 10, + ideal: 15, + maximum: 20, + ), height: const VideoSizeConstraint( - minimum: 15, ideal: 20, maximum: 25), + minimum: 15, + ideal: 20, + maximum: 25, + ), deviceId: 'deviceId', ), ), @@ -91,9 +103,7 @@ void main() { 'facingMode': videoConstraints.facingMode!.toJson(), 'width': videoConstraints.width!.toJson(), 'height': videoConstraints.height!.toJson(), - 'deviceId': { - 'exact': 'deviceId', - } + 'deviceId': {'exact': 'deviceId'}, }), ); }); @@ -102,19 +112,31 @@ void main() { expect( VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.environment), - width: - const VideoSizeConstraint(minimum: 90, ideal: 100, maximum: 100), - height: - const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50), + width: const VideoSizeConstraint( + minimum: 90, + ideal: 100, + maximum: 100, + ), + height: const VideoSizeConstraint( + minimum: 40, + ideal: 50, + maximum: 50, + ), deviceId: 'deviceId', ), equals( VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.environment), width: const VideoSizeConstraint( - minimum: 90, ideal: 100, maximum: 100), - height: - const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50), + minimum: 90, + ideal: 100, + maximum: 100, + ), + height: const VideoSizeConstraint( + minimum: 40, + ideal: 50, + maximum: 50, + ), deviceId: 'deviceId', ), ), @@ -124,8 +146,7 @@ void main() { group('FacingModeConstraint', () { group('ideal', () { - testWidgets( - 'serializes correctly ' + testWidgets('serializes correctly ' 'for environment camera type', (WidgetTester tester) async { expect( FacingModeConstraint(CameraType.environment).toJson(), @@ -133,8 +154,7 @@ void main() { ); }); - testWidgets( - 'serializes correctly ' + testWidgets('serializes correctly ' 'for user camera type', (WidgetTester tester) async { expect( FacingModeConstraint(CameraType.user).toJson(), @@ -151,8 +171,7 @@ void main() { }); group('exact', () { - testWidgets( - 'serializes correctly ' + testWidgets('serializes correctly ' 'for environment camera type', (WidgetTester tester) async { expect( FacingModeConstraint.exact(CameraType.environment).toJson(), @@ -160,8 +179,7 @@ void main() { ); }); - testWidgets( - 'serializes correctly ' + testWidgets('serializes correctly ' 'for user camera type', (WidgetTester tester) async { expect( FacingModeConstraint.exact(CameraType.user).toJson(), @@ -186,27 +204,15 @@ void main() { ideal: 400, maximum: 400, ).toJson(), - equals({ - 'min': 200, - 'ideal': 400, - 'max': 400, - }), + equals({'min': 200, 'ideal': 400, 'max': 400}), ); }); testWidgets('supports value equality', (WidgetTester tester) async { expect( - const VideoSizeConstraint( - minimum: 100, - ideal: 200, - maximum: 300, - ), + const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300), equals( - const VideoSizeConstraint( - minimum: 100, - ideal: 200, - maximum: 300, - ), + const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300), ), ); }); 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 b755bb249ae..493ba807bbd 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 @@ -55,26 +55,28 @@ void main() { // Mock JsUtil to return the real getProperty from dart:js_util. when(jsUtil.getProperty(any, any)).thenAnswer( (Invocation invocation) => - (invocation.positionalArguments[0] as JSObject) - .getProperty(invocation.positionalArguments[1] as JSAny), + (invocation.positionalArguments[0] as JSObject).getProperty( + invocation.positionalArguments[1] as JSAny, + ), ); cameraService = CameraService()..window = window; }); group('getMediaStreamForOptions', () { - testWidgets( - 'calls MediaDevices.getUserMedia ' + 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; + capturedConstraints = constraints; + final web.MediaStream stream = + createJSInteropWrapper( + FakeMediaStream([]), + ) + as web.MediaStream; + return Future.value(stream).toJS; + }.toJS; final CameraOptions options = CameraOptions( video: VideoConstraints( @@ -96,15 +98,15 @@ void main() { }); group('throws CameraWebException', () { - testWidgets( - 'with notFound error ' + 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( @@ -113,23 +115,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.notFound), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.notFound, + ), ), ); }); - testWidgets( - 'with notFound error ' + 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( @@ -138,23 +146,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.notFound), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.notFound, + ), ), ); }); - testWidgets( - 'with notReadable error ' + 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(), @@ -162,23 +176,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.notReadable), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.notReadable, + ), ), ); }); - testWidgets( - 'with notReadable error ' + 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( @@ -187,23 +207,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.notReadable), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.notReadable, + ), ), ); }); - testWidgets( - 'with overconstrained error ' + 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( @@ -212,23 +238,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.overconstrained), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.overconstrained, + ), ), ); }); - testWidgets( - 'with overconstrained error ' + 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( @@ -237,23 +269,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.overconstrained), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.overconstrained, + ), ), ); }); - testWidgets( - 'with permissionDenied error ' + 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( @@ -262,23 +300,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.permissionDenied), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.permissionDenied, + ), ), ); }); - testWidgets( - 'with permissionDenied error ' + 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( @@ -287,23 +331,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.permissionDenied), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.permissionDenied, + ), ), ); }); - testWidgets( - 'with type error ' + 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( @@ -312,23 +362,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.type), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.type, + ), ), ); }); - testWidgets( - 'with abort error ' + 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( @@ -337,23 +393,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.abort), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.abort, + ), ), ); }); - testWidgets( - 'with security error ' + 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( @@ -362,23 +424,29 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.security), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.security, + ), ), ); }); - testWidgets( - 'with unknown error ' + 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( @@ -387,23 +455,30 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.unknown), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.unknown, + ), ), ); }); - testWidgets( - 'with unknown error ' - '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; + testWidgets('with unknown error ' + '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; expect( () => cameraService.getMediaStreamForOptions( @@ -412,10 +487,16 @@ void main() { ), throwsA( isA() - .having((CameraWebException e) => e.cameraId, 'cameraId', - cameraId) - .having((CameraWebException e) => e.code, 'code', - CameraErrorCode.unknown), + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + cameraId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.unknown, + ), ), ); }); @@ -445,21 +526,22 @@ void main() { cameraService.jsUtil = jsUtil; }); - testWidgets( - 'returns the zoom level capability ' + testWidgets('returns the zoom level capability ' 'based on the first video track', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = () { - return web.MediaTrackSupportedConstraints(zoom: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = + () { + return web.MediaTrackSupportedConstraints(zoom: true); + }.toJS; - mockVideoTrack.getCapabilities = () { - return web.MediaTrackCapabilities( - zoom: web.MediaSettingsRange(min: 100, max: 400, step: 2), - ); - }.toJS; + mockVideoTrack.getCapabilities = + () { + return web.MediaTrackCapabilities( + zoom: web.MediaSettingsRange(min: 100, max: 400, step: 2), + ); + }.toJS; - final ZoomLevelCapability zoomLevelCapability = - cameraService.getZoomLevelCapabilityForCamera(camera); + final ZoomLevelCapability zoomLevelCapability = cameraService + .getZoomLevelCapabilityForCamera(camera); expect(zoomLevelCapability.minimum, equals(100.0)); expect(zoomLevelCapability.maximum, equals(400.0)); @@ -467,19 +549,20 @@ void main() { }); group('throws CameraWebException', () { - testWidgets( - 'with zoomLevelNotSupported error ' + 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), @@ -499,13 +582,14 @@ void main() { ); }); - testWidgets( - 'with notStarted error ' - 'when the camera stream has not been initialized', - (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = () { - return web.MediaTrackSupportedConstraints(zoom: true); - }.toJS; + testWidgets('with notStarted error ' + 'when the camera stream has not been initialized', ( + WidgetTester tester, + ) async { + mockMediaDevices.getSupportedConstraints = + () { + return web.MediaTrackSupportedConstraints(zoom: true); + }.toJS; // Create a camera stream with no video tracks. when(camera.stream).thenReturn( @@ -538,12 +622,12 @@ void main() { cameraService.jsUtil = jsUtil; }); - testWidgets( - 'returns null ' + 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()) @@ -562,81 +646,95 @@ void main() { videoTrack = createJSInteropWrapper(mockVideoTrack) as web.MediaStreamTrack; - when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)) - .thenReturn(true); + when( + 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 ' + 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); + final String? facingMode = cameraService.getFacingModeForVideoTrack( + videoTrack, + ); expect(facingMode, equals('user')); }); - testWidgets( - 'returns an appropriate facing mode ' + testWidgets('returns an appropriate facing mode ' 'based on the video track capabilities ' - '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; - - when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)) - .thenReturn(true); - - final String? facingMode = - cameraService.getFacingModeForVideoTrack(videoTrack); + '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; + + when( + jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), + ).thenReturn(true); + + final String? facingMode = cameraService.getFacingModeForVideoTrack( + videoTrack, + ); expect(facingMode, equals('environment')); }); - testWidgets( - 'returns null ' + 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; - - final String? facingMode = - cameraService.getFacingModeForVideoTrack(videoTrack); + mockVideoTrack.getSettings = + () { + return web.MediaTrackSettings(facingMode: ''); + }.toJS; + mockVideoTrack.getCapabilities = + () { + return web.MediaTrackCapabilities( + facingMode: [].toJS, + ); + }.toJS; + + final String? facingMode = cameraService.getFacingModeForVideoTrack( + videoTrack, + ); expect(facingMode, isNull); }); - testWidgets( - 'returns null ' + testWidgets('returns null ' 'when the facing mode setting is empty and ' - 'the video track capabilities are not supported', - (WidgetTester tester) async { - mockVideoTrack.getSettings = () { - return web.MediaTrackSettings(facingMode: ''); - }.toJS; - - when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)) - .thenReturn(false); - - final String? facingMode = - cameraService.getFacingModeForVideoTrack(videoTrack); + 'the video track capabilities are not supported', ( + WidgetTester tester, + ) async { + mockVideoTrack.getSettings = + () { + return web.MediaTrackSettings(facingMode: ''); + }.toJS; + + when( + jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), + ).thenReturn(false); + + final String? facingMode = cameraService.getFacingModeForVideoTrack( + videoTrack, + ); expect(facingMode, isNull); }); @@ -644,8 +742,7 @@ void main() { }); group('mapFacingModeToLensDirection', () { - testWidgets( - 'returns front ' + testWidgets('returns front ' 'when the facing mode is user', (WidgetTester tester) async { expect( cameraService.mapFacingModeToLensDirection('user'), @@ -653,8 +750,7 @@ void main() { ); }); - testWidgets( - 'returns back ' + testWidgets('returns back ' 'when the facing mode is environment', (WidgetTester tester) async { expect( cameraService.mapFacingModeToLensDirection('environment'), @@ -662,8 +758,7 @@ void main() { ); }); - testWidgets( - 'returns external ' + testWidgets('returns external ' 'when the facing mode is left', (WidgetTester tester) async { expect( cameraService.mapFacingModeToLensDirection('left'), @@ -671,8 +766,7 @@ void main() { ); }); - testWidgets( - 'returns external ' + testWidgets('returns external ' 'when the facing mode is right', (WidgetTester tester) async { expect( cameraService.mapFacingModeToLensDirection('right'), @@ -682,8 +776,7 @@ void main() { }); group('mapFacingModeToCameraType', () { - testWidgets( - 'returns user ' + testWidgets('returns user ' 'when the facing mode is user', (WidgetTester tester) async { expect( cameraService.mapFacingModeToCameraType('user'), @@ -691,8 +784,7 @@ void main() { ); }); - testWidgets( - 'returns environment ' + testWidgets('returns environment ' 'when the facing mode is environment', (WidgetTester tester) async { expect( cameraService.mapFacingModeToCameraType('environment'), @@ -700,8 +792,7 @@ void main() { ); }); - testWidgets( - 'returns user ' + testWidgets('returns user ' 'when the facing mode is left', (WidgetTester tester) async { expect( cameraService.mapFacingModeToCameraType('left'), @@ -709,8 +800,7 @@ void main() { ); }); - testWidgets( - 'returns user ' + testWidgets('returns user ' 'when the facing mode is right', (WidgetTester tester) async { expect( cameraService.mapFacingModeToCameraType('right'), @@ -720,8 +810,7 @@ void main() { }); group('mapResolutionPresetToSize', () { - testWidgets( - 'returns 4096x2160 ' + testWidgets('returns 4096x2160 ' 'when the resolution preset is max', (WidgetTester tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.max), @@ -729,28 +818,27 @@ void main() { ); }); - testWidgets( - 'returns 4096x2160 ' - 'when the resolution preset is ultraHigh', - (WidgetTester tester) async { + testWidgets('returns 4096x2160 ' + 'when the resolution preset is ultraHigh', ( + WidgetTester tester, + ) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh), equals(const Size(4096, 2160)), ); }); - testWidgets( - 'returns 1920x1080 ' - 'when the resolution preset is veryHigh', - (WidgetTester tester) async { + testWidgets('returns 1920x1080 ' + 'when the resolution preset is veryHigh', ( + WidgetTester tester, + ) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.veryHigh), equals(const Size(1920, 1080)), ); }); - testWidgets( - 'returns 1280x720 ' + testWidgets('returns 1280x720 ' 'when the resolution preset is high', (WidgetTester tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.high), @@ -758,8 +846,7 @@ void main() { ); }); - testWidgets( - 'returns 720x480 ' + testWidgets('returns 720x480 ' 'when the resolution preset is medium', (WidgetTester tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.medium), @@ -767,8 +854,7 @@ void main() { ); }); - testWidgets( - 'returns 320x240 ' + testWidgets('returns 320x240 ' 'when the resolution preset is low', (WidgetTester tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.low), @@ -778,10 +864,10 @@ void main() { }); group('mapDeviceOrientationToOrientationType', () { - testWidgets( - 'returns portraitPrimary ' - 'when the device orientation is portraitUp', - (WidgetTester tester) async { + testWidgets('returns portraitPrimary ' + 'when the device orientation is portraitUp', ( + WidgetTester tester, + ) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.portraitUp, @@ -790,10 +876,10 @@ void main() { ); }); - testWidgets( - 'returns landscapePrimary ' - 'when the device orientation is landscapeLeft', - (WidgetTester tester) async { + testWidgets('returns landscapePrimary ' + 'when the device orientation is landscapeLeft', ( + WidgetTester tester, + ) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.landscapeLeft, @@ -802,10 +888,10 @@ void main() { ); }); - testWidgets( - 'returns portraitSecondary ' - 'when the device orientation is portraitDown', - (WidgetTester tester) async { + testWidgets('returns portraitSecondary ' + 'when the device orientation is portraitDown', ( + WidgetTester tester, + ) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.portraitDown, @@ -814,10 +900,10 @@ void main() { ); }); - testWidgets( - 'returns landscapeSecondary ' - 'when the device orientation is landscapeRight', - (WidgetTester tester) async { + testWidgets('returns landscapeSecondary ' + 'when the device orientation is landscapeRight', ( + WidgetTester tester, + ) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.landscapeRight, @@ -828,10 +914,10 @@ void main() { }); group('mapOrientationTypeToDeviceOrientation', () { - testWidgets( - 'returns portraitUp ' - 'when the orientation type is portraitPrimary', - (WidgetTester tester) async { + testWidgets('returns portraitUp ' + 'when the orientation type is portraitPrimary', ( + WidgetTester tester, + ) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitPrimary, @@ -840,10 +926,10 @@ void main() { ); }); - testWidgets( - 'returns landscapeLeft ' - 'when the orientation type is landscapePrimary', - (WidgetTester tester) async { + testWidgets('returns landscapeLeft ' + 'when the orientation type is landscapePrimary', ( + WidgetTester tester, + ) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.landscapePrimary, @@ -852,10 +938,10 @@ void main() { ); }); - testWidgets( - 'returns portraitDown ' - 'when the orientation type is portraitSecondary', - (WidgetTester tester) async { + testWidgets('returns portraitDown ' + 'when the orientation type is portraitSecondary', ( + WidgetTester tester, + ) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitSecondary, @@ -864,10 +950,10 @@ void main() { ); }); - testWidgets( - 'returns portraitDown ' - 'when the orientation type is portraitSecondary', - (WidgetTester tester) async { + testWidgets('returns portraitDown ' + 'when the orientation type is portraitSecondary', ( + WidgetTester tester, + ) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitSecondary, @@ -876,10 +962,10 @@ void main() { ); }); - testWidgets( - 'returns landscapeRight ' - 'when the orientation type is landscapeSecondary', - (WidgetTester tester) async { + testWidgets('returns landscapeRight ' + 'when the orientation type is landscapeSecondary', ( + WidgetTester tester, + ) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.landscapeSecondary, @@ -888,13 +974,10 @@ void main() { ); }); - testWidgets( - 'returns portraitUp ' + testWidgets('returns portraitUp ' 'for an unknown orientation type', (WidgetTester tester) async { expect( - cameraService.mapOrientationTypeToDeviceOrientation( - 'unknown', - ), + cameraService.mapOrientationTypeToDeviceOrientation('unknown'), equals(DeviceOrientation.portraitUp), ); }); 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 520da0e87a8..ac35b46caa3 100644 --- a/packages/camera/camera_web/example/integration_test/camera_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_test.dart @@ -50,8 +50,9 @@ void main() { cameraService = MockCameraService(); - final HTMLVideoElement videoElement = - getVideoElementWithBlankStream(const Size(10, 10)); + final HTMLVideoElement videoElement = getVideoElementWithBlankStream( + const Size(10, 10), + ); mediaStream = videoElement.captureStream(); when( @@ -63,8 +64,7 @@ void main() { }); group('initialize', () { - testWidgets( - 'calls CameraService.getMediaStreamForOptions ' + testWidgets('calls CameraService.getMediaStreamForOptions ' 'with provided options', (WidgetTester tester) async { final CameraOptions options = CameraOptions( video: VideoConstraints( @@ -82,22 +82,17 @@ void main() { await camera.initialize(); verify( - cameraService.getMediaStreamForOptions( - options, - cameraId: textureId, - ), + cameraService.getMediaStreamForOptions(options, cameraId: textureId), ).called(1); }); - testWidgets( - 'creates a video element ' + testWidgets('creates a video element ' 'with correct properties', (WidgetTester tester) async { - const AudioConstraints audioConstraints = - AudioConstraints(enabled: true); + const AudioConstraints audioConstraints = AudioConstraints( + enabled: true, + ); final VideoConstraints videoConstraints = VideoConstraints( - facingMode: FacingModeConstraint( - CameraType.user, - ), + facingMode: FacingModeConstraint(CameraType.user), ); final Camera camera = Camera( @@ -115,31 +110,30 @@ void main() { expect(camera.videoElement.autoplay, isFalse); expect(camera.videoElement.muted, isTrue); expect(camera.videoElement.srcObject, mediaStream); - expect(camera.videoElement.attributes.getNamedItem('playsinline'), - isNotNull); + expect( + camera.videoElement.attributes.getNamedItem('playsinline'), + isNotNull, + ); expect( - camera.videoElement.style.transformOrigin, equals('center center')); + camera.videoElement.style.transformOrigin, + equals('center center'), + ); expect(camera.videoElement.style.pointerEvents, equals('none')); expect(camera.videoElement.style.width, equals('100%')); expect(camera.videoElement.style.height, equals('100%')); expect(camera.videoElement.style.objectFit, equals('cover')); }); - testWidgets( - 'flips the video element horizontally ' + testWidgets('flips the video element horizontally ' 'for a back camera', (WidgetTester tester) async { final VideoConstraints videoConstraints = VideoConstraints( - facingMode: FacingModeConstraint( - CameraType.environment, - ), + facingMode: FacingModeConstraint(CameraType.environment), ); final Camera camera = Camera( textureId: textureId, - options: CameraOptions( - video: videoConstraints, - ), + options: CameraOptions(video: videoConstraints), cameraService: cameraService, ); @@ -148,8 +142,7 @@ void main() { expect(camera.videoElement.style.transform, equals('scaleX(-1)')); }); - testWidgets( - 'creates a wrapping div element ' + testWidgets('creates a wrapping div element ' 'with correct properties', (WidgetTester tester) async { final Camera camera = Camera( textureId: textureId, @@ -160,9 +153,12 @@ void main() { expect(camera.divElement, isNotNull); expect(camera.divElement.style.objectFit, equals('cover')); - final JSArray? array = (globalContext['Array']! as JSObject) - .callMethod('from'.toJS, camera.divElement.children) - as JSArray?; + final JSArray? array = + (globalContext['Array']! as JSObject).callMethod( + 'from'.toJS, + camera.divElement.children, + ) + as JSArray?; expect(array?.toDart, contains(camera.videoElement)); }); @@ -177,12 +173,13 @@ void main() { expect(camera.stream, mediaStream); }); - testWidgets( - 'throws an exception ' - 'when CameraService.getMediaStreamForOptions throws', - (WidgetTester tester) async { - final Exception exception = - Exception('A media stream exception occured.'); + testWidgets('throws an exception ' + 'when CameraService.getMediaStreamForOptions throws', ( + WidgetTester tester, + ) async { + final Exception exception = Exception( + 'A media stream exception occured.', + ); when( cameraService.getMediaStreamForOptions( @@ -196,16 +193,14 @@ void main() { cameraService: cameraService, ); - expect( - camera.initialize, - throwsA(exception), - ); + expect(camera.initialize, throwsA(exception)); }); }); group('play', () { - testWidgets('starts playing the video element', - (WidgetTester tester) async { + testWidgets('starts playing the video element', ( + WidgetTester tester, + ) async { bool startedPlaying = false; final Camera camera = Camera( @@ -216,7 +211,8 @@ void main() { await camera.initialize(); final StreamSubscription cameraPlaySubscription = camera - .videoElement.onPlay + .videoElement + .onPlay .listen((Event event) => startedPlaying = true); await camera.play(); @@ -226,14 +222,11 @@ void main() { await cameraPlaySubscription.cancel(); }); - testWidgets( - 'initializes the camera stream ' + testWidgets('initializes the camera stream ' 'from CameraService.getMediaStreamForOptions ' 'if it does not exist', (WidgetTester tester) async { const CameraOptions options = CameraOptions( - video: VideoConstraints( - width: VideoSizeConstraint(ideal: 100), - ), + video: VideoConstraints(width: VideoSizeConstraint(ideal: 100)), ); final Camera camera = Camera( @@ -252,10 +245,7 @@ void main() { // Should be called twice: for initialize and play. verify( - cameraService.getMediaStreamForOptions( - options, - cameraId: textureId, - ), + cameraService.getMediaStreamForOptions(options, cameraId: textureId), ).called(2); expect(camera.videoElement.srcObject, mediaStream); @@ -313,8 +303,7 @@ void main() { expect(pictureFile, isNotNull); }); - group( - 'enables the torch mode ' + group('enables the torch mode ' 'when taking a picture', () { late MockMediaStreamTrack mockVideoTrack; late List videoTracks; @@ -327,39 +316,40 @@ void main() { createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack, createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ]; - videoStream = createJSInteropWrapper(FakeMediaStream(videoTracks)) - as MediaStream; + videoStream = + createJSInteropWrapper(FakeMediaStream(videoTracks)) + as MediaStream; 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 { - final Camera camera = Camera( - textureId: textureId, - cameraService: cameraService, - ) - ..window = window - ..stream = videoStream - ..videoElement = videoElement - ..flashMode = FlashMode.auto; + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream + ..videoElement = videoElement + ..flashMode = FlashMode.auto; await camera.play(); final List capturedConstraints = []; - mockVideoTrack.applyConstraints = ([ - MediaTrackConstraints? constraints, - ]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = + ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; final XFile _ = await camera.takePicture(); @@ -369,27 +359,24 @@ void main() { }); testWidgets('if the flash mode is always', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: textureId, - cameraService: cameraService, - ) - ..window = window - ..stream = videoStream - ..videoElement = videoElement - ..flashMode = FlashMode.always; + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream + ..videoElement = videoElement + ..flashMode = FlashMode.always; await camera.play(); final List capturedConstraints = []; - mockVideoTrack.applyConstraints = ([ - MediaTrackConstraints? constraints, - ]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = + ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; final XFile _ = await camera.takePicture(); @@ -401,14 +388,15 @@ void main() { }); group('getVideoSize', () { - testWidgets( - 'returns a size ' - 'based on the first video track settings', - (WidgetTester tester) async { + testWidgets('returns a size ' + 'based on the first video track settings', ( + WidgetTester tester, + ) async { const Size videoSize = Size(1280, 720); - final HTMLVideoElement videoElement = - getVideoElementWithBlankStream(videoSize); + final HTMLVideoElement videoElement = getVideoElementWithBlankStream( + videoSize, + ); mediaStream = videoElement.captureStream(); final Camera camera = Camera( @@ -418,14 +406,10 @@ void main() { await camera.initialize(); - expect( - camera.getVideoSize(), - equals(videoSize), - ); + expect(camera.getVideoSize(), equals(videoSize)); }); - testWidgets( - 'returns Size.zero ' + testWidgets('returns Size.zero ' 'if the camera is missing video tracks', (WidgetTester tester) async { // Create a video stream with no video tracks. final HTMLVideoElement videoElement = HTMLVideoElement(); @@ -438,10 +422,7 @@ void main() { await camera.initialize(); - expect( - camera.getVideoSize(), - equals(Size.zero), - ); + expect(camera.getVideoSize(), equals(Size.zero)); }); }); @@ -459,71 +440,66 @@ void main() { videoStream = createJSInteropWrapper(FakeMediaStream(videoTracks)) as MediaStream; - mockVideoTrack.applyConstraints = ([ - MediaTrackConstraints? constraints, - ]) { - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = + ([MediaTrackConstraints? constraints]) { + 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, - ) - ..window = window - ..stream = videoStream; + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; const FlashMode flashMode = FlashMode.always; camera.setFlashMode(flashMode); - expect( - camera.flashMode, - equals(flashMode), - ); + expect(camera.flashMode, equals(flashMode)); }); - testWidgets( - 'enables the torch mode ' + 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, - ) - ..window = window - ..stream = videoStream; + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; final List capturedConstraints = []; - mockVideoTrack.applyConstraints = ([ - MediaTrackConstraints? constraints, - ]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = + ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; camera.setFlashMode(FlashMode.torch); @@ -531,34 +507,32 @@ void main() { expect(capturedConstraints[0].torch.dartify(), true); }); - testWidgets( - 'disables the torch mode ' + 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, - ) - ..window = window - ..stream = videoStream; + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; final List capturedConstraints = []; - mockVideoTrack.applyConstraints = ([ - MediaTrackConstraints? constraints, - ]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = + ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; camera.setFlashMode(FlashMode.auto); @@ -567,24 +541,25 @@ void main() { }); group('throws a CameraWebException', () { - testWidgets( - 'with torchModeNotSupported error ' + testWidgets('with torchModeNotSupported error ' 'when the torch mode is not supported ' 'in the browser', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = () { - return MediaTrackSupportedConstraints(torch: false); - }.toJS; - - mockVideoTrack.getCapabilities = () { - return MediaTrackCapabilities(torch: [true.toJS].toJS); - }.toJS; - - final Camera camera = Camera( - textureId: textureId, - cameraService: cameraService, - ) - ..window = window - ..stream = videoStream; + mockMediaDevices.getSupportedConstraints = + () { + return MediaTrackSupportedConstraints(torch: false); + }.toJS; + + mockVideoTrack.getCapabilities = + () { + return MediaTrackCapabilities( + torch: [true.toJS].toJS, + ); + }.toJS; + + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; expect( () => camera.setFlashMode(FlashMode.always), @@ -604,24 +579,25 @@ void main() { ); }); - testWidgets( - 'with torchModeNotSupported error ' + testWidgets('with torchModeNotSupported error ' 'when the torch mode is not supported ' 'by the camera', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; - - mockVideoTrack.getCapabilities = () { - return MediaTrackCapabilities(torch: [false.toJS].toJS); - }.toJS; - - final Camera camera = Camera( - textureId: textureId, - cameraService: cameraService, - ) - ..window = window - ..stream = videoStream; + mockMediaDevices.getSupportedConstraints = + () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; + + mockVideoTrack.getCapabilities = + () { + return MediaTrackCapabilities( + torch: [false.toJS].toJS, + ); + }.toJS; + + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; expect( () => camera.setFlashMode(FlashMode.always), @@ -641,17 +617,21 @@ void main() { ); }); - testWidgets( - 'with notStarted error ' - 'when the camera stream has not been initialized', - (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; - - mockVideoTrack.getCapabilities = () { - return MediaTrackCapabilities(torch: [true.toJS].toJS); - }.toJS; + testWidgets('with notStarted error ' + 'when the camera stream has not been initialized', ( + WidgetTester tester, + ) async { + mockMediaDevices.getSupportedConstraints = + () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; + + mockVideoTrack.getCapabilities = + () { + return MediaTrackCapabilities( + torch: [true.toJS].toJS, + ); + }.toJS; final Camera camera = Camera( textureId: textureId, @@ -680,10 +660,10 @@ void main() { group('zoomLevel', () { group('getMaxZoomLevel', () { - testWidgets( - 'returns maximum ' - 'from CameraService.getZoomLevelCapabilityForCamera', - (WidgetTester tester) async { + testWidgets('returns maximum ' + 'from CameraService.getZoomLevelCapabilityForCamera', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -692,30 +672,30 @@ void main() { final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, ); - when(cameraService.getZoomLevelCapabilityForCamera(camera)) - .thenReturn(zoomLevelCapability); + when( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).thenReturn(zoomLevelCapability); final double maximumZoomLevel = camera.getMaxZoomLevel(); - verify(cameraService.getZoomLevelCapabilityForCamera(camera)) - .called(1); + verify( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).called(1); - expect( - maximumZoomLevel, - equals(zoomLevelCapability.maximum), - ); + expect(maximumZoomLevel, equals(zoomLevelCapability.maximum)); }); }); group('getMinZoomLevel', () { - testWidgets( - 'returns minimum ' - 'from CameraService.getZoomLevelCapabilityForCamera', - (WidgetTester tester) async { + testWidgets('returns minimum ' + 'from CameraService.getZoomLevelCapabilityForCamera', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -724,30 +704,30 @@ void main() { final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, ); - when(cameraService.getZoomLevelCapabilityForCamera(camera)) - .thenReturn(zoomLevelCapability); + when( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).thenReturn(zoomLevelCapability); final double minimumZoomLevel = camera.getMinZoomLevel(); - verify(cameraService.getZoomLevelCapabilityForCamera(camera)) - .called(1); + verify( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).called(1); - expect( - minimumZoomLevel, - equals(zoomLevelCapability.minimum), - ); + expect(minimumZoomLevel, equals(zoomLevelCapability.minimum)); }); }); group('setZoomLevel', () { - testWidgets( - 'applies zoom on the video track ' - 'from CameraService.getZoomLevelCapabilityForCamera', - (WidgetTester tester) async { + testWidgets('applies zoom on the video track ' + 'from CameraService.getZoomLevelCapabilityForCamera', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -765,17 +745,17 @@ void main() { final List capturedConstraints = []; - mockVideoTrack.applyConstraints = ([ - MediaTrackConstraints? constraints, - ]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; - - when(cameraService.getZoomLevelCapabilityForCamera(camera)) - .thenReturn(zoomLevelCapability); + mockVideoTrack.applyConstraints = + ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; + + when( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).thenReturn(zoomLevelCapability); const double zoom = 75.0; @@ -786,10 +766,10 @@ void main() { }); group('throws a CameraWebException', () { - testWidgets( - 'with zoomLevelInvalid error ' - 'when the provided zoom level is below minimum', - (WidgetTester tester) async { + testWidgets('with zoomLevelInvalid error ' + 'when the provided zoom level is below minimum', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -798,34 +778,37 @@ void main() { final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, ); - when(cameraService.getZoomLevelCapabilityForCamera(camera)) - .thenReturn(zoomLevelCapability); + when( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).thenReturn(zoomLevelCapability); expect( - () => camera.setZoomLevel(45.0), - throwsA( - isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.zoomLevelInvalid, - ), - )); + () => camera.setZoomLevel(45.0), + throwsA( + isA() + .having( + (CameraWebException e) => e.cameraId, + 'cameraId', + textureId, + ) + .having( + (CameraWebException e) => e.code, + 'code', + CameraErrorCode.zoomLevelInvalid, + ), + ), + ); }); - testWidgets( - 'with zoomLevelInvalid error ' - 'when the provided zoom level is below minimum', - (WidgetTester tester) async { + testWidgets('with zoomLevelInvalid error ' + 'when the provided zoom level is below minimum', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -834,12 +817,14 @@ void main() { final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, ); - when(cameraService.getZoomLevelCapabilityForCamera(camera)) - .thenReturn(zoomLevelCapability); + when( + cameraService.getZoomLevelCapabilityForCamera(camera), + ).thenReturn(zoomLevelCapability); expect( () => camera.setZoomLevel(105.0), @@ -863,10 +848,10 @@ void main() { }); group('getLensDirection', () { - testWidgets( - 'returns a lens direction ' - 'based on the first video track settings', - (WidgetTester tester) async { + testWidgets('returns a lens direction ' + 'based on the first video track settings', ( + WidgetTester tester, + ) async { final MockVideoElement mockVideoElement = MockVideoElement(); final HTMLVideoElement videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; @@ -878,33 +863,32 @@ void main() { final MockMediaStreamTrack firstVideoTrack = MockMediaStreamTrack(); - mockVideoElement.srcObject = createJSInteropWrapper( - FakeMediaStream( - [ - createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ], - ), - ) as MediaStream; - - firstVideoTrack.getSettings = () { - return MediaTrackSettings(facingMode: 'environment'); - }.toJS; + mockVideoElement.srcObject = + createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + ]), + ) + as MediaStream; + + firstVideoTrack.getSettings = + () { + return MediaTrackSettings(facingMode: 'environment'); + }.toJS; - when(cameraService.mapFacingModeToLensDirection('environment')) - .thenReturn(CameraLensDirection.external); + when( + cameraService.mapFacingModeToLensDirection('environment'), + ).thenReturn(CameraLensDirection.external); - expect( - camera.getLensDirection(), - equals(CameraLensDirection.external), - ); + expect(camera.getLensDirection(), equals(CameraLensDirection.external)); }); - testWidgets( - 'returns null ' - 'if the first video track is missing the facing mode', - (WidgetTester tester) async { + testWidgets('returns null ' + 'if the first video track is missing the facing mode', ( + WidgetTester tester, + ) async { final MockVideoElement mockVideoElement = MockVideoElement(); final HTMLVideoElement videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; @@ -916,28 +900,25 @@ void main() { final MockMediaStreamTrack firstVideoTrack = MockMediaStreamTrack(); - videoElement.srcObject = createJSInteropWrapper( - FakeMediaStream( - [ - createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ], - ), - ) as MediaStream; - - firstVideoTrack.getSettings = () { - return MediaTrackSettings(); - }.toJS; - - expect( - camera.getLensDirection(), - isNull, - ); + videoElement.srcObject = + createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + ]), + ) + as MediaStream; + + firstVideoTrack.getSettings = + () { + return MediaTrackSettings(); + }.toJS; + + expect(camera.getLensDirection(), isNull); }); - testWidgets( - 'returns null ' + testWidgets('returns null ' 'if the camera is missing video tracks', (WidgetTester tester) async { // Create a video stream with no video tracks. final HTMLVideoElement videoElement = HTMLVideoElement(); @@ -950,10 +931,7 @@ void main() { await camera.initialize(); - expect( - camera.getLensDirection(), - isNull, - ); + expect(camera.getLensDirection(), isNull); }); }); @@ -988,8 +966,7 @@ void main() { }); group('startVideoRecording', () { - testWidgets( - 'creates a media recorder ' + testWidgets('creates a media recorder ' 'with appropriate options', (WidgetTester tester) async { final Camera camera = Camera( textureId: 1, @@ -1001,42 +978,29 @@ void main() { await camera.startVideoRecording(); - expect( - camera.mediaRecorder!.stream, - equals(camera.stream), - ); + expect(camera.mediaRecorder!.stream, equals(camera.stream)); - expect( - camera.mediaRecorder!.mimeType, - equals(supportedVideoType), - ); + expect(camera.mediaRecorder!.mimeType, equals(supportedVideoType)); - expect( - camera.mediaRecorder!.state, - equals('recording'), - ); + expect(camera.mediaRecorder!.state, equals('recording')); }); - testWidgets('listens to the media recorder data events', - (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + testWidgets('listens to the media recorder data events', ( + WidgetTester tester, + ) async { + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); final List capturedEvents = []; - mockMediaRecorder.addEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - capturedEvents.add(type); - }.toJS; + mockMediaRecorder.addEventListener = + (String type, EventListener? callback, [JSAny? options]) { + capturedEvents.add(type); + }.toJS; await camera.startVideoRecording(); @@ -1046,50 +1010,42 @@ void main() { ); }); - testWidgets('listens to the media recorder stop events', - (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + testWidgets('listens to the media recorder stop events', ( + WidgetTester tester, + ) async { + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); final List capturedEvents = []; - mockMediaRecorder.addEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - capturedEvents.add(type); - }.toJS; + mockMediaRecorder.addEventListener = + (String type, EventListener? callback, [JSAny? options]) { + capturedEvents.add(type); + }.toJS; await camera.startVideoRecording(); - expect( - capturedEvents.where((String e) => e == 'stop').length, - 1, - ); + expect(capturedEvents.where((String e) => e == 'stop').length, 1); }); testWidgets('starts a video recording', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); 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(); @@ -1097,8 +1053,7 @@ void main() { }); group('throws a CameraWebException', () { - testWidgets( - 'with notSupported error ' + testWidgets('with notSupported error ' 'when no video types are supported', (WidgetTester tester) async { final Camera camera = Camera( textureId: 1, @@ -1136,20 +1091,21 @@ void main() { )..mediaRecorder = mediaRecorder; int pauses = 0; - mockMediaRecorder.pause = () { - pauses++; - }.toJS; + mockMediaRecorder.pause = + () { + pauses++; + }.toJS; await camera.pauseVideoRecording(); expect(pauses, 1); }); - testWidgets( - 'throws a CameraWebException ' + testWidgets('throws a CameraWebException ' 'with videoRecordingNotStarted error ' - 'if the video recording was not started', - (WidgetTester tester) async { + 'if the video recording was not started', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: 1, cameraService: cameraService, @@ -1182,20 +1138,21 @@ void main() { )..mediaRecorder = mediaRecorder; int resumes = 0; - mockMediaRecorder.resume = () { - resumes++; - }.toJS; + mockMediaRecorder.resume = + () { + resumes++; + }.toJS; await camera.resumeVideoRecording(); expect(resumes, 1); }); - testWidgets( - 'throws a CameraWebException ' + testWidgets('throws a CameraWebException ' 'with videoRecordingNotStarted error ' - 'if the video recording was not started', - (WidgetTester tester) async { + 'if the video recording was not started', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: 1, cameraService: cameraService, @@ -1221,16 +1178,13 @@ void main() { }); group('stopVideoRecording', () { - testWidgets( - 'stops a video recording and ' + testWidgets('stops a video recording and ' 'returns the captured file ' 'based on all video data parts', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); @@ -1238,17 +1192,14 @@ void main() { late EventListener videoDataAvailableListener; late EventListener videoRecordingStoppedListener; - mockMediaRecorder.addEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - if (type == 'dataavailable') { - videoDataAvailableListener = callback!; - } else if (type == 'stop') { - videoRecordingStoppedListener = callback!; - } - }.toJS; + mockMediaRecorder.addEventListener = + (String type, EventListener? callback, [JSAny? options]) { + if (type == 'dataavailable') { + videoDataAvailableListener = callback!; + } else if (type == 'stop') { + videoRecordingStoppedListener = callback!; + } + }.toJS; Blob? finalVideo; List? videoParts; @@ -1261,9 +1212,10 @@ void main() { await camera.startVideoRecording(); int stops = 0; - mockMediaRecorder.stop = () { - stops++; - }.toJS; + mockMediaRecorder.stop = + () { + stops++; + }.toJS; final Future videoFileFuture = camera.stopVideoRecording(); @@ -1292,32 +1244,20 @@ void main() { expect(stops, 1); - expect( - videoFile, - isNotNull, - ); + expect(videoFile, isNotNull); - expect( - videoFile.mimeType, - equals(supportedVideoType), - ); + expect(videoFile.mimeType, equals(supportedVideoType)); - expect( - videoFile.name, - equals(finalVideo.hashCode.toString()), - ); + expect(videoFile.name, equals(finalVideo.hashCode.toString())); - expect( - videoParts, - equals(capturedVideoParts), - ); + expect(videoParts, equals(capturedVideoParts)); }); - testWidgets( - 'throws a CameraWebException ' + testWidgets('throws a CameraWebException ' 'with videoRecordingNotStarted error ' - 'if the video recording was not started', - (WidgetTester tester) async { + 'if the video recording was not started', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: 1, cameraService: cameraService, @@ -1346,25 +1286,21 @@ void main() { late EventListener videoRecordingStoppedListener; setUp(() { - mockMediaRecorder.addEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - if (type == 'stop') { - videoRecordingStoppedListener = callback!; - } - }.toJS; + mockMediaRecorder.addEventListener = + (String type, EventListener? callback, [JSAny? options]) { + if (type == 'stop') { + videoRecordingStoppedListener = callback!; + } + }.toJS; }); - testWidgets('stops listening to the media recorder data events', - (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + testWidgets('stops listening to the media recorder data events', ( + WidgetTester tester, + ) async { + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); @@ -1372,13 +1308,10 @@ void main() { await camera.startVideoRecording(); final List capturedEvents = []; - mockMediaRecorder.removeEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - capturedEvents.add(type); - }.toJS; + mockMediaRecorder.removeEventListener = + (String type, EventListener? callback, [JSAny? options]) { + capturedEvents.add(type); + }.toJS; videoRecordingStoppedListener.callAsFunction(null, Event('stop')); @@ -1390,14 +1323,13 @@ void main() { ); }); - testWidgets('stops listening to the media recorder stop events', - (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + testWidgets('stops listening to the media recorder stop events', ( + WidgetTester tester, + ) async { + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); @@ -1405,41 +1337,35 @@ void main() { await camera.startVideoRecording(); final List capturedEvents = []; - mockMediaRecorder.removeEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - capturedEvents.add(type); - }.toJS; + mockMediaRecorder.removeEventListener = + (String type, EventListener? callback, [JSAny? options]) { + capturedEvents.add(type); + }.toJS; videoRecordingStoppedListener.callAsFunction(null, Event('stop')); await Future.microtask(() {}); - expect( - capturedEvents.where((String e) => e == 'stop').length, - 1, - ); + expect(capturedEvents.where((String e) => e == 'stop').length, 1); }); - testWidgets('stops listening to the media recorder errors', - (WidgetTester tester) async { + testWidgets('stops listening to the media recorder errors', ( + WidgetTester tester, + ) async { final StreamController onErrorStreamController = StreamController(); final MockEventStreamProvider provider = MockEventStreamProvider(); - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported - ..mediaRecorderOnErrorProvider = provider; + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported + ..mediaRecorderOnErrorProvider = provider; - when(provider.forTarget(mediaRecorder)) - .thenAnswer((_) => onErrorStreamController.stream); + when( + provider.forTarget(mediaRecorder), + ).thenAnswer((_) => onErrorStreamController.stream); await camera.initialize(); await camera.play(); @@ -1450,17 +1376,15 @@ void main() { await Future.microtask(() {}); - expect( - onErrorStreamController.hasListener, - isFalse, - ); + expect(onErrorStreamController.hasListener, isFalse); }); }); }); group('dispose', () { - testWidgets("resets the video element's source", - (WidgetTester tester) async { + testWidgets("resets the video element's source", ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -1481,14 +1405,12 @@ void main() { await camera.initialize(); await camera.dispose(); - expect( - camera.onEndedController.isClosed, - isTrue, - ); + expect(camera.onEndedController.isClosed, isTrue); }); - testWidgets('closes the onVideoRecordedEvent stream', - (WidgetTester tester) async { + testWidgets('closes the onVideoRecordedEvent stream', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -1497,14 +1419,12 @@ void main() { await camera.initialize(); await camera.dispose(); - expect( - camera.videoRecorderController.isClosed, - isTrue, - ); + expect(camera.videoRecorderController.isClosed, isTrue); }); - testWidgets('closes the onVideoRecordingError stream', - (WidgetTester tester) async { + testWidgets('closes the onVideoRecordingError stream', ( + WidgetTester tester, + ) async { final Camera camera = Camera( textureId: textureId, cameraService: cameraService, @@ -1513,17 +1433,13 @@ void main() { await camera.initialize(); await camera.dispose(); - expect( - camera.videoRecordingErrorController.isClosed, - isTrue, - ); + expect(camera.videoRecordingErrorController.isClosed, isTrue); }); }); group('events', () { group('onVideoRecordedEvent', () { - testWidgets( - 'emits a VideoRecordedEvent ' + testWidgets('emits a VideoRecordedEvent ' 'when a video recording is created', (WidgetTester tester) async { const String supportedVideoType = 'video/webm'; @@ -1531,12 +1447,10 @@ void main() { final MediaRecorder mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = (String type) => type == 'video/webm'; + final Camera camera = + Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = (String type) => type == 'video/webm'; await camera.initialize(); await camera.play(); @@ -1544,17 +1458,14 @@ void main() { late EventListener videoDataAvailableListener; late EventListener videoRecordingStoppedListener; - mockMediaRecorder.addEventListener = ( - String type, - EventListener? callback, [ - JSAny? options, - ]) { - if (type == 'dataavailable') { - videoDataAvailableListener = callback!; - } else if (type == 'stop') { - videoRecordingStoppedListener = callback!; - } - }.toJS; + mockMediaRecorder.addEventListener = + (String type, EventListener? callback, [JSAny? options]) { + if (type == 'dataavailable') { + videoDataAvailableListener = callback!; + } else if (type == 'stop') { + videoRecordingStoppedListener = callback!; + } + }.toJS; final StreamQueue streamQueue = StreamQueue(camera.onVideoRecordedEvent); @@ -1605,8 +1516,7 @@ void main() { }); group('onEnded', () { - testWidgets( - 'emits the default video track ' + testWidgets('emits the default video track ' 'when it emits an ended event', (WidgetTester tester) async { final Camera camera = Camera( textureId: textureId, @@ -1624,16 +1534,12 @@ void main() { defaultVideoTrack.dispatchEvent(Event('ended')); - expect( - await streamQueue.next, - equals(defaultVideoTrack), - ); + expect(await streamQueue.next, equals(defaultVideoTrack)); await streamQueue.cancel(); }); - testWidgets( - 'emits the default video track ' + testWidgets('emits the default video track ' 'when the camera is stopped', (WidgetTester tester) async { final Camera camera = Camera( textureId: textureId, @@ -1651,18 +1557,14 @@ void main() { camera.stop(); - expect( - await streamQueue.next, - equals(defaultVideoTrack), - ); + expect(await streamQueue.next, equals(defaultVideoTrack)); await streamQueue.cancel(); }); }); group('onVideoRecordingError', () { - testWidgets( - 'emits an ErrorEvent ' + testWidgets('emits an ErrorEvent ' 'when the media recorder fails ' 'when recording a video', (WidgetTester tester) async { final MockMediaRecorder mockMediaRecorder = MockMediaRecorder(); @@ -1673,18 +1575,18 @@ void main() { final MockEventStreamProvider provider = MockEventStreamProvider(); - final Camera camera = Camera( - textureId: textureId, - cameraService: cameraService, - ) - ..mediaRecorder = mediaRecorder - ..mediaRecorderOnErrorProvider = provider; + final Camera camera = + Camera(textureId: textureId, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..mediaRecorderOnErrorProvider = provider; - when(provider.forTarget(mediaRecorder)) - .thenAnswer((_) => errorController.stream); + when( + provider.forTarget(mediaRecorder), + ).thenAnswer((_) => errorController.stream); - final StreamQueue streamQueue = - StreamQueue(camera.onVideoRecordingError); + final StreamQueue streamQueue = StreamQueue( + camera.onVideoRecordingError, + ); await camera.initialize(); await camera.play(); @@ -1694,10 +1596,7 @@ void main() { final ErrorEvent errorEvent = ErrorEvent('type'); errorController.add(errorEvent); - expect( - await streamQueue.next, - equals(errorEvent), - ); + expect(await streamQueue.next, equals(errorEvent)); await streamQueue.cancel(); }); diff --git a/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart b/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart index 2647fe7f2b3..075a5de307d 100644 --- a/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart @@ -16,22 +16,29 @@ void main() { const CameraErrorCode code = CameraErrorCode.notFound; const String description = 'The camera is not found.'; - final CameraWebException exception = - CameraWebException(cameraId, code, description); + final CameraWebException exception = CameraWebException( + cameraId, + code, + description, + ); expect(exception.cameraId, equals(cameraId)); expect(exception.code, equals(code)); expect(exception.description, equals(description)); }); - testWidgets('toString includes all properties', - (WidgetTester tester) async { + testWidgets('toString includes all properties', ( + WidgetTester tester, + ) async { const int cameraId = 2; const CameraErrorCode code = CameraErrorCode.notReadable; const String description = 'The camera is not readable.'; - final CameraWebException exception = - CameraWebException(cameraId, code, description); + final CameraWebException exception = CameraWebException( + cameraId, + code, + description, + ); expect( exception.toString(), 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 248b129a5f8..55bab345589 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 @@ -93,17 +93,15 @@ void main() { any, cameraId: anyNamed('cameraId'), ), - ).thenAnswer( - (_) async => videoElement.captureStream(), - ); + ).thenAnswer((_) async => videoElement.captureStream()); - CameraPlatform.instance = CameraPlugin( - cameraService: cameraService, - )..window = window; + CameraPlatform.instance = CameraPlugin(cameraService: cameraService) + ..window = window; }); - testWidgets('CameraPlugin is the live instance', - (WidgetTester tester) async { + testWidgets('CameraPlugin is the live instance', ( + WidgetTester tester, + ) async { expect(CameraPlatform.instance, isA()); }); @@ -111,11 +109,12 @@ 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 { @@ -127,25 +126,26 @@ void main() { ).called(1); }); - testWidgets( - 'releases the camera stream ' + testWidgets('releases the camera stream ' 'used to request video permissions', (WidgetTester tester) async { final MockMediaStreamTrack mockVideoTrack = MockMediaStreamTrack(); final MediaStreamTrack videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; bool videoTrackStopped = false; - mockVideoTrack.stop = () { - videoTrackStopped = true; - }.toJS; + mockVideoTrack.stop = + () { + videoTrackStopped = true; + }.toJS; when( cameraService.getMediaStreamForOptions(const CameraOptions()), ).thenAnswer( (_) => Future.value( createJSInteropWrapper( - FakeMediaStream([videoTrack]), - ) as MediaStream, + FakeMediaStream([videoTrack]), + ) + as MediaStream, ), ); @@ -155,22 +155,24 @@ void main() { expect(videoTrackStopped, isTrue); }); - testWidgets( - 'gets a video stream ' + testWidgets('gets a video stream ' 'for a video input device', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; - - mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS) - .toJS; - }.toJS; + final MediaDeviceInfo videoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '1', + 'Camera 1', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; + + mockMediaDevices.enumerateDevices = + () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; final List _ = await CameraPlatform.instance.availableCameras(); @@ -178,31 +180,31 @@ void main() { verify( cameraService.getMediaStreamForOptions( CameraOptions( - video: VideoConstraints( - deviceId: videoDevice.deviceId, - ), + video: VideoConstraints(deviceId: videoDevice.deviceId), ), ), ).called(1); }); - testWidgets( - 'does not get a video stream ' + testWidgets('does not get a video stream ' 'for the video input device ' 'with an empty device id', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; - - mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS) - .toJS; - }.toJS; + final MediaDeviceInfo videoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '', + 'Camera 1', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; + + mockMediaDevices.enumerateDevices = + () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; final List _ = await CameraPlatform.instance.availableCameras(); @@ -210,36 +212,35 @@ void main() { verifyNever( cameraService.getMediaStreamForOptions( CameraOptions( - video: VideoConstraints( - deviceId: videoDevice.deviceId, - ), + video: VideoConstraints(deviceId: videoDevice.deviceId), ), ), ); }); - testWidgets( - 'gets the facing mode ' + testWidgets('gets the facing mode ' 'from the first available video track ' 'of the video input device', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; - - final MediaStream videoStream = createJSInteropWrapper( - FakeMediaStream( - [ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ], - ), - ) as MediaStream; + final MediaDeviceInfo videoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '1', + 'Camera 1', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; + + final MediaStream videoStream = + createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + ]), + ) + as MediaStream; when( cameraService.getMediaStreamForOptions( @@ -249,11 +250,12 @@ 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(); @@ -265,72 +267,78 @@ void main() { ).called(1); }); - testWidgets( - 'returns appropriate camera descriptions ' + testWidgets('returns appropriate camera descriptions ' 'for multiple video devices ' 'based on video streams', (WidgetTester tester) async { - final MediaDeviceInfo firstVideoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; - - final MediaDeviceInfo secondVideoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '4', - 'Camera 4', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; + final MediaDeviceInfo firstVideoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '1', + 'Camera 1', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; + + final MediaDeviceInfo secondVideoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '4', + 'Camera 4', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; // Create a video stream for the first video device. - final MediaStream firstVideoStream = createJSInteropWrapper( - FakeMediaStream( - [ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ], - ), - ) as MediaStream; + final MediaStream firstVideoStream = + createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + ]), + ) + as MediaStream; // Create a video stream for the second video device. - final MediaStream secondVideoStream = createJSInteropWrapper( - FakeMediaStream( - [ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ], - ), - ) as MediaStream; + final MediaStream secondVideoStream = + createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + ]), + ) + as MediaStream; // 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. @@ -360,8 +368,9 @@ void main() { ), ).thenReturn('user'); - when(cameraService.mapFacingModeToLensDirection('user')) - .thenReturn(CameraLensDirection.front); + when( + cameraService.mapFacingModeToLensDirection('user'), + ).thenReturn(CameraLensDirection.front); // Mock camera service to return an environment facing mode // for the second video stream. @@ -371,8 +380,9 @@ void main() { ), ).thenReturn('environment'); - when(cameraService.mapFacingModeToLensDirection('environment')) - .thenReturn(CameraLensDirection.back); + when( + cameraService.mapFacingModeToLensDirection('environment'), + ).thenReturn(CameraLensDirection.back); final List cameras = await CameraPlatform.instance.availableCameras(); @@ -390,38 +400,40 @@ void main() { name: secondVideoDevice.label, lensDirection: CameraLensDirection.back, sensorOrientation: 0, - ) + ), ]), ); }); - testWidgets( - 'sets camera metadata ' + testWidgets('sets camera metadata ' 'for the camera description', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; - - final MediaStream videoStream = createJSInteropWrapper( - FakeMediaStream( - [ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ], - ), - ) as MediaStream; + final MediaDeviceInfo videoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '1', + 'Camera 1', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; - mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS) - .toJS; - }.toJS; + final MediaStream videoStream = + createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) + as MediaStreamTrack, + ]), + ) + as MediaStream; + + mockMediaDevices.enumerateDevices = + () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; when( cameraService.getMediaStreamForOptions( @@ -437,8 +449,9 @@ void main() { ), ).thenReturn('left'); - when(cameraService.mapFacingModeToLensDirection('left')) - .thenReturn(CameraLensDirection.external); + when( + cameraService.mapFacingModeToLensDirection('left'), + ).thenReturn(CameraLensDirection.external); final CameraDescription camera = (await CameraPlatform.instance.availableCameras()).first; @@ -449,40 +462,43 @@ void main() { camera: CameraMetadata( deviceId: videoDevice.deviceId, facingMode: 'left', - ) + ), }), ); }); - testWidgets( - 'releases the video stream ' + testWidgets('releases the video stream ' 'of a video input device', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) as MediaDeviceInfo; + final MediaDeviceInfo videoDevice = + createJSInteropWrapper( + FakeMediaDeviceInfo( + '1', + 'Camera 1', + MediaDeviceKind.videoInput, + ), + ) + as MediaDeviceInfo; final List tracks = []; 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( @@ -499,17 +515,19 @@ void main() { }); group('throws CameraException', () { - testWidgets('when MediaDevices.enumerateDevices throws DomException', - (WidgetTester tester) async { + testWidgets('when MediaDevices.enumerateDevices throws DomException', ( + WidgetTester tester, + ) 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(), @@ -523,8 +541,7 @@ void main() { ); }); - testWidgets( - 'when CameraService.getMediaStreamForOptions ' + testWidgets('when CameraService.getMediaStreamForOptions ' 'throws CameraWebException', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -532,8 +549,9 @@ void main() { 'description', ); - when(cameraService.getMediaStreamForOptions(any)) - .thenThrow(exception); + when( + cameraService.getMediaStreamForOptions(any), + ).thenThrow(exception); expect( CameraPlatform.instance.availableCameras(), @@ -547,16 +565,16 @@ void main() { ); }); - testWidgets( - 'when CameraService.getMediaStreamForOptions ' + testWidgets('when CameraService.getMediaStreamForOptions ' 'throws PlatformException', (WidgetTester tester) async { final PlatformException exception = PlatformException( code: CameraErrorCode.notSupported.toString(), message: 'message', ); - when(cameraService.getMediaStreamForOptions(any)) - .thenThrow(exception); + when( + cameraService.getMediaStreamForOptions(any), + ).thenThrow(exception); expect( () => CameraPlatform.instance.availableCameras(), @@ -591,7 +609,8 @@ void main() { setUp(() { // Add metadata for the camera description. (CameraPlatform.instance as CameraPlugin) - .camerasMetadata[cameraDescription] = cameraMetadata; + .camerasMetadata[cameraDescription] = + cameraMetadata; when( cameraService.mapFacingModeToCameraType('user'), @@ -615,31 +634,38 @@ void main() { expect(camera, isA()); expect(camera!.textureId, cameraId); expect(camera.options.audio.enabled, isTrue); - expect(camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user))); - expect(camera.options.video.width!.ideal, - ultraHighResolutionSize.width.toInt()); - expect(camera.options.video.height!.ideal, - ultraHighResolutionSize.height.toInt()); + expect( + camera.options.video.facingMode, + equals(FacingModeConstraint(CameraType.user)), + ); + expect( + camera.options.video.width!.ideal, + ultraHighResolutionSize.width.toInt(), + ); + expect( + camera.options.video.height!.ideal, + ultraHighResolutionSize.height.toInt(), + ); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); - testWidgets('with appropriate createCameraWithSettings options', - (WidgetTester tester) async { + testWidgets('with appropriate createCameraWithSettings options', ( + WidgetTester tester, + ) async { when( cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh), ).thenReturn(ultraHighResolutionSize); - final int cameraId = - await CameraPlatform.instance.createCameraWithSettings( - cameraDescription, - const MediaSettings( - resolutionPreset: ResolutionPreset.ultraHigh, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ), - ); + final int cameraId = await CameraPlatform.instance + .createCameraWithSettings( + cameraDescription, + const MediaSettings( + resolutionPreset: ResolutionPreset.ultraHigh, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ), + ); final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; @@ -647,17 +673,22 @@ void main() { expect(camera, isA()); expect(camera!.textureId, cameraId); expect(camera.options.audio.enabled, isTrue); - expect(camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user))); - expect(camera.options.video.width!.ideal, - ultraHighResolutionSize.width.toInt()); - expect(camera.options.video.height!.ideal, - ultraHighResolutionSize.height.toInt()); + expect( + camera.options.video.facingMode, + equals(FacingModeConstraint(CameraType.user)), + ); + expect( + camera.options.video.width!.ideal, + ultraHighResolutionSize.width.toInt(), + ); + expect( + camera.options.video.height!.ideal, + ultraHighResolutionSize.height.toInt(), + ); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); - testWidgets( - 'with a max resolution preset ' + testWidgets('with a max resolution preset ' 'and enabled audio set to false ' 'when no options are specified', (WidgetTester tester) async { when( @@ -675,17 +706,22 @@ void main() { expect(camera, isA()); expect(camera!.textureId, cameraId); expect(camera.options.audio.enabled, isFalse); - expect(camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user))); - expect(camera.options.video.width!.ideal, - maxResolutionSize.width.toInt()); - expect(camera.options.video.height!.ideal, - maxResolutionSize.height.toInt()); + expect( + camera.options.video.facingMode, + equals(FacingModeConstraint(CameraType.user)), + ); + expect( + camera.options.video.width!.ideal, + maxResolutionSize.width.toInt(), + ); + expect( + camera.options.video.height!.ideal, + maxResolutionSize.height.toInt(), + ); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); - testWidgets( - 'with a max resolution preset ' + testWidgets('with a max resolution preset ' 'and enabled audio set to false ' 'when no options are specified ' 'using createCameraWithSettings', (WidgetTester tester) async { @@ -693,31 +729,34 @@ void main() { cameraService.mapResolutionPresetToSize(ResolutionPreset.max), ).thenReturn(maxResolutionSize); - final int cameraId = - await CameraPlatform.instance.createCameraWithSettings( - cameraDescription, - const MediaSettings( - resolutionPreset: ResolutionPreset.max, - ), - ); + final int cameraId = await CameraPlatform.instance + .createCameraWithSettings( + cameraDescription, + const MediaSettings(resolutionPreset: ResolutionPreset.max), + ); final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; expect(camera, isA()); expect(camera!.options.audio.enabled, isFalse); - expect(camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user))); - expect(camera.options.video.width!.ideal, - maxResolutionSize.width.toInt()); - expect(camera.options.video.height!.ideal, - maxResolutionSize.height.toInt()); + expect( + camera.options.video.facingMode, + equals(FacingModeConstraint(CameraType.user)), + ); + expect( + camera.options.video.width!.ideal, + maxResolutionSize.width.toInt(), + ); + expect( + camera.options.video.height!.ideal, + maxResolutionSize.height.toInt(), + ); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); }); - testWidgets( - 'throws CameraException ' + testWidgets('throws CameraException ' 'with missingMetadata error ' 'if there is no metadata ' 'for the given camera description', (WidgetTester tester) async { @@ -740,8 +779,7 @@ void main() { ); }); - testWidgets( - 'throws CameraException ' + testWidgets('throws CameraException ' 'with missingMetadata error ' 'if there is no metadata ' 'for the given camera description ' @@ -816,8 +854,9 @@ void main() { when(camera.onEnded).thenAnswer((_) => endedStreamController.stream); }); - testWidgets('initializes and plays the camera', - (WidgetTester tester) async { + testWidgets('initializes and plays the camera', ( + WidgetTester tester, + ) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -827,22 +866,25 @@ void main() { verify(camera.play()).called(1); }); - testWidgets('starts listening to the camera video error and abort events', - (WidgetTester tester) async { - // Save the camera in the camera plugin. - (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; + testWidgets( + 'starts listening to the camera video error and abort events', + (WidgetTester tester) async { + // Save the camera in the camera plugin. + (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - expect(errorStreamController.hasListener, isFalse); - expect(abortStreamController.hasListener, isFalse); + expect(errorStreamController.hasListener, isFalse); + expect(abortStreamController.hasListener, isFalse); - await CameraPlatform.instance.initializeCamera(cameraId); + await CameraPlatform.instance.initializeCamera(cameraId); - expect(errorStreamController.hasListener, isTrue); - expect(abortStreamController.hasListener, isTrue); - }); + expect(errorStreamController.hasListener, isTrue); + expect(abortStreamController.hasListener, isTrue); + }, + ); - testWidgets('starts listening to the camera ended events', - (WidgetTester tester) async { + testWidgets('starts listening to the camera ended events', ( + WidgetTester tester, + ) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -854,8 +896,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.initializeCamera(cameraId), @@ -869,8 +910,9 @@ void main() { ); }); - testWidgets('when camera throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when camera throws CameraWebException', ( + WidgetTester tester, + ) async { final CameraWebException exception = CameraWebException( cameraId, CameraErrorCode.permissionDenied, @@ -894,8 +936,9 @@ void main() { ); }); - testWidgets('when camera throws DomException', - (WidgetTester tester) async { + testWidgets('when camera throws DomException', ( + WidgetTester tester, + ) async { final DOMException exception = DOMException('NotAllowedError'); when(camera.initialize()).thenAnswer((_) => Future.value()); @@ -925,14 +968,14 @@ void main() { ).thenReturn(OrientationType.portraitPrimary); }); - testWidgets( - 'requests full-screen mode ' + 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, @@ -942,8 +985,7 @@ void main() { expect(fullscreenCalls, 1); }); - testWidgets( - 'locks the capture orientation ' + testWidgets('locks the capture orientation ' 'based on the given device orientation', (WidgetTester tester) async { when( cameraService.mapDeviceOrientationToOrientationType( @@ -952,10 +994,11 @@ 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, @@ -973,10 +1016,10 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with orientationNotSupported error ' - 'when documentElement is not available', - (WidgetTester tester) async { + testWidgets('with orientationNotSupported error ' + 'when documentElement is not available', ( + WidgetTester tester, + ) async { mockDocument.documentElement = null; expect( @@ -996,15 +1039,17 @@ void main() { mockDocument.documentElement = documentElement; }); - testWidgets('when lock throws DomException', - (WidgetTester tester) async { + testWidgets('when lock throws DomException', ( + WidgetTester tester, + ) 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( @@ -1030,31 +1075,29 @@ void main() { ).thenReturn(OrientationType.portraitPrimary); }); - testWidgets('unlocks the capture orientation', - (WidgetTester tester) async { + testWidgets('unlocks the capture orientation', ( + WidgetTester tester, + ) async { int unlocks = 0; - mockScreenOrientation.unlock = () { - unlocks++; - }.toJS; + mockScreenOrientation.unlock = + () { + unlocks++; + }.toJS; - await CameraPlatform.instance.unlockCaptureOrientation( - cameraId, - ); + await CameraPlatform.instance.unlockCaptureOrientation(cameraId); expect(unlocks, 1); }); group('throws PlatformException', () { - testWidgets( - 'with orientationNotSupported error ' - 'when documentElement is not available', - (WidgetTester tester) async { + testWidgets('with orientationNotSupported error ' + 'when documentElement is not available', ( + WidgetTester tester, + ) async { mockDocument.documentElement = null; expect( - () => CameraPlatform.instance.unlockCaptureOrientation( - cameraId, - ), + () => CameraPlatform.instance.unlockCaptureOrientation(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1067,20 +1110,20 @@ void main() { mockDocument.documentElement = documentElement; }); - testWidgets('when unlock throws DomException', - (WidgetTester tester) async { + testWidgets('when unlock throws DomException', ( + WidgetTester tester, + ) 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, - ), + () => CameraPlatform.instance.unlockCaptureOrientation(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1103,8 +1146,9 @@ void main() { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final XFile picture = - await CameraPlatform.instance.takePicture(cameraId); + final XFile picture = await CameraPlatform.instance.takePicture( + cameraId, + ); verify(camera.takePicture()).called(1); @@ -1112,8 +1156,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.takePicture(cameraId), @@ -1127,8 +1170,9 @@ void main() { ); }); - testWidgets('when takePicture throws DomException', - (WidgetTester tester) async { + testWidgets('when takePicture throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -1149,8 +1193,9 @@ void main() { ); }); - testWidgets('when takePicture throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when takePicture throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1185,8 +1230,9 @@ void main() { when(camera.startVideoRecording()).thenAnswer((_) async {}); - when(camera.onVideoRecordingError) - .thenAnswer((_) => const Stream.empty()); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => const Stream.empty()); }); testWidgets('starts a video recording', (WidgetTester tester) async { @@ -1198,28 +1244,26 @@ void main() { verify(camera.startVideoRecording()).called(1); }); - testWidgets('listens to the onVideoRecordingError stream', - (WidgetTester tester) async { + testWidgets('listens to the onVideoRecordingError stream', ( + WidgetTester tester, + ) async { final StreamController videoRecordingErrorController = StreamController(); - when(camera.onVideoRecordingError) - .thenAnswer((_) => videoRecordingErrorController.stream); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => videoRecordingErrorController.stream); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; await CameraPlatform.instance.startVideoRecording(cameraId); - expect( - videoRecordingErrorController.hasListener, - isTrue, - ); + expect(videoRecordingErrorController.hasListener, isTrue); }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.startVideoRecording(cameraId), @@ -1233,8 +1277,9 @@ void main() { ); }); - testWidgets('when startVideoRecording throws DomException', - (WidgetTester tester) async { + testWidgets('when startVideoRecording throws DomException', ( + WidgetTester tester, + ) async { final DOMException exception = DOMException('InvalidStateError'); when(camera.startVideoRecording()).thenThrow(exception); @@ -1254,8 +1299,9 @@ void main() { ); }); - testWidgets('when startVideoRecording throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when startVideoRecording throws CameraWebException', ( + WidgetTester tester, + ) async { final CameraWebException exception = CameraWebException( cameraId, CameraErrorCode.notStarted, @@ -1289,8 +1335,9 @@ void main() { when(camera.startVideoRecording()).thenAnswer((_) async {}); - when(camera.onVideoRecordingError) - .thenAnswer((_) => const Stream.empty()); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => const Stream.empty()); }); testWidgets('fails if trying to stream', (WidgetTester tester) async { @@ -1298,12 +1345,13 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () => CameraPlatform.instance.startVideoCapturing(VideoCaptureOptions( + () => CameraPlatform.instance.startVideoCapturing( + VideoCaptureOptions( cameraId, - streamCallback: (CameraImageData imageData) {})), - throwsA( - isA(), + streamCallback: (CameraImageData imageData) {}, + ), ), + throwsA(isA()), ); }); }); @@ -1313,22 +1361,25 @@ void main() { final MockCamera camera = MockCamera(); final XFile capturedVideo = XFile('/bogus/test'); - when(camera.stopVideoRecording()) - .thenAnswer((_) async => capturedVideo); + when( + camera.stopVideoRecording(), + ).thenAnswer((_) async => capturedVideo); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final XFile video = - await CameraPlatform.instance.stopVideoRecording(cameraId); + final XFile video = await CameraPlatform.instance.stopVideoRecording( + cameraId, + ); verify(camera.stopVideoRecording()).called(1); expect(video, capturedVideo); }); - testWidgets('stops listening to the onVideoRecordingError stream', - (WidgetTester tester) async { + testWidgets('stops listening to the onVideoRecordingError stream', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final StreamController videoRecordingErrorController = StreamController(); @@ -1336,28 +1387,27 @@ void main() { when(camera.startVideoRecording()).thenAnswer((_) async {}); - when(camera.stopVideoRecording()) - .thenAnswer((_) async => capturedVideo); + when( + camera.stopVideoRecording(), + ).thenAnswer((_) async => capturedVideo); - when(camera.onVideoRecordingError) - .thenAnswer((_) => videoRecordingErrorController.stream); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => videoRecordingErrorController.stream); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; await CameraPlatform.instance.startVideoRecording(cameraId); - final XFile _ = - await CameraPlatform.instance.stopVideoRecording(cameraId); - - expect( - videoRecordingErrorController.hasListener, - isFalse, + final XFile _ = await CameraPlatform.instance.stopVideoRecording( + cameraId, ); + + expect(videoRecordingErrorController.hasListener, isFalse); }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.stopVideoRecording(cameraId), @@ -1371,8 +1421,9 @@ void main() { ); }); - testWidgets('when stopVideoRecording throws DomException', - (WidgetTester tester) async { + testWidgets('when stopVideoRecording throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('InvalidStateError'); @@ -1393,8 +1444,9 @@ void main() { ); }); - testWidgets('when stopVideoRecording throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when stopVideoRecording throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1436,8 +1488,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.pauseVideoRecording(cameraId), @@ -1451,8 +1502,9 @@ void main() { ); }); - testWidgets('when pauseVideoRecording throws DomException', - (WidgetTester tester) async { + testWidgets('when pauseVideoRecording throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('InvalidStateError'); @@ -1473,8 +1525,9 @@ void main() { ); }); - testWidgets('when pauseVideoRecording throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when pauseVideoRecording throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1516,8 +1569,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.resumeVideoRecording(cameraId), @@ -1531,8 +1583,9 @@ void main() { ); }); - testWidgets('when resumeVideoRecording throws DomException', - (WidgetTester tester) async { + testWidgets('when resumeVideoRecording throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('InvalidStateError'); @@ -1553,8 +1606,9 @@ void main() { ); }); - testWidgets('when resumeVideoRecording throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when resumeVideoRecording throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1582,25 +1636,22 @@ void main() { }); group('setFlashMode', () { - testWidgets('calls setFlashMode on the camera', - (WidgetTester tester) async { + testWidgets('calls setFlashMode on the camera', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); const FlashMode flashMode = FlashMode.always; // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - await CameraPlatform.instance.setFlashMode( - cameraId, - flashMode, - ); + await CameraPlatform.instance.setFlashMode(cameraId, flashMode); verify(camera.setFlashMode(flashMode)).called(1); }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.setFlashMode( @@ -1617,8 +1668,9 @@ void main() { ); }); - testWidgets('when setFlashMode throws DomException', - (WidgetTester tester) async { + testWidgets('when setFlashMode throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -1642,8 +1694,9 @@ void main() { ); }); - testWidgets('when setFlashMode throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when setFlashMode throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1657,10 +1710,8 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () => CameraPlatform.instance.setFlashMode( - cameraId, - FlashMode.torch, - ), + () => + CameraPlatform.instance.setFlashMode(cameraId, FlashMode.torch), throwsA( isA().having( (PlatformException e) => e.code, @@ -1673,8 +1724,9 @@ void main() { }); }); - testWidgets('setExposureMode throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('setExposureMode throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( () => CameraPlatform.instance.setExposureMode( cameraId, @@ -1684,8 +1736,9 @@ void main() { ); }); - testWidgets('setExposurePoint throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('setExposurePoint throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( () => CameraPlatform.instance.setExposurePoint( cameraId, @@ -1695,54 +1748,54 @@ void main() { ); }); - testWidgets('getMinExposureOffset throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('getMinExposureOffset throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( () => CameraPlatform.instance.getMinExposureOffset(cameraId), throwsUnimplementedError, ); }); - testWidgets('getMaxExposureOffset throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('getMaxExposureOffset throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( () => CameraPlatform.instance.getMaxExposureOffset(cameraId), throwsUnimplementedError, ); }); - testWidgets('getExposureOffsetStepSize throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('getExposureOffsetStepSize throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( () => CameraPlatform.instance.getExposureOffsetStepSize(cameraId), throwsUnimplementedError, ); }); - testWidgets('setExposureOffset throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('setExposureOffset throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( - () => CameraPlatform.instance.setExposureOffset( - cameraId, - 0, - ), + () => CameraPlatform.instance.setExposureOffset(cameraId, 0), throwsUnimplementedError, ); }); - testWidgets('setFocusMode throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('setFocusMode throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( - () => CameraPlatform.instance.setFocusMode( - cameraId, - FocusMode.auto, - ), + () => CameraPlatform.instance.setFocusMode(cameraId, FocusMode.auto), throwsUnimplementedError, ); }); - testWidgets('setFocusPoint throws UnimplementedError', - (WidgetTester tester) async { + testWidgets('setFocusPoint throws UnimplementedError', ( + WidgetTester tester, + ) async { expect( () => CameraPlatform.instance.setFocusPoint( cameraId, @@ -1753,8 +1806,9 @@ void main() { }); group('getMaxZoomLevel', () { - testWidgets('calls getMaxZoomLevel on the camera', - (WidgetTester tester) async { + testWidgets('calls getMaxZoomLevel on the camera', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); const double maximumZoomLevel = 100.0; @@ -1764,9 +1818,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - await CameraPlatform.instance.getMaxZoomLevel( - cameraId, - ), + await CameraPlatform.instance.getMaxZoomLevel(cameraId), equals(maximumZoomLevel), ); @@ -1774,13 +1826,10 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( - () async => CameraPlatform.instance.getMaxZoomLevel( - cameraId, - ), + () async => CameraPlatform.instance.getMaxZoomLevel(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1791,8 +1840,9 @@ void main() { ); }); - testWidgets('when getMaxZoomLevel throws DomException', - (WidgetTester tester) async { + testWidgets('when getMaxZoomLevel throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -1802,9 +1852,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.getMaxZoomLevel( - cameraId, - ), + () async => CameraPlatform.instance.getMaxZoomLevel(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1815,8 +1863,9 @@ void main() { ); }); - testWidgets('when getMaxZoomLevel throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when getMaxZoomLevel throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1830,9 +1879,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.getMaxZoomLevel( - cameraId, - ), + () async => CameraPlatform.instance.getMaxZoomLevel(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1846,8 +1893,9 @@ void main() { }); group('getMinZoomLevel', () { - testWidgets('calls getMinZoomLevel on the camera', - (WidgetTester tester) async { + testWidgets('calls getMinZoomLevel on the camera', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); const double minimumZoomLevel = 100.0; @@ -1857,9 +1905,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - await CameraPlatform.instance.getMinZoomLevel( - cameraId, - ), + await CameraPlatform.instance.getMinZoomLevel(cameraId), equals(minimumZoomLevel), ); @@ -1867,13 +1913,10 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( - () async => CameraPlatform.instance.getMinZoomLevel( - cameraId, - ), + () async => CameraPlatform.instance.getMinZoomLevel(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1884,8 +1927,9 @@ void main() { ); }); - testWidgets('when getMinZoomLevel throws DomException', - (WidgetTester tester) async { + testWidgets('when getMinZoomLevel throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -1895,9 +1939,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.getMinZoomLevel( - cameraId, - ), + () async => CameraPlatform.instance.getMinZoomLevel(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1908,8 +1950,9 @@ void main() { ); }); - testWidgets('when getMinZoomLevel throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when getMinZoomLevel throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -1923,9 +1966,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.getMinZoomLevel( - cameraId, - ), + () async => CameraPlatform.instance.getMinZoomLevel(cameraId), throwsA( isA().having( (PlatformException e) => e.code, @@ -1939,8 +1980,9 @@ void main() { }); group('setZoomLevel', () { - testWidgets('calls setZoomLevel on the camera', - (WidgetTester tester) async { + testWidgets('calls setZoomLevel on the camera', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); // Save the camera in the camera plugin. @@ -1954,14 +1996,10 @@ void main() { }); group('throws CameraException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( - () async => CameraPlatform.instance.setZoomLevel( - cameraId, - 100.0, - ), + () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), throwsA( isA().having( (CameraException e) => e.code, @@ -1972,8 +2010,9 @@ void main() { ); }); - testWidgets('when setZoomLevel throws DomException', - (WidgetTester tester) async { + testWidgets('when setZoomLevel throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -1983,10 +2022,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.setZoomLevel( - cameraId, - 100.0, - ), + () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), throwsA( isA().having( (CameraException e) => e.code, @@ -1997,8 +2033,9 @@ void main() { ); }); - testWidgets('when setZoomLevel throws PlatformException', - (WidgetTester tester) async { + testWidgets('when setZoomLevel throws PlatformException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final PlatformException exception = PlatformException( code: CameraErrorCode.notSupported.toString(), @@ -2011,10 +2048,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.setZoomLevel( - cameraId, - 100.0, - ), + () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), throwsA( isA().having( (CameraException e) => e.code, @@ -2025,8 +2059,9 @@ void main() { ); }); - testWidgets('when setZoomLevel throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when setZoomLevel throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -2040,10 +2075,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () async => CameraPlatform.instance.setZoomLevel( - cameraId, - 100.0, - ), + () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), throwsA( isA().having( (CameraException e) => e.code, @@ -2069,8 +2101,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () async => CameraPlatform.instance.pausePreview(cameraId), @@ -2084,8 +2115,9 @@ void main() { ); }); - testWidgets('when pause throws DomException', - (WidgetTester tester) async { + testWidgets('when pause throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -2123,8 +2155,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () async => CameraPlatform.instance.resumePreview(cameraId), @@ -2138,8 +2169,9 @@ void main() { ); }); - testWidgets('when play throws DomException', - (WidgetTester tester) async { + testWidgets('when play throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('NotSupportedError'); @@ -2160,8 +2192,9 @@ void main() { ); }); - testWidgets('when play throws CameraWebException', - (WidgetTester tester) async { + testWidgets('when play throws CameraWebException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final CameraWebException exception = CameraWebException( cameraId, @@ -2188,8 +2221,7 @@ void main() { }); }); - testWidgets( - 'buildPreview returns an HtmlElementView ' + testWidgets('buildPreview returns an HtmlElementView ' 'with an appropriate view type', (WidgetTester tester) async { final Camera camera = Camera( textureId: cameraId, @@ -2255,8 +2287,9 @@ void main() { when(camera.onEnded).thenAnswer((_) => endedStreamController.stream); - when(camera.onVideoRecordingError) - .thenAnswer((_) => videoRecordingErrorController.stream); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => videoRecordingErrorController.stream); when(camera.startVideoRecording()).thenAnswer((_) async {}); }); @@ -2287,14 +2320,13 @@ void main() { // The first camera should be removed from the camera plugin. expect( (CameraPlatform.instance as CameraPlugin).cameras, - equals({ - secondCameraId: secondCamera, - }), + equals({secondCameraId: secondCamera}), ); }); - testWidgets('cancels the camera video error and abort subscriptions', - (WidgetTester tester) async { + testWidgets('cancels the camera video error and abort subscriptions', ( + WidgetTester tester, + ) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -2305,8 +2337,9 @@ void main() { expect(abortStreamController.hasListener, isFalse); }); - testWidgets('cancels the camera ended subscriptions', - (WidgetTester tester) async { + testWidgets('cancels the camera ended subscriptions', ( + WidgetTester tester, + ) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -2316,8 +2349,9 @@ void main() { expect(endedStreamController.hasListener, isFalse); }); - testWidgets('cancels the camera video recording error subscriptions', - (WidgetTester tester) async { + testWidgets('cancels the camera video recording error subscriptions', ( + WidgetTester tester, + ) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -2329,8 +2363,7 @@ void main() { }); group('throws PlatformException', () { - testWidgets( - 'with notFound error ' + testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( () => CameraPlatform.instance.dispose(cameraId), @@ -2344,8 +2377,9 @@ void main() { ); }); - testWidgets('when dispose throws DomException', - (WidgetTester tester) async { + testWidgets('when dispose throws DomException', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final DOMException exception = DOMException('InvalidAccessError'); @@ -2384,8 +2418,7 @@ void main() { ); }); - testWidgets( - 'throws PlatformException ' + testWidgets('throws PlatformException ' 'with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( @@ -2446,14 +2479,14 @@ void main() { when(camera.onEnded).thenAnswer((_) => endedStreamController.stream); - when(camera.onVideoRecordingError) - .thenAnswer((_) => videoRecordingErrorController.stream); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => videoRecordingErrorController.stream); when(camera.startVideoRecording()).thenAnswer((_) async {}); }); - testWidgets( - 'onCameraInitialized emits a CameraInitializedEvent ' + testWidgets('onCameraInitialized emits a CameraInitializedEvent ' 'on initializeCamera', (WidgetTester tester) async { // Mock the camera to use a blank video stream of size 1280x720. const Size videoSize = Size(1280, 720); @@ -2461,10 +2494,7 @@ void main() { videoElement = getVideoElementWithBlankStream(videoSize); when( - cameraService.getMediaStreamForOptions( - any, - cameraId: cameraId, - ), + cameraService.getMediaStreamForOptions(any, cameraId: cameraId), ).thenAnswer((_) async => videoElement.captureStream()); final Camera camera = Camera( @@ -2475,8 +2505,9 @@ void main() { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final Stream eventStream = - CameraPlatform.instance.onCameraInitialized(cameraId); + final Stream eventStream = CameraPlatform + .instance + .onCameraInitialized(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -2501,21 +2532,22 @@ void main() { await streamQueue.cancel(); }); - testWidgets('onCameraResolutionChanged emits an empty stream', - (WidgetTester tester) async { - final Stream stream = - CameraPlatform.instance.onCameraResolutionChanged(cameraId); + testWidgets('onCameraResolutionChanged emits an empty stream', ( + WidgetTester tester, + ) async { + final Stream stream = CameraPlatform + .instance + .onCameraResolutionChanged(cameraId); expect(await stream.isEmpty, isTrue); }); - testWidgets( - 'onCameraClosing emits a CameraClosingEvent ' + testWidgets('onCameraClosing emits a CameraClosingEvent ' 'on the camera ended event', (WidgetTester tester) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final Stream eventStream = - CameraPlatform.instance.onCameraClosing(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraClosing(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -2528,9 +2560,7 @@ void main() { expect( await streamQueue.next, - equals( - const CameraClosingEvent(cameraId), - ), + equals(const CameraClosingEvent(cameraId)), ); await streamQueue.cancel(); @@ -2542,27 +2572,29 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on the camera video error event ' 'with a message', (WidgetTester tester) async { - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); - final MediaError error = createJSInteropWrapper( - FakeMediaError( - MediaError.MEDIA_ERR_NETWORK, - 'A network error occurred.', - ), - ) as MediaError; + final MediaError error = + createJSInteropWrapper( + FakeMediaError( + MediaError.MEDIA_ERR_NETWORK, + 'A network error occurred.', + ), + ) + as MediaError; - final CameraErrorCode errorCode = - CameraErrorCode.fromMediaError(error); + final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( + error, + ); mockVideoElement.error = error; errorStreamController.add(Event('error')); @@ -2580,23 +2612,25 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on the camera video error event ' 'with no message', (WidgetTester tester) async { - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); - final MediaError error = createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_NETWORK), - ) as MediaError; - final CameraErrorCode errorCode = - CameraErrorCode.fromMediaError(error); + final MediaError error = + createJSInteropWrapper( + FakeMediaError(MediaError.MEDIA_ERR_NETWORK), + ) + as MediaError; + final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( + error, + ); mockVideoElement.error = error; errorStreamController.add(Event('error')); @@ -2614,11 +2648,10 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on the camera video abort event', (WidgetTester tester) async { - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -2640,8 +2673,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on takePicture error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2651,17 +2683,15 @@ void main() { when(camera.takePicture()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.takePicture(cameraId), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -2677,8 +2707,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on setFlashMode error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2688,8 +2717,8 @@ void main() { when(camera.setFlashMode(any)).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -2699,9 +2728,7 @@ void main() { cameraId, FlashMode.always, ), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -2717,8 +2744,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on getMaxZoomLevel error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2728,19 +2754,15 @@ void main() { when(camera.getMaxZoomLevel()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( - () async => CameraPlatform.instance.getMaxZoomLevel( - cameraId, - ), - throwsA( - isA(), - ), + () async => CameraPlatform.instance.getMaxZoomLevel(cameraId), + throwsA(isA()), ); expect( @@ -2756,8 +2778,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on getMinZoomLevel error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2767,19 +2788,15 @@ void main() { when(camera.getMinZoomLevel()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( - () async => CameraPlatform.instance.getMinZoomLevel( - cameraId, - ), - throwsA( - isA(), - ), + () async => CameraPlatform.instance.getMinZoomLevel(cameraId), + throwsA(isA()), ); expect( @@ -2795,8 +2812,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on setZoomLevel error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2806,20 +2822,15 @@ void main() { when(camera.setZoomLevel(any)).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( - () async => CameraPlatform.instance.setZoomLevel( - cameraId, - 100.0, - ), - throwsA( - isA(), - ), + () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), + throwsA(isA()), ); expect( @@ -2835,8 +2846,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on resumePreview error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2846,17 +2856,15 @@ void main() { when(camera.play()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.resumePreview(cameraId), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -2872,8 +2880,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on startVideoRecording error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2881,22 +2888,21 @@ void main() { 'description', ); - when(camera.onVideoRecordingError) - .thenAnswer((_) => const Stream.empty()); + when( + camera.onVideoRecordingError, + ).thenAnswer((_) => const Stream.empty()); when(camera.startVideoRecording()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.startVideoRecording(cameraId), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -2912,12 +2918,12 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' - 'on the camera video recording error event', - (WidgetTester tester) async { - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + testWidgets('emits a CameraErrorEvent ' + 'on the camera video recording error event', ( + WidgetTester tester, + ) async { + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -2944,8 +2950,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on stopVideoRecording error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2955,17 +2960,15 @@ void main() { when(camera.stopVideoRecording()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.stopVideoRecording(cameraId), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -2981,8 +2984,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on pauseVideoRecording error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -2992,17 +2994,15 @@ void main() { when(camera.pauseVideoRecording()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.pauseVideoRecording(cameraId), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -3018,8 +3018,7 @@ void main() { await streamQueue.cancel(); }); - testWidgets( - 'emits a CameraErrorEvent ' + testWidgets('emits a CameraErrorEvent ' 'on resumeVideoRecording error', (WidgetTester tester) async { final CameraWebException exception = CameraWebException( cameraId, @@ -3029,17 +3028,15 @@ void main() { when(camera.resumeVideoRecording()).thenThrow(exception); - final Stream eventStream = - CameraPlatform.instance.onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance + .onCameraError(cameraId); final StreamQueue streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.resumeVideoRecording(cameraId), - throwsA( - isA(), - ), + throwsA(isA()), ); expect( @@ -3056,13 +3053,15 @@ void main() { }); }); - testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', - (WidgetTester tester) async { + testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', ( + WidgetTester tester, + ) async { final MockCamera camera = MockCamera(); final XFile capturedVideo = XFile('/bogus/test'); final Stream stream = Stream.value( - VideoRecordedEvent(cameraId, capturedVideo, Duration.zero)); + VideoRecordedEvent(cameraId, capturedVideo, Duration.zero), + ); when(camera.onVideoRecordedEvent).thenAnswer((_) => stream); // Save the camera in the camera plugin. @@ -3070,13 +3069,12 @@ void main() { final StreamQueue streamQueue = StreamQueue( - CameraPlatform.instance.onVideoRecordedEvent(cameraId)); + CameraPlatform.instance.onVideoRecordedEvent(cameraId), + ); expect( await streamQueue.next, - equals( - VideoRecordedEvent(cameraId, capturedVideo, Duration.zero), - ), + equals(VideoRecordedEvent(cameraId, capturedVideo, Duration.zero)), ); }); @@ -3089,12 +3087,14 @@ void main() { MockEventStreamProvider(); (CameraPlatform.instance as CameraPlugin) .orientationOnChangeProvider = provider; - when(provider.forTarget(any)) - .thenAnswer((_) => eventStreamController.stream); + when( + provider.forTarget(any), + ).thenAnswer((_) => eventStreamController.stream); }); - testWidgets('emits the initial DeviceOrientationChangedEvent', - (WidgetTester tester) async { + testWidgets('emits the initial DeviceOrientationChangedEvent', ( + WidgetTester tester, + ) async { when( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitPrimary, @@ -3113,19 +3113,17 @@ void main() { expect( await streamQueue.next, equals( - const DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ), + const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp), ), ); await streamQueue.cancel(); }); - testWidgets( - 'emits a DeviceOrientationChangedEvent ' - 'when the screen orientation is changed', - (WidgetTester tester) async { + testWidgets('emits a DeviceOrientationChangedEvent ' + 'when the screen orientation is changed', ( + WidgetTester tester, + ) async { when( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.landscapePrimary, 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 eb94d399eb8..69a443dbae7 100644 --- a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart +++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart @@ -81,9 +81,10 @@ 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; @@ -98,9 +99,10 @@ 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() @@ -126,9 +128,10 @@ 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; @@ -191,10 +194,7 @@ class FakeMediaDeviceInfo { /// A fake [MediaError] that returns the provided error [_code] and [_message]. @JSExport() class FakeMediaError { - FakeMediaError( - this.code, [ - this.message = '', - ]); + FakeMediaError(this.code, [this.message = '']); final int code; final String message; @@ -208,8 +208,12 @@ class FakeElementStream extends Fake final Stream _stream; @override - StreamSubscription listen(void Function(T event)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { + StreamSubscription listen( + void Function(T event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { return _stream.listen( onData, onError: onError, @@ -230,10 +234,7 @@ class FakeBlobEvent { /// A fake [DomException] that returns the provided error [_name] and [_message]. @JSExport() class FakeErrorEvent { - FakeErrorEvent( - this.type, [ - this.message = '', - ]); + FakeErrorEvent(this.type, [this.message = '']); final String type; final String message; @@ -247,13 +248,14 @@ 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.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.HTMLVideoElement videoElement = + web.HTMLVideoElement()..srcObject = canvasElement.captureStream(); return videoElement; } @@ -261,32 +263,28 @@ web.HTMLVideoElement getVideoElementWithBlankStream(Size videoSize) { class MockEventStreamProvider extends Mock implements web.EventStreamProvider { @override - Stream forTarget( - web.EventTarget? e, { - bool? useCapture = false, - }) { + Stream forTarget(web.EventTarget? e, {bool? useCapture = false}) { return super.noSuchMethod( - Invocation.method( - #forTarget, - [e], - {#useCapture: useCapture}, - ), - returnValue: Stream.empty(), - ) as Stream; + Invocation.method( + #forTarget, + [e], + {#useCapture: useCapture}, + ), + returnValue: Stream.empty(), + ) + as Stream; } @override - ElementStream forElement( - web.Element? e, { - bool? useCapture = false, - }) { + ElementStream forElement(web.Element? e, {bool? useCapture = false}) { return super.noSuchMethod( - Invocation.method( - #forElement, - [e], - {#useCapture: useCapture}, - ), - returnValue: FakeElementStream(Stream.empty()), - ) as ElementStream; + Invocation.method( + #forElement, + [e], + {#useCapture: useCapture}, + ), + returnValue: FakeElementStream(Stream.empty()), + ) + as ElementStream; } } diff --git a/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart b/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart index a544cbbed68..321507d7717 100644 --- a/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart +++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart @@ -36,52 +36,52 @@ import 'mocks.dart' as _i9; class _FakeJsUtil_0 extends _i1.SmartFake implements _i2.JsUtil { _FakeJsUtil_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeZoomLevelCapability_1 extends _i1.SmartFake implements _i3.ZoomLevelCapability { _FakeZoomLevelCapability_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeSize_2 extends _i1.SmartFake implements _i4.Size { _FakeSize_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeCameraOptions_3 extends _i1.SmartFake implements _i3.CameraOptions { _FakeCameraOptions_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeStreamController_4 extends _i1.SmartFake implements _i5.StreamController { _FakeStreamController_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeEventStreamProvider_5 extends _i1.SmartFake implements _i6.EventStreamProvider { _FakeEventStreamProvider_5(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeXFile_6 extends _i1.SmartFake implements _i7.XFile { _FakeXFile_6(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeAudioConstraints_7 extends _i1.SmartFake implements _i3.AudioConstraints { _FakeAudioConstraints_7(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } class _FakeVideoConstraints_8 extends _i1.SmartFake implements _i3.VideoConstraints { _FakeVideoConstraints_8(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } /// A class which mocks [CameraService]. @@ -89,33 +89,37 @@ class _FakeVideoConstraints_8 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockCameraService extends _i1.Mock implements _i8.CameraService { @override - _i6.Window get window => (super.noSuchMethod( - Invocation.getter(#window), - returnValue: _i9.windowShim(), - returnValueForMissingStub: _i9.windowShim(), - ) as _i6.Window); + _i6.Window get window => + (super.noSuchMethod( + Invocation.getter(#window), + returnValue: _i9.windowShim(), + returnValueForMissingStub: _i9.windowShim(), + ) + as _i6.Window); @override set window(_i6.Window? _window) => super.noSuchMethod( - Invocation.setter(#window, _window), - returnValueForMissingStub: null, - ); + Invocation.setter(#window, _window), + returnValueForMissingStub: null, + ); @override - _i2.JsUtil get jsUtil => (super.noSuchMethod( - Invocation.getter(#jsUtil), - returnValue: _FakeJsUtil_0(this, Invocation.getter(#jsUtil)), - returnValueForMissingStub: _FakeJsUtil_0( - this, - Invocation.getter(#jsUtil), - ), - ) as _i2.JsUtil); + _i2.JsUtil get jsUtil => + (super.noSuchMethod( + Invocation.getter(#jsUtil), + returnValue: _FakeJsUtil_0(this, Invocation.getter(#jsUtil)), + returnValueForMissingStub: _FakeJsUtil_0( + this, + Invocation.getter(#jsUtil), + ), + ) + as _i2.JsUtil); @override set jsUtil(_i2.JsUtil? _jsUtil) => super.noSuchMethod( - Invocation.setter(#jsUtil, _jsUtil), - returnValueForMissingStub: null, - ); + Invocation.setter(#jsUtil, _jsUtil), + returnValueForMissingStub: null, + ); @override _i5.Future<_i6.MediaStream> getMediaStreamForOptions( @@ -123,131 +127,141 @@ class MockCameraService extends _i1.Mock implements _i8.CameraService { int? cameraId = 0, }) => (super.noSuchMethod( - Invocation.method( - #getMediaStreamForOptions, - [options], - {#cameraId: cameraId}, - ), - returnValue: _i9.getMediaStreamForOptionsShim( - options, - cameraId: cameraId, - ), - returnValueForMissingStub: _i9.getMediaStreamForOptionsShim( - options, - cameraId: cameraId, - ), - ) as _i5.Future<_i6.MediaStream>); + Invocation.method( + #getMediaStreamForOptions, + [options], + {#cameraId: cameraId}, + ), + returnValue: _i9.getMediaStreamForOptionsShim( + options, + cameraId: cameraId, + ), + returnValueForMissingStub: _i9.getMediaStreamForOptionsShim( + options, + cameraId: cameraId, + ), + ) + as _i5.Future<_i6.MediaStream>); @override _i3.ZoomLevelCapability getZoomLevelCapabilityForCamera( _i10.Camera? camera, ) => (super.noSuchMethod( - Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), - returnValue: _FakeZoomLevelCapability_1( - this, - Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), - ), - returnValueForMissingStub: _FakeZoomLevelCapability_1( - this, - Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), - ), - ) as _i3.ZoomLevelCapability); + Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), + returnValue: _FakeZoomLevelCapability_1( + this, + Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), + ), + returnValueForMissingStub: _FakeZoomLevelCapability_1( + this, + Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), + ), + ) + as _i3.ZoomLevelCapability); @override String? getFacingModeForVideoTrack(_i6.MediaStreamTrack? videoTrack) => (super.noSuchMethod( - Invocation.method(#getFacingModeForVideoTrack, [videoTrack]), - returnValueForMissingStub: null, - ) as String?); + Invocation.method(#getFacingModeForVideoTrack, [videoTrack]), + returnValueForMissingStub: null, + ) + as String?); @override _i7.CameraLensDirection mapFacingModeToLensDirection(String? facingMode) => (super.noSuchMethod( - Invocation.method(#mapFacingModeToLensDirection, [facingMode]), - returnValue: _i7.CameraLensDirection.front, - returnValueForMissingStub: _i7.CameraLensDirection.front, - ) as _i7.CameraLensDirection); + Invocation.method(#mapFacingModeToLensDirection, [facingMode]), + returnValue: _i7.CameraLensDirection.front, + returnValueForMissingStub: _i7.CameraLensDirection.front, + ) + as _i7.CameraLensDirection); @override _i3.CameraType mapFacingModeToCameraType(String? facingMode) => (super.noSuchMethod( - Invocation.method(#mapFacingModeToCameraType, [facingMode]), - returnValue: _i3.CameraType.environment, - returnValueForMissingStub: _i3.CameraType.environment, - ) as _i3.CameraType); + Invocation.method(#mapFacingModeToCameraType, [facingMode]), + returnValue: _i3.CameraType.environment, + returnValueForMissingStub: _i3.CameraType.environment, + ) + as _i3.CameraType); @override _i4.Size mapResolutionPresetToSize(_i7.ResolutionPreset? resolutionPreset) => (super.noSuchMethod( - Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), - returnValue: _FakeSize_2( - this, - Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), - ), - returnValueForMissingStub: _FakeSize_2( - this, - Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), - ), - ) as _i4.Size); + Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), + returnValue: _FakeSize_2( + this, + Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), + ), + returnValueForMissingStub: _FakeSize_2( + this, + Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), + ), + ) + as _i4.Size); @override int mapResolutionPresetToVideoBitrate( _i7.ResolutionPreset? resolutionPreset, ) => (super.noSuchMethod( - Invocation.method(#mapResolutionPresetToVideoBitrate, [ - resolutionPreset, - ]), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + Invocation.method(#mapResolutionPresetToVideoBitrate, [ + resolutionPreset, + ]), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override int mapResolutionPresetToAudioBitrate( _i7.ResolutionPreset? resolutionPreset, ) => (super.noSuchMethod( - Invocation.method(#mapResolutionPresetToAudioBitrate, [ - resolutionPreset, - ]), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + Invocation.method(#mapResolutionPresetToAudioBitrate, [ + resolutionPreset, + ]), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override String mapDeviceOrientationToOrientationType( _i11.DeviceOrientation? deviceOrientation, ) => (super.noSuchMethod( - Invocation.method(#mapDeviceOrientationToOrientationType, [ - deviceOrientation, - ]), - returnValue: _i12.dummyValue( - this, - Invocation.method(#mapDeviceOrientationToOrientationType, [ - deviceOrientation, - ]), - ), - returnValueForMissingStub: _i12.dummyValue( - this, - Invocation.method(#mapDeviceOrientationToOrientationType, [ - deviceOrientation, - ]), - ), - ) as String); + Invocation.method(#mapDeviceOrientationToOrientationType, [ + deviceOrientation, + ]), + returnValue: _i12.dummyValue( + this, + Invocation.method(#mapDeviceOrientationToOrientationType, [ + deviceOrientation, + ]), + ), + returnValueForMissingStub: _i12.dummyValue( + this, + Invocation.method(#mapDeviceOrientationToOrientationType, [ + deviceOrientation, + ]), + ), + ) + as String); @override _i11.DeviceOrientation mapOrientationTypeToDeviceOrientation( String? orientationType, ) => (super.noSuchMethod( - Invocation.method(#mapOrientationTypeToDeviceOrientation, [ - orientationType, - ]), - returnValue: _i11.DeviceOrientation.portraitUp, - returnValueForMissingStub: _i11.DeviceOrientation.portraitUp, - ) as _i11.DeviceOrientation); + Invocation.method(#mapOrientationTypeToDeviceOrientation, [ + orientationType, + ]), + returnValue: _i11.DeviceOrientation.portraitUp, + returnValueForMissingStub: _i11.DeviceOrientation.portraitUp, + ) + as _i11.DeviceOrientation); } /// A class which mocks [JsUtil]. @@ -255,18 +269,21 @@ class MockCameraService extends _i1.Mock implements _i8.CameraService { /// See the documentation for Mockito's code generation for more information. class MockJsUtil extends _i1.Mock implements _i2.JsUtil { @override - bool hasProperty(_i13.JSObject? o, _i13.JSAny? name) => (super.noSuchMethod( - Invocation.method(#hasProperty, [o, name]), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool hasProperty(_i13.JSObject? o, _i13.JSAny? name) => + (super.noSuchMethod( + Invocation.method(#hasProperty, [o, name]), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override _i13.JSAny? getProperty(_i13.JSObject? o, _i13.JSAny? name) => (super.noSuchMethod( - Invocation.method(#getProperty, [o, name]), - returnValueForMissingStub: null, - ) as _i13.JSAny?); + Invocation.method(#getProperty, [o, name]), + returnValueForMissingStub: null, + ) + as _i13.JSAny?); } /// A class which mocks [Camera]. @@ -274,151 +291,166 @@ class MockJsUtil extends _i1.Mock implements _i2.JsUtil { /// See the documentation for Mockito's code generation for more information. class MockCamera extends _i1.Mock implements _i10.Camera { @override - int get textureId => (super.noSuchMethod( - Invocation.getter(#textureId), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + int get textureId => + (super.noSuchMethod( + Invocation.getter(#textureId), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override - _i3.CameraOptions get options => (super.noSuchMethod( - Invocation.getter(#options), - returnValue: _FakeCameraOptions_3( - this, - Invocation.getter(#options), - ), - returnValueForMissingStub: _FakeCameraOptions_3( - this, - Invocation.getter(#options), - ), - ) as _i3.CameraOptions); + _i3.CameraOptions get options => + (super.noSuchMethod( + Invocation.getter(#options), + returnValue: _FakeCameraOptions_3( + this, + Invocation.getter(#options), + ), + returnValueForMissingStub: _FakeCameraOptions_3( + this, + Invocation.getter(#options), + ), + ) + as _i3.CameraOptions); @override ({int? audioBitrate, int? videoBitrate}) get recorderOptions => (super.noSuchMethod( - Invocation.getter(#recorderOptions), - returnValue: (audioBitrate: null, videoBitrate: null), - returnValueForMissingStub: (audioBitrate: null, videoBitrate: null), - ) as ({int? audioBitrate, int? videoBitrate})); + Invocation.getter(#recorderOptions), + returnValue: (audioBitrate: null, videoBitrate: null), + returnValueForMissingStub: (audioBitrate: null, videoBitrate: null), + ) + as ({int? audioBitrate, int? videoBitrate})); @override - _i6.HTMLVideoElement get videoElement => (super.noSuchMethod( - Invocation.getter(#videoElement), - returnValue: _i9.videoElementShim(), - returnValueForMissingStub: _i9.videoElementShim(), - ) as _i6.HTMLVideoElement); + _i6.HTMLVideoElement get videoElement => + (super.noSuchMethod( + Invocation.getter(#videoElement), + returnValue: _i9.videoElementShim(), + returnValueForMissingStub: _i9.videoElementShim(), + ) + as _i6.HTMLVideoElement); @override set videoElement(_i6.HTMLVideoElement? _videoElement) => super.noSuchMethod( - Invocation.setter(#videoElement, _videoElement), - returnValueForMissingStub: null, - ); + Invocation.setter(#videoElement, _videoElement), + returnValueForMissingStub: null, + ); @override - _i6.HTMLDivElement get divElement => (super.noSuchMethod( - Invocation.getter(#divElement), - returnValue: _i9.divElementShim(), - returnValueForMissingStub: _i9.divElementShim(), - ) as _i6.HTMLDivElement); + _i6.HTMLDivElement get divElement => + (super.noSuchMethod( + Invocation.getter(#divElement), + returnValue: _i9.divElementShim(), + returnValueForMissingStub: _i9.divElementShim(), + ) + as _i6.HTMLDivElement); @override set divElement(_i6.HTMLDivElement? _divElement) => super.noSuchMethod( - Invocation.setter(#divElement, _divElement), - returnValueForMissingStub: null, - ); + Invocation.setter(#divElement, _divElement), + returnValueForMissingStub: null, + ); @override set stream(_i6.MediaStream? _stream) => super.noSuchMethod( - Invocation.setter(#stream, _stream), - returnValueForMissingStub: null, - ); + Invocation.setter(#stream, _stream), + returnValueForMissingStub: null, + ); @override _i5.StreamController<_i6.MediaStreamTrack> get onEndedController => (super.noSuchMethod( - Invocation.getter(#onEndedController), - returnValue: _FakeStreamController_4<_i6.MediaStreamTrack>( - this, - Invocation.getter(#onEndedController), - ), - returnValueForMissingStub: - _FakeStreamController_4<_i6.MediaStreamTrack>( - this, - Invocation.getter(#onEndedController), - ), - ) as _i5.StreamController<_i6.MediaStreamTrack>); + Invocation.getter(#onEndedController), + returnValue: _FakeStreamController_4<_i6.MediaStreamTrack>( + this, + Invocation.getter(#onEndedController), + ), + returnValueForMissingStub: + _FakeStreamController_4<_i6.MediaStreamTrack>( + this, + Invocation.getter(#onEndedController), + ), + ) + as _i5.StreamController<_i6.MediaStreamTrack>); @override _i6.EventStreamProvider<_i6.Event> get mediaRecorderOnErrorProvider => (super.noSuchMethod( - Invocation.getter(#mediaRecorderOnErrorProvider), - returnValue: _FakeEventStreamProvider_5<_i6.Event>( - this, - Invocation.getter(#mediaRecorderOnErrorProvider), - ), - returnValueForMissingStub: _FakeEventStreamProvider_5<_i6.Event>( - this, - Invocation.getter(#mediaRecorderOnErrorProvider), - ), - ) as _i6.EventStreamProvider<_i6.Event>); + Invocation.getter(#mediaRecorderOnErrorProvider), + returnValue: _FakeEventStreamProvider_5<_i6.Event>( + this, + Invocation.getter(#mediaRecorderOnErrorProvider), + ), + returnValueForMissingStub: _FakeEventStreamProvider_5<_i6.Event>( + this, + Invocation.getter(#mediaRecorderOnErrorProvider), + ), + ) + as _i6.EventStreamProvider<_i6.Event>); @override set mediaRecorderOnErrorProvider( _i6.EventStreamProvider<_i6.Event>? _mediaRecorderOnErrorProvider, - ) => - super.noSuchMethod( - Invocation.setter( - #mediaRecorderOnErrorProvider, - _mediaRecorderOnErrorProvider, - ), - returnValueForMissingStub: null, - ); + ) => super.noSuchMethod( + Invocation.setter( + #mediaRecorderOnErrorProvider, + _mediaRecorderOnErrorProvider, + ), + returnValueForMissingStub: null, + ); @override _i5.StreamController<_i6.ErrorEvent> get videoRecordingErrorController => (super.noSuchMethod( - Invocation.getter(#videoRecordingErrorController), - returnValue: _FakeStreamController_4<_i6.ErrorEvent>( - this, - Invocation.getter(#videoRecordingErrorController), - ), - returnValueForMissingStub: _FakeStreamController_4<_i6.ErrorEvent>( - this, - Invocation.getter(#videoRecordingErrorController), - ), - ) as _i5.StreamController<_i6.ErrorEvent>); + Invocation.getter(#videoRecordingErrorController), + returnValue: _FakeStreamController_4<_i6.ErrorEvent>( + this, + Invocation.getter(#videoRecordingErrorController), + ), + returnValueForMissingStub: _FakeStreamController_4<_i6.ErrorEvent>( + this, + Invocation.getter(#videoRecordingErrorController), + ), + ) + as _i5.StreamController<_i6.ErrorEvent>); @override set flashMode(_i7.FlashMode? _flashMode) => super.noSuchMethod( - Invocation.setter(#flashMode, _flashMode), - returnValueForMissingStub: null, - ); + Invocation.setter(#flashMode, _flashMode), + returnValueForMissingStub: null, + ); @override - _i6.Window get window => (super.noSuchMethod( - Invocation.getter(#window), - returnValue: _i9.windowShim(), - returnValueForMissingStub: _i9.windowShim(), - ) as _i6.Window); + _i6.Window get window => + (super.noSuchMethod( + Invocation.getter(#window), + returnValue: _i9.windowShim(), + returnValueForMissingStub: _i9.windowShim(), + ) + as _i6.Window); @override set window(_i6.Window? _window) => super.noSuchMethod( - Invocation.setter(#window, _window), - returnValueForMissingStub: null, - ); + Invocation.setter(#window, _window), + returnValueForMissingStub: null, + ); @override set mediaRecorder(_i6.MediaRecorder? _mediaRecorder) => super.noSuchMethod( - Invocation.setter(#mediaRecorder, _mediaRecorder), - returnValueForMissingStub: null, - ); + Invocation.setter(#mediaRecorder, _mediaRecorder), + returnValueForMissingStub: null, + ); @override - bool Function(String) get isVideoTypeSupported => (super.noSuchMethod( - Invocation.getter(#isVideoTypeSupported), - returnValue: (String __p0) => false, - returnValueForMissingStub: (String __p0) => false, - ) as bool Function(String)); + bool Function(String) get isVideoTypeSupported => + (super.noSuchMethod( + Invocation.getter(#isVideoTypeSupported), + returnValue: (String __p0) => false, + returnValueForMissingStub: (String __p0) => false, + ) + as bool Function(String)); @override set isVideoTypeSupported(bool Function(String)? _isVideoTypeSupported) => @@ -430,10 +462,11 @@ class MockCamera extends _i1.Mock implements _i10.Camera { @override _i6.Blob Function(List<_i6.Blob>, String) get blobBuilder => (super.noSuchMethod( - Invocation.getter(#blobBuilder), - returnValue: _i9.blobBuilderShim(), - returnValueForMissingStub: _i9.blobBuilderShim(), - ) as _i6.Blob Function(List<_i6.Blob>, String)); + Invocation.getter(#blobBuilder), + returnValue: _i9.blobBuilderShim(), + returnValueForMissingStub: _i9.blobBuilderShim(), + ) + as _i6.Blob Function(List<_i6.Blob>, String)); @override set blobBuilder(_i6.Blob Function(List<_i6.Blob>, String)? _blobBuilder) => @@ -445,167 +478,198 @@ class MockCamera extends _i1.Mock implements _i10.Camera { @override _i5.StreamController<_i7.VideoRecordedEvent> get videoRecorderController => (super.noSuchMethod( - Invocation.getter(#videoRecorderController), - returnValue: _FakeStreamController_4<_i7.VideoRecordedEvent>( - this, - Invocation.getter(#videoRecorderController), - ), - returnValueForMissingStub: - _FakeStreamController_4<_i7.VideoRecordedEvent>( - this, - Invocation.getter(#videoRecorderController), - ), - ) as _i5.StreamController<_i7.VideoRecordedEvent>); - - @override - _i5.Stream<_i6.MediaStreamTrack> get onEnded => (super.noSuchMethod( - Invocation.getter(#onEnded), - returnValue: _i5.Stream<_i6.MediaStreamTrack>.empty(), - returnValueForMissingStub: _i5.Stream<_i6.MediaStreamTrack>.empty(), - ) as _i5.Stream<_i6.MediaStreamTrack>); + Invocation.getter(#videoRecorderController), + returnValue: _FakeStreamController_4<_i7.VideoRecordedEvent>( + this, + Invocation.getter(#videoRecorderController), + ), + returnValueForMissingStub: + _FakeStreamController_4<_i7.VideoRecordedEvent>( + this, + Invocation.getter(#videoRecorderController), + ), + ) + as _i5.StreamController<_i7.VideoRecordedEvent>); + + @override + _i5.Stream<_i6.MediaStreamTrack> get onEnded => + (super.noSuchMethod( + Invocation.getter(#onEnded), + returnValue: _i5.Stream<_i6.MediaStreamTrack>.empty(), + returnValueForMissingStub: _i5.Stream<_i6.MediaStreamTrack>.empty(), + ) + as _i5.Stream<_i6.MediaStreamTrack>); @override - _i5.Stream<_i6.ErrorEvent> get onVideoRecordingError => (super.noSuchMethod( - Invocation.getter(#onVideoRecordingError), - returnValue: _i5.Stream<_i6.ErrorEvent>.empty(), - returnValueForMissingStub: _i5.Stream<_i6.ErrorEvent>.empty(), - ) as _i5.Stream<_i6.ErrorEvent>); + _i5.Stream<_i6.ErrorEvent> get onVideoRecordingError => + (super.noSuchMethod( + Invocation.getter(#onVideoRecordingError), + returnValue: _i5.Stream<_i6.ErrorEvent>.empty(), + returnValueForMissingStub: _i5.Stream<_i6.ErrorEvent>.empty(), + ) + as _i5.Stream<_i6.ErrorEvent>); @override _i5.Stream<_i7.VideoRecordedEvent> get onVideoRecordedEvent => (super.noSuchMethod( - Invocation.getter(#onVideoRecordedEvent), - returnValue: _i5.Stream<_i7.VideoRecordedEvent>.empty(), - returnValueForMissingStub: _i5.Stream<_i7.VideoRecordedEvent>.empty(), - ) as _i5.Stream<_i7.VideoRecordedEvent>); + Invocation.getter(#onVideoRecordedEvent), + returnValue: _i5.Stream<_i7.VideoRecordedEvent>.empty(), + returnValueForMissingStub: + _i5.Stream<_i7.VideoRecordedEvent>.empty(), + ) + as _i5.Stream<_i7.VideoRecordedEvent>); @override - _i5.Future initialize() => (super.noSuchMethod( - Invocation.method(#initialize, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future initialize() => + (super.noSuchMethod( + Invocation.method(#initialize, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future play() => (super.noSuchMethod( - Invocation.method(#play, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future play() => + (super.noSuchMethod( + Invocation.method(#play, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override void pause() => super.noSuchMethod( - Invocation.method(#pause, []), - returnValueForMissingStub: null, - ); + Invocation.method(#pause, []), + returnValueForMissingStub: null, + ); @override void stop() => super.noSuchMethod( - Invocation.method(#stop, []), - returnValueForMissingStub: null, - ); + Invocation.method(#stop, []), + returnValueForMissingStub: null, + ); @override - _i5.Future<_i7.XFile> takePicture() => (super.noSuchMethod( - Invocation.method(#takePicture, []), - returnValue: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#takePicture, [])), - ), - returnValueForMissingStub: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#takePicture, [])), - ), - ) as _i5.Future<_i7.XFile>); - - @override - _i4.Size getVideoSize() => (super.noSuchMethod( - Invocation.method(#getVideoSize, []), - returnValue: _FakeSize_2( - this, - Invocation.method(#getVideoSize, []), - ), - returnValueForMissingStub: _FakeSize_2( - this, - Invocation.method(#getVideoSize, []), - ), - ) as _i4.Size); + _i5.Future<_i7.XFile> takePicture() => + (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#takePicture, [])), + ), + returnValueForMissingStub: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#takePicture, [])), + ), + ) + as _i5.Future<_i7.XFile>); + + @override + _i4.Size getVideoSize() => + (super.noSuchMethod( + Invocation.method(#getVideoSize, []), + returnValue: _FakeSize_2( + this, + Invocation.method(#getVideoSize, []), + ), + returnValueForMissingStub: _FakeSize_2( + this, + Invocation.method(#getVideoSize, []), + ), + ) + as _i4.Size); @override void setFlashMode(_i7.FlashMode? mode) => super.noSuchMethod( - Invocation.method(#setFlashMode, [mode]), - returnValueForMissingStub: null, - ); + Invocation.method(#setFlashMode, [mode]), + returnValueForMissingStub: null, + ); @override - double getMaxZoomLevel() => (super.noSuchMethod( - Invocation.method(#getMaxZoomLevel, []), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) as double); + double getMaxZoomLevel() => + (super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, []), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) + as double); @override - double getMinZoomLevel() => (super.noSuchMethod( - Invocation.method(#getMinZoomLevel, []), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) as double); + double getMinZoomLevel() => + (super.noSuchMethod( + Invocation.method(#getMinZoomLevel, []), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) + as double); @override void setZoomLevel(double? zoom) => super.noSuchMethod( - Invocation.method(#setZoomLevel, [zoom]), - returnValueForMissingStub: null, - ); + Invocation.method(#setZoomLevel, [zoom]), + returnValueForMissingStub: null, + ); + + @override + String getViewType() => + (super.noSuchMethod( + Invocation.method(#getViewType, []), + returnValue: _i12.dummyValue( + this, + Invocation.method(#getViewType, []), + ), + returnValueForMissingStub: _i12.dummyValue( + this, + Invocation.method(#getViewType, []), + ), + ) + as String); + + @override + _i5.Future startVideoRecording() => + (super.noSuchMethod( + Invocation.method(#startVideoRecording, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future pauseVideoRecording() => + (super.noSuchMethod( + Invocation.method(#pauseVideoRecording, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - String getViewType() => (super.noSuchMethod( - Invocation.method(#getViewType, []), - returnValue: _i12.dummyValue( - this, - Invocation.method(#getViewType, []), - ), - returnValueForMissingStub: _i12.dummyValue( - this, - Invocation.method(#getViewType, []), - ), - ) as String); - - @override - _i5.Future startVideoRecording() => (super.noSuchMethod( - Invocation.method(#startVideoRecording, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future pauseVideoRecording() => (super.noSuchMethod( - Invocation.method(#pauseVideoRecording, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future resumeVideoRecording() => (super.noSuchMethod( - Invocation.method(#resumeVideoRecording, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future<_i7.XFile> stopVideoRecording() => (super.noSuchMethod( - Invocation.method(#stopVideoRecording, []), - returnValue: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), - ), - returnValueForMissingStub: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), - ), - ) as _i5.Future<_i7.XFile>); - - @override - _i5.Future dispose() => (super.noSuchMethod( - Invocation.method(#dispose, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future resumeVideoRecording() => + (super.noSuchMethod( + Invocation.method(#resumeVideoRecording, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i7.XFile> stopVideoRecording() => + (super.noSuchMethod( + Invocation.method(#stopVideoRecording, []), + returnValue: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), + ), + returnValueForMissingStub: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), + ), + ) + as _i5.Future<_i7.XFile>); + + @override + _i5.Future dispose() => + (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [CameraOptions]. @@ -614,35 +678,41 @@ class MockCamera extends _i1.Mock implements _i10.Camera { // ignore: must_be_immutable class MockCameraOptions extends _i1.Mock implements _i3.CameraOptions { @override - _i3.AudioConstraints get audio => (super.noSuchMethod( - Invocation.getter(#audio), - returnValue: _FakeAudioConstraints_7( - this, - Invocation.getter(#audio), - ), - returnValueForMissingStub: _FakeAudioConstraints_7( - this, - Invocation.getter(#audio), - ), - ) as _i3.AudioConstraints); - - @override - _i3.VideoConstraints get video => (super.noSuchMethod( - Invocation.getter(#video), - returnValue: _FakeVideoConstraints_8( - this, - Invocation.getter(#video), - ), - returnValueForMissingStub: _FakeVideoConstraints_8( - this, - Invocation.getter(#video), - ), - ) as _i3.VideoConstraints); - - @override - _i6.MediaStreamConstraints toMediaStreamConstraints() => (super.noSuchMethod( - Invocation.method(#toMediaStreamConstraints, []), - returnValue: _i9.toMediaStreamConstraintsShim(), - returnValueForMissingStub: _i9.toMediaStreamConstraintsShim(), - ) as _i6.MediaStreamConstraints); + _i3.AudioConstraints get audio => + (super.noSuchMethod( + Invocation.getter(#audio), + returnValue: _FakeAudioConstraints_7( + this, + Invocation.getter(#audio), + ), + returnValueForMissingStub: _FakeAudioConstraints_7( + this, + Invocation.getter(#audio), + ), + ) + as _i3.AudioConstraints); + + @override + _i3.VideoConstraints get video => + (super.noSuchMethod( + Invocation.getter(#video), + returnValue: _FakeVideoConstraints_8( + this, + Invocation.getter(#video), + ), + returnValueForMissingStub: _FakeVideoConstraints_8( + this, + Invocation.getter(#video), + ), + ) + as _i3.VideoConstraints); + + @override + _i6.MediaStreamConstraints toMediaStreamConstraints() => + (super.noSuchMethod( + Invocation.method(#toMediaStreamConstraints, []), + returnValue: _i9.toMediaStreamConstraintsShim(), + returnValueForMissingStub: _i9.toMediaStreamConstraintsShim(), + ) + as _i6.MediaStreamConstraints); } diff --git a/packages/camera/camera_web/example/pubspec.yaml b/packages/camera/camera_web/example/pubspec.yaml index 9b9812ae0df..d9f9854bc1f 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 124f595fecf..4098a1ae98e 100644 --- a/packages/camera/camera_web/lib/src/camera.dart +++ b/packages/camera/camera_web/lib/src/camera.dart @@ -170,11 +170,12 @@ 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), @@ -197,8 +198,8 @@ class Camera { _onEndedSubscription = EventStreamProviders.endedEvent .forTarget(defaultVideoTrack) .listen((web.Event _) { - onEndedController.add(defaultVideoTrack); - }); + onEndedController.add(defaultVideoTrack); + }); } } @@ -253,9 +254,10 @@ 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. @@ -296,7 +298,7 @@ class Camera { Size getVideoSize() { final List videoTracks = (videoElement.srcObject as web.MediaStream?)?.getVideoTracks().toDart ?? - []; + []; if (videoTracks.isEmpty) { return Size.zero; @@ -355,7 +357,8 @@ class Camera { if (videoTracks.isNotEmpty) { final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; - final bool canEnableTorchMode = defaultVideoTrack + final bool canEnableTorchMode = + defaultVideoTrack .getCapabilities() .torchNullable ?.toDart @@ -365,7 +368,8 @@ class Camera { if (canEnableTorchMode) { defaultVideoTrack.applyWebTweakConstraints( - WebTweakMediaTrackConstraints(torch: enabled.toJS)); + WebTweakMediaTrackConstraints(torch: enabled.toJS), + ); } else { throw CameraWebException( textureId, @@ -401,8 +405,8 @@ class Camera { /// Throws a [CameraWebException] if the zoom level is invalid, /// not supported or the camera has not been initialized or started. void setZoomLevel(double zoom) { - final ZoomLevelCapability zoomLevelCapability = - _cameraService.getZoomLevelCapabilityForCamera(this); + final ZoomLevelCapability zoomLevelCapability = _cameraService + .getZoomLevelCapabilityForCamera(this); if (zoom < zoomLevelCapability.minimum || zoom > zoomLevelCapability.maximum) { @@ -414,7 +418,8 @@ class Camera { } zoomLevelCapability.videoTrack.applyWebTweakConstraints( - WebTweakMediaTrackConstraints(zoom: zoom.toJS)); + WebTweakMediaTrackConstraints(zoom: zoom.toJS), + ); } /// Returns a lens direction of this camera. @@ -424,7 +429,7 @@ class Camera { CameraLensDirection? getLensDirection() { final List videoTracks = (videoElement.srcObject as web.MediaStream?)?.getVideoTracks().toDart ?? - []; + []; if (videoTracks.isEmpty) { return null; @@ -451,8 +456,9 @@ class Camera { /// Throws a [CameraWebException] if the browser does not support any of the /// available video mime types from [_videoMimeType]. Future startVideoRecording() async { - final web.MediaRecorderOptions options = - web.MediaRecorderOptions(mimeType: _videoMimeType); + final web.MediaRecorderOptions options = web.MediaRecorderOptions( + mimeType: _videoMimeType, + ); if (recorderOptions.audioBitrate != null) { options.audioBitsPerSecond = recorderOptions.audioBitrate!; } @@ -460,8 +466,10 @@ class Camera { options.videoBitsPerSecond = recorderOptions.videoBitrate!; } - mediaRecorder ??= - web.MediaRecorder(videoElement.srcObject! as web.MediaStream, options); + mediaRecorder ??= web.MediaRecorder( + videoElement.srcObject! as web.MediaStream, + options, + ); _videoAvailableCompleter = Completer(); @@ -484,9 +492,9 @@ class Camera { _onVideoRecordingErrorSubscription = mediaRecorderOnErrorProvider .forTarget(mediaRecorder) .listen((web.Event event) { - final web.ErrorEvent error = event as web.ErrorEvent; - videoRecordingErrorController.add(error); - }); + final web.ErrorEvent error = event as web.ErrorEvent; + videoRecordingErrorController.add(error); + }); mediaRecorder!.start(); } @@ -510,9 +518,7 @@ class Camera { ); // Emit an event containing the recorded video file. - videoRecorderController.add( - VideoRecordedEvent(textureId, file, null), - ); + videoRecorderController.add(VideoRecordedEvent(textureId, file, null)); _videoAvailableCompleter?.complete(file); } @@ -607,20 +613,22 @@ 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(',')}.', + ), ); } - CameraWebException get _videoRecordingNotStartedException => - CameraWebException( - textureId, - CameraErrorCode.videoRecordingNotStarted, - 'The video recorder is uninitialized. The recording might not have been started. Make sure to call `startVideoRecording` first.', - ); + CameraWebException + get _videoRecordingNotStartedException => CameraWebException( + textureId, + CameraErrorCode.videoRecordingNotStarted, + 'The video recorder is uninitialized. The recording might not have been started. Make sure to call `startVideoRecording` first.', + ); /// Applies default styles to the video [element]. void _applyDefaultVideoStyles(web.HTMLVideoElement element) { diff --git a/packages/camera/camera_web/lib/src/camera_service.dart b/packages/camera/camera_web/lib/src/camera_service.dart index 072fe06859f..13146d6e240 100644 --- a/packages/camera/camera_web/lib/src/camera_service.dart +++ b/packages/camera/camera_web/lib/src/camera_service.dart @@ -35,9 +35,7 @@ class CameraService { try { return await mediaDevices - .getUserMedia( - options.toMediaStreamConstraints(), - ) + .getUserMedia(options.toMediaStreamConstraints()) .toDart; } on web.DOMException catch (e) { switch (e.name) { @@ -110,9 +108,7 @@ class CameraService { /// /// Throws a [CameraWebException] if the zoom level is not supported /// or the camera has not been initialized or started. - ZoomLevelCapability getZoomLevelCapabilityForCamera( - Camera camera, - ) { + ZoomLevelCapability getZoomLevelCapabilityForCamera(Camera camera) { final web.MediaDevices mediaDevices = window.navigator.mediaDevices; final web.MediaTrackSupportedConstraints supportedConstraints = mediaDevices.getSupportedConstraints(); @@ -203,10 +199,10 @@ class CameraService { // 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 11d14316971..1f01f83f0c6 100644 --- a/packages/camera/camera_web/lib/src/camera_web.dart +++ b/packages/camera/camera_web/lib/src/camera_web.dart @@ -30,13 +30,11 @@ class CameraPlugin extends CameraPlatform { /// Creates a new instance of [CameraPlugin] /// with the given [cameraService]. CameraPlugin({required CameraService cameraService}) - : _cameraService = cameraService; + : _cameraService = cameraService; /// Registers this class as the default instance of [CameraPlatform]. static void registerWith(Registrar registrar) { - CameraPlatform.instance = CameraPlugin( - cameraService: CameraService(), - ); + CameraPlatform.instance = CameraPlugin(cameraService: CameraService()); } final CameraService _cameraService; @@ -77,17 +75,16 @@ class CameraPlugin extends CameraPlatform { >{}; final Map> - _cameraEndedSubscriptions = - >{}; + _cameraEndedSubscriptions = >{}; final Map> - _cameraVideoRecordingErrorSubscriptions = + _cameraVideoRecordingErrorSubscriptions = >{}; /// Returns a stream of camera events for the given [cameraId]. - Stream _cameraEvents(int cameraId) => - cameraEventStreamController.stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => cameraEventStreamController + .stream + .where((CameraEvent event) => event.cameraId == cameraId); /// The stream provider for [web.ScreenOrientation] change events. @visibleForTesting @@ -105,14 +102,13 @@ class CameraPlugin extends CameraPlatform { final List cameras = []; // Request video permissions only. - final web.MediaStream cameraStream = - await _cameraService.getMediaStreamForOptions(const CameraOptions()); + final web.MediaStream cameraStream = await _cameraService + .getMediaStreamForOptions(const CameraOptions()); // Release the camera stream used to request video permissions. - cameraStream - .getVideoTracks() - .toDart - .forEach((web.MediaStreamTrack videoTrack) => videoTrack.stop()); + cameraStream.getVideoTracks().toDart.forEach( + (web.MediaStreamTrack videoTrack) => videoTrack.stop(), + ); // Request available media devices. final List devices = @@ -124,7 +120,6 @@ class CameraPlugin extends CameraPlatform { (web.MediaDeviceInfo device) => device.kind == MediaDeviceKind.videoInput, ) - /// The device id property is currently not supported on Internet Explorer: /// https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/deviceId#browser_compatibility .where((web.MediaDeviceInfo device) => device.deviceId.isNotEmpty); @@ -133,8 +128,9 @@ class CameraPlugin extends CameraPlatform { for (final web.MediaDeviceInfo videoInputDevice in videoInputDevices) { // Get the video stream for the current video input device // to later use for the available video tracks. - final web.MediaStream videoStream = - await _getVideoStreamForDevice(videoInputDevice.deviceId); + final web.MediaStream videoStream = await _getVideoStreamForDevice( + videoInputDevice.deviceId, + ); // Get all video tracks in the video stream // to later extract the lens direction from the first track. @@ -143,15 +139,17 @@ class CameraPlugin extends CameraPlatform { if (videoTracks.isNotEmpty) { // Get the facing mode from the first available video track. - final String? facingMode = - _cameraService.getFacingModeForVideoTrack(videoTracks.first); + final String? facingMode = _cameraService.getFacingModeForVideoTrack( + videoTracks.first, + ); // 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. // @@ -203,13 +201,10 @@ class CameraPlugin extends CameraPlatform { CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, - }) => - createCameraWithSettings( - cameraDescription, - MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - )); + }) => createCameraWithSettings( + cameraDescription, + MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio), + ); @override Future createCameraWithSettings( @@ -229,14 +224,18 @@ 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. final Size videoSize = _cameraService.mapResolutionPresetToSize( - mediaSettings?.resolutionPreset ?? ResolutionPreset.max); + mediaSettings?.resolutionPreset ?? ResolutionPreset.max, + ); // Create a camera with the given audio and video constraints. // Sensor orientation is currently not supported. @@ -248,12 +247,8 @@ class CameraPlugin extends CameraPlatform { video: VideoConstraints( facingMode: cameraType != null ? FacingModeConstraint(cameraType) : null, - width: VideoSizeConstraint( - ideal: videoSize.width.toInt(), - ), - height: VideoSizeConstraint( - ideal: videoSize.height.toInt(), - ), + width: VideoSizeConstraint(ideal: videoSize.width.toInt()), + height: VideoSizeConstraint(ideal: videoSize.height.toInt()), deviceId: cameraMetadata.deviceId, ), ), @@ -287,44 +282,45 @@ class CameraPlugin extends CameraPlatform { _cameraVideoErrorSubscriptions[cameraId] = videoElementOnErrorProvider .forElement(camera.videoElement) .listen((web.Event _) { - // The Event itself (_) doesn't contain information about the actual error. - // We need to look at the HTMLMediaElement.error. - // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error - final web.MediaError error = camera.videoElement.error!; - final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error); - final String errorMessage = - error.message != '' ? error.message : _kDefaultErrorMessage; - - cameraEventStreamController.add( - CameraErrorEvent( - cameraId, - 'Error code: $errorCode, error message: $errorMessage', - ), - ); - }); + // The Event itself (_) doesn't contain information about the actual error. + // We need to look at the HTMLMediaElement.error. + // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error + final web.MediaError error = camera.videoElement.error!; + final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( + error, + ); + final String errorMessage = + error.message != '' ? error.message : _kDefaultErrorMessage; + + cameraEventStreamController.add( + CameraErrorEvent( + cameraId, + 'Error code: $errorCode, error message: $errorMessage', + ), + ); + }); // Add camera's video abort events to the camera events stream. // The abort event fires when the video element's source has not fully loaded. _cameraVideoAbortSubscriptions[cameraId] = videoElementOnAbortProvider .forElement(camera.videoElement) .listen((web.Event _) { - cameraEventStreamController.add( - CameraErrorEvent( - cameraId, - "Error code: ${CameraErrorCode.abort}, error message: The video element's source has not fully loaded.", - ), - ); - }); + cameraEventStreamController.add( + CameraErrorEvent( + cameraId, + "Error code: ${CameraErrorCode.abort}, error message: The video element's source has not fully loaded.", + ), + ); + }); await camera.play(); // Add camera's closing events to the camera events stream. // The onEnded stream fires when there is no more camera stream data. - _cameraEndedSubscriptions[cameraId] = - camera.onEnded.listen((web.MediaStreamTrack _) { - cameraEventStreamController.add( - CameraClosingEvent(cameraId), - ); + _cameraEndedSubscriptions[cameraId] = camera.onEnded.listen(( + web.MediaStreamTrack _, + ) { + cameraEventStreamController.add(CameraClosingEvent(cameraId)); }); final Size cameraSize = camera.getVideoSize(); @@ -391,13 +387,11 @@ class CameraPlugin extends CameraPlatform { return orientationOnChangeProvider .forTarget(orientation) .startWith(initialOrientationEvent) - .map( - (web.Event _) { - final DeviceOrientation deviceOrientation = _cameraService - .mapOrientationTypeToDeviceOrientation(orientation.type); - return DeviceOrientationChangedEvent(deviceOrientation); - }, - ); + .map((web.Event _) { + final DeviceOrientation deviceOrientation = _cameraService + .mapOrientationTypeToDeviceOrientation(orientation.type); + return DeviceOrientationChangedEvent(deviceOrientation); + }); } @override @@ -410,8 +404,8 @@ class CameraPlugin extends CameraPlatform { final web.Element? documentElement = window.document.documentElement; if (documentElement != null) { - final String orientationType = - _cameraService.mapDeviceOrientationToOrientationType(orientation); + final String orientationType = _cameraService + .mapDeviceOrientationToOrientationType(orientation); // Full-screen mode may be required to modify the device orientation. // See: https://w3c.github.io/screen-orientation/#interaction-with-fullscreen-api @@ -485,8 +479,10 @@ class CameraPlugin extends CameraPlatform { // Add camera's video recording errors to the camera events stream. // The error event fires when the video recording is not allowed or an unsupported // codec is used. - _cameraVideoRecordingErrorSubscriptions[options.cameraId] = - camera.onVideoRecordingError.listen((web.ErrorEvent errorEvent) { + _cameraVideoRecordingErrorSubscriptions[options + .cameraId] = camera.onVideoRecordingError.listen(( + web.ErrorEvent errorEvent, + ) { cameraEventStreamController.add( CameraErrorEvent( options.cameraId, @@ -656,9 +652,7 @@ class CameraPlugin extends CameraPlatform { @override Widget buildPreview(int cameraId) { - return HtmlElementView( - viewType: getCamera(cameraId).getViewType(), - ); + return HtmlElementView(viewType: getCamera(cameraId).getViewType()); } @override @@ -681,9 +675,7 @@ class CameraPlugin extends CameraPlatform { } /// Returns a media video stream for the device with the given [deviceId]. - Future _getVideoStreamForDevice( - String deviceId, - ) { + Future _getVideoStreamForDevice(String deviceId) { // Create camera options with the desired device id. final CameraOptions cameraOptions = CameraOptions( video: VideoConstraints(deviceId: deviceId), diff --git a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart index fb0e84ef377..d333bc887e7 100644 --- a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart +++ b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart @@ -42,11 +42,7 @@ extension NonStandardFieldsOnMediaTrackSettings on MediaTrackSettings { /// Brought over from package:web 1.0.0 extension type WebTweakMediaSettingsRange._(JSObject _) implements JSObject { @JS('MediaSettingsRange') - external factory WebTweakMediaSettingsRange({ - num max, - num min, - num step, - }); + external factory WebTweakMediaSettingsRange({num max, num min, num step}); external double get max; external set max(num value); @@ -59,8 +55,9 @@ extension type WebTweakMediaSettingsRange._(JSObject _) implements JSObject { /// Adds an applyConstraints method that accepts the WebTweakMediaTrackConstraints. extension WebTweakMethodVersions on MediaStreamTrack { @JS('applyConstraints') - external JSPromise applyWebTweakConstraints( - [WebTweakMediaTrackConstraints constraints]); + external JSPromise applyWebTweakConstraints([ + WebTweakMediaTrackConstraints constraints, + ]); } /// Allows creating the MediaTrackConstraints that are needed. diff --git a/packages/camera/camera_web/lib/src/types/camera_error_code.dart b/packages/camera/camera_web/lib/src/types/camera_error_code.dart index 6619e5fb388..75e07ee4e11 100644 --- a/packages/camera/camera_web/lib/src/types/camera_error_code.dart +++ b/packages/camera/camera_web/lib/src/types/camera_error_code.dart @@ -15,24 +15,28 @@ class CameraErrorCode { String toString() => _type; /// The camera is not supported. - static const CameraErrorCode notSupported = - CameraErrorCode._('cameraNotSupported'); + static const CameraErrorCode notSupported = CameraErrorCode._( + 'cameraNotSupported', + ); /// The camera is not found. static const CameraErrorCode notFound = CameraErrorCode._('cameraNotFound'); /// The camera is not readable. - static const CameraErrorCode notReadable = - CameraErrorCode._('cameraNotReadable'); + static const CameraErrorCode notReadable = CameraErrorCode._( + 'cameraNotReadable', + ); /// The camera options are impossible to satisfy. - static const CameraErrorCode overconstrained = - CameraErrorCode._('cameraOverconstrained'); + static const CameraErrorCode overconstrained = CameraErrorCode._( + 'cameraOverconstrained', + ); /// The camera cannot be used or the permission /// to access the camera is not granted. - static const CameraErrorCode permissionDenied = - CameraErrorCode._('CameraAccessDenied'); + static const CameraErrorCode permissionDenied = CameraErrorCode._( + 'CameraAccessDenied', + ); /// The camera options are incorrect or attempted /// to access the media input from an insecure context. @@ -45,32 +49,39 @@ class CameraErrorCode { static const CameraErrorCode security = CameraErrorCode._('cameraSecurity'); /// The camera metadata is missing. - static const CameraErrorCode missingMetadata = - CameraErrorCode._('cameraMissingMetadata'); + static const CameraErrorCode missingMetadata = CameraErrorCode._( + 'cameraMissingMetadata', + ); /// The camera orientation is not supported. - static const CameraErrorCode orientationNotSupported = - CameraErrorCode._('orientationNotSupported'); + static const CameraErrorCode orientationNotSupported = CameraErrorCode._( + 'orientationNotSupported', + ); /// The camera torch mode is not supported. - static const CameraErrorCode torchModeNotSupported = - CameraErrorCode._('torchModeNotSupported'); + static const CameraErrorCode torchModeNotSupported = CameraErrorCode._( + 'torchModeNotSupported', + ); /// The camera zoom level is not supported. - static const CameraErrorCode zoomLevelNotSupported = - CameraErrorCode._('zoomLevelNotSupported'); + static const CameraErrorCode zoomLevelNotSupported = CameraErrorCode._( + 'zoomLevelNotSupported', + ); /// The camera zoom level is invalid. - static const CameraErrorCode zoomLevelInvalid = - CameraErrorCode._('zoomLevelInvalid'); + static const CameraErrorCode zoomLevelInvalid = CameraErrorCode._( + 'zoomLevelInvalid', + ); /// The camera has not been initialized or started. - static const CameraErrorCode notStarted = - CameraErrorCode._('cameraNotStarted'); + static const CameraErrorCode notStarted = CameraErrorCode._( + 'cameraNotStarted', + ); /// The video recording was not started. - static const CameraErrorCode videoRecordingNotStarted = - CameraErrorCode._('videoRecordingNotStarted'); + static const CameraErrorCode videoRecordingNotStarted = CameraErrorCode._( + 'videoRecordingNotStarted', + ); /// An unknown camera error. static const CameraErrorCode unknown = CameraErrorCode._('cameraUnknown'); diff --git a/packages/camera/camera_web/lib/src/types/camera_options.dart b/packages/camera/camera_web/lib/src/types/camera_options.dart index 45b446215a8..7d1bc551a7e 100644 --- a/packages/camera/camera_web/lib/src/types/camera_options.dart +++ b/packages/camera/camera_web/lib/src/types/camera_options.dart @@ -19,11 +19,9 @@ import 'package:web/web.dart' as web; class CameraOptions { /// Creates a new instance of [CameraOptions] /// with the given [audio] and [video] constraints. - const CameraOptions({ - AudioConstraints? audio, - VideoConstraints? video, - }) : audio = audio ?? const AudioConstraints(), - video = video ?? const VideoConstraints(); + const CameraOptions({AudioConstraints? audio, VideoConstraints? video}) + : audio = audio ?? const AudioConstraints(), + video = video ?? const VideoConstraints(); /// The audio constraints for the camera. final AudioConstraints audio; diff --git a/packages/camera/camera_web/pubspec.yaml b/packages/camera/camera_web/pubspec.yaml index 68def3ca3f3..c32cfb084b0 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/camera/camera_windows/CHANGELOG.md b/packages/camera/camera_windows/CHANGELOG.md index 4be03155c2d..9a001ea738d 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 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 01db9e2aee4..b8d66eaa58e 100644 --- a/packages/camera/camera_windows/example/integration_test/camera_test.dart +++ b/packages/camera/camera_windows/example/integration_test/camera_test.dart @@ -19,68 +19,87 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('initializeCamera', () { - testWidgets('throws exception if camera is not created', - (WidgetTester _) async { + testWidgets('throws exception if camera is not created', ( + WidgetTester _, + ) async { final CameraPlatform camera = CameraPlatform.instance; - expect(() async => camera.initializeCamera(1234), - throwsA(isA())); + expect( + () async => camera.initializeCamera(1234), + throwsA(isA()), + ); }); }); group('takePicture', () { - testWidgets('throws exception if camera is not created', - (WidgetTester _) async { + testWidgets('throws exception if camera is not created', ( + WidgetTester _, + ) async { final CameraPlatform camera = CameraPlatform.instance; - expect(() async => camera.takePicture(1234), - throwsA(isA())); + expect( + () async => camera.takePicture(1234), + throwsA(isA()), + ); }); }); group('startVideoRecording', () { - testWidgets('throws exception if camera is not created', - (WidgetTester _) async { + testWidgets('throws exception if camera is not created', ( + WidgetTester _, + ) async { final CameraPlatform camera = CameraPlatform.instance; - expect(() async => camera.startVideoRecording(1234), - throwsA(isA())); + expect( + () async => camera.startVideoRecording(1234), + throwsA(isA()), + ); }); }); group('stopVideoRecording', () { - testWidgets('throws exception if camera is not created', - (WidgetTester _) async { + testWidgets('throws exception if camera is not created', ( + WidgetTester _, + ) async { final CameraPlatform camera = CameraPlatform.instance; - expect(() async => camera.stopVideoRecording(1234), - throwsA(isA())); + expect( + () async => camera.stopVideoRecording(1234), + throwsA(isA()), + ); }); }); group('pausePreview', () { - testWidgets('throws exception if camera is not created', - (WidgetTester _) async { + testWidgets('throws exception if camera is not created', ( + WidgetTester _, + ) async { final CameraPlatform camera = CameraPlatform.instance; - expect(() async => camera.pausePreview(1234), - throwsA(isA())); + expect( + () async => camera.pausePreview(1234), + throwsA(isA()), + ); }); }); group('resumePreview', () { - testWidgets('throws exception if camera is not created', - (WidgetTester _) async { + testWidgets('throws exception if camera is not created', ( + WidgetTester _, + ) async { final CameraPlatform camera = CameraPlatform.instance; - expect(() async => camera.resumePreview(1234), - throwsA(isA())); + expect( + () async => camera.resumePreview(1234), + throwsA(isA()), + ); }); }); group('onDeviceOrientationChanged', () { - testWidgets('emits the initial DeviceOrientationChangedEvent', - (WidgetTester _) async { + testWidgets('emits the initial DeviceOrientationChangedEvent', ( + WidgetTester _, + ) async { final Stream eventStream = CameraPlatform.instance.onDeviceOrientationChanged(); @@ -90,9 +109,7 @@ void main() { expect( await streamQueue.next, equals( - const DeviceOrientationChangedEvent( - DeviceOrientation.landscapeRight, - ), + const DeviceOrientationChangedEvent(DeviceOrientation.landscapeRight), ), ); }); diff --git a/packages/camera/camera_windows/example/lib/main.dart b/packages/camera/camera_windows/example/lib/main.dart index 5523a13a797..b5a12736a2c 100644 --- a/packages/camera/camera_windows/example/lib/main.dart +++ b/packages/camera/camera_windows/example/lib/main.dart @@ -116,15 +116,10 @@ class _MyAppState extends State { final Future initialized = CameraPlatform.instance.onCameraInitialized(cameraId).first; - await CameraPlatform.instance.initializeCamera( - cameraId, - ); + await CameraPlatform.instance.initializeCamera(cameraId); final CameraInitializedEvent event = await initialized; - _previewSize = Size( - event.previewWidth, - event.previewHeight, - ); + _previewSize = Size(event.previewWidth, event.previewHeight); if (mounted) { setState(() { @@ -197,18 +192,19 @@ class _MyAppState extends State { Future _recordTimed(int seconds) async { if (_initialized && _cameraId > 0 && !_recordingTimed) { - unawaited(CameraPlatform.instance - .onVideoRecordedEvent(_cameraId) - .first - .then((VideoRecordedEvent event) async { - if (mounted) { - setState(() { - _recordingTimed = false; - }); - - _showInSnackBar('Video captured to: ${event.file.path}'); - } - })); + unawaited( + CameraPlatform.instance.onVideoRecordedEvent(_cameraId).first.then(( + VideoRecordedEvent event, + ) async { + if (mounted) { + setState(() { + _recordingTimed = false; + }); + + _showInSnackBar('Video captured to: ${event.file.path}'); + } + }), + ); await CameraPlatform.instance.startVideoRecording( _cameraId, @@ -232,8 +228,9 @@ class _MyAppState extends State { if (!_recording) { await CameraPlatform.instance.startVideoRecording(_cameraId); } else { - final XFile file = - await CameraPlatform.instance.stopVideoRecording(_cameraId); + final XFile file = await CameraPlatform.instance.stopVideoRecording( + _cameraId, + ); _showInSnackBar('Video captured to: ${file.path}'); } @@ -315,7 +312,8 @@ class _MyAppState extends State { void _onCameraError(CameraErrorEvent event) { if (mounted) { _scaffoldMessengerKey.currentState?.showSnackBar( - SnackBar(content: Text('Error: ${event.description}'))); + SnackBar(content: Text('Error: ${event.description}')), + ); // Dispose camera on camera error as it can not be used anymore. _disposeCurrentCamera(); @@ -330,10 +328,9 @@ class _MyAppState extends State { } void _showInSnackBar(String message) { - _scaffoldMessengerKey.currentState?.showSnackBar(SnackBar( - content: Text(message), - duration: const Duration(seconds: 1), - )); + _scaffoldMessengerKey.currentState?.showSnackBar( + SnackBar(content: Text(message), duration: const Duration(seconds: 1)), + ); } final GlobalKey _scaffoldMessengerKey = @@ -342,27 +339,23 @@ class _MyAppState extends State { @override Widget build(BuildContext context) { final List> resolutionItems = - ResolutionPreset.values - .map>((ResolutionPreset value) { - return DropdownMenuItem( - value: value, - child: Text(value.toString()), - ); - }).toList(); + ResolutionPreset.values.map>(( + ResolutionPreset value, + ) { + return DropdownMenuItem( + value: value, + child: Text(value.toString()), + ); + }).toList(); return MaterialApp( scaffoldMessengerKey: _scaffoldMessengerKey, home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), + appBar: AppBar(title: const Text('Plugin example app')), body: ListView( children: [ Padding( - padding: const EdgeInsets.symmetric( - vertical: 5, - horizontal: 10, - ), + padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), child: Text(_cameraInfo), ), if (_cameras.isEmpty) @@ -386,15 +379,18 @@ class _MyAppState extends State { const SizedBox(width: 20), const Text('Audio:'), Switch( - value: _mediaSettings.enableAudio, - onChanged: (bool state) => _onAudioChange(state)), + value: _mediaSettings.enableAudio, + onChanged: (bool state) => _onAudioChange(state), + ), const SizedBox(width: 20), ElevatedButton( - onPressed: _initialized - ? _disposeCurrentCamera - : _initializeCamera, - child: - Text(_initialized ? 'Dispose camera' : 'Create camera'), + onPressed: + _initialized + ? _disposeCurrentCamera + : _initializeCamera, + child: Text( + _initialized ? 'Dispose camera' : 'Create camera', + ), ), const SizedBox(width: 5), ElevatedButton( @@ -419,35 +415,28 @@ class _MyAppState extends State { ), const SizedBox(width: 5), ElevatedButton( - onPressed: (_initialized && !_recording && !_recordingTimed) - ? () => _recordTimed(5) - : null, - child: const Text( - 'Record 5 seconds', - ), + onPressed: + (_initialized && !_recording && !_recordingTimed) + ? () => _recordTimed(5) + : null, + child: const Text('Record 5 seconds'), ), if (_cameras.length > 1) ...[ const SizedBox(width: 5), ElevatedButton( onPressed: _switchCamera, - child: const Text( - 'Switch camera', - ), + child: const Text('Switch camera'), ), - ] + ], ], ), const SizedBox(height: 5), if (_initialized && _cameraId > 0 && _previewSize != null) Padding( - padding: const EdgeInsets.symmetric( - vertical: 10, - ), + padding: const EdgeInsets.symmetric(vertical: 10), child: Align( child: Container( - constraints: const BoxConstraints( - maxHeight: 500, - ), + constraints: const BoxConstraints(maxHeight: 500), child: AspectRatio( aspectRatio: _previewSize!.width / _previewSize!.height, child: _buildPreview(), diff --git a/packages/camera/camera_windows/example/pubspec.yaml b/packages/camera/camera_windows/example/pubspec.yaml index 1c93fb9f149..26b1e43bfa6 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: camera_platform_interface: ^2.6.0 diff --git a/packages/camera/camera_windows/lib/camera_windows.dart b/packages/camera/camera_windows/lib/camera_windows.dart index 523b41b6975..0e344b1acb3 100644 --- a/packages/camera/camera_windows/lib/camera_windows.dart +++ b/packages/camera/camera_windows/lib/camera_windows.dart @@ -16,7 +16,7 @@ import 'src/messages.g.dart'; class CameraWindows extends CameraPlatform { /// Creates a new Windows [CameraPlatform] implementation instance. CameraWindows({@visibleForTesting CameraApi? api}) - : _hostApi = api ?? CameraApi(); + : _hostApi = api ?? CameraApi(); /// Registers the Windows implementation of CameraPlatform. static void registerWith() { @@ -43,9 +43,9 @@ class CameraWindows extends CameraPlatform { StreamController.broadcast(); /// Returns a stream of camera events for the given [cameraId]. - Stream _cameraEvents(int cameraId) => - cameraEventStreamController.stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => cameraEventStreamController + .stream + .where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { @@ -74,13 +74,10 @@ class CameraWindows extends CameraPlatform { CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, - }) => - createCameraWithSettings( - cameraDescription, - MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - )); + }) => createCameraWithSettings( + cameraDescription, + MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio), + ); @override Future createCameraWithSettings( @@ -90,7 +87,9 @@ class CameraWindows extends CameraPlatform { try { // If resolutionPreset is not specified, plugin selects the highest resolution possible. return await _hostApi.create( - cameraDescription.name, _pigeonMediaSettings(mediaSettings)); + cameraDescription.name, + _pigeonMediaSettings(mediaSettings), + ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -101,8 +100,10 @@ class CameraWindows extends CameraPlatform { int cameraId, { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) async { - hostCameraHandlers.putIfAbsent(cameraId, - () => HostCameraMessageHandler(cameraId, cameraEventStreamController)); + hostCameraHandlers.putIfAbsent( + cameraId, + () => HostCameraMessageHandler(cameraId, cameraEventStreamController), + ); final PlatformSize reply; try { @@ -198,8 +199,10 @@ class CameraWindows extends CameraPlatform { } @override - Future startVideoRecording(int cameraId, - {Duration? maxVideoDuration}) async { + Future startVideoRecording( + int cameraId, { + Duration? maxVideoDuration, + }) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -208,7 +211,8 @@ class CameraWindows extends CameraPlatform { Future startVideoCapturing(VideoCaptureOptions options) async { if (options.streamCallback != null || options.streamOptions != null) { throw UnimplementedError( - 'Streaming is not currently supported on Windows'); + 'Streaming is not currently supported on Windows', + ); } // Currently none of `options` is supported on Windows, so it's not passed. @@ -225,13 +229,15 @@ class CameraWindows extends CameraPlatform { @override Future pauseVideoRecording(int cameraId) async { throw UnsupportedError( - 'pauseVideoRecording() is not supported due to Win32 API limitations.'); + 'pauseVideoRecording() is not supported due to Win32 API limitations.', + ); } @override Future resumeVideoRecording(int cameraId) async { throw UnsupportedError( - 'resumeVideoRecording() is not supported due to Win32 API limitations.'); + 'resumeVideoRecording() is not supported due to Win32 API limitations.', + ); } @override @@ -252,7 +258,8 @@ class CameraWindows extends CameraPlatform { assert(point == null || point.y >= 0 && point.y <= 1); throw UnsupportedError( - 'setExposurePoint() is not supported due to Win32 API limitations.'); + 'setExposurePoint() is not supported due to Win32 API limitations.', + ); } @override @@ -294,7 +301,8 @@ class CameraWindows extends CameraPlatform { assert(point == null || point.y >= 0 && point.y <= 1); throw UnsupportedError( - 'setFocusPoint() is not supported due to Win32 API limitations.'); + 'setFocusPoint() is not supported due to Win32 API limitations.', + ); } @override @@ -345,7 +353,8 @@ class CameraWindows extends CameraPlatform { /// Returns a [ResolutionPreset]'s Pigeon representation. PlatformResolutionPreset _pigeonResolutionPreset( - ResolutionPreset? resolutionPreset) { + ResolutionPreset? resolutionPreset, + ) { if (resolutionPreset == null) { // Provide a default if one isn't provided, since the native side needs // to set something. diff --git a/packages/camera/camera_windows/lib/src/messages.g.dart b/packages/camera/camera_windows/lib/src/messages.g.dart index a351d6d9cee..66a09bace63 100644 --- a/packages/camera/camera_windows/lib/src/messages.g.dart +++ b/packages/camera/camera_windows/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -30,14 +33,7 @@ List wrapResponse( } /// Pigeon version of platform interface's ResolutionPreset. -enum PlatformResolutionPreset { - low, - medium, - high, - veryHigh, - ultraHigh, - max, -} +enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } /// Pigeon version of MediaSettings. class PlatformMediaSettings { @@ -83,20 +79,14 @@ class PlatformMediaSettings { /// A representation of a size from the native camera APIs. class PlatformSize { - PlatformSize({ - required this.width, - required this.height, - }); + PlatformSize({required this.width, required this.height}); double width; double height; Object encode() { - return [ - width, - height, - ]; + return [width, height]; } static PlatformSize decode(Object result) { @@ -149,11 +139,12 @@ class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - CameraApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + CameraApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -166,10 +157,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -196,12 +187,13 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.create$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([cameraName, settings]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([cameraName, settings]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -226,10 +218,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.initialize$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -256,10 +248,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.dispose$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -282,10 +274,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.takePicture$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -312,10 +304,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -338,10 +330,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -368,10 +360,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.pausePreview$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -393,10 +385,10 @@ class CameraApi { 'dev.flutter.pigeon.camera_windows.CameraApi.resumePreview$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([cameraId]) as List?; if (pigeonVar_replyList == null) { @@ -430,12 +422,12 @@ abstract class CameraEventApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_windows.CameraEventApi.cameraClosing$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_windows.CameraEventApi.cameraClosing$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -447,28 +439,33 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.camera_windows.CameraEventApi.error$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_windows.CameraEventApi.error$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.camera_windows.CameraEventApi.error was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.camera_windows.CameraEventApi.error was null.', + ); final List args = (message as List?)!; final String? arg_errorMessage = (args[0] as String?); - assert(arg_errorMessage != null, - 'Argument for dev.flutter.pigeon.camera_windows.CameraEventApi.error was null, expected non-null String.'); + assert( + arg_errorMessage != null, + 'Argument for dev.flutter.pigeon.camera_windows.CameraEventApi.error was null, expected non-null String.', + ); try { api.error(arg_errorMessage!); return wrapResponse(empty: true); @@ -476,7 +473,8 @@ abstract class CameraEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/camera/camera_windows/pigeons/messages.dart b/packages/camera/camera_windows/pigeons/messages.dart index cb70021a0ef..6c2c06b127c 100644 --- a/packages/camera/camera_windows/pigeons/messages.dart +++ b/packages/camera/camera_windows/pigeons/messages.dart @@ -4,14 +4,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - cppOptions: CppOptions(namespace: 'camera_windows'), - cppHeaderOut: 'windows/messages.g.h', - cppSourceOut: 'windows/messages.g.cpp', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + cppOptions: CppOptions(namespace: 'camera_windows'), + cppHeaderOut: 'windows/messages.g.h', + cppSourceOut: 'windows/messages.g.cpp', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Pigeon version of platform interface's ResolutionPreset. enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } diff --git a/packages/camera/camera_windows/pubspec.yaml b/packages/camera/camera_windows/pubspec.yaml index 284f053cd91..d064fa093a0 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 7d21af5f782..0bf34834671 100644 --- a/packages/camera/camera_windows/test/camera_windows_test.dart +++ b/packages/camera/camera_windows/test/camera_windows_test.dart @@ -35,9 +35,10 @@ void main() { // Act final int cameraId = await plugin.createCameraWithSettings( const CameraDescription( - name: cameraName, - lensDirection: CameraLensDirection.front, - sensorOrientation: 0), + name: cameraName, + lensDirection: CameraLensDirection.front, + sensorOrientation: 0, + ), const MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 15, @@ -47,8 +48,9 @@ void main() { ); // Assert - final VerificationResult verification = - verify(mockApi.create(captureAny, captureAny)); + final VerificationResult verification = verify( + mockApi.create(captureAny, captureAny), + ); expect(verification.captured[0], cameraName); final PlatformMediaSettings? settings = verification.captured[1] as PlatformMediaSettings?; @@ -58,37 +60,43 @@ void main() { }); test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - const String exceptionCode = 'TESTING_ERROR_CODE'; - const String exceptionMessage = - 'Mock error message used during testing.'; - final MockCameraApi mockApi = MockCameraApi(); - when(mockApi.create(any, any)).thenAnswer((_) async { - throw PlatformException( - code: exceptionCode, message: exceptionMessage); - }); - final CameraWindows camera = CameraWindows(api: mockApi); + 'Should throw CameraException when create throws a PlatformException', + () { + // Arrange + const String exceptionCode = 'TESTING_ERROR_CODE'; + const String exceptionMessage = + 'Mock error message used during testing.'; + final MockCameraApi mockApi = MockCameraApi(); + when(mockApi.create(any, any)).thenAnswer((_) async { + throw PlatformException( + code: exceptionCode, + message: exceptionMessage, + ); + }); + final CameraWindows camera = CameraWindows(api: mockApi); - // Act - expect( - () => camera.createCamera( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + // Act + expect( + () => camera.createCamera( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, + ), + ResolutionPreset.high, ), - ResolutionPreset.high, - ), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', exceptionCode) - .having((CameraException e) => e.description, 'description', - exceptionMessage), - ), - ); - }); + throwsA( + isA() + .having((CameraException e) => e.code, 'code', exceptionCode) + .having( + (CameraException e) => e.description, + 'description', + exceptionMessage, + ), + ), + ); + }, + ); test( 'Should throw CameraException when initialize throws a PlatformException', @@ -100,7 +108,9 @@ void main() { final MockCameraApi mockApi = MockCameraApi(); when(mockApi.initialize(any)).thenAnswer((_) async { throw PlatformException( - code: exceptionCode, message: exceptionMessage); + code: exceptionCode, + message: exceptionMessage, + ); }); final CameraWindows plugin = CameraWindows(api: mockApi); @@ -109,8 +119,11 @@ void main() { () => plugin.initializeCamera(0), throwsA( isA() - .having((CameraException e) => e.code, 'code', - 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) .having( (CameraException e) => e.description, 'description', @@ -124,8 +137,9 @@ void main() { test('Should send initialization data', () async { // Arrange final MockCameraApi mockApi = MockCameraApi(); - when(mockApi.initialize(any)) - .thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); + when( + mockApi.initialize(any), + ).thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); final CameraWindows plugin = CameraWindows(api: mockApi); final int cameraId = await plugin.createCameraWithSettings( const CameraDescription( @@ -146,16 +160,18 @@ void main() { await plugin.initializeCamera(cameraId); // Assert - final VerificationResult verification = - verify(mockApi.initialize(captureAny)); + final VerificationResult verification = verify( + mockApi.initialize(captureAny), + ); expect(verification.captured[0], cameraId); }); test('Should send a disposal call on dispose', () async { // Arrange final MockCameraApi mockApi = MockCameraApi(); - when(mockApi.initialize(any)) - .thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); + when( + mockApi.initialize(any), + ).thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); final CameraWindows plugin = CameraWindows(api: mockApi); final int cameraId = await plugin.createCameraWithSettings( const CameraDescription( @@ -177,8 +193,9 @@ void main() { await plugin.dispose(cameraId); // Assert - final VerificationResult verification = - verify(mockApi.dispose(captureAny)); + final VerificationResult verification = verify( + mockApi.dispose(captureAny), + ); expect(verification.captured[0], cameraId); }); }); @@ -189,8 +206,9 @@ void main() { setUp(() async { final MockCameraApi mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); - when(mockApi.initialize(any)) - .thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); + when( + mockApi.initialize(any), + ).thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); plugin = CameraWindows(api: mockApi); cameraId = await plugin.createCameraWithSettings( const CameraDescription( @@ -211,8 +229,9 @@ void main() { test('Should receive camera closing events', () async { // Act - final Stream eventStream = - plugin.onCameraClosing(cameraId); + final Stream eventStream = plugin.onCameraClosing( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -233,8 +252,9 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = - plugin.onCameraError(cameraId); + final Stream errorStream = plugin.onCameraError( + cameraId, + ); final StreamQueue streamQueue = StreamQueue(errorStream); @@ -263,8 +283,9 @@ void main() { setUp(() async { mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); - when(mockApi.initialize(any)) - .thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); + when( + mockApi.initialize(any), + ).thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); plugin = CameraWindows(api: mockApi); cameraId = await plugin.createCameraWithSettings( const CameraDescription( @@ -284,50 +305,60 @@ void main() { clearInteractions(mockApi); }); - test('Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final List returnData = [ - 'Test 1', - 'Test 2', - ]; - when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); - - // Act - final List cameras = await plugin.availableCameras(); + test( + 'Should fetch CameraDescription instances for available cameras', + () async { + // Arrange + final List returnData = ['Test 1', 'Test 2']; + when( + mockApi.getAvailableCameras(), + ).thenAnswer((_) async => returnData); - // Assert - expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { - expect(cameras[i].name, returnData[i]); - // This value isn't provided by the platform, so is hard-coded to front. - expect(cameras[i].lensDirection, CameraLensDirection.front); - // This value isn't provided by the platform, so is hard-coded to 0. - expect(cameras[i].sensorOrientation, 0); - } - }); + // Act + final List cameras = + await plugin.availableCameras(); + + // Assert + expect(cameras.length, returnData.length); + for (int i = 0; i < returnData.length; i++) { + expect(cameras[i].name, returnData[i]); + // This value isn't provided by the platform, so is hard-coded to front. + expect(cameras[i].lensDirection, CameraLensDirection.front); + // This value isn't provided by the platform, so is hard-coded to 0. + expect(cameras[i].sensorOrientation, 0); + } + }, + ); test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - // Arrange - const String code = 'TESTING_ERROR_CODE'; - const String message = 'Mock error message used during testing.'; - when(mockApi.getAvailableCameras()).thenAnswer( - (_) async => throw PlatformException(code: code, message: message)); + 'Should throw CameraException when availableCameras throws a PlatformException', + () { + // Arrange + const String code = 'TESTING_ERROR_CODE'; + const String message = 'Mock error message used during testing.'; + when(mockApi.getAvailableCameras()).thenAnswer( + (_) async => throw PlatformException(code: code, message: message), + ); - // Act - expect( - plugin.availableCameras, - throwsA( - isA() - .having( - (CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') - .having((CameraException e) => e.description, 'description', - 'Mock error message used during testing.'), - ), - ); - }); + // Act + expect( + plugin.availableCameras, + throwsA( + isA() + .having( + (CameraException e) => e.code, + 'code', + 'TESTING_ERROR_CODE', + ) + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }, + ); test('Should take a picture and return an XFile instance', () async { // Arrange @@ -360,8 +391,12 @@ void main() { test('capturing fails if trying to stream', () async { // Act and Assert expect( - () => plugin.startVideoCapturing(VideoCaptureOptions(cameraId, - streamCallback: (CameraImageData imageData) {})), + () => plugin.startVideoCapturing( + VideoCaptureOptions( + cameraId, + streamCallback: (CameraImageData imageData) {}, + ), + ), throwsA(isA()), ); }); @@ -378,24 +413,27 @@ void main() { expect(file.path, '/test/path.mp4'); }); - test('Should throw UnsupportedError when pause video recording is called', - () async { - // Act - expect( - () => plugin.pauseVideoRecording(cameraId), - throwsA(isA()), - ); - }); + test( + 'Should throw UnsupportedError when pause video recording is called', + () async { + // Act + expect( + () => plugin.pauseVideoRecording(cameraId), + throwsA(isA()), + ); + }, + ); test( - 'Should throw UnsupportedError when resume video recording is called', - () async { - // Act - expect( - () => plugin.resumeVideoRecording(cameraId), - throwsA(isA()), - ); - }); + 'Should throw UnsupportedError when resume video recording is called', + () async { + // Act + expect( + () => plugin.resumeVideoRecording(cameraId), + throwsA(isA()), + ); + }, + ); test('Should throw UnimplementedError when flash mode is set', () async { // Act @@ -405,28 +443,33 @@ void main() { ); }); - test('Should throw UnimplementedError when exposure mode is set', - () async { - // Act - expect( - () => plugin.setExposureMode(cameraId, ExposureMode.auto), - throwsA(isA()), - ); - }); + test( + 'Should throw UnimplementedError when exposure mode is set', + () async { + // Act + expect( + () => plugin.setExposureMode(cameraId, ExposureMode.auto), + throwsA(isA()), + ); + }, + ); - test('Should throw UnsupportedError when exposure point is set', - () async { - // Act - expect( - () => plugin.setExposurePoint(cameraId, null), - throwsA(isA()), - ); - }); + test( + 'Should throw UnsupportedError when exposure point is set', + () async { + // Act + expect( + () => plugin.setExposurePoint(cameraId, null), + throwsA(isA()), + ); + }, + ); test('Should get the min exposure offset', () async { // Act - final double minExposureOffset = - await plugin.getMinExposureOffset(cameraId); + final double minExposureOffset = await plugin.getMinExposureOffset( + cameraId, + ); // Assert expect(minExposureOffset, 0.0); @@ -434,8 +477,9 @@ void main() { test('Should get the max exposure offset', () async { // Act - final double maxExposureOffset = - await plugin.getMaxExposureOffset(cameraId); + final double maxExposureOffset = await plugin.getMaxExposureOffset( + cameraId, + ); // Assert expect(maxExposureOffset, 0.0); @@ -443,21 +487,24 @@ void main() { test('Should get the exposure offset step size', () async { // Act - final double stepSize = - await plugin.getExposureOffsetStepSize(cameraId); + final double stepSize = await plugin.getExposureOffsetStepSize( + cameraId, + ); // Assert expect(stepSize, 1.0); }); - test('Should throw UnimplementedError when exposure offset is set', - () async { - // Act - expect( - () => plugin.setExposureOffset(cameraId, 0.5), - throwsA(isA()), - ); - }); + test( + 'Should throw UnimplementedError when exposure offset is set', + () async { + // Act + expect( + () => plugin.setExposureOffset(cameraId, 0.5), + throwsA(isA()), + ); + }, + ); test('Should throw UnimplementedError when focus mode is set', () async { // Act @@ -467,14 +514,16 @@ void main() { ); }); - test('Should throw UnsupportedError when exposure point is set', - () async { - // Act - expect( - () => plugin.setFocusMode(cameraId, FocusMode.auto), - throwsA(isA()), - ); - }); + test( + 'Should throw UnsupportedError when exposure point is set', + () async { + // Act + expect( + () => plugin.setFocusMode(cameraId, FocusMode.auto), + throwsA(isA()), + ); + }, + ); test('Should build a texture widget as preview widget', () async { // Act @@ -510,32 +559,35 @@ void main() { }); test( - 'Should throw UnimplementedError when lock capture orientation is called', - () async { - // Act - expect( - () => plugin.setZoomLevel(cameraId, 2.0), - throwsA(isA()), - ); - }); + 'Should throw UnimplementedError when lock capture orientation is called', + () async { + // Act + expect( + () => plugin.setZoomLevel(cameraId, 2.0), + throwsA(isA()), + ); + }, + ); test( - 'Should throw UnimplementedError when unlock capture orientation is called', - () async { - // Act - expect( - () => plugin.unlockCaptureOrientation(cameraId), - throwsA(isA()), - ); - }); + 'Should throw UnimplementedError when unlock capture orientation is called', + () async { + // Act + expect( + () => plugin.unlockCaptureOrientation(cameraId), + throwsA(isA()), + ); + }, + ); test('Should pause the camera preview', () async { // Act await plugin.pausePreview(cameraId); // Assert - final VerificationResult verification = - verify(mockApi.pausePreview(captureAny)); + final VerificationResult verification = verify( + mockApi.pausePreview(captureAny), + ); expect(verification.captured[0], cameraId); }); @@ -544,8 +596,9 @@ void main() { await plugin.resumePreview(cameraId); // Assert - final VerificationResult verification = - verify(mockApi.resumePreview(captureAny)); + final VerificationResult verification = verify( + mockApi.resumePreview(captureAny), + ); expect(verification.captured[0], cameraId); }); }); diff --git a/packages/camera/camera_windows/test/camera_windows_test.mocks.dart b/packages/camera/camera_windows/test/camera_windows_test.mocks.dart index 7e22e173918..c81dceca765 100644 --- a/packages/camera/camera_windows/test/camera_windows_test.mocks.dart +++ b/packages/camera/camera_windows/test/camera_windows_test.mocks.dart @@ -23,13 +23,8 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: subtype_of_sealed_class class _FakePlatformSize_0 extends _i1.SmartFake implements _i2.PlatformSize { - _FakePlatformSize_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformSize_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [CameraApi]. @@ -37,27 +32,30 @@ class _FakePlatformSize_0 extends _i1.SmartFake implements _i2.PlatformSize { /// See the documentation for Mockito's code generation for more information. class MockCameraApi extends _i1.Mock implements _i2.CameraApi { @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override - _i4.Future> getAvailableCameras() => (super.noSuchMethod( - Invocation.method( - #getAvailableCameras, - [], - ), - returnValue: _i4.Future>.value([]), - returnValueForMissingStub: _i4.Future>.value([]), - ) as _i4.Future>); + _i4.Future> getAvailableCameras() => + (super.noSuchMethod( + Invocation.method(#getAvailableCameras, []), + returnValue: _i4.Future>.value([]), + returnValueForMissingStub: _i4.Future>.value( + [], + ), + ) + as _i4.Future>); @override _i4.Future create( @@ -65,143 +63,120 @@ class MockCameraApi extends _i1.Mock implements _i2.CameraApi { _i2.PlatformMediaSettings? settings, ) => (super.noSuchMethod( - Invocation.method( - #create, - [ - cameraName, - settings, - ], - ), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) as _i4.Future); + Invocation.method(#create, [cameraName, settings]), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) + as _i4.Future); @override - _i4.Future<_i2.PlatformSize> initialize(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #initialize, - [cameraId], - ), - returnValue: _i4.Future<_i2.PlatformSize>.value(_FakePlatformSize_0( - this, - Invocation.method( - #initialize, - [cameraId], - ), - )), - returnValueForMissingStub: - _i4.Future<_i2.PlatformSize>.value(_FakePlatformSize_0( - this, - Invocation.method( - #initialize, - [cameraId], - ), - )), - ) as _i4.Future<_i2.PlatformSize>); + _i4.Future<_i2.PlatformSize> initialize(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#initialize, [cameraId]), + returnValue: _i4.Future<_i2.PlatformSize>.value( + _FakePlatformSize_0( + this, + Invocation.method(#initialize, [cameraId]), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformSize>.value( + _FakePlatformSize_0( + this, + Invocation.method(#initialize, [cameraId]), + ), + ), + ) + as _i4.Future<_i2.PlatformSize>); @override - _i4.Future dispose(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #dispose, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future dispose(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#dispose, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future takePicture(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #takePicture, - [cameraId], - ), - returnValue: _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #takePicture, - [cameraId], - ), - )), - returnValueForMissingStub: - _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #takePicture, - [cameraId], - ), - )), - ) as _i4.Future); + _i4.Future takePicture(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#takePicture, [cameraId]), + returnValue: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#takePicture, [cameraId]), + ), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#takePicture, [cameraId]), + ), + ), + ) + as _i4.Future); @override - _i4.Future startVideoRecording(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #startVideoRecording, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future startVideoRecording(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#startVideoRecording, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future stopVideoRecording(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #stopVideoRecording, - [cameraId], - ), - returnValue: _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #stopVideoRecording, - [cameraId], - ), - )), - returnValueForMissingStub: - _i4.Future.value(_i3.dummyValue( - this, - Invocation.method( - #stopVideoRecording, - [cameraId], - ), - )), - ) as _i4.Future); + _i4.Future stopVideoRecording(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#stopVideoRecording, [cameraId]), + returnValue: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#stopVideoRecording, [cameraId]), + ), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#stopVideoRecording, [cameraId]), + ), + ), + ) + as _i4.Future); @override - _i4.Future startImageStream(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #startImageStream, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future startImageStream(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#startImageStream, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future stopImageStream(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #stopImageStream, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future stopImageStream(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#stopImageStream, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future pausePreview(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #pausePreview, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future pausePreview(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#pausePreview, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future resumePreview(int? cameraId) => (super.noSuchMethod( - Invocation.method( - #resumePreview, - [cameraId], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future resumePreview(int? cameraId) => + (super.noSuchMethod( + Invocation.method(#resumePreview, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/cross_file/CHANGELOG.md b/packages/cross_file/CHANGELOG.md index fc9852568d3..8db113b687e 100644 --- a/packages/cross_file/CHANGELOG.md +++ b/packages/cross_file/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.3.4+2 diff --git a/packages/cross_file/example/pubspec.yaml b/packages/cross_file/example/pubspec.yaml index d76125b84b1..8bb5355bdec 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.6.0 + sdk: ^3.7.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 8bc5361bbfb..b1ce6f5d767 100644 --- a/packages/cross_file/lib/src/types/html.dart +++ b/packages/cross_file/lib/src/types/html.dart @@ -36,13 +36,13 @@ class XFile extends XFileBase { Uint8List? bytes, DateTime? lastModified, @visibleForTesting CrossFileTestOverrides? overrides, - }) : _mimeType = mimeType, - _path = path, - _length = length, - _overrides = overrides, - _lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0), - _name = name ?? '', - super(path) { + }) : _mimeType = mimeType, + _path = path, + _length = length, + _overrides = overrides, + _lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0), + _name = name ?? '', + super(path) { // Cache `bytes` as Blob, if passed. if (bytes != null) { _browserBlob = _createBlobFromBytes(bytes, mimeType); @@ -58,12 +58,12 @@ class XFile extends XFileBase { DateTime? lastModified, String? path, @visibleForTesting CrossFileTestOverrides? overrides, - }) : _mimeType = mimeType, - _length = length, - _overrides = overrides, - _lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0), - _name = name ?? '', - super(path) { + }) : _mimeType = mimeType, + _length = length, + _overrides = overrides, + _lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0), + _name = name ?? '', + super(path) { if (path == null) { _browserBlob = _createBlobFromBytes(bytes, mimeType); _path = URL.createObjectURL(_browserBlob!); @@ -77,7 +77,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. @@ -136,21 +138,27 @@ 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; } @@ -208,9 +216,11 @@ 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/lib/src/types/interface.dart b/packages/cross_file/lib/src/types/interface.dart index c83e5734d32..eacfdc5ccec 100644 --- a/packages/cross_file/lib/src/types/interface.dart +++ b/packages/cross_file/lib/src/types/interface.dart @@ -31,7 +31,8 @@ class XFile extends XFileBase { @visibleForTesting CrossFileTestOverrides? overrides, }) { throw UnimplementedError( - 'CrossFile is not available in your current platform.'); + 'CrossFile is not available in your current platform.', + ); } /// Construct a CrossFile object from its data @@ -45,7 +46,8 @@ class XFile extends XFileBase { @visibleForTesting CrossFileTestOverrides? overrides, }) : super(path) { throw UnimplementedError( - 'CrossFile is not available in your current platform.'); + 'CrossFile is not available in your current platform.', + ); } } diff --git a/packages/cross_file/lib/src/types/io.dart b/packages/cross_file/lib/src/types/io.dart index a6979e53498..353f966356c 100644 --- a/packages/cross_file/lib/src/types/io.dart +++ b/packages/cross_file/lib/src/types/io.dart @@ -32,11 +32,11 @@ class XFile extends XFileBase { int? length, Uint8List? bytes, DateTime? lastModified, - }) : _mimeType = mimeType, - _file = File(path), - _bytes = null, - _lastModified = lastModified, - super(path); + }) : _mimeType = mimeType, + _file = File(path), + _bytes = null, + _lastModified = lastModified, + super(path); /// Construct an CrossFile from its data /// @@ -49,12 +49,12 @@ class XFile extends XFileBase { String? name, int? length, DateTime? lastModified, - }) : _mimeType = mimeType, - _bytes = bytes, - _file = File(path ?? ''), - _length = length, - _lastModified = lastModified, - super(path) { + }) : _mimeType = mimeType, + _bytes = bytes, + _file = File(path ?? ''), + _length = length, + _lastModified = lastModified, + super(path) { if (length == null) { _length = bytes.length; } diff --git a/packages/cross_file/pubspec.yaml b/packages/cross_file/pubspec.yaml index a7b25984808..13e5474fbf9 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.4+2 environment: - sdk: ^3.6.0 + sdk: ^3.7.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 dedd8806f01..9f038b2c4ce 100644 --- a/packages/cross_file/test/x_file_html_test.dart +++ b/packages/cross_file/test/x_file_html_test.dart @@ -15,12 +15,14 @@ import 'package:web/web.dart' as html; const String expectedStringContents = 'Hello, world! I ❤ ñ! 空手'; final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents)); -final html.File textFile = - html.File([bytes.toJS].toJS, 'hello.txt'); +final html.File textFile = html.File( + [bytes.toJS].toJS, + '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', () { @@ -94,8 +96,9 @@ void main() { await file.saveTo(''); - final html.Element? container = - html.document.querySelector('#$crossFileDomElementId'); + final html.Element? container = html.document.querySelector( + '#$crossFileDomElementId', + ); expect(container, isNotNull); }); @@ -130,8 +133,11 @@ void main() { createAnchorElement: (_, __) => mockAnchor, ); - final XFile file = - XFile.fromData(bytes, name: textFile.name, overrides: overrides); + final XFile file = XFile.fromData( + bytes, + name: textFile.name, + overrides: overrides, + ); bool clicked = false; mockAnchor.onClick.listen((html.MouseEvent event) => clicked = true); diff --git a/packages/espresso/CHANGELOG.md b/packages/espresso/CHANGELOG.md index 60b8d79482e..76b49d74b3b 100644 --- a/packages/espresso/CHANGELOG.md +++ b/packages/espresso/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.4.0+7 * Removes obsolete code related to supporting SDK <21. diff --git a/packages/espresso/example/pubspec.yaml b/packages/espresso/example/pubspec.yaml index 9d9dbc1a500..85d482f4eb2 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/espresso/pubspec.yaml b/packages/espresso/pubspec.yaml index bba71351f0f..f9e24e15523 100644 --- a/packages/espresso/pubspec.yaml +++ b/packages/espresso/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.4.0+7 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: 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 6ce508403a2..13720c1e0c9 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md +++ b/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 3.0.0 * **BREAKING CHANGES**: diff --git a/packages/extension_google_sign_in_as_googleapis_auth/README.md b/packages/extension_google_sign_in_as_googleapis_auth/README.md index 4a6fb1aca1f..6490974fd30 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/README.md +++ b/packages/extension_google_sign_in_as_googleapis_auth/README.md @@ -27,11 +27,8 @@ import 'package:googleapis_auth/googleapis_auth.dart' as auth show AuthClient; // Prepare a People Service authenticated client. final PeopleServiceApi peopleApi = PeopleServiceApi(client); // Retrieve a list of connected contacts' names. - final ListConnectionsResponse response = - await peopleApi.people.connections.list( - 'people/me', - personFields: 'names', - ); + final ListConnectionsResponse response = await peopleApi.people.connections + .list('people/me', personFields: 'names'); ``` ## Example diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart b/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart index dd59b43c7af..b2f5683fe9b 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart @@ -19,10 +19,7 @@ const List scopes = [PeopleServiceApi.contactsReadonlyScope]; void main() { runApp( - const MaterialApp( - title: 'Google Sign In + googleapis', - home: SignInDemo(), - ), + const MaterialApp(title: 'Google Sign In + googleapis', home: SignInDemo()), ); } @@ -48,28 +45,30 @@ class SignInDemoState extends State { final GoogleSignIn signIn = GoogleSignIn.instance; _signInInitialized = signIn.initialize( - // Add your client IDs here as necessary for your supported platforms. - ); - signIn.authenticationEvents.listen((GoogleSignInAuthenticationEvent event) { - if (!mounted) { - return; - } - setState(() { - switch (event) { - case GoogleSignInAuthenticationEventSignIn(): - _currentUser = event.user; - case GoogleSignInAuthenticationEventSignOut(): - _currentUser = null; - _authorization = null; - } - }); - - if (_currentUser != null) { - _checkAuthorization(); - } - }).onError((Object error) { - debugPrint(error.toString()); - }); + // Add your client IDs here as necessary for your supported platforms. + ); + signIn.authenticationEvents + .listen((GoogleSignInAuthenticationEvent event) { + if (!mounted) { + return; + } + setState(() { + switch (event) { + case GoogleSignInAuthenticationEventSignIn(): + _currentUser = event.user; + case GoogleSignInAuthenticationEventSignOut(): + _currentUser = null; + _authorization = null; + } + }); + + if (_currentUser != null) { + _checkAuthorization(); + } + }) + .onError((Object error) { + debugPrint(error.toString()); + }); _signInInitialized.then((void value) { signIn.attemptLightweightAuthentication(); @@ -91,16 +90,21 @@ class SignInDemoState extends State { Future _checkAuthorization() async { _updateAuthorization( - await _currentUser?.authorizationClient.authorizationForScopes(scopes)); + await _currentUser?.authorizationClient.authorizationForScopes(scopes), + ); } Future _requestAuthorization() async { - _updateAuthorization(await _currentUser?.authorizationClient - .authorizeScopes([PeopleServiceApi.contactsReadonlyScope])); + _updateAuthorization( + await _currentUser?.authorizationClient.authorizeScopes([ + PeopleServiceApi.contactsReadonlyScope, + ]), + ); } Future _handleGetContact( - GoogleSignInClientAuthorization authorization) async { + GoogleSignInClientAuthorization authorization, + ) async { if (!mounted) { return; } @@ -115,15 +119,13 @@ class SignInDemoState extends State { // Prepare a People Service authenticated client. final PeopleServiceApi peopleApi = PeopleServiceApi(client); // Retrieve a list of connected contacts' names. - final ListConnectionsResponse response = - await peopleApi.people.connections.list( - 'people/me', - personFields: 'names', - ); + final ListConnectionsResponse response = await peopleApi.people.connections + .list('people/me', personFields: 'names'); // #enddocregion CreateAPIClient - final String? firstNamedContactName = - _pickFirstNamedContact(response.connections); + final String? firstNamedContactName = _pickFirstNamedContact( + response.connections, + ); if (mounted) { setState(() { @@ -138,13 +140,9 @@ class SignInDemoState extends State { String? _pickFirstNamedContact(List? connections) { return connections - ?.firstWhere( - (Person person) => person.names != null, - ) + ?.firstWhere((Person person) => person.names != null) .names - ?.firstWhere( - (Name name) => name.displayName != null, - ) + ?.firstWhere((Name name) => name.displayName != null) .displayName; } @@ -161,72 +159,66 @@ class SignInDemoState extends State { Widget _buildBody() { return FutureBuilder( - future: _signInInitialized, - builder: (BuildContext context, AsyncSnapshot snapshot) { - final GoogleSignInAccount? user = _currentUser; - final GoogleSignInClientAuthorization? authorization = _authorization; - final List children; - if (snapshot.hasError) { - children = [ - const Text('Error initializing sign in.'), - ]; - } else if (snapshot.connectionState == ConnectionState.done) { - children = [ - if (user != null) ...[ - ListTile( - leading: GoogleUserCircleAvatar( - identity: user, - ), - title: Text(user.displayName ?? ''), - subtitle: Text(user.email), - ), - const Text('Signed in successfully.'), - if (authorization != null) ...[ - Text(_contactText), - ElevatedButton( - onPressed: () => _handleGetContact(authorization), - child: const Text('REFRESH'), - ), - ] else ...[ - ElevatedButton( - onPressed: _requestAuthorization, - child: const Text('LOAD CONTACTS'), - ), - ], + future: _signInInitialized, + builder: (BuildContext context, AsyncSnapshot snapshot) { + final GoogleSignInAccount? user = _currentUser; + final GoogleSignInClientAuthorization? authorization = _authorization; + final List children; + if (snapshot.hasError) { + children = [const Text('Error initializing sign in.')]; + } else if (snapshot.connectionState == ConnectionState.done) { + children = [ + if (user != null) ...[ + ListTile( + leading: GoogleUserCircleAvatar(identity: user), + title: Text(user.displayName ?? ''), + subtitle: Text(user.email), + ), + const Text('Signed in successfully.'), + if (authorization != null) ...[ + Text(_contactText), ElevatedButton( - onPressed: _handleSignOut, - child: const Text('SIGN OUT'), + onPressed: () => _handleGetContact(authorization), + child: const Text('REFRESH'), ), ] else ...[ - const Text('You are not currently signed in.'), ElevatedButton( - onPressed: _handleSignIn, - child: const Text('SIGN IN'), + onPressed: _requestAuthorization, + child: const Text('LOAD CONTACTS'), ), ], - ]; - } else { - children = [ - const CircularProgressIndicator(), - ]; - } + ElevatedButton( + onPressed: _handleSignOut, + child: const Text('SIGN OUT'), + ), + ] else ...[ + const Text('You are not currently signed in.'), + ElevatedButton( + onPressed: _handleSignIn, + child: const Text('SIGN IN'), + ), + ], + ]; + } else { + children = [const CircularProgressIndicator()]; + } - return Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: children, - ); - }); + return Column( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: children, + ); + }, + ); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Google Sign In + googleapis'), - ), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - )); + appBar: AppBar(title: const Text('Google Sign In + googleapis')), + body: ConstrainedBox( + constraints: const BoxConstraints.expand(), + child: _buildBody(), + ), + ); } } 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 ab40142c25a..8a297916798 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: extension_google_sign_in_as_googleapis_auth: diff --git a/packages/extension_google_sign_in_as_googleapis_auth/lib/extension_google_sign_in_as_googleapis_auth.dart b/packages/extension_google_sign_in_as_googleapis_auth/lib/extension_google_sign_in_as_googleapis_auth.dart index 1d9091ee08a..f26a8337ed1 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/lib/extension_google_sign_in_as_googleapis_auth.dart +++ b/packages/extension_google_sign_in_as_googleapis_auth/lib/extension_google_sign_in_as_googleapis_auth.dart @@ -15,9 +15,7 @@ extension GoogleApisGoogleSignInAuth on GoogleSignInClientAuthorization { /// The [scopes] passed here should be the same as the scopes used to request /// the authorization. Passing scopes here that have not been authorized will /// likely result in API errors when using the client. - gapis.AuthClient authClient({ - required List scopes, - }) { + gapis.AuthClient authClient({required List scopes}) { final gapis.AccessCredentials credentials = gapis.AccessCredentials( gapis.AccessToken( 'Bearer', 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 062a46e0027..c36b2a630e2 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart b/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart index 5cf8429b1a1..f57baf549ee 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart +++ b/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart @@ -16,15 +16,18 @@ class FakeGoogleSignInClientAuthorization extends Fake } void main() { - test('authClient returned client contains the expected information', - () async { - const List scopes = ['some-scope', 'another-scope']; - final FakeGoogleSignInClientAuthorization signInAuth = - FakeGoogleSignInClientAuthorization(); - final gapis.AuthClient client = signInAuth.authClient( - scopes: scopes, - ); - expect(client.credentials.accessToken.data, equals(SOME_FAKE_ACCESS_TOKEN)); - expect(client.credentials.scopes, equals(scopes)); - }); + test( + 'authClient returned client contains the expected information', + () async { + const List scopes = ['some-scope', 'another-scope']; + final FakeGoogleSignInClientAuthorization signInAuth = + FakeGoogleSignInClientAuthorization(); + final gapis.AuthClient client = signInAuth.authClient(scopes: scopes); + expect( + client.credentials.accessToken.data, + equals(SOME_FAKE_ACCESS_TOKEN), + ); + expect(client.credentials.scopes, equals(scopes)); + }, + ); } diff --git a/packages/file_selector/file_selector/CHANGELOG.md b/packages/file_selector/file_selector/CHANGELOG.md index 6f51955393b..b9ed354daa1 100644 --- a/packages/file_selector/file_selector/CHANGELOG.md +++ b/packages/file_selector/file_selector/CHANGELOG.md @@ -1,7 +1,7 @@ ## NEXT +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. * Updates README to indicate that Andoid SDK <21 is no longer supported. -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. ## 1.0.3 diff --git a/packages/file_selector/file_selector/README.md b/packages/file_selector/file_selector/README.md index 13327f9e1db..3339d57c260 100644 --- a/packages/file_selector/file_selector/README.md +++ b/packages/file_selector/file_selector/README.md @@ -39,8 +39,9 @@ const XTypeGroup typeGroup = XTypeGroup( label: 'images', extensions: ['jpg', 'png'], ); -final XFile? file = - await openFile(acceptedTypeGroups: [typeGroup]); +final XFile? file = await openFile( + acceptedTypeGroups: [typeGroup], +); ``` #### Open multiple files at once @@ -55,10 +56,9 @@ const XTypeGroup pngTypeGroup = XTypeGroup( label: 'PNGs', extensions: ['png'], ); -final List files = await openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, -]); +final List files = await openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], +); ``` #### Save a file @@ -66,8 +66,9 @@ final List files = await openFiles(acceptedTypeGroups: [ ```dart const String fileName = 'suggested_name.txt'; -final FileSaveLocation? result = - await getSaveLocation(suggestedName: fileName); +final FileSaveLocation? result = await getSaveLocation( + suggestedName: fileName, +); if (result == null) { // Operation was canceled by the user. return; @@ -75,8 +76,11 @@ if (result == null) { final Uint8List fileData = Uint8List.fromList('Hello World!'.codeUnits); const String mimeType = 'text/plain'; -final XFile textFile = - XFile.fromData(fileData, mimeType: mimeType, name: fileName); +final XFile textFile = XFile.fromData( + fileData, + mimeType: mimeType, + name: fileName, +); await textFile.saveTo(result.path); ``` diff --git a/packages/file_selector/file_selector/example/lib/get_directory_page.dart b/packages/file_selector/file_selector/example/lib/get_directory_page.dart index 6066374b3aa..79c138d5240 100644 --- a/packages/file_selector/file_selector/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector/example/lib/get_directory_page.dart @@ -33,9 +33,7 @@ class GetDirectoryPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -46,9 +44,7 @@ class GetDirectoryPage extends StatelessWidget { foregroundColor: Colors.white, ), onPressed: _isIOS ? null : () => _getDirectoryPath(context), - child: const Text( - 'Press to ask user to choose a directory.', - ), + child: const Text('Press to ask user to choose a directory.'), ), ], ), @@ -70,9 +66,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directory'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoryPath), - ), + child: SingleChildScrollView(child: Text(directoryPath)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart index 56d8e67e4cf..86bcfcffe95 100644 --- a/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart @@ -35,9 +35,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Select multiple directories'), - ), + appBar: AppBar(title: const Text('Select multiple directories')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -48,7 +46,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { foregroundColor: Colors.white, ), child: const Text( - 'Press to ask user to choose multiple directories'), + 'Press to ask user to choose multiple directories', + ), onPressed: () => _getDirectoryPaths(context), ), ], @@ -71,9 +70,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directories'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoriesPaths), - ), + child: SingleChildScrollView(child: Text(directoriesPaths)), ), actions: [ TextButton( 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 f46a6bbd6bb..14761fc8a7f 100644 --- a/packages/file_selector/file_selector/example/lib/home_page.dart +++ b/packages/file_selector/file_selector/example/lib/home_page.dart @@ -19,9 +19,7 @@ class HomePage extends StatelessWidget { foregroundColor: Colors.white, ); return Scaffold( - appBar: AppBar( - title: const Text('File Selector Demo Home Page'), - ), + appBar: AppBar(title: const Text('File Selector Demo Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -66,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 19ef8c0242f..4163289c011 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_image_page.dart b/packages/file_selector/file_selector/example/lib/open_image_page.dart index 3b36f686683..2694e1144c6 100644 --- a/packages/file_selector/file_selector/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector/example/lib/open_image_page.dart @@ -19,8 +19,9 @@ class OpenImagePage extends StatelessWidget { label: 'images', extensions: ['jpg', 'png'], ); - final XFile? file = - await openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await openFile( + acceptedTypeGroups: [typeGroup], + ); // #enddocregion SingleOpen if (file == null) { // Operation was canceled by the user. @@ -40,9 +41,7 @@ class OpenImagePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open an image'), - ), + appBar: AppBar(title: const Text('Open an image')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, 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 4cb49c02a27..28bfeaa53d6 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 @@ -23,10 +23,9 @@ class OpenMultipleImagesPage extends StatelessWidget { label: 'PNGs', extensions: ['png'], ); - final List files = await openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, - ]); + final List files = await openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], + ); // #enddocregion MultiOpen if (files.isEmpty) { // Operation was canceled by the user. @@ -43,9 +42,7 @@ class OpenMultipleImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open multiple images'), - ), + appBar: AppBar(title: const Text('Open multiple images')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -84,10 +81,12 @@ 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 e9eb48b720d..e5c123aaadb 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 @@ -44,9 +44,7 @@ class OpenTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -82,9 +80,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: Text(fileName), content: Scrollbar( - child: SingleChildScrollView( - child: Text(fileContent), - ), + child: SingleChildScrollView(child: Text(fileContent)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart b/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart index cc0a051e218..d2e681d5a35 100644 --- a/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart +++ b/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart @@ -28,9 +28,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('README snippet app'), - ), + appBar: AppBar(title: const Text('README snippet app')), body: const Text('See example in main.dart'), ), ); @@ -39,8 +37,9 @@ class _MyAppState extends State { Future saveFile() async { // #docregion Save const String fileName = 'suggested_name.txt'; - final FileSaveLocation? result = - await getSaveLocation(suggestedName: fileName); + final FileSaveLocation? result = await getSaveLocation( + suggestedName: fileName, + ); if (result == null) { // Operation was canceled by the user. return; @@ -48,8 +47,11 @@ class _MyAppState extends State { final Uint8List fileData = Uint8List.fromList('Hello World!'.codeUnits); const String mimeType = 'text/plain'; - final XFile textFile = - XFile.fromData(fileData, mimeType: mimeType, name: fileName); + final XFile textFile = XFile.fromData( + fileData, + mimeType: mimeType, + name: fileName, + ); await textFile.saveTo(result.path); // #enddocregion Save } 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 a8938fa6db8..f83e953e76a 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,9 +23,10 @@ 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, @@ -38,8 +39,11 @@ class SaveTextPage extends StatelessWidget { final String text = _contentController.text; final Uint8List fileData = Uint8List.fromList(text.codeUnits); const String fileMimeType = 'text/plain'; - final XFile textFile = - XFile.fromData(fileData, mimeType: fileMimeType, name: fileName); + final XFile textFile = XFile.fromData( + fileData, + mimeType: fileMimeType, + name: fileName, + ); await textFile.saveTo(result.path); } @@ -47,9 +51,7 @@ class SaveTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Save text into a file'), - ), + appBar: AppBar(title: const Text('Save text into a file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -83,9 +85,7 @@ class SaveTextPage extends StatelessWidget { foregroundColor: Colors.white, ), onPressed: _isIOS ? null : () => _saveFile(), - child: const Text( - 'Press to save a text file.', - ), + child: const Text('Press to save a text file.'), ), ], ), diff --git a/packages/file_selector/file_selector/example/pubspec.yaml b/packages/file_selector/file_selector/example/pubspec.yaml index 3999fbb4c60..bd8a1c0881b 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: file_selector: diff --git a/packages/file_selector/file_selector/lib/file_selector.dart b/packages/file_selector/file_selector/lib/file_selector.dart index f489e0bacba..3220bac4ff3 100644 --- a/packages/file_selector/file_selector/lib/file_selector.dart +++ b/packages/file_selector/file_selector/lib/file_selector.dart @@ -35,9 +35,10 @@ Future openFile({ String? confirmButtonText, }) { return FileSelectorPlatform.instance.openFile( - acceptedTypeGroups: acceptedTypeGroups, - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText); + acceptedTypeGroups: acceptedTypeGroups, + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ); } /// Opens a file selection dialog and returns the list of paths chosen by the @@ -66,9 +67,10 @@ Future> openFiles({ String? confirmButtonText, }) { return FileSelectorPlatform.instance.openFiles( - acceptedTypeGroups: acceptedTypeGroups, - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText); + acceptedTypeGroups: acceptedTypeGroups, + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ); } /// Opens a save dialog and returns the target path chosen by the user. @@ -99,11 +101,13 @@ Future getSaveLocation({ String? confirmButtonText, }) async { return FileSelectorPlatform.instance.getSaveLocation( - acceptedTypeGroups: acceptedTypeGroups, - options: SaveDialogOptions( - initialDirectory: initialDirectory, - suggestedName: suggestedName, - confirmButtonText: confirmButtonText)); + acceptedTypeGroups: acceptedTypeGroups, + options: SaveDialogOptions( + initialDirectory: initialDirectory, + suggestedName: suggestedName, + confirmButtonText: confirmButtonText, + ), + ); } /// Opens a directory selection dialog and returns the path chosen by the user. @@ -123,7 +127,9 @@ Future getDirectoryPath({ String? confirmButtonText, }) async { return FileSelectorPlatform.instance.getDirectoryPath( - initialDirectory: initialDirectory, confirmButtonText: confirmButtonText); + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ); } /// Opens a directory selection dialog and returns a list of the paths chosen @@ -144,5 +150,7 @@ Future> getDirectoryPaths({ String? confirmButtonText, }) async { return FileSelectorPlatform.instance.getDirectoryPaths( - initialDirectory: initialDirectory, confirmButtonText: confirmButtonText); + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ); } diff --git a/packages/file_selector/file_selector/pubspec.yaml b/packages/file_selector/file_selector/pubspec.yaml index 6fc31542a7b..028209dd94f 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.3 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 5de1ca5b9bb..56bd7c3dfb3 100644 --- a/packages/file_selector/file_selector/test/file_selector_test.dart +++ b/packages/file_selector/file_selector/test/file_selector_test.dart @@ -13,14 +13,14 @@ void main() { const String confirmButtonText = 'Use this profile picture'; const String suggestedName = 'suggested_name'; const List acceptedTypeGroups = [ - XTypeGroup(label: 'documents', mimeTypes: [ - 'application/msword', - 'application/vnd.openxmlformats-officedocument.wordprocessing', - ]), - XTypeGroup(label: 'images', extensions: [ - 'jpg', - 'png', - ]), + XTypeGroup( + label: 'documents', + mimeTypes: [ + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessing', + ], + ), + XTypeGroup(label: 'images', extensions: ['jpg', 'png']), ]; setUp(() { @@ -34,9 +34,10 @@ void main() { test('works', () async { fakePlatformImplementation ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - acceptedTypeGroups: acceptedTypeGroups) + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + acceptedTypeGroups: acceptedTypeGroups, + ) ..setFileResponse([expectedFile]); final XFile? file = await openFile( @@ -79,8 +80,9 @@ void main() { ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse([expectedFile]); - final XFile? file = - await openFile(acceptedTypeGroups: acceptedTypeGroups); + final XFile? file = await openFile( + acceptedTypeGroups: acceptedTypeGroups, + ); expect(file, expectedFile); }); }); @@ -91,9 +93,10 @@ void main() { test('works', () async { fakePlatformImplementation ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - acceptedTypeGroups: acceptedTypeGroups) + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + acceptedTypeGroups: acceptedTypeGroups, + ) ..setFileResponse(expectedFiles); final List files = await openFiles( @@ -118,8 +121,9 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setFileResponse(expectedFiles); - final List files = - await openFiles(initialDirectory: initialDirectory); + final List files = await openFiles( + initialDirectory: initialDirectory, + ); expect(files, expectedFiles); }); @@ -128,8 +132,9 @@ void main() { ..setExpectations(confirmButtonText: confirmButtonText) ..setFileResponse(expectedFiles); - final List files = - await openFiles(confirmButtonText: confirmButtonText); + final List files = await openFiles( + confirmButtonText: confirmButtonText, + ); expect(files, expectedFiles); }); @@ -138,8 +143,9 @@ void main() { ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse(expectedFiles); - final List files = - await openFiles(acceptedTypeGroups: acceptedTypeGroups); + final List files = await openFiles( + acceptedTypeGroups: acceptedTypeGroups, + ); expect(files, expectedFiles); }); }); @@ -151,12 +157,14 @@ void main() { const int expectedActiveFilter = 1; fakePlatformImplementation ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - acceptedTypeGroups: acceptedTypeGroups, - suggestedName: suggestedName) - ..setPathsResponse([expectedSavePath], - activeFilter: expectedActiveFilter); + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + acceptedTypeGroups: acceptedTypeGroups, + suggestedName: suggestedName, + ) + ..setPathsResponse([ + expectedSavePath, + ], activeFilter: expectedActiveFilter); final FileSaveLocation? location = await getSaveLocation( initialDirectory: initialDirectory, @@ -181,8 +189,9 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setPathsResponse([expectedSavePath]); - final FileSaveLocation? location = - await getSaveLocation(initialDirectory: initialDirectory); + final FileSaveLocation? location = await getSaveLocation( + initialDirectory: initialDirectory, + ); expect(location?.path, expectedSavePath); }); @@ -191,8 +200,9 @@ void main() { ..setExpectations(confirmButtonText: confirmButtonText) ..setPathsResponse([expectedSavePath]); - final FileSaveLocation? location = - await getSaveLocation(confirmButtonText: confirmButtonText); + final FileSaveLocation? location = await getSaveLocation( + confirmButtonText: confirmButtonText, + ); expect(location?.path, expectedSavePath); }); @@ -201,8 +211,9 @@ void main() { ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setPathsResponse([expectedSavePath]); - final FileSaveLocation? location = - await getSaveLocation(acceptedTypeGroups: acceptedTypeGroups); + final FileSaveLocation? location = await getSaveLocation( + acceptedTypeGroups: acceptedTypeGroups, + ); expect(location?.path, expectedSavePath); }); @@ -211,8 +222,9 @@ void main() { ..setExpectations(suggestedName: suggestedName) ..setPathsResponse([expectedSavePath]); - final FileSaveLocation? location = - await getSaveLocation(suggestedName: suggestedName); + final FileSaveLocation? location = await getSaveLocation( + suggestedName: suggestedName, + ); expect(location?.path, expectedSavePath); }); }); @@ -223,8 +235,9 @@ void main() { test('works', () async { fakePlatformImplementation ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText) + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ) ..setPathsResponse([expectedDirectoryPath]); final String? directoryPath = await getDirectoryPath( @@ -236,8 +249,9 @@ void main() { }); test('works with no arguments', () async { - fakePlatformImplementation - .setPathsResponse([expectedDirectoryPath]); + fakePlatformImplementation.setPathsResponse([ + expectedDirectoryPath, + ]); final String? directoryPath = await getDirectoryPath(); expect(directoryPath, expectedDirectoryPath); @@ -248,8 +262,9 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setPathsResponse([expectedDirectoryPath]); - final String? directoryPath = - await getDirectoryPath(initialDirectory: initialDirectory); + final String? directoryPath = await getDirectoryPath( + initialDirectory: initialDirectory, + ); expect(directoryPath, expectedDirectoryPath); }); @@ -258,8 +273,9 @@ void main() { ..setExpectations(confirmButtonText: confirmButtonText) ..setPathsResponse([expectedDirectoryPath]); - final String? directoryPath = - await getDirectoryPath(confirmButtonText: confirmButtonText); + final String? directoryPath = await getDirectoryPath( + confirmButtonText: confirmButtonText, + ); expect(directoryPath, expectedDirectoryPath); }); }); @@ -267,14 +283,15 @@ void main() { group('getDirectoryPaths', () { const List expectedDirectoryPaths = [ '/example/path', - '/example/2/path' + '/example/2/path', ]; test('works', () async { fakePlatformImplementation ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText) + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ) ..setPathsResponse(expectedDirectoryPaths); final List directoryPaths = await getDirectoryPaths( @@ -297,8 +314,9 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setPathsResponse(expectedDirectoryPaths); - final List directoryPaths = - await getDirectoryPaths(initialDirectory: initialDirectory); + final List directoryPaths = await getDirectoryPaths( + initialDirectory: initialDirectory, + ); expect(directoryPaths, expectedDirectoryPaths); }); @@ -307,8 +325,9 @@ void main() { ..setExpectations(confirmButtonText: confirmButtonText) ..setPathsResponse(expectedDirectoryPaths); - final List directoryPaths = - await getDirectoryPaths(confirmButtonText: confirmButtonText); + final List directoryPaths = await getDirectoryPaths( + confirmButtonText: confirmButtonText, + ); expect(directoryPaths, expectedDirectoryPaths); }); }); @@ -404,10 +423,13 @@ class FakeFileSelector extends Fake final int? activeFilterIndex = activeFilter; return path == null ? null - : FileSaveLocation(path, - activeFilter: activeFilterIndex == null - ? null - : acceptedTypeGroups?[activeFilterIndex]); + : FileSaveLocation( + 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 cd6be65f831..7c13a80ce17 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.29/Dart 3.7. + ## 0.5.1+15 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/file_selector/file_selector_android/example/lib/home_page.dart b/packages/file_selector/file_selector_android/example/lib/home_page.dart index 38f534f89dc..16b53a77965 100644 --- a/packages/file_selector/file_selector_android/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_android/example/lib/home_page.dart @@ -16,9 +16,7 @@ class HomePage extends StatelessWidget { backgroundColor: Colors.white, ); return Scaffold( - appBar: AppBar( - title: const Text('File Selector Demo Home Page'), - ), + appBar: AppBar(title: const Text('File Selector Demo Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, 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 bfa91e6cb5f..6be47cea049 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/lib/open_image_page.dart b/packages/file_selector/file_selector_android/example/lib/open_image_page.dart index 08a1ec968bd..cf7a83026d0 100644 --- a/packages/file_selector/file_selector_android/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_android/example/lib/open_image_page.dart @@ -18,8 +18,9 @@ class OpenImagePage extends StatelessWidget { extensions: ['jpg', 'png'], uniformTypeIdentifiers: ['public.image'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -38,9 +39,7 @@ class OpenImagePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open an image'), - ), + appBar: AppBar(title: const Text('Open an image')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart index 305ce38ec97..1e1baeed4b4 100644 --- a/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart @@ -23,11 +23,9 @@ class OpenMultipleImagesPage extends StatelessWidget { extensions: ['png'], uniformTypeIdentifiers: ['public.png'], ); - final List files = await FileSelectorPlatform.instance - .openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, - ]); + final List files = await FileSelectorPlatform.instance.openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], + ); if (files.isEmpty) { // Operation was canceled by the user. return; @@ -48,9 +46,7 @@ class OpenMultipleImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open multiple images'), - ), + appBar: AppBar(title: const Text('Open multiple images')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -91,7 +87,7 @@ class MultipleImagesDisplay extends StatelessWidget { Flexible( key: Key('result_image_name$i'), child: Image.memory(fileBytes[i]), - ) + ), ], ), ), diff --git a/packages/file_selector/file_selector_android/example/lib/open_text_page.dart b/packages/file_selector/file_selector_android/example/lib/open_text_page.dart index 8d21e4337cf..fb2b3135ba7 100644 --- a/packages/file_selector/file_selector_android/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_android/example/lib/open_text_page.dart @@ -17,8 +17,9 @@ class OpenTextPage extends StatelessWidget { extensions: ['txt', 'json'], uniformTypeIdentifiers: ['public.text'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -37,9 +38,7 @@ class OpenTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -75,9 +74,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: Text(fileName), content: Scrollbar( - child: SingleChildScrollView( - child: Text(fileContent), - ), + child: SingleChildScrollView(child: Text(fileContent)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_android/example/pubspec.yaml b/packages/file_selector/file_selector_android/example/pubspec.yaml index c32c7d3fa9d..8b7074557c2 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: file_selector_android: diff --git a/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart b/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart index 8f9e46be017..52206ebba17 100644 --- a/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart +++ b/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart @@ -13,7 +13,7 @@ import 'types/native_illegal_argument_exception.dart'; /// An implementation of [FileSelectorPlatform] for Android. class FileSelectorAndroid extends FileSelectorPlatform { FileSelectorAndroid({@visibleForTesting FileSelectorApi? api}) - : _api = api ?? FileSelectorApi(); + : _api = api ?? FileSelectorApi(); final FileSelectorApi _api; @@ -103,14 +103,16 @@ class FileSelectorAndroid extends FileSelectorPlatform { /// Translates a [FileSelectorExceptionCode] to its corresponding error and /// handles throwing. void _resolveErrorCodeAndMaybeThrow( - FileSelectorNativeException fileSelectorNativeException) { + FileSelectorNativeException fileSelectorNativeException, + ) { switch (fileSelectorNativeException.fileSelectorExceptionCode) { case FileSelectorExceptionCode.illegalArgumentException: throw NativeIllegalArgumentException( - fileSelectorNativeException.message); + fileSelectorNativeException.message, + ); case (FileSelectorExceptionCode.illegalStateException || - FileSelectorExceptionCode.ioException || - FileSelectorExceptionCode.securityException): + FileSelectorExceptionCode.ioException || + FileSelectorExceptionCode.securityException): // unused for now } } diff --git a/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart b/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart index 73341425bf5..766e198bfc3 100644 --- a/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart +++ b/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart @@ -36,10 +36,7 @@ class FileSelectorNativeException { String message; Object encode() { - return [ - fileSelectorExceptionCode, - message, - ]; + return [fileSelectorExceptionCode, message]; } static FileSelectorNativeException decode(Object result) { @@ -98,20 +95,14 @@ class FileResponse { } class FileTypes { - FileTypes({ - required this.mimeTypes, - required this.extensions, - }); + FileTypes({required this.mimeTypes, required this.extensions}); List mimeTypes; List extensions; Object encode() { - return [ - mimeTypes, - extensions, - ]; + return [mimeTypes, extensions]; } static FileTypes decode(Object result) { @@ -170,11 +161,12 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + FileSelectorApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -185,17 +177,20 @@ class FileSelectorApi { /// /// Returns `null` if user cancels the operation. Future openFile( - String? initialDirectory, FileTypes allowedTypes) async { + String? initialDirectory, + FileTypes allowedTypes, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_android.FileSelectorApi.openFile$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([initialDirectory, allowedTypes]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([initialDirectory, allowedTypes]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -212,17 +207,20 @@ class FileSelectorApi { /// Opens a file dialog for loading files and returns a list of file responses /// chosen by the user. Future> openFiles( - String? initialDirectory, FileTypes allowedTypes) async { + String? initialDirectory, + FileTypes allowedTypes, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_android.FileSelectorApi.openFiles$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([initialDirectory, allowedTypes]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([initialDirectory, allowedTypes]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -249,12 +247,13 @@ class FileSelectorApi { 'dev.flutter.pigeon.file_selector_android.FileSelectorApi.getDirectoryPath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([initialDirectory]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([initialDirectory]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_android/pubspec.yaml b/packages/file_selector/file_selector_android/pubspec.yaml index 00f94a02ace..77e06a472e5 100644 --- a/packages/file_selector/file_selector_android/pubspec.yaml +++ b/packages/file_selector/file_selector_android/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.5.1+15 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_android/test/file_selector_android_test.dart b/packages/file_selector/file_selector_android/test/file_selector_android_test.dart index dc4ef92fbae..c5b43aae555 100644 --- a/packages/file_selector/file_selector_android/test/file_selector_android_test.dart +++ b/packages/file_selector/file_selector_android/test/file_selector_android_test.dart @@ -36,15 +36,17 @@ void main() { mockApi.openFile( 'some/path/', argThat( - isA().having( - (FileTypes types) => types.mimeTypes, - 'mimeTypes', - ['text/plain', 'image/jpg'], - ).having( - (FileTypes types) => types.extensions, - 'extensions', - ['txt', 'jpg'], - ), + isA() + .having( + (FileTypes types) => types.mimeTypes, + 'mimeTypes', + ['text/plain', 'image/jpg'], + ) + .having( + (FileTypes types) => types.extensions, + 'extensions', + ['txt', 'jpg'], + ), ), ), ).thenAnswer( @@ -87,35 +89,35 @@ void main() { mockApi.openFiles( 'some/path/', argThat( - isA().having( - (FileTypes types) => types.mimeTypes, - 'mimeTypes', - ['text/plain', 'image/jpg'], - ).having( - (FileTypes types) => types.extensions, - 'extensions', - ['txt', 'jpg'], - ), + isA() + .having( + (FileTypes types) => types.mimeTypes, + 'mimeTypes', + ['text/plain', 'image/jpg'], + ) + .having( + (FileTypes types) => types.extensions, + 'extensions', + ['txt', 'jpg'], + ), ), ), ).thenAnswer( - (_) => Future>.value( - [ - FileResponse( - path: 'some/path.txt', - size: 30, - bytes: Uint8List(0), - name: 'name', - mimeType: 'text/plain', - ), - FileResponse( - path: 'other/dir.jpg', - size: 40, - bytes: Uint8List(0), - mimeType: 'image/jpg', - ), - ], - ), + (_) => Future>.value([ + FileResponse( + path: 'some/path.txt', + size: 30, + bytes: Uint8List(0), + name: 'name', + mimeType: 'text/plain', + ), + FileResponse( + path: 'other/dir.jpg', + size: 40, + bytes: Uint8List(0), + mimeType: 'image/jpg', + ), + ]), ); const XTypeGroup group = XTypeGroup( @@ -146,8 +148,9 @@ void main() { }); test('getDirectoryPath', () async { - when(mockApi.getDirectoryPath('some/path')) - .thenAnswer((_) => Future.value('some/path/chosen/')); + when( + mockApi.getDirectoryPath('some/path'), + ).thenAnswer((_) => Future.value('some/path/chosen/')); final String? path = await plugin.getDirectoryPath( initialDirectory: 'some/path', diff --git a/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart b/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart index 8f465c9a79a..45cfa755255 100644 --- a/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart +++ b/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart @@ -31,13 +31,15 @@ class MockFileSelectorApi extends _i1.Mock implements _i2.FileSelectorApi { } @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override _i4.Future<_i2.FileResponse?> openFile( @@ -45,15 +47,10 @@ class MockFileSelectorApi extends _i1.Mock implements _i2.FileSelectorApi { _i2.FileTypes? allowedTypes, ) => (super.noSuchMethod( - Invocation.method( - #openFile, - [ - initialDirectory, - allowedTypes, - ], - ), - returnValue: _i4.Future<_i2.FileResponse?>.value(), - ) as _i4.Future<_i2.FileResponse?>); + Invocation.method(#openFile, [initialDirectory, allowedTypes]), + returnValue: _i4.Future<_i2.FileResponse?>.value(), + ) + as _i4.Future<_i2.FileResponse?>); @override _i4.Future> openFiles( @@ -61,24 +58,18 @@ class MockFileSelectorApi extends _i1.Mock implements _i2.FileSelectorApi { _i2.FileTypes? allowedTypes, ) => (super.noSuchMethod( - Invocation.method( - #openFiles, - [ - initialDirectory, - allowedTypes, - ], - ), - returnValue: - _i4.Future>.value(<_i2.FileResponse>[]), - ) as _i4.Future>); + Invocation.method(#openFiles, [initialDirectory, allowedTypes]), + returnValue: _i4.Future>.value( + <_i2.FileResponse>[], + ), + ) + as _i4.Future>); @override _i4.Future getDirectoryPath(String? initialDirectory) => (super.noSuchMethod( - Invocation.method( - #getDirectoryPath, - [initialDirectory], - ), - returnValue: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#getDirectoryPath, [initialDirectory]), + returnValue: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/file_selector/file_selector_ios/CHANGELOG.md b/packages/file_selector/file_selector_ios/CHANGELOG.md index 9bbea7376a4..b34eedbd891 100644 --- a/packages/file_selector/file_selector_ios/CHANGELOG.md +++ b/packages/file_selector/file_selector_ios/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.5.3+2 * Updates to Pigeon 25.5.0. diff --git a/packages/file_selector/file_selector_ios/example/lib/home_page.dart b/packages/file_selector/file_selector_ios/example/lib/home_page.dart index 22d55f07623..e64746ea8f2 100644 --- a/packages/file_selector/file_selector_ios/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/home_page.dart @@ -16,9 +16,7 @@ class HomePage extends StatelessWidget { foregroundColor: Colors.white, ); return Scaffold( - appBar: AppBar( - title: const Text('File Selector Demo Home Page'), - ), + appBar: AppBar(title: const Text('File Selector Demo Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_ios/example/lib/main.dart b/packages/file_selector/file_selector_ios/example/lib/main.dart index 1f3508a149e..cadfa1a4640 100644 --- a/packages/file_selector/file_selector_ios/example/lib/main.dart +++ b/packages/file_selector/file_selector_ios/example/lib/main.dart @@ -30,8 +30,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(), '/open/any': (BuildContext context) => const OpenAnyPage(), }, diff --git a/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart index 7b672179185..41a7cf741e3 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart @@ -29,9 +29,7 @@ class OpenAnyPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a file'), - ), + appBar: AppBar(title: const Text('Open a file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_ios/example/lib/open_image_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_image_page.dart index 9b46571b900..d5e45e88978 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_image_page.dart @@ -20,8 +20,9 @@ class OpenImagePage extends StatelessWidget { extensions: ['jpg', 'png'], uniformTypeIdentifiers: ['public.image'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -40,9 +41,7 @@ class OpenImagePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open an image'), - ), + appBar: AppBar(title: const Text('Open an image')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart index 3ea4ced58ad..8dd05f9b7e1 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart @@ -25,11 +25,9 @@ class OpenMultipleImagesPage extends StatelessWidget { extensions: ['png'], uniformTypeIdentifiers: ['public.png'], ); - final List files = await FileSelectorPlatform.instance - .openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, - ]); + final List files = await FileSelectorPlatform.instance.openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], + ); if (files.isEmpty) { // Operation was canceled by the user. return; @@ -45,9 +43,7 @@ class OpenMultipleImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open multiple images'), - ), + appBar: AppBar(title: const Text('Open multiple images')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -86,10 +82,12 @@ 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_ios/example/lib/open_text_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart index 890cb4ab4d4..732ce41bc85 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart @@ -17,8 +17,9 @@ class OpenTextPage extends StatelessWidget { extensions: ['txt', 'json'], uniformTypeIdentifiers: ['public.text'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -37,9 +38,7 @@ class OpenTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -75,9 +74,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: Text(fileName), content: Scrollbar( - child: SingleChildScrollView( - child: Text(fileContent), - ), + child: SingleChildScrollView(child: Text(fileContent)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_ios/example/pubspec.yaml b/packages/file_selector/file_selector_ios/example/pubspec.yaml index ad9500e24ed..447581c923a 100644 --- a/packages/file_selector/file_selector_ios/example/pubspec.yaml +++ b/packages/file_selector/file_selector_ios/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: # The following adds the Cupertino Icons font to your application. diff --git a/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart b/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart index a1ee201937a..488fb82e883 100644 --- a/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart +++ b/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart @@ -21,8 +21,11 @@ class FileSelectorIOS extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List path = await _hostApi.openFile(FileSelectorConfig( - utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups))); + final List path = await _hostApi.openFile( + FileSelectorConfig( + utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups), + ), + ); return path.isEmpty ? null : XFile(path.first); } @@ -32,9 +35,12 @@ class FileSelectorIOS extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List pathList = await _hostApi.openFile(FileSelectorConfig( + final List pathList = await _hostApi.openFile( + FileSelectorConfig( utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups), - allowMultiSelection: true)); + allowMultiSelection: true, + ), + ); return pathList.map((String path) => XFile(path)).toList(); } @@ -55,8 +61,10 @@ class FileSelectorIOS extends FileSelectorPlatform { return allowAny; } if (typeGroup.uniformTypeIdentifiers?.isEmpty ?? true) { - throw ArgumentError('The provided type group $typeGroup should either ' - 'allow all files, or have a non-empty "uniformTypeIdentifiers"'); + throw ArgumentError( + 'The provided type group $typeGroup should either ' + 'allow all files, or have a non-empty "uniformTypeIdentifiers"', + ); } allowedUTIs.addAll(typeGroup.uniformTypeIdentifiers!); } diff --git a/packages/file_selector/file_selector_ios/lib/src/messages.g.dart b/packages/file_selector/file_selector_ios/lib/src/messages.g.dart index 59e67959051..40f2aa02d98 100644 --- a/packages/file_selector/file_selector_ios/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_ios/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -32,14 +35,17 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -55,10 +61,7 @@ class FileSelectorConfig { bool allowMultiSelection; List _toList() { - return [ - utis, - allowMultiSelection, - ]; + return [utis, allowMultiSelection]; } Object encode() { @@ -120,11 +123,12 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + FileSelectorApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -136,12 +140,13 @@ class FileSelectorApi { 'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [config], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([config]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/file_selector/file_selector_ios/pigeons/messages.dart b/packages/file_selector/file_selector_ios/pigeons/messages.dart index ade4b17835c..2294110e209 100644 --- a/packages/file_selector/file_selector_ios/pigeons/messages.dart +++ b/packages/file_selector/file_selector_ios/pigeons/messages.dart @@ -4,15 +4,20 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - dartTestOut: 'test/test_api.g.dart', - swiftOut: 'ios/file_selector_ios/Sources/file_selector_ios/messages.g.swift', - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + dartTestOut: 'test/test_api.g.dart', + swiftOut: + 'ios/file_selector_ios/Sources/file_selector_ios/messages.g.swift', + copyrightHeader: 'pigeons/copyright.txt', + ), +) class FileSelectorConfig { - FileSelectorConfig( - {this.utis = const [], this.allowMultiSelection = false}); + FileSelectorConfig({ + this.utis = const [], + this.allowMultiSelection = false, + }); List utis; bool allowMultiSelection; } diff --git a/packages/file_selector/file_selector_ios/pubspec.yaml b/packages/file_selector/file_selector_ios/pubspec.yaml index a3ea607806a..e3d711e277d 100644 --- a/packages/file_selector/file_selector_ios/pubspec.yaml +++ b/packages/file_selector/file_selector_ios/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.5.3+2 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart b/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart index 41c6fe869d2..6ee812773f6 100644 --- a/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart +++ b/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart @@ -44,11 +44,12 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); await plugin.openFile(acceptedTypeGroups: [group, groupTwo]); @@ -57,8 +58,10 @@ void main() { result.captured[0] as FileSelectorConfig; // iOS only accepts uniformTypeIdentifiers. - expect(listEquals(config.utis, ['public.text', 'public.image']), - isTrue); + expect( + listEquals(config.utis, ['public.text', 'public.image']), + isTrue, + ); expect(config.allowMultiSelection, isFalse); }); test('throws for a type group that does not support iOS', () async { @@ -68,8 +71,9 @@ void main() { ); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFile(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('correctly handles no type groups', () async { @@ -81,12 +85,12 @@ void main() { }); test('correctly handles a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), completes); + plugin.openFile(acceptedTypeGroups: [group]), + completes, + ); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; @@ -108,11 +112,12 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); await plugin.openFiles(acceptedTypeGroups: [group, groupTwo]); @@ -121,8 +126,10 @@ void main() { result.captured[0] as FileSelectorConfig; // iOS only accepts uniformTypeIdentifiers. - expect(listEquals(config.utis, ['public.text', 'public.image']), - isTrue); + expect( + listEquals(config.utis, ['public.text', 'public.image']), + isTrue, + ); expect(config.allowMultiSelection, isTrue); }); @@ -133,8 +140,9 @@ void main() { ); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFiles(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('correctly handles no type groups', () async { @@ -146,12 +154,12 @@ void main() { }); test('correctly handles a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), completes); + plugin.openFiles(acceptedTypeGroups: [group]), + completes, + ); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; diff --git a/packages/file_selector/file_selector_ios/test/file_selector_ios_test.mocks.dart b/packages/file_selector/file_selector_ios/test/file_selector_ios_test.mocks.dart index 713bd3f29ba..eac7136aabc 100644 --- a/packages/file_selector/file_selector_ios/test/file_selector_ios_test.mocks.dart +++ b/packages/file_selector/file_selector_ios/test/file_selector_ios_test.mocks.dart @@ -35,10 +35,8 @@ class MockTestFileSelectorApi extends _i1.Mock @override _i3.Future> openFile(_i4.FileSelectorConfig? config) => (super.noSuchMethod( - Invocation.method( - #openFile, - [config], - ), - returnValue: _i3.Future>.value([]), - ) as _i3.Future>); + Invocation.method(#openFile, [config]), + returnValue: _i3.Future>.value([]), + ) + as _i3.Future>); } diff --git a/packages/file_selector/file_selector_ios/test/test_api.g.dart b/packages/file_selector/file_selector_ios/test/test_api.g.dart index 5a95dc1782d..90d93e4142d 100644 --- a/packages/file_selector/file_selector_ios/test/test_api.g.dart +++ b/packages/file_selector/file_selector_ios/test/test_api.g.dart @@ -54,36 +54,45 @@ abstract class TestFileSelectorApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile was null.'); - final List args = (message as List?)!; - final FileSelectorConfig? arg_config = - (args[0] as FileSelectorConfig?); - assert(arg_config != null, - 'Argument for dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile was null, expected non-null FileSelectorConfig.'); - try { - final List output = await api.openFile(arg_config!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile was null.', + ); + final List args = (message as List?)!; + final FileSelectorConfig? arg_config = + (args[0] as FileSelectorConfig?); + assert( + arg_config != null, + 'Argument for dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile was null, expected non-null FileSelectorConfig.', + ); + try { + final List output = await api.openFile(arg_config!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/packages/file_selector/file_selector_linux/CHANGELOG.md b/packages/file_selector/file_selector_linux/CHANGELOG.md index 10da5f6da70..bcff55dae5a 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.9.3+2 diff --git a/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart b/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart index 351b403ca61..d227652335a 100644 --- a/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart @@ -13,10 +13,8 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const String confirmButtonText = 'Choose'; - final String? directoryPath = - await FileSelectorPlatform.instance.getDirectoryPath( - confirmButtonText: confirmButtonText, - ); + final String? directoryPath = await FileSelectorPlatform.instance + .getDirectoryPath(confirmButtonText: confirmButtonText); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -32,9 +30,7 @@ class GetDirectoryPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -67,9 +63,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directory'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoryPath), - ), + child: SingleChildScrollView(child: Text(directoryPath)), ), actions: [ TextButton( 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 af53822ae5b..b87e2e57a65 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 @@ -13,10 +13,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { Future _getDirectoryPaths(BuildContext context) async { const String confirmButtonText = 'Choose'; - final List directoryPaths = - await FileSelectorPlatform.instance.getDirectoryPaths( - confirmButtonText: confirmButtonText, - ); + final List directoryPaths = await FileSelectorPlatform.instance + .getDirectoryPaths(confirmButtonText: confirmButtonText); if (directoryPaths.isEmpty) { // Operation was canceled by the user. return; @@ -24,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')), ); } } @@ -33,9 +31,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Select multiple directories'), - ), + appBar: AppBar(title: const Text('Select multiple directories')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -46,7 +42,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { foregroundColor: Colors.white, ), child: const Text( - 'Press to ask user to choose multiple directories'), + 'Press to ask user to choose multiple directories', + ), onPressed: () => _getDirectoryPaths(context), ), ], @@ -69,9 +66,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directories'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoriesPaths), - ), + child: SingleChildScrollView(child: Text(directoriesPaths)), ), actions: [ TextButton( 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 4715f267e36..9cfb34155c2 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 @@ -16,9 +16,7 @@ class HomePage extends StatelessWidget { foregroundColor: Colors.white, ); return Scaffold( - appBar: AppBar( - title: const Text('File Selector Demo Home Page'), - ), + appBar: AppBar(title: const Text('File Selector Demo Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -56,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 a88f850f5d6..3763baaad86 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_image_page.dart b/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart index e39dee95d4d..33ff35ee01e 100644 --- a/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart @@ -19,8 +19,9 @@ class OpenImagePage extends StatelessWidget { label: 'images', extensions: ['jpg', 'png'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -39,9 +40,7 @@ class OpenImagePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open an image'), - ), + appBar: AppBar(title: const Text('Open an image')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, 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 decb1b64c7e..07a3829a5a9 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 @@ -23,11 +23,9 @@ class OpenMultipleImagesPage extends StatelessWidget { label: 'PNGs', extensions: ['png'], ); - final List files = await FileSelectorPlatform.instance - .openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, - ]); + final List files = await FileSelectorPlatform.instance.openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], + ); if (files.isEmpty) { // Operation was canceled by the user. return; @@ -43,9 +41,7 @@ class OpenMultipleImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open multiple images'), - ), + appBar: AppBar(title: const Text('Open multiple images')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -84,10 +80,12 @@ 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/lib/open_text_page.dart b/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart index 6ffbd28c92a..9a9f21da32e 100644 --- a/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart @@ -16,8 +16,9 @@ class OpenTextPage extends StatelessWidget { label: 'text', extensions: ['txt', 'json'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -36,9 +37,7 @@ class OpenTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -74,9 +73,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: Text(fileName), content: Scrollbar( - child: SingleChildScrollView( - child: Text(fileContent), - ), + child: SingleChildScrollView(child: Text(fileContent)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart b/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart index 100da3ab89f..c76d64acc43 100644 --- a/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart @@ -17,10 +17,8 @@ class SaveTextPage extends StatelessWidget { Future _saveFile() async { final String fileName = _nameController.text; - final FileSaveLocation? result = - await FileSelectorPlatform.instance.getSaveLocation( - options: SaveDialogOptions(suggestedName: fileName), - ); + final FileSaveLocation? result = await FileSelectorPlatform.instance + .getSaveLocation(options: SaveDialogOptions(suggestedName: fileName)); // Operation was canceled by the user. if (result == null) { return; @@ -28,17 +26,18 @@ class SaveTextPage extends StatelessWidget { final String text = _contentController.text; final Uint8List fileData = Uint8List.fromList(text.codeUnits); const String fileMimeType = 'text/plain'; - final XFile textFile = - XFile.fromData(fileData, mimeType: fileMimeType, name: fileName); + final XFile textFile = XFile.fromData( + fileData, + mimeType: fileMimeType, + name: fileName, + ); await textFile.saveTo(result.path); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Save text into a file'), - ), + appBar: AppBar(title: const Text('Save text into a file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_linux/example/pubspec.yaml b/packages/file_selector/file_selector_linux/example/pubspec.yaml index f733cb7d96a..ae1fd0f3234 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: file_selector_linux: diff --git a/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart b/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart index 3a05243c311..60aa454828d 100644 --- a/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart +++ b/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart @@ -10,9 +10,8 @@ import 'src/messages.g.dart'; /// An implementation of [FileSelectorPlatform] for Linux. class FileSelectorLinux extends FileSelectorPlatform { /// Creates a new plugin implementation instance. - FileSelectorLinux({ - @visibleForTesting FileSelectorApi? api, - }) : _hostApi = api ?? FileSelectorApi(); + FileSelectorLinux({@visibleForTesting FileSelectorApi? api}) + : _hostApi = api ?? FileSelectorApi(); final FileSelectorApi _hostApi; @@ -28,14 +27,16 @@ class FileSelectorLinux extends FileSelectorPlatform { String? confirmButtonText, }) async { final List paths = await _hostApi.showFileChooser( - PlatformFileChooserActionType.open, - PlatformFileChooserOptions( - allowedFileTypes: - _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups), - currentFolderPath: initialDirectory, - acceptButtonLabel: confirmButtonText, - selectMultiple: false, - )); + PlatformFileChooserActionType.open, + PlatformFileChooserOptions( + allowedFileTypes: _platformTypeGroupsFromXTypeGroups( + acceptedTypeGroups, + ), + currentFolderPath: initialDirectory, + acceptButtonLabel: confirmButtonText, + selectMultiple: false, + ), + ); return paths.isEmpty ? null : XFile(paths.first); } @@ -46,14 +47,16 @@ class FileSelectorLinux extends FileSelectorPlatform { String? confirmButtonText, }) async { final List paths = await _hostApi.showFileChooser( - PlatformFileChooserActionType.open, - PlatformFileChooserOptions( - allowedFileTypes: - _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups), - currentFolderPath: initialDirectory, - acceptButtonLabel: confirmButtonText, - selectMultiple: true, - )); + PlatformFileChooserActionType.open, + PlatformFileChooserOptions( + allowedFileTypes: _platformTypeGroupsFromXTypeGroups( + acceptedTypeGroups, + ), + currentFolderPath: initialDirectory, + acceptButtonLabel: confirmButtonText, + selectMultiple: true, + ), + ); return paths.map((String path) => XFile(path)).toList(); } @@ -65,12 +68,13 @@ class FileSelectorLinux extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileSaveLocation? location = await getSaveLocation( - acceptedTypeGroups: acceptedTypeGroups, - options: SaveDialogOptions( - initialDirectory: initialDirectory, - suggestedName: suggestedName, - confirmButtonText: confirmButtonText, - )); + acceptedTypeGroups: acceptedTypeGroups, + options: SaveDialogOptions( + initialDirectory: initialDirectory, + suggestedName: suggestedName, + confirmButtonText: confirmButtonText, + ), + ); return location?.path; } @@ -82,14 +86,16 @@ class FileSelectorLinux extends FileSelectorPlatform { // TODO(stuartmorgan): Add the selected type group here and return it. See // https://github.com/flutter/flutter/issues/107093 final List paths = await _hostApi.showFileChooser( - PlatformFileChooserActionType.save, - PlatformFileChooserOptions( - allowedFileTypes: - _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups), - currentFolderPath: options.initialDirectory, - currentName: options.suggestedName, - acceptButtonLabel: options.confirmButtonText, - )); + PlatformFileChooserActionType.save, + PlatformFileChooserOptions( + allowedFileTypes: _platformTypeGroupsFromXTypeGroups( + acceptedTypeGroups, + ), + currentFolderPath: options.initialDirectory, + currentName: options.suggestedName, + acceptButtonLabel: options.confirmButtonText, + ), + ); return paths.isEmpty ? null : FileSaveLocation(paths.first); } @@ -99,12 +105,13 @@ class FileSelectorLinux extends FileSelectorPlatform { String? confirmButtonText, }) async { final List paths = await _hostApi.showFileChooser( - PlatformFileChooserActionType.chooseDirectory, - PlatformFileChooserOptions( - currentFolderPath: initialDirectory, - acceptButtonLabel: confirmButtonText, - selectMultiple: false, - )); + PlatformFileChooserActionType.chooseDirectory, + PlatformFileChooserOptions( + currentFolderPath: initialDirectory, + acceptButtonLabel: confirmButtonText, + selectMultiple: false, + ), + ); return paths.isEmpty ? null : paths.first; } @@ -114,41 +121,42 @@ class FileSelectorLinux extends FileSelectorPlatform { String? confirmButtonText, }) async { return _hostApi.showFileChooser( - PlatformFileChooserActionType.chooseDirectory, - PlatformFileChooserOptions( - currentFolderPath: initialDirectory, - acceptButtonLabel: confirmButtonText, - selectMultiple: true, - )); + PlatformFileChooserActionType.chooseDirectory, + PlatformFileChooserOptions( + currentFolderPath: initialDirectory, + acceptButtonLabel: confirmButtonText, + selectMultiple: true, + ), + ); } } List? _platformTypeGroupsFromXTypeGroups( - List? groups) { + List? groups, +) { return groups?.map(_platformTypeGroupFromXTypeGroup).toList(); } PlatformTypeGroup _platformTypeGroupFromXTypeGroup(XTypeGroup group) { final String label = group.label ?? ''; if (group.allowsAny) { - return PlatformTypeGroup( - label: label, - extensions: ['*'], - ); + return PlatformTypeGroup(label: label, extensions: ['*']); } if ((group.extensions?.isEmpty ?? true) && (group.mimeTypes?.isEmpty ?? true)) { - throw ArgumentError('Provided type group $group does not allow ' - 'all files, but does not set any of the Linux-supported filter ' - 'categories. "extensions" or "mimeTypes" must be non-empty for Linux ' - 'if anything is non-empty.'); + throw ArgumentError( + 'Provided type group $group does not allow ' + 'all files, but does not set any of the Linux-supported filter ' + 'categories. "extensions" or "mimeTypes" must be non-empty for Linux ' + 'if anything is non-empty.', + ); } return PlatformTypeGroup( - label: label, - // Covert to GtkFileFilter's *. format. - extensions: group.extensions - ?.map((String extension) => '*.$extension') - .toList() ?? - [], - mimeTypes: group.mimeTypes ?? []); + label: label, + // Covert to GtkFileFilter's *. format. + extensions: + group.extensions?.map((String extension) => '*.$extension').toList() ?? + [], + mimeTypes: group.mimeTypes ?? [], + ); } 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 6b5e65e2168..6d5a9b84775 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 @@ -19,11 +19,7 @@ PlatformException _createConnectionError(String channelName) { } /// A Pigeon representation of the GTK_FILE_CHOOSER_ACTION_* options. -enum PlatformFileChooserActionType { - open, - chooseDirectory, - save, -} +enum PlatformFileChooserActionType { open, chooseDirectory, save } /// A Pigeon representation of the Linux portion of an `XTypeGroup`. class PlatformTypeGroup { @@ -40,11 +36,7 @@ class PlatformTypeGroup { List mimeTypes; Object encode() { - return [ - label, - extensions, - mimeTypes, - ]; + return [label, extensions, mimeTypes]; } static PlatformTypeGroup decode(Object result) { @@ -148,11 +140,12 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + FileSelectorApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -163,18 +156,21 @@ class FileSelectorApi { /// list of selected paths. /// /// An empty list corresponds to a cancelled selection. - Future> showFileChooser(PlatformFileChooserActionType type, - PlatformFileChooserOptions options) async { + Future> showFileChooser( + PlatformFileChooserActionType type, + PlatformFileChooserOptions options, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_linux.FileSelectorApi.showFileChooser$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([type, options]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([type, options]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_linux/pigeons/messages.dart b/packages/file_selector/file_selector_linux/pigeons/messages.dart index f10d67cd515..3f393e88a6a 100644 --- a/packages/file_selector/file_selector_linux/pigeons/messages.dart +++ b/packages/file_selector/file_selector_linux/pigeons/messages.dart @@ -3,15 +3,16 @@ // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - input: 'pigeons/messages.dart', - gobjectHeaderOut: 'linux/messages.g.h', - gobjectSourceOut: 'linux/messages.g.cc', - gobjectOptions: GObjectOptions(module: 'Ffs'), - dartOut: 'lib/src/messages.g.dart', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + input: 'pigeons/messages.dart', + gobjectHeaderOut: 'linux/messages.g.h', + gobjectSourceOut: 'linux/messages.g.cc', + gobjectOptions: GObjectOptions(module: 'Ffs'), + dartOut: 'lib/src/messages.g.dart', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// A Pigeon representation of the GTK_FILE_CHOOSER_ACTION_* options. enum PlatformFileChooserActionType { open, chooseDirectory, save } @@ -58,5 +59,7 @@ abstract class FileSelectorApi { /// /// An empty list corresponds to a cancelled selection. List showFileChooser( - PlatformFileChooserActionType type, PlatformFileChooserOptions options); + PlatformFileChooserActionType type, + PlatformFileChooserOptions options, + ); } diff --git a/packages/file_selector/file_selector_linux/pubspec.yaml b/packages/file_selector/file_selector_linux/pubspec.yaml index b10f40f4425..e5450ed6da9 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart b/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart index dbf4bcf4bc3..973a8c61cbd 100644 --- a/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart +++ b/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart @@ -58,15 +58,21 @@ void main() { expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, - ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ + '*.txt', + ]); expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); + api.passedOptions?.allowedFileTypes?[0].mimeTypes, + group.mimeTypes, + ); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, - ['*.jpg']); - expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ + '*.jpg', + ]); + expect( + api.passedOptions?.allowedFileTypes?[1].mimeTypes, + groupTwo.mimeTypes, + ); }); test('passes initialDirectory correctly', () async { @@ -90,14 +96,13 @@ void main() { ); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFile(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('passes a wildcard group correctly', () async { - const XTypeGroup group = XTypeGroup( - label: 'any', - ); + const XTypeGroup group = XTypeGroup(label: 'any'); await plugin.openFile(acceptedTypeGroups: [group]); @@ -136,15 +141,21 @@ void main() { expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, - ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ + '*.txt', + ]); expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); + api.passedOptions?.allowedFileTypes?[0].mimeTypes, + group.mimeTypes, + ); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, - ['*.jpg']); - expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ + '*.jpg', + ]); + expect( + api.passedOptions?.allowedFileTypes?[1].mimeTypes, + groupTwo.mimeTypes, + ); }); test('passes initialDirectory correctly', () async { @@ -168,14 +179,13 @@ void main() { ); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFiles(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('passes a wildcard group correctly', () async { - const XTypeGroup group = XTypeGroup( - label: 'any', - ); + const XTypeGroup group = XTypeGroup(label: 'any'); await plugin.openFiles(acceptedTypeGroups: [group]); @@ -206,26 +216,34 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin - .getSaveLocation(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSaveLocation( + acceptedTypeGroups: [group, groupTwo], + ); expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, - ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ + '*.txt', + ]); expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); + api.passedOptions?.allowedFileTypes?[0].mimeTypes, + group.mimeTypes, + ); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, - ['*.jpg']); - expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ + '*.jpg', + ]); + expect( + api.passedOptions?.allowedFileTypes?[1].mimeTypes, + groupTwo.mimeTypes, + ); }); test('passes initialDirectory correctly', () async { const String path = '/example/directory'; await plugin.getSaveLocation( - options: const SaveDialogOptions(initialDirectory: path)); + options: const SaveDialogOptions(initialDirectory: path), + ); expect(api.passedOptions?.currentFolderPath, path); }); @@ -233,7 +251,8 @@ void main() { test('passes confirmButtonText correctly', () async { const String button = 'Open File'; await plugin.getSaveLocation( - options: const SaveDialogOptions(confirmButtonText: button)); + options: const SaveDialogOptions(confirmButtonText: button), + ); expect(api.passedOptions?.acceptButtonLabel, button); }); @@ -245,14 +264,13 @@ void main() { ); await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.getSaveLocation(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('passes a wildcard group correctly', () async { - const XTypeGroup group = XTypeGroup( - label: 'any', - ); + const XTypeGroup group = XTypeGroup(label: 'any'); await plugin.getSaveLocation(acceptedTypeGroups: [group]); @@ -283,20 +301,27 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin - .getSavePath(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSavePath( + acceptedTypeGroups: [group, groupTwo], + ); expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, - ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ + '*.txt', + ]); expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); + api.passedOptions?.allowedFileTypes?[0].mimeTypes, + group.mimeTypes, + ); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, - ['*.jpg']); - expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ + '*.jpg', + ]); + expect( + api.passedOptions?.allowedFileTypes?[1].mimeTypes, + groupTwo.mimeTypes, + ); }); test('passes initialDirectory correctly', () async { @@ -320,14 +345,13 @@ void main() { ); await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.getSavePath(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('passes a wildcard group correctly', () async { - const XTypeGroup group = XTypeGroup( - label: 'any', - ); + const XTypeGroup group = XTypeGroup(label: 'any'); await plugin.getSavePath(acceptedTypeGroups: [group]); @@ -400,8 +424,10 @@ class FakeFileSelectorApi implements FileSelectorApi { PlatformFileChooserOptions? passedOptions; @override - Future> showFileChooser(PlatformFileChooserActionType type, - PlatformFileChooserOptions options) async { + Future> showFileChooser( + PlatformFileChooserActionType type, + PlatformFileChooserOptions options, + ) async { passedType = type; passedOptions = options; return result; diff --git a/packages/file_selector/file_selector_macos/CHANGELOG.md b/packages/file_selector/file_selector_macos/CHANGELOG.md index c65d5d3a93c..0404c64bbca 100644 --- a/packages/file_selector/file_selector_macos/CHANGELOG.md +++ b/packages/file_selector/file_selector_macos/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.9.4+4 * Updates to Pigeon 25.5.0. diff --git a/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart b/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart index 0ee3bd6cd3b..f7b607c33ff 100644 --- a/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart @@ -13,10 +13,8 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const String confirmButtonText = 'Choose'; - final String? directoryPath = - await FileSelectorPlatform.instance.getDirectoryPath( - confirmButtonText: confirmButtonText, - ); + final String? directoryPath = await FileSelectorPlatform.instance + .getDirectoryPath(confirmButtonText: confirmButtonText); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -32,9 +30,7 @@ class GetDirectoryPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -67,9 +63,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directory'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoryPath), - ), + child: SingleChildScrollView(child: Text(directoryPath)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart index ebe1f2ac825..1a236605e53 100644 --- a/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart @@ -13,10 +13,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { Future _getDirectoryPaths(BuildContext context) async { const String confirmButtonText = 'Choose'; - final List directoriesPaths = - await FileSelectorPlatform.instance.getDirectoryPaths( - confirmButtonText: confirmButtonText, - ); + final List directoriesPaths = await FileSelectorPlatform.instance + .getDirectoryPaths(confirmButtonText: confirmButtonText); if (directoriesPaths.isEmpty) { // Operation was canceled by the user. return; @@ -24,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')), ); } } @@ -33,9 +31,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Select multiple directories'), - ), + appBar: AppBar(title: const Text('Select multiple directories')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -46,7 +42,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { foregroundColor: Colors.white, ), child: const Text( - 'Press to ask user to choose multiple directories'), + 'Press to ask user to choose multiple directories', + ), onPressed: () => _getDirectoryPaths(context), ), ], @@ -69,9 +66,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directories'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoryPaths), - ), + child: SingleChildScrollView(child: Text(directoryPaths)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_macos/example/lib/home_page.dart b/packages/file_selector/file_selector_macos/example/lib/home_page.dart index 4715f267e36..9cfb34155c2 100644 --- a/packages/file_selector/file_selector_macos/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/home_page.dart @@ -16,9 +16,7 @@ class HomePage extends StatelessWidget { foregroundColor: Colors.white, ); return Scaffold( - appBar: AppBar( - title: const Text('File Selector Demo Home Page'), - ), + appBar: AppBar(title: const Text('File Selector Demo Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -56,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_macos/example/lib/main.dart b/packages/file_selector/file_selector_macos/example/lib/main.dart index a88f850f5d6..3763baaad86 100644 --- a/packages/file_selector/file_selector_macos/example/lib/main.dart +++ b/packages/file_selector/file_selector_macos/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_macos/example/lib/open_image_page.dart b/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart index e39dee95d4d..33ff35ee01e 100644 --- a/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart @@ -19,8 +19,9 @@ class OpenImagePage extends StatelessWidget { label: 'images', extensions: ['jpg', 'png'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -39,9 +40,7 @@ class OpenImagePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open an image'), - ), + appBar: AppBar(title: const Text('Open an image')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart index decb1b64c7e..07a3829a5a9 100644 --- a/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart @@ -23,11 +23,9 @@ class OpenMultipleImagesPage extends StatelessWidget { label: 'PNGs', extensions: ['png'], ); - final List files = await FileSelectorPlatform.instance - .openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, - ]); + final List files = await FileSelectorPlatform.instance.openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], + ); if (files.isEmpty) { // Operation was canceled by the user. return; @@ -43,9 +41,7 @@ class OpenMultipleImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open multiple images'), - ), + appBar: AppBar(title: const Text('Open multiple images')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -84,10 +80,12 @@ 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_macos/example/lib/open_text_page.dart b/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart index 6ffbd28c92a..9a9f21da32e 100644 --- a/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart @@ -16,8 +16,9 @@ class OpenTextPage extends StatelessWidget { label: 'text', extensions: ['txt', 'json'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -36,9 +37,7 @@ class OpenTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -74,9 +73,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: Text(fileName), content: Scrollbar( - child: SingleChildScrollView( - child: Text(fileContent), - ), + child: SingleChildScrollView(child: Text(fileContent)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart b/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart index f18050bcf7b..6e8f334dd71 100644 --- a/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart @@ -17,10 +17,8 @@ class SaveTextPage extends StatelessWidget { Future _saveFile() async { final String fileName = _nameController.text; - final FileSaveLocation? result = - await FileSelectorPlatform.instance.getSaveLocation( - options: SaveDialogOptions(suggestedName: fileName), - ); + final FileSaveLocation? result = await FileSelectorPlatform.instance + .getSaveLocation(options: SaveDialogOptions(suggestedName: fileName)); if (result == null) { // Operation was canceled by the user. return; @@ -28,17 +26,18 @@ class SaveTextPage extends StatelessWidget { final String text = _contentController.text; final Uint8List fileData = Uint8List.fromList(text.codeUnits); const String fileMimeType = 'text/plain'; - final XFile textFile = - XFile.fromData(fileData, mimeType: fileMimeType, name: fileName); + final XFile textFile = XFile.fromData( + fileData, + mimeType: fileMimeType, + name: fileName, + ); await textFile.saveTo(result.path); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Save text into a file'), - ), + appBar: AppBar(title: const Text('Save text into a file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_macos/example/pubspec.yaml b/packages/file_selector/file_selector_macos/example/pubspec.yaml index 237db1d8656..d27a6935bcf 100644 --- a/packages/file_selector/file_selector_macos/example/pubspec.yaml +++ b/packages/file_selector/file_selector_macos/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: file_selector_macos: diff --git a/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart b/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart index 3489938a73a..6f71f837f63 100644 --- a/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart +++ b/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart @@ -21,16 +21,18 @@ class FileSelectorMacOS extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List paths = - await _hostApi.displayOpenPanel(OpenPanelOptions( - allowsMultipleSelection: false, - canChooseDirectories: false, - canChooseFiles: true, - baseOptions: SavePanelOptions( - allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), - directoryPath: initialDirectory, - prompt: confirmButtonText, - ))); + final List paths = await _hostApi.displayOpenPanel( + OpenPanelOptions( + allowsMultipleSelection: false, + canChooseDirectories: false, + canChooseFiles: true, + baseOptions: SavePanelOptions( + allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), + directoryPath: initialDirectory, + prompt: confirmButtonText, + ), + ), + ); return paths.isEmpty ? null : XFile(paths.first!); } @@ -40,16 +42,18 @@ class FileSelectorMacOS extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List paths = - await _hostApi.displayOpenPanel(OpenPanelOptions( - allowsMultipleSelection: true, - canChooseDirectories: false, - canChooseFiles: true, - baseOptions: SavePanelOptions( - allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), - directoryPath: initialDirectory, - prompt: confirmButtonText, - ))); + final List paths = await _hostApi.displayOpenPanel( + OpenPanelOptions( + allowsMultipleSelection: true, + canChooseDirectories: false, + canChooseFiles: true, + baseOptions: SavePanelOptions( + allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), + directoryPath: initialDirectory, + prompt: confirmButtonText, + ), + ), + ); return paths.map((String? path) => XFile(path!)).toList(); } @@ -61,12 +65,13 @@ class FileSelectorMacOS extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileSaveLocation? location = await getSaveLocation( - acceptedTypeGroups: acceptedTypeGroups, - options: SaveDialogOptions( - initialDirectory: initialDirectory, - suggestedName: suggestedName, - confirmButtonText: confirmButtonText, - )); + acceptedTypeGroups: acceptedTypeGroups, + options: SaveDialogOptions( + initialDirectory: initialDirectory, + suggestedName: suggestedName, + confirmButtonText: confirmButtonText, + ), + ); return location?.path; } @@ -75,12 +80,14 @@ class FileSelectorMacOS extends FileSelectorPlatform { List? acceptedTypeGroups, SaveDialogOptions options = const SaveDialogOptions(), }) async { - final String? path = await _hostApi.displaySavePanel(SavePanelOptions( - allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), - directoryPath: options.initialDirectory, - nameFieldStringValue: options.suggestedName, - prompt: options.confirmButtonText, - )); + final String? path = await _hostApi.displaySavePanel( + SavePanelOptions( + allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), + directoryPath: options.initialDirectory, + nameFieldStringValue: options.suggestedName, + prompt: options.confirmButtonText, + ), + ); return path == null ? null : FileSaveLocation(path); } @@ -89,15 +96,17 @@ class FileSelectorMacOS extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List paths = - await _hostApi.displayOpenPanel(OpenPanelOptions( - allowsMultipleSelection: false, - canChooseDirectories: true, - canChooseFiles: false, - baseOptions: SavePanelOptions( - directoryPath: initialDirectory, - prompt: confirmButtonText, - ))); + final List paths = await _hostApi.displayOpenPanel( + OpenPanelOptions( + allowsMultipleSelection: false, + canChooseDirectories: true, + canChooseFiles: false, + baseOptions: SavePanelOptions( + directoryPath: initialDirectory, + prompt: confirmButtonText, + ), + ), + ); return paths.isEmpty ? null : paths.first; } @@ -106,15 +115,17 @@ class FileSelectorMacOS extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List paths = - await _hostApi.displayOpenPanel(OpenPanelOptions( - allowsMultipleSelection: true, - canChooseDirectories: true, - canChooseFiles: false, - baseOptions: SavePanelOptions( - directoryPath: initialDirectory, - prompt: confirmButtonText, - ))); + final List paths = await _hostApi.displayOpenPanel( + OpenPanelOptions( + allowsMultipleSelection: true, + canChooseDirectories: true, + canChooseFiles: false, + baseOptions: SavePanelOptions( + directoryPath: initialDirectory, + prompt: confirmButtonText, + ), + ), + ); return paths.isEmpty ? [] : List.from(paths); } @@ -139,11 +150,13 @@ class FileSelectorMacOS extends FileSelectorPlatform { if ((typeGroup.extensions?.isEmpty ?? true) && (typeGroup.uniformTypeIdentifiers?.isEmpty ?? true) && (typeGroup.mimeTypes?.isEmpty ?? true)) { - throw ArgumentError('Provided type group $typeGroup does not allow ' - 'all files, but does not set any of the macOS-supported filter ' - 'categories. At least one of "extensions", ' - '"uniformTypeIdentifiers", or "mimeTypes" must be non-empty for ' - 'macOS if anything is non-empty.'); + throw ArgumentError( + 'Provided type group $typeGroup does not allow ' + 'all files, but does not set any of the macOS-supported filter ' + 'categories. At least one of "extensions", ' + '"uniformTypeIdentifiers", or "mimeTypes" must be non-empty for ' + 'macOS if anything is non-empty.', + ); } allowedTypes.extensions.addAll(typeGroup.extensions ?? []); allowedTypes.mimeTypes.addAll(typeGroup.mimeTypes ?? []); diff --git a/packages/file_selector/file_selector_macos/lib/src/messages.g.dart b/packages/file_selector/file_selector_macos/lib/src/messages.g.dart index 087f9abbadb..2f0bb410d14 100644 --- a/packages/file_selector/file_selector_macos/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_macos/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -32,14 +35,17 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -59,11 +65,7 @@ class AllowedTypes { List utis; List _toList() { - return [ - extensions, - mimeTypes, - utis, - ]; + return [extensions, mimeTypes, utis]; } Object encode() { @@ -255,11 +257,12 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + FileSelectorApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -275,12 +278,13 @@ class FileSelectorApi { 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [options], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([options]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -309,12 +313,13 @@ class FileSelectorApi { 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [options], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([options]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/file_selector/file_selector_macos/pigeons/messages.dart b/packages/file_selector/file_selector_macos/pigeons/messages.dart index fa92741d4cd..34268b5fc5d 100644 --- a/packages/file_selector/file_selector_macos/pigeons/messages.dart +++ b/packages/file_selector/file_selector_macos/pigeons/messages.dart @@ -3,15 +3,16 @@ // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - input: 'pigeons/messages.dart', - swiftOut: - 'macos/file_selector_macos/Sources/file_selector_macos/messages.g.swift', - dartOut: 'lib/src/messages.g.dart', - dartTestOut: 'test/messages_test.g.dart', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + input: 'pigeons/messages.dart', + swiftOut: + 'macos/file_selector_macos/Sources/file_selector_macos/messages.g.swift', + dartOut: 'lib/src/messages.g.dart', + dartTestOut: 'test/messages_test.g.dart', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// A Pigeon representation of the macOS portion of an `XTypeGroup`. class AllowedTypes { const AllowedTypes({ diff --git a/packages/file_selector/file_selector_macos/pubspec.yaml b/packages/file_selector/file_selector_macos/pubspec.yaml index 2c73dc8add7..0890520cc13 100644 --- a/packages/file_selector/file_selector_macos/pubspec.yaml +++ b/packages/file_selector/file_selector_macos/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.9.4+4 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart b/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart index 39534230f01..1033ae5f3ae 100644 --- a/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart +++ b/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart @@ -38,14 +38,16 @@ void main() { group('openFile', () { test('works as expected with no arguments', () async { - when(mockApi.displayOpenPanel(any)) - .thenAnswer((_) async => ['foo']); + when( + mockApi.displayOpenPanel(any), + ).thenAnswer((_) async => ['foo']); final XFile? file = await plugin.openFile(); expect(file!.path, 'foo'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.allowsMultipleSelection, false); expect(options.canChooseFiles, true); @@ -73,30 +75,39 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); await plugin.openFile(acceptedTypeGroups: [group, groupTwo]); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; - expect(options.baseOptions.allowedFileTypes!.extensions, - ['txt', 'jpg']); - expect(options.baseOptions.allowedFileTypes!.mimeTypes, - ['text/plain', 'image/jpg']); - expect(options.baseOptions.allowedFileTypes!.utis, - ['public.text', 'public.image']); + expect(options.baseOptions.allowedFileTypes!.extensions, [ + 'txt', + 'jpg', + ]); + expect(options.baseOptions.allowedFileTypes!.mimeTypes, [ + 'text/plain', + 'image/jpg', + ]); + expect(options.baseOptions.allowedFileTypes!.utis, [ + 'public.text', + 'public.image', + ]); }); test('passes initialDirectory correctly', () async { await plugin.openFile(initialDirectory: '/example/directory'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.directoryPath, '/example/directory'); }); @@ -104,8 +115,9 @@ void main() { test('passes confirmButtonText correctly', () async { await plugin.openFile(confirmButtonText: 'Open File'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.prompt, 'Open File'); }); @@ -117,31 +129,34 @@ void main() { ); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFile(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), completes); + plugin.openFile(acceptedTypeGroups: [group]), + completes, + ); }); }); group('openFiles', () { test('works as expected with no arguments', () async { - when(mockApi.displayOpenPanel(any)) - .thenAnswer((_) async => ['foo', 'bar']); + when( + mockApi.displayOpenPanel(any), + ).thenAnswer((_) async => ['foo', 'bar']); final List files = await plugin.openFiles(); expect(files[0].path, 'foo'); expect(files[1].path, 'bar'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.allowsMultipleSelection, true); expect(options.canChooseFiles, true); @@ -169,30 +184,39 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); await plugin.openFiles(acceptedTypeGroups: [group, groupTwo]); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; - expect(options.baseOptions.allowedFileTypes!.extensions, - ['txt', 'jpg']); - expect(options.baseOptions.allowedFileTypes!.mimeTypes, - ['text/plain', 'image/jpg']); - expect(options.baseOptions.allowedFileTypes!.utis, - ['public.text', 'public.image']); + expect(options.baseOptions.allowedFileTypes!.extensions, [ + 'txt', + 'jpg', + ]); + expect(options.baseOptions.allowedFileTypes!.mimeTypes, [ + 'text/plain', + 'image/jpg', + ]); + expect(options.baseOptions.allowedFileTypes!.utis, [ + 'public.text', + 'public.image', + ]); }); test('passes initialDirectory correctly', () async { await plugin.openFiles(initialDirectory: '/example/directory'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.directoryPath, '/example/directory'); }); @@ -200,8 +224,9 @@ void main() { test('passes confirmButtonText correctly', () async { await plugin.openFiles(confirmButtonText: 'Open File'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.prompt, 'Open File'); }); @@ -213,17 +238,18 @@ void main() { ); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFiles(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), completes); + plugin.openFiles(acceptedTypeGroups: [group]), + completes, + ); }); }); @@ -234,8 +260,9 @@ void main() { final String? path = await plugin.getSavePath(); expect(path, 'foo'); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.allowedFileTypes, null); expect(options.directoryPath, null); @@ -260,30 +287,38 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); - await plugin - .getSavePath(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSavePath( + acceptedTypeGroups: [group, groupTwo], + ); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.allowedFileTypes!.extensions, ['txt', 'jpg']); - expect(options.allowedFileTypes!.mimeTypes, - ['text/plain', 'image/jpg']); - expect(options.allowedFileTypes!.utis, - ['public.text', 'public.image']); + expect(options.allowedFileTypes!.mimeTypes, [ + 'text/plain', + 'image/jpg', + ]); + expect(options.allowedFileTypes!.utis, [ + 'public.text', + 'public.image', + ]); }); test('passes initialDirectory correctly', () async { await plugin.getSavePath(initialDirectory: '/example/directory'); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.directoryPath, '/example/directory'); }); @@ -291,8 +326,9 @@ void main() { test('passes confirmButtonText correctly', () async { await plugin.getSavePath(confirmButtonText: 'Open File'); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.prompt, 'Open File'); }); @@ -304,41 +340,42 @@ void main() { ); await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.getSavePath(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - completes); + plugin.getSavePath(acceptedTypeGroups: [group]), + completes, + ); }); test('ignores all type groups if any of them is a wildcard', () async { - await plugin.getSavePath(acceptedTypeGroups: [ - const XTypeGroup( - label: 'text', - extensions: ['txt'], - mimeTypes: ['text/plain'], - uniformTypeIdentifiers: ['public.text'], - ), - const XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - ), - const XTypeGroup( - label: 'any', - ), - ]); + await plugin.getSavePath( + acceptedTypeGroups: [ + const XTypeGroup( + label: 'text', + extensions: ['txt'], + mimeTypes: ['text/plain'], + uniformTypeIdentifiers: ['public.text'], + ), + const XTypeGroup( + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + ), + const XTypeGroup(label: 'any'), + ], + ); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.allowedFileTypes, null); }); @@ -351,8 +388,9 @@ void main() { final FileSaveLocation? location = await plugin.getSaveLocation(); expect(location?.path, 'foo'); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.allowedFileTypes, null); expect(options.directoryPath, null); @@ -377,42 +415,54 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); - await plugin - .getSaveLocation(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSaveLocation( + acceptedTypeGroups: [group, groupTwo], + ); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.allowedFileTypes!.extensions, ['txt', 'jpg']); - expect(options.allowedFileTypes!.mimeTypes, - ['text/plain', 'image/jpg']); - expect(options.allowedFileTypes!.utis, - ['public.text', 'public.image']); + expect(options.allowedFileTypes!.mimeTypes, [ + 'text/plain', + 'image/jpg', + ]); + expect(options.allowedFileTypes!.utis, [ + 'public.text', + 'public.image', + ]); }); test('passes initialDirectory correctly', () async { await plugin.getSaveLocation( - options: - const SaveDialogOptions(initialDirectory: '/example/directory')); + options: const SaveDialogOptions( + initialDirectory: '/example/directory', + ), + ); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.directoryPath, '/example/directory'); }); test('passes confirmButtonText correctly', () async { await plugin.getSaveLocation( - options: const SaveDialogOptions(confirmButtonText: 'Open File')); + options: const SaveDialogOptions(confirmButtonText: 'Open File'), + ); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.prompt, 'Open File'); }); @@ -424,41 +474,42 @@ void main() { ); await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.getSaveLocation(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - completes); + plugin.getSaveLocation(acceptedTypeGroups: [group]), + completes, + ); }); test('ignores all type groups if any of them is a wildcard', () async { - await plugin.getSaveLocation(acceptedTypeGroups: [ - const XTypeGroup( - label: 'text', - extensions: ['txt'], - mimeTypes: ['text/plain'], - uniformTypeIdentifiers: ['public.text'], - ), - const XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - ), - const XTypeGroup( - label: 'any', - ), - ]); + await plugin.getSaveLocation( + acceptedTypeGroups: [ + const XTypeGroup( + label: 'text', + extensions: ['txt'], + mimeTypes: ['text/plain'], + uniformTypeIdentifiers: ['public.text'], + ), + const XTypeGroup( + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + ), + const XTypeGroup(label: 'any'), + ], + ); - final VerificationResult result = - verify(mockApi.displaySavePanel(captureAny)); + final VerificationResult result = verify( + mockApi.displaySavePanel(captureAny), + ); final SavePanelOptions options = result.captured[0] as SavePanelOptions; expect(options.allowedFileTypes, null); }); @@ -466,14 +517,16 @@ void main() { group('getDirectoryPath', () { test('works as expected with no arguments', () async { - when(mockApi.displayOpenPanel(any)) - .thenAnswer((_) async => ['foo']); + when( + mockApi.displayOpenPanel(any), + ).thenAnswer((_) async => ['foo']); final String? path = await plugin.getDirectoryPath(); expect(path, 'foo'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.allowsMultipleSelection, false); expect(options.canChooseFiles, false); @@ -495,8 +548,9 @@ void main() { test('passes initialDirectory correctly', () async { await plugin.getDirectoryPath(initialDirectory: '/example/directory'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.directoryPath, '/example/directory'); }); @@ -504,8 +558,9 @@ void main() { test('passes confirmButtonText correctly', () async { await plugin.getDirectoryPath(confirmButtonText: 'Open File'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.prompt, 'Open File'); }); @@ -513,15 +568,24 @@ void main() { group('getDirectoryPaths', () { test('works as expected with no arguments', () async { - when(mockApi.displayOpenPanel(any)).thenAnswer((_) async => - ['firstDirectory', 'secondDirectory', 'thirdDirectory']); + when(mockApi.displayOpenPanel(any)).thenAnswer( + (_) async => [ + 'firstDirectory', + 'secondDirectory', + 'thirdDirectory', + ], + ); final List path = await plugin.getDirectoryPaths(); - expect(path, - ['firstDirectory', 'secondDirectory', 'thirdDirectory']); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + expect(path, [ + 'firstDirectory', + 'secondDirectory', + 'thirdDirectory', + ]); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.allowsMultipleSelection, true); expect(options.canChooseFiles, false); @@ -543,8 +607,9 @@ void main() { test('passes confirmButtonText correctly', () async { await plugin.getDirectoryPaths(confirmButtonText: 'Select directories'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.prompt, 'Select directories'); }); @@ -552,8 +617,9 @@ void main() { test('passes initialDirectory correctly', () async { await plugin.getDirectoryPaths(initialDirectory: '/example/directory'); - final VerificationResult result = - verify(mockApi.displayOpenPanel(captureAny)); + final VerificationResult result = verify( + mockApi.displayOpenPanel(captureAny), + ); final OpenPanelOptions options = result.captured[0] as OpenPanelOptions; expect(options.baseOptions.directoryPath, '/example/directory'); }); diff --git a/packages/file_selector/file_selector_macos/test/file_selector_macos_test.mocks.dart b/packages/file_selector/file_selector_macos/test/file_selector_macos_test.mocks.dart index 63ade67d21a..6d8611a2a1c 100644 --- a/packages/file_selector/file_selector_macos/test/file_selector_macos_test.mocks.dart +++ b/packages/file_selector/file_selector_macos/test/file_selector_macos_test.mocks.dart @@ -35,20 +35,16 @@ class MockTestFileSelectorApi extends _i1.Mock @override _i3.Future> displayOpenPanel(_i4.OpenPanelOptions? options) => (super.noSuchMethod( - Invocation.method( - #displayOpenPanel, - [options], - ), - returnValue: _i3.Future>.value([]), - ) as _i3.Future>); + Invocation.method(#displayOpenPanel, [options]), + returnValue: _i3.Future>.value([]), + ) + as _i3.Future>); @override _i3.Future displaySavePanel(_i4.SavePanelOptions? options) => (super.noSuchMethod( - Invocation.method( - #displaySavePanel, - [options], - ), - returnValue: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#displaySavePanel, [options]), + returnValue: _i3.Future.value(), + ) + as _i3.Future); } diff --git a/packages/file_selector/file_selector_macos/test/messages_test.g.dart b/packages/file_selector/file_selector_macos/test/messages_test.g.dart index ec908611ec3..c7592486ad7 100644 --- a/packages/file_selector/file_selector_macos/test/messages_test.g.dart +++ b/packages/file_selector/file_selector_macos/test/messages_test.g.dart @@ -73,68 +73,89 @@ abstract class TestFileSelectorApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel was null.'); - final List args = (message as List?)!; - final OpenPanelOptions? arg_options = (args[0] as OpenPanelOptions?); - assert(arg_options != null, - 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel was null, expected non-null OpenPanelOptions.'); - try { - final List output = - await api.displayOpenPanel(arg_options!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel was null.', + ); + final List args = (message as List?)!; + final OpenPanelOptions? arg_options = + (args[0] as OpenPanelOptions?); + assert( + arg_options != null, + 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel was null, expected non-null OpenPanelOptions.', + ); + try { + final List output = await api.displayOpenPanel( + arg_options!, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel was null.'); - final List args = (message as List?)!; - final SavePanelOptions? arg_options = (args[0] as SavePanelOptions?); - assert(arg_options != null, - 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel was null, expected non-null SavePanelOptions.'); - try { - final String? output = await api.displaySavePanel(arg_options!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel was null.', + ); + final List args = (message as List?)!; + final SavePanelOptions? arg_options = + (args[0] as SavePanelOptions?); + assert( + arg_options != null, + 'Argument for dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel was null, expected non-null SavePanelOptions.', + ); + try { + final String? output = await api.displaySavePanel(arg_options!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/packages/file_selector/file_selector_platform_interface/CHANGELOG.md b/packages/file_selector/file_selector_platform_interface/CHANGELOG.md index 506f2809830..4274cd53af5 100644 --- a/packages/file_selector/file_selector_platform_interface/CHANGELOG.md +++ b/packages/file_selector/file_selector_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.6.2 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 98184cab876..8d787f4fa3b 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 @@ -7,8 +7,9 @@ import 'package:flutter/services.dart'; import '../../file_selector_platform_interface.dart'; -const MethodChannel _channel = - MethodChannel('plugins.flutter.io/file_selector'); +const MethodChannel _channel = MethodChannel( + 'plugins.flutter.io/file_selector', +); /// An implementation of [FileSelectorPlatform] that uses method channels. class MethodChannelFileSelector extends FileSelectorPlatform { @@ -22,17 +23,16 @@ class MethodChannelFileSelector extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List? path = await _channel.invokeListMethod( - 'openFile', - { - 'acceptedTypeGroups': acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), - 'initialDirectory': initialDirectory, - 'confirmButtonText': confirmButtonText, - 'multiple': false, - }, - ); + final List? path = await _channel + .invokeListMethod('openFile', { + 'acceptedTypeGroups': + acceptedTypeGroups + ?.map((XTypeGroup group) => group.toJSON()) + .toList(), + 'initialDirectory': initialDirectory, + 'confirmButtonText': confirmButtonText, + 'multiple': false, + }); return path == null ? null : XFile(path.first); } @@ -42,17 +42,16 @@ class MethodChannelFileSelector extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List? pathList = await _channel.invokeListMethod( - 'openFile', - { - 'acceptedTypeGroups': acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), - 'initialDirectory': initialDirectory, - 'confirmButtonText': confirmButtonText, - 'multiple': true, - }, - ); + final List? pathList = await _channel + .invokeListMethod('openFile', { + 'acceptedTypeGroups': + acceptedTypeGroups + ?.map((XTypeGroup group) => group.toJSON()) + .toList(), + 'initialDirectory': initialDirectory, + 'confirmButtonText': confirmButtonText, + 'multiple': true, + }); return pathList?.map((String path) => XFile(path)).toList() ?? []; } @@ -63,17 +62,15 @@ class MethodChannelFileSelector extends FileSelectorPlatform { String? suggestedName, String? confirmButtonText, }) async { - return _channel.invokeMethod( - 'getSavePath', - { - 'acceptedTypeGroups': acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), - 'initialDirectory': initialDirectory, - 'suggestedName': suggestedName, - 'confirmButtonText': confirmButtonText, - }, - ); + return _channel.invokeMethod('getSavePath', { + 'acceptedTypeGroups': + acceptedTypeGroups + ?.map((XTypeGroup group) => group.toJSON()) + .toList(), + 'initialDirectory': initialDirectory, + 'suggestedName': suggestedName, + 'confirmButtonText': confirmButtonText, + }); } @override @@ -81,18 +78,17 @@ class MethodChannelFileSelector extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - return _channel.invokeMethod( - 'getDirectoryPath', - { - 'initialDirectory': initialDirectory, - 'confirmButtonText': confirmButtonText, - }, - ); + return _channel.invokeMethod('getDirectoryPath', { + 'initialDirectory': initialDirectory, + 'confirmButtonText': confirmButtonText, + }); } @override - Future> getDirectoryPaths( - {String? initialDirectory, String? confirmButtonText}) async { + Future> getDirectoryPaths({ + String? initialDirectory, + String? confirmButtonText, + }) async { final List? pathList = await _channel.invokeListMethod( 'getDirectoryPaths', { diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/types/file_dialog_options.dart b/packages/file_selector/file_selector_platform_interface/lib/src/types/file_dialog_options.dart index 5797e356b27..f456b4ae157 100644 --- a/packages/file_selector/file_selector_platform_interface/lib/src/types/file_dialog_options.dart +++ b/packages/file_selector/file_selector_platform_interface/lib/src/types/file_dialog_options.dart @@ -21,8 +21,11 @@ class FileDialogOptions { @immutable class SaveDialogOptions extends FileDialogOptions { /// Creates a new options set with the given settings. - const SaveDialogOptions( - {super.initialDirectory, super.confirmButtonText, this.suggestedName}); + const SaveDialogOptions({ + super.initialDirectory, + super.confirmButtonText, + this.suggestedName, + }); /// The suggested name of the file to save or open. final String? suggestedName; 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 0a556b3a2f0..e2690399cfb 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 @@ -17,10 +17,12 @@ class XTypeGroup { List? uniformTypeIdentifiers, this.webWildCards, @Deprecated('Use uniformTypeIdentifiers instead') List? macUTIs, - }) : _extensions = extensions, - assert(uniformTypeIdentifiers == null || macUTIs == null, - 'Only one of uniformTypeIdentifiers or macUTIs can be non-null'), - uniformTypeIdentifiers = uniformTypeIdentifiers ?? macUTIs; + }) : _extensions = extensions, + assert( + uniformTypeIdentifiers == null || macUTIs == null, + 'Only one of uniformTypeIdentifiers or macUTIs can be non-null', + ), + uniformTypeIdentifiers = uniformTypeIdentifiers ?? macUTIs; /// The 'name' or reference to this group of types. final String? label; @@ -68,7 +70,8 @@ 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 833ed7dd82a..b52bcc0944b 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.6.2 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: cross_file: ^0.3.0 diff --git a/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart b/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart index 7870951f321..cbacbbf648f 100644 --- a/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart +++ b/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart @@ -17,13 +17,12 @@ void main() { setUp(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - plugin.channel, - (MethodCall methodCall) async { - log.add(methodCall); - return null; - }, - ); + .setMockMethodCallHandler(plugin.channel, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); log.clear(); }); @@ -38,14 +37,16 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); - await plugin - .openFile(acceptedTypeGroups: [group, groupTwo]); + await plugin.openFile( + acceptedTypeGroups: [group, groupTwo], + ); expectMethodCall( log, @@ -53,7 +54,7 @@ void main() { arguments: { 'acceptedTypeGroups': >[ group.toJSON(), - groupTwo.toJSON() + groupTwo.toJSON(), ], 'initialDirectory': null, 'confirmButtonText': null, @@ -100,14 +101,16 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); - await plugin - .openFiles(acceptedTypeGroups: [group, groupTwo]); + await plugin.openFiles( + acceptedTypeGroups: [group, groupTwo], + ); expectMethodCall( log, @@ -115,7 +118,7 @@ void main() { arguments: { 'acceptedTypeGroups': >[ group.toJSON(), - groupTwo.toJSON() + groupTwo.toJSON(), ], 'initialDirectory': null, 'confirmButtonText': null, @@ -163,14 +166,16 @@ void main() { ); const XTypeGroup groupTwo = XTypeGroup( - label: 'image', - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - uniformTypeIdentifiers: ['public.image'], - webWildCards: ['image/*']); + label: 'image', + extensions: ['jpg'], + mimeTypes: ['image/jpg'], + uniformTypeIdentifiers: ['public.image'], + webWildCards: ['image/*'], + ); - await plugin - .getSavePath(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSavePath( + acceptedTypeGroups: [group, groupTwo], + ); expectMethodCall( log, @@ -178,7 +183,7 @@ void main() { arguments: { 'acceptedTypeGroups': >[ group.toJSON(), - groupTwo.toJSON() + groupTwo.toJSON(), ], 'initialDirectory': null, 'suggestedName': null, @@ -256,7 +261,8 @@ void main() { }); test('passes confirmButtonText correctly', () async { await plugin.getDirectoryPaths( - confirmButtonText: 'Select one or more Folders'); + confirmButtonText: 'Select one or more Folders', + ); expectMethodCall( log, diff --git a/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart b/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart index 0a36c82be9b..f83267873ef 100644 --- a/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart +++ b/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart @@ -32,9 +32,7 @@ void main() { }); test('a wildcard group can be created', () { - const XTypeGroup group = XTypeGroup( - label: 'Any', - ); + const XTypeGroup group = XTypeGroup(label: 'Any'); final Map jsonMap = group.toJSON(); expect(jsonMap['extensions'], null); @@ -57,14 +55,22 @@ void main() { }); test('allowsAny returns false if anything is set', () { - const XTypeGroup extensionOnly = - XTypeGroup(label: 'extensions', extensions: ['txt']); - const XTypeGroup mimeOnly = - XTypeGroup(label: 'mime', mimeTypes: ['text/plain']); + const XTypeGroup extensionOnly = XTypeGroup( + label: 'extensions', + extensions: ['txt'], + ); + const XTypeGroup mimeOnly = XTypeGroup( + label: 'mime', + mimeTypes: ['text/plain'], + ); const XTypeGroup utiOnly = XTypeGroup( - label: 'utis', uniformTypeIdentifiers: ['public.text']); - const XTypeGroup webOnly = - XTypeGroup(label: 'web', webWildCards: ['.txt']); + label: 'utis', + uniformTypeIdentifiers: ['public.text'], + ); + const XTypeGroup webOnly = XTypeGroup( + label: 'web', + webWildCards: ['.txt'], + ); expect(extensionOnly.allowsAny, false); expect(mimeOnly.allowsAny, false); @@ -75,70 +81,75 @@ void main() { group('macUTIs -> uniformTypeIdentifiers transition', () { test('passing only macUTIs should fill uniformTypeIdentifiers', () { const List uniformTypeIdentifiers = [ - 'public.plain-text' + 'public.plain-text', ]; - const XTypeGroup group = XTypeGroup( - macUTIs: uniformTypeIdentifiers, - ); + const XTypeGroup group = XTypeGroup(macUTIs: uniformTypeIdentifiers); expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers); }); test( - 'passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers', - () { - const List uniformTypeIdentifiers = [ - 'public.plain-text' - ]; - const XTypeGroup group = XTypeGroup( - uniformTypeIdentifiers: uniformTypeIdentifiers, - ); - - expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers); - }); + 'passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers', + () { + const List uniformTypeIdentifiers = [ + 'public.plain-text', + ]; + const XTypeGroup group = XTypeGroup( + uniformTypeIdentifiers: uniformTypeIdentifiers, + ); + + expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers); + }, + ); test('macUTIs getter return macUTIs value passed in constructor', () { const List uniformTypeIdentifiers = [ - 'public.plain-text' + 'public.plain-text', ]; - const XTypeGroup group = XTypeGroup( - macUTIs: uniformTypeIdentifiers, - ); + const XTypeGroup group = XTypeGroup(macUTIs: uniformTypeIdentifiers); expect(group.macUTIs, uniformTypeIdentifiers); }); test( - 'macUTIs getter returns uniformTypeIdentifiers value passed in constructor', - () { - const List uniformTypeIdentifiers = [ - 'public.plain-text' - ]; - const XTypeGroup group = XTypeGroup( - uniformTypeIdentifiers: uniformTypeIdentifiers, - ); - - expect(group.macUTIs, uniformTypeIdentifiers); - }); + 'macUTIs getter returns uniformTypeIdentifiers value passed in constructor', + () { + const List uniformTypeIdentifiers = [ + 'public.plain-text', + ]; + const XTypeGroup group = XTypeGroup( + uniformTypeIdentifiers: uniformTypeIdentifiers, + ); + + expect(group.macUTIs, uniformTypeIdentifiers); + }, + ); test('passing both uniformTypeIdentifiers and macUTIs should throw', () { expect( - () => XTypeGroup( - macUTIs: const ['public.plain-text'], - uniformTypeIdentifiers: const ['public.plain-images']), - throwsA(predicate((Object? e) => - e is AssertionError && - e.message == - 'Only one of uniformTypeIdentifiers or macUTIs can be non-null'))); + () => XTypeGroup( + macUTIs: const ['public.plain-text'], + uniformTypeIdentifiers: const ['public.plain-images'], + ), + throwsA( + predicate( + (Object? e) => + e is AssertionError && + e.message == + 'Only one of uniformTypeIdentifiers or macUTIs can be non-null', + ), + ), + ); }); test( - 'having uniformTypeIdentifiers and macUTIs as null should leave uniformTypeIdentifiers as null', - () { - const XTypeGroup group = XTypeGroup(); + 'having uniformTypeIdentifiers and macUTIs as null should leave uniformTypeIdentifiers as null', + () { + const XTypeGroup group = XTypeGroup(); - expect(group.uniformTypeIdentifiers, null); - }); + expect(group.uniformTypeIdentifiers, null); + }, + ); }); test('leading dots are removed from extensions', () { diff --git a/packages/file_selector/file_selector_web/CHANGELOG.md b/packages/file_selector/file_selector_web/CHANGELOG.md index c8e78ee96c0..5323271b741 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 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 aa9dcdba187..741fc07eb97 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', () { @@ -117,13 +117,19 @@ void main() { input: input, ); - expect(input.isConnected, true, - reason: 'input must be injected into the DOM'); + expect( + input.isConnected, + true, + reason: 'input must be injected into the DOM', + ); expect(input.accept, accept); expect(input.multiple, multiple); - expect(await wasClicked, true, - reason: - 'The should be clicked otherwise no dialog will be shown'); + expect( + await wasClicked, + true, + reason: + 'The should be clicked otherwise no dialog will be shown', + ); setFilesAndTriggerChange([]); await futureFile; diff --git a/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart b/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart index 80376c5449f..8a0a4f554a1 100644 --- a/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart +++ b/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart @@ -20,11 +20,13 @@ void main() { final XFile mockFile = createXFile('1001', 'identity.png'); final MockDomHelper mockDomHelper = MockDomHelper( - files: [mockFile], - expectAccept: '.jpg,.jpeg,image/png,image/*'); + files: [mockFile], + expectAccept: '.jpg,.jpeg,image/png,image/*', + ); - final FileSelectorWeb plugin = - FileSelectorWeb(domHelper: mockDomHelper); + final FileSelectorWeb plugin = FileSelectorWeb( + domHelper: mockDomHelper, + ); const XTypeGroup typeGroup = XTypeGroup( label: 'images', @@ -33,8 +35,9 @@ void main() { webWildCards: ['image/*'], ); - final XFile? file = - await plugin.openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await plugin.openFile( + acceptedTypeGroups: [typeGroup], + ); expect(file, isNotNull); expect(file!.name, mockFile.name); @@ -43,15 +46,15 @@ void main() { expect(await file.lastModified(), isNotNull); }); - testWidgets('returns null when getFiles returns an empty list', - (WidgetTester _) async { + testWidgets('returns null when getFiles returns an empty list', ( + WidgetTester _, + ) async { // Simulate returning an empty list of files from the DomHelper... - final MockDomHelper mockDomHelper = MockDomHelper( - files: [], - ); + final MockDomHelper mockDomHelper = MockDomHelper(files: []); - final FileSelectorWeb plugin = - FileSelectorWeb(domHelper: mockDomHelper); + final FileSelectorWeb plugin = FileSelectorWeb( + domHelper: mockDomHelper, + ); final XFile? file = await plugin.openFile(); @@ -65,20 +68,23 @@ void main() { final XFile mockFile2 = createXFile('', 'file2.txt'); final MockDomHelper mockDomHelper = MockDomHelper( - files: [mockFile1, mockFile2], - expectAccept: '.txt', - expectMultiple: true); + files: [mockFile1, mockFile2], + expectAccept: '.txt', + expectMultiple: true, + ); - final FileSelectorWeb plugin = - FileSelectorWeb(domHelper: mockDomHelper); + final FileSelectorWeb plugin = FileSelectorWeb( + domHelper: mockDomHelper, + ); const XTypeGroup typeGroup = XTypeGroup( label: 'files', extensions: ['.txt'], ); - final List files = - await plugin.openFiles(acceptedTypeGroups: [typeGroup]); + final List files = await plugin.openFiles( + acceptedTypeGroups: [typeGroup], + ); expect(files.length, 2); @@ -109,9 +115,9 @@ class MockDomHelper implements DomHelper { List files = const [], String expectAccept = '', bool expectMultiple = false, - }) : _files = files, - _expectedAccept = expectAccept, - _expectedMultiple = expectMultiple; + }) : _files = files, + _expectedAccept = expectAccept, + _expectedMultiple = expectMultiple; final List _files; final String _expectedAccept; @@ -123,10 +129,16 @@ class MockDomHelper implements DomHelper { bool multiple = false, HTMLInputElement? input, }) { - expect(accept, _expectedAccept, - reason: 'Expected "accept" value does not match.'); - expect(multiple, _expectedMultiple, - reason: 'Expected "multiple" value does not match.'); + expect( + accept, + _expectedAccept, + reason: 'Expected "accept" value does not match.', + ); + expect( + multiple, + _expectedMultiple, + reason: 'Expected "multiple" value does not match.', + ); return Future>.value(_files); } } diff --git a/packages/file_selector/file_selector_web/example/pubspec.yaml b/packages/file_selector/file_selector_web/example/pubspec.yaml index f2c8c2a1ee0..96fdf0fad6e 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: file_selector_platform_interface: ^2.6.0 diff --git a/packages/file_selector/file_selector_web/lib/file_selector_web.dart b/packages/file_selector/file_selector_web/lib/file_selector_web.dart index 53e0c6d5ab3..2b8a611e950 100644 --- a/packages/file_selector/file_selector_web/lib/file_selector_web.dart +++ b/packages/file_selector/file_selector_web/lib/file_selector_web.dart @@ -19,7 +19,7 @@ class FileSelectorWeb extends FileSelectorPlatform { /// to interact with the DOM. /// overrides parameter allows for testing to override functions FileSelectorWeb({@visibleForTesting DomHelper? domHelper}) - : _domHelper = domHelper ?? DomHelper(); + : _domHelper = domHelper ?? DomHelper(); final DomHelper _domHelper; @@ -34,8 +34,9 @@ class FileSelectorWeb extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List files = - await _openFiles(acceptedTypeGroups: acceptedTypeGroups); + final List files = await _openFiles( + acceptedTypeGroups: acceptedTypeGroups, + ); return files.isNotEmpty ? files.first : null; } @@ -57,8 +58,7 @@ class FileSelectorWeb extends FileSelectorPlatform { String? initialDirectory, String? suggestedName, String? confirmButtonText, - }) async => - ''; + }) async => ''; @override Future getSaveLocation({ @@ -74,17 +74,13 @@ class FileSelectorWeb extends FileSelectorPlatform { Future getDirectoryPath({ String? initialDirectory, String? confirmButtonText, - }) async => - null; + }) async => null; Future> _openFiles({ List? acceptedTypeGroups, bool multiple = false, }) async { final String accept = acceptedTypesToString(acceptedTypeGroups); - return _domHelper.getFiles( - accept: accept, - multiple: multiple, - ); + return _domHelper.getFiles(accept: accept, multiple: multiple); } } 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 c19748b9244..bf04632812b 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,11 @@ 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); }); @@ -72,9 +72,9 @@ class DomHelper { } XFile _convertFileToXFile(File file) => XFile( - URL.createObjectURL(file), - name: file.name, - length: file.size, - lastModified: DateTime.fromMillisecondsSinceEpoch(file.lastModified), - ); + URL.createObjectURL(file), + name: file.name, + length: file.size, + lastModified: DateTime.fromMillisecondsSinceEpoch(file.lastModified), + ); } diff --git a/packages/file_selector/file_selector_web/lib/src/utils.dart b/packages/file_selector/file_selector_web/lib/src/utils.dart index 7a7aa7a6950..3adfc995dbd 100644 --- a/packages/file_selector/file_selector_web/lib/src/utils.dart +++ b/packages/file_selector/file_selector_web/lib/src/utils.dart @@ -34,11 +34,13 @@ void _validateTypeGroup(XTypeGroup group) { if ((group.extensions?.isEmpty ?? true) && (group.mimeTypes?.isEmpty ?? true) && (group.webWildCards?.isEmpty ?? true)) { - throw ArgumentError('Provided type group $group does not allow ' - 'all files, but does not set any of the web-supported filter ' - 'categories. At least one of "extensions", "mimeTypes", or ' - '"webWildCards" must be non-empty for web if anything is ' - 'non-empty.'); + throw ArgumentError( + 'Provided type group $group does not allow ' + 'all files, but does not set any of the web-supported filter ' + 'categories. At least one of "extensions", "mimeTypes", or ' + '"webWildCards" must be non-empty for web if anything is ' + 'non-empty.', + ); } } diff --git a/packages/file_selector/file_selector_web/pubspec.yaml b/packages/file_selector/file_selector_web/pubspec.yaml index 449f8bb100b..52cd67b2c53 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_web/test/utils_test.dart b/packages/file_selector/file_selector_web/test/utils_test.dart index c1717572713..f40fccdc402 100644 --- a/packages/file_selector/file_selector_web/test/utils_test.dart +++ b/packages/file_selector/file_selector_web/test/utils_test.dart @@ -40,7 +40,9 @@ void main() { test('works with mime types', () { const List acceptedTypes = [ XTypeGroup( - label: 'jpgs', mimeTypes: ['image/jpeg', 'image/jpg']), + label: 'jpgs', + mimeTypes: ['image/jpeg', 'image/jpg'], + ), XTypeGroup(label: 'pngs', mimeTypes: ['image/png']), ]; final String accepts = acceptedTypesToString(acceptedTypes); @@ -60,7 +62,9 @@ void main() { test('throws for a type group that does not support web', () { const List acceptedTypes = [ XTypeGroup( - label: 'text', uniformTypeIdentifiers: ['public.text']), + label: 'text', + uniformTypeIdentifiers: ['public.text'], + ), ]; expect(() => acceptedTypesToString(acceptedTypes), throwsArgumentError); }); diff --git a/packages/file_selector/file_selector_windows/CHANGELOG.md b/packages/file_selector/file_selector_windows/CHANGELOG.md index f2d89d71236..8eaeeb2292f 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.9.3+4 diff --git a/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart b/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart index 351b403ca61..d227652335a 100644 --- a/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart @@ -13,10 +13,8 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const String confirmButtonText = 'Choose'; - final String? directoryPath = - await FileSelectorPlatform.instance.getDirectoryPath( - confirmButtonText: confirmButtonText, - ); + final String? directoryPath = await FileSelectorPlatform.instance + .getDirectoryPath(confirmButtonText: confirmButtonText); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -32,9 +30,7 @@ class GetDirectoryPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -67,9 +63,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directory'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoryPath), - ), + child: SingleChildScrollView(child: Text(directoryPath)), ), actions: [ TextButton( 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 ebe1f2ac825..1a236605e53 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 @@ -13,10 +13,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { Future _getDirectoryPaths(BuildContext context) async { const String confirmButtonText = 'Choose'; - final List directoriesPaths = - await FileSelectorPlatform.instance.getDirectoryPaths( - confirmButtonText: confirmButtonText, - ); + final List directoriesPaths = await FileSelectorPlatform.instance + .getDirectoryPaths(confirmButtonText: confirmButtonText); if (directoriesPaths.isEmpty) { // Operation was canceled by the user. return; @@ -24,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')), ); } } @@ -33,9 +31,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Select multiple directories'), - ), + appBar: AppBar(title: const Text('Select multiple directories')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -46,7 +42,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { foregroundColor: Colors.white, ), child: const Text( - 'Press to ask user to choose multiple directories'), + 'Press to ask user to choose multiple directories', + ), onPressed: () => _getDirectoryPaths(context), ), ], @@ -69,9 +66,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: const Text('Selected Directories'), content: Scrollbar( - child: SingleChildScrollView( - child: Text(directoryPaths), - ), + child: SingleChildScrollView(child: Text(directoryPaths)), ), actions: [ TextButton( 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 4715f267e36..9cfb34155c2 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 @@ -16,9 +16,7 @@ class HomePage extends StatelessWidget { foregroundColor: Colors.white, ); return Scaffold( - appBar: AppBar( - title: const Text('File Selector Demo Home Page'), - ), + appBar: AppBar(title: const Text('File Selector Demo Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -56,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 a88f850f5d6..3763baaad86 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_image_page.dart b/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart index e39dee95d4d..33ff35ee01e 100644 --- a/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart @@ -19,8 +19,9 @@ class OpenImagePage extends StatelessWidget { label: 'images', extensions: ['jpg', 'png'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -39,9 +40,7 @@ class OpenImagePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open an image'), - ), + appBar: AppBar(title: const Text('Open an image')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, 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 decb1b64c7e..07a3829a5a9 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 @@ -23,11 +23,9 @@ class OpenMultipleImagesPage extends StatelessWidget { label: 'PNGs', extensions: ['png'], ); - final List files = await FileSelectorPlatform.instance - .openFiles(acceptedTypeGroups: [ - jpgsTypeGroup, - pngTypeGroup, - ]); + final List files = await FileSelectorPlatform.instance.openFiles( + acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], + ); if (files.isEmpty) { // Operation was canceled by the user. return; @@ -43,9 +41,7 @@ class OpenMultipleImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open multiple images'), - ), + appBar: AppBar(title: const Text('Open multiple images')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -84,10 +80,12 @@ 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/lib/open_text_page.dart b/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart index 6ffbd28c92a..9a9f21da32e 100644 --- a/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart @@ -16,8 +16,9 @@ class OpenTextPage extends StatelessWidget { label: 'text', extensions: ['txt', 'json'], ); - final XFile? file = await FileSelectorPlatform.instance - .openFile(acceptedTypeGroups: [typeGroup]); + final XFile? file = await FileSelectorPlatform.instance.openFile( + acceptedTypeGroups: [typeGroup], + ); if (file == null) { // Operation was canceled by the user. return; @@ -36,9 +37,7 @@ class OpenTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Open a text file'), - ), + appBar: AppBar(title: const Text('Open a text file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -74,9 +73,7 @@ class TextDisplay extends StatelessWidget { return AlertDialog( title: Text(fileName), content: Scrollbar( - child: SingleChildScrollView( - child: Text(fileContent), - ), + child: SingleChildScrollView(child: Text(fileContent)), ), actions: [ TextButton( diff --git a/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart b/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart index 811ceb98ee1..e276dd4632e 100644 --- a/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart @@ -18,20 +18,14 @@ class SaveTextPage extends StatelessWidget { Future _saveFile() async { final String fileName = _nameController.text; - final FileSaveLocation? result = - await FileSelectorPlatform.instance.getSaveLocation( - options: SaveDialogOptions(suggestedName: fileName), - acceptedTypeGroups: const [ - XTypeGroup( - label: 'Plain text', - extensions: ['txt'], - ), - XTypeGroup( - label: 'JSON', - extensions: ['json'], - ), - ], - ); + final FileSaveLocation? result = await FileSelectorPlatform.instance + .getSaveLocation( + options: SaveDialogOptions(suggestedName: fileName), + acceptedTypeGroups: const [ + XTypeGroup(label: 'Plain text', extensions: ['txt']), + XTypeGroup(label: 'JSON', extensions: ['json']), + ], + ); // Operation was canceled by the user. if (result == null) { return; @@ -56,9 +50,7 @@ class SaveTextPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Save text into a file'), - ), + appBar: AppBar(title: const Text('Save text into a file')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/packages/file_selector/file_selector_windows/example/pubspec.yaml b/packages/file_selector/file_selector_windows/example/pubspec.yaml index 75e148954d6..7414ec65fdb 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 150e165fd21..510663d01ae 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 @@ -22,11 +22,12 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileDialogResult result = await _hostApi.showOpenDialog( - SelectionOptions( - allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), - ), - initialDirectory, - confirmButtonText); + SelectionOptions( + allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), + ), + initialDirectory, + confirmButtonText, + ); return result.paths.isEmpty ? null : XFile(result.paths.first); } @@ -37,12 +38,13 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileDialogResult result = await _hostApi.showOpenDialog( - SelectionOptions( - allowMultiple: true, - allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), - ), - initialDirectory, - confirmButtonText); + SelectionOptions( + allowMultiple: true, + allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), + ), + initialDirectory, + confirmButtonText, + ); return result.paths.map((String? path) => XFile(path!)).toList(); } @@ -54,12 +56,13 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileSaveLocation? location = await getSaveLocation( - acceptedTypeGroups: acceptedTypeGroups, - options: SaveDialogOptions( - initialDirectory: initialDirectory, - suggestedName: suggestedName, - confirmButtonText: confirmButtonText, - )); + acceptedTypeGroups: acceptedTypeGroups, + options: SaveDialogOptions( + initialDirectory: initialDirectory, + suggestedName: suggestedName, + confirmButtonText: confirmButtonText, + ), + ); return location?.path; } @@ -69,18 +72,21 @@ class FileSelectorWindows extends FileSelectorPlatform { SaveDialogOptions options = const SaveDialogOptions(), }) async { final FileDialogResult result = await _hostApi.showSaveDialog( - SelectionOptions( - allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), - ), - options.initialDirectory, - options.suggestedName, - options.confirmButtonText); + SelectionOptions( + allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), + ), + options.initialDirectory, + options.suggestedName, + options.confirmButtonText, + ); final int? groupIndex = result.typeGroupIndex; return result.paths.isEmpty ? null - : FileSaveLocation(result.paths.first, - activeFilter: - groupIndex == null ? null : acceptedTypeGroups?[groupIndex]); + : FileSaveLocation( + result.paths.first, + activeFilter: + groupIndex == null ? null : acceptedTypeGroups?[groupIndex], + ); } @override @@ -89,12 +95,10 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileDialogResult result = await _hostApi.showOpenDialog( - SelectionOptions( - selectFolders: true, - allowedTypes: [], - ), - initialDirectory, - confirmButtonText); + SelectionOptions(selectFolders: true, allowedTypes: []), + initialDirectory, + confirmButtonText, + ); return result.paths.isEmpty ? null : result.paths.first; } @@ -104,13 +108,14 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileDialogResult result = await _hostApi.showOpenDialog( - SelectionOptions( - allowMultiple: true, - selectFolders: true, - allowedTypes: [], - ), - initialDirectory, - confirmButtonText); + SelectionOptions( + allowMultiple: true, + selectFolders: true, + allowedTypes: [], + ), + initialDirectory, + confirmButtonText, + ); return result.paths.isEmpty ? [] : List.from(result.paths); } } @@ -118,12 +123,16 @@ class FileSelectorWindows extends FileSelectorPlatform { List _typeGroupsFromXTypeGroups(List? xtypes) { return (xtypes ?? []).map((XTypeGroup xtype) { if (!xtype.allowsAny && (xtype.extensions?.isEmpty ?? true)) { - throw ArgumentError('Provided type group $xtype does not allow ' - 'all files, but does not set any of the Windows-supported filter ' - 'categories. "extensions" must be non-empty for Windows if ' - 'anything is non-empty.'); + throw ArgumentError( + 'Provided type group $xtype does not allow ' + 'all files, but does not set any of the Windows-supported filter ' + 'categories. "extensions" must be non-empty for Windows if ' + 'anything is non-empty.', + ); } return TypeGroup( - label: xtype.label ?? '', extensions: xtype.extensions ?? []); + label: xtype.label ?? '', + extensions: xtype.extensions ?? [], + ); }).toList(); } 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 6ec5eee613c..5c4f8dd6943 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 @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -30,20 +33,14 @@ List wrapResponse( } class TypeGroup { - TypeGroup({ - required this.label, - required this.extensions, - }); + TypeGroup({required this.label, required this.extensions}); String label; List extensions; Object encode() { - return [ - label, - extensions, - ]; + return [label, extensions]; } static TypeGroup decode(Object result) { @@ -69,11 +66,7 @@ class SelectionOptions { List allowedTypes; Object encode() { - return [ - allowMultiple, - selectFolders, - allowedTypes, - ]; + return [allowMultiple, selectFolders, allowedTypes]; } static SelectionOptions decode(Object result) { @@ -88,10 +81,7 @@ class SelectionOptions { /// The result from an open or save dialog. class FileDialogResult { - FileDialogResult({ - required this.paths, - this.typeGroupIndex, - }); + FileDialogResult({required this.paths, this.typeGroupIndex}); /// The selected paths. /// @@ -105,10 +95,7 @@ class FileDialogResult { int? typeGroupIndex; Object encode() { - return [ - paths, - typeGroupIndex, - ]; + return [paths, typeGroupIndex]; } static FileDialogResult decode(Object result) { @@ -160,30 +147,38 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + FileSelectorApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); final String pigeonVar_messageChannelSuffix; - Future showOpenDialog(SelectionOptions options, - String? initialDirectory, String? confirmButtonText) async { + Future showOpenDialog( + SelectionOptions options, + String? initialDirectory, + String? confirmButtonText, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([options, initialDirectory, confirmButtonText]) - as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([ + options, + initialDirectory, + confirmButtonText, + ]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -203,25 +198,27 @@ class FileSelectorApi { } Future showSaveDialog( - SelectionOptions options, - String? initialDirectory, - String? suggestedName, - String? confirmButtonText) async { + SelectionOptions options, + String? initialDirectory, + String? suggestedName, + String? confirmButtonText, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([ - options, - initialDirectory, - suggestedName, - confirmButtonText - ]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([ + options, + initialDirectory, + suggestedName, + confirmButtonText, + ]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_windows/pigeons/messages.dart b/packages/file_selector/file_selector_windows/pigeons/messages.dart index 75ba308dc14..2a20c8a0a6e 100644 --- a/packages/file_selector/file_selector_windows/pigeons/messages.dart +++ b/packages/file_selector/file_selector_windows/pigeons/messages.dart @@ -4,14 +4,16 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - dartTestOut: 'test/test_api.g.dart', - cppOptions: CppOptions(namespace: 'file_selector_windows'), - cppHeaderOut: 'windows/messages.g.h', - cppSourceOut: 'windows/messages.g.cpp', - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + dartTestOut: 'test/test_api.g.dart', + cppOptions: CppOptions(namespace: 'file_selector_windows'), + cppHeaderOut: 'windows/messages.g.h', + cppSourceOut: 'windows/messages.g.cpp', + copyrightHeader: 'pigeons/copyright.txt', + ), +) class TypeGroup { TypeGroup(this.label, {required this.extensions}); diff --git a/packages/file_selector/file_selector_windows/pubspec.yaml b/packages/file_selector/file_selector_windows/pubspec.yaml index a42201304a8..48966187bfd 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart b/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart index 3a4510672f2..8241ce84d8a 100644 --- a/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart +++ b/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart @@ -32,16 +32,18 @@ void main() { group('openFile', () { setUp(() { - when(mockApi.showOpenDialog(any, any, any)) - .thenReturn(FileDialogResult(paths: ['foo'])); + when( + mockApi.showOpenDialog(any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo'])); }); test('simple call works', () async { final XFile? file = await plugin.openFile(); expect(file!.path, 'foo'); - final VerificationResult result = - verify(mockApi.showOpenDialog(captureAny, null, null)); + final VerificationResult result = verify( + mockApi.showOpenDialog(captureAny, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect(options.allowMultiple, false); expect(options.selectFolders, false); @@ -62,15 +64,17 @@ void main() { await plugin.openFile(acceptedTypeGroups: [group, groupTwo]); - final VerificationResult result = - verify(mockApi.showOpenDialog(captureAny, null, null)); + final VerificationResult result = verify( + mockApi.showOpenDialog(captureAny, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect( - _typeGroupListsMatch(options.allowedTypes, [ - TypeGroup(label: 'text', extensions: ['txt']), - TypeGroup(label: 'image', extensions: ['jpg']), - ]), - true); + _typeGroupListsMatch(options.allowedTypes, [ + TypeGroup(label: 'text', extensions: ['txt']), + TypeGroup(label: 'image', extensions: ['jpg']), + ]), + true, + ); }); test('passes initialDirectory correctly', () async { @@ -92,24 +96,26 @@ void main() { ); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFile(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), completes); + plugin.openFile(acceptedTypeGroups: [group]), + completes, + ); }); }); group('openFiles', () { setUp(() { - when(mockApi.showOpenDialog(any, any, any)) - .thenReturn(FileDialogResult(paths: ['foo', 'bar'])); + when( + mockApi.showOpenDialog(any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo', 'bar'])); }); test('simple call works', () async { @@ -117,8 +123,9 @@ void main() { expect(file[0].path, 'foo'); expect(file[1].path, 'bar'); - final VerificationResult result = - verify(mockApi.showOpenDialog(captureAny, null, null)); + final VerificationResult result = verify( + mockApi.showOpenDialog(captureAny, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect(options.allowMultiple, true); expect(options.selectFolders, false); @@ -139,15 +146,17 @@ void main() { await plugin.openFiles(acceptedTypeGroups: [group, groupTwo]); - final VerificationResult result = - verify(mockApi.showOpenDialog(captureAny, null, null)); + final VerificationResult result = verify( + mockApi.showOpenDialog(captureAny, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect( - _typeGroupListsMatch(options.allowedTypes, [ - TypeGroup(label: 'text', extensions: ['txt']), - TypeGroup(label: 'image', extensions: ['jpg']), - ]), - true); + _typeGroupListsMatch(options.allowedTypes, [ + TypeGroup(label: 'text', extensions: ['txt']), + TypeGroup(label: 'image', extensions: ['jpg']), + ]), + true, + ); }); test('passes initialDirectory correctly', () async { @@ -169,32 +178,35 @@ void main() { ); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.openFiles(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), completes); + plugin.openFiles(acceptedTypeGroups: [group]), + completes, + ); }); }); group('getDirectoryPath', () { setUp(() { - when(mockApi.showOpenDialog(any, any, any)) - .thenReturn(FileDialogResult(paths: ['foo'])); + when( + mockApi.showOpenDialog(any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo'])); }); test('simple call works', () async { final String? path = await plugin.getDirectoryPath(); expect(path, 'foo'); - final VerificationResult result = - verify(mockApi.showOpenDialog(captureAny, null, null)); + final VerificationResult result = verify( + mockApi.showOpenDialog(captureAny, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect(options.allowMultiple, false); expect(options.selectFolders, true); @@ -215,8 +227,9 @@ void main() { group('getDirectoryPaths', () { setUp(() { - when(mockApi.showOpenDialog(any, any, any)) - .thenReturn(FileDialogResult(paths: ['foo', 'bar'])); + when( + mockApi.showOpenDialog(any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo', 'bar'])); }); test('simple call works', () async { @@ -224,8 +237,9 @@ void main() { expect(paths[0], 'foo'); expect(paths[1], 'bar'); - final VerificationResult result = - verify(mockApi.showOpenDialog(captureAny, null, null)); + final VerificationResult result = verify( + mockApi.showOpenDialog(captureAny, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect(options.allowMultiple, true); expect(options.selectFolders, true); @@ -246,8 +260,9 @@ void main() { group('getSaveLocation', () { setUp(() { - when(mockApi.showSaveDialog(any, any, any, any)) - .thenReturn(FileDialogResult(paths: ['foo'])); + when( + mockApi.showSaveDialog(any, any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo'])); }); test('simple call works', () async { @@ -255,8 +270,9 @@ void main() { expect(location?.path, 'foo'); expect(location?.activeFilter, null); - final VerificationResult result = - verify(mockApi.showSaveDialog(captureAny, null, null, null)); + final VerificationResult result = verify( + mockApi.showSaveDialog(captureAny, null, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect(options.allowMultiple, false); expect(options.selectFolders, false); @@ -275,23 +291,27 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin - .getSaveLocation(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSaveLocation( + acceptedTypeGroups: [group, groupTwo], + ); - final VerificationResult result = - verify(mockApi.showSaveDialog(captureAny, null, null, null)); + final VerificationResult result = verify( + mockApi.showSaveDialog(captureAny, null, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect( - _typeGroupListsMatch(options.allowedTypes, [ - TypeGroup(label: 'text', extensions: ['txt']), - TypeGroup(label: 'image', extensions: ['jpg']), - ]), - true); + _typeGroupListsMatch(options.allowedTypes, [ + TypeGroup(label: 'text', extensions: ['txt']), + TypeGroup(label: 'image', extensions: ['jpg']), + ]), + true, + ); }); test('returns the selected type group correctly', () async { - when(mockApi.showSaveDialog(any, any, any, any)).thenReturn( - FileDialogResult(paths: ['foo'], typeGroupIndex: 1)); + when( + mockApi.showSaveDialog(any, any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo'], typeGroupIndex: 1)); const XTypeGroup group = XTypeGroup( label: 'text', extensions: ['txt'], @@ -304,8 +324,9 @@ void main() { mimeTypes: ['image/jpg'], ); - final FileSaveLocation? result = await plugin - .getSaveLocation(acceptedTypeGroups: [group, groupTwo]); + final FileSaveLocation? result = await plugin.getSaveLocation( + acceptedTypeGroups: [group, groupTwo], + ); verify(mockApi.showSaveDialog(captureAny, null, null, null)); @@ -314,22 +335,26 @@ void main() { test('passes initialDirectory correctly', () async { await plugin.getSaveLocation( - options: - const SaveDialogOptions(initialDirectory: '/example/directory')); + options: const SaveDialogOptions( + initialDirectory: '/example/directory', + ), + ); verify(mockApi.showSaveDialog(any, '/example/directory', null, null)); }); test('passes suggestedName correctly', () async { await plugin.getSaveLocation( - options: const SaveDialogOptions(suggestedName: 'baz.txt')); + options: const SaveDialogOptions(suggestedName: 'baz.txt'), + ); verify(mockApi.showSaveDialog(any, null, 'baz.txt', null)); }); test('passes confirmButtonText correctly', () async { await plugin.getSaveLocation( - options: const SaveDialogOptions(confirmButtonText: 'Save File')); + options: const SaveDialogOptions(confirmButtonText: 'Save File'), + ); verify(mockApi.showSaveDialog(any, null, null, 'Save File')); }); @@ -341,33 +366,35 @@ void main() { ); await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.getSaveLocation(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - completes); + plugin.getSaveLocation(acceptedTypeGroups: [group]), + completes, + ); }); }); group('getSavePath (deprecated)', () { setUp(() { - when(mockApi.showSaveDialog(any, any, any, any)) - .thenReturn(FileDialogResult(paths: ['foo'])); + when( + mockApi.showSaveDialog(any, any, any, any), + ).thenReturn(FileDialogResult(paths: ['foo'])); }); test('simple call works', () async { final String? path = await plugin.getSavePath(); expect(path, 'foo'); - final VerificationResult result = - verify(mockApi.showSaveDialog(captureAny, null, null, null)); + final VerificationResult result = verify( + mockApi.showSaveDialog(captureAny, null, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect(options.allowMultiple, false); expect(options.selectFolders, false); @@ -386,18 +413,21 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin - .getSavePath(acceptedTypeGroups: [group, groupTwo]); + await plugin.getSavePath( + acceptedTypeGroups: [group, groupTwo], + ); - final VerificationResult result = - verify(mockApi.showSaveDialog(captureAny, null, null, null)); + final VerificationResult result = verify( + mockApi.showSaveDialog(captureAny, null, null, null), + ); final SelectionOptions options = result.captured[0] as SelectionOptions; expect( - _typeGroupListsMatch(options.allowedTypes, [ - TypeGroup(label: 'text', extensions: ['txt']), - TypeGroup(label: 'image', extensions: ['jpg']), - ]), - true); + _typeGroupListsMatch(options.allowedTypes, [ + TypeGroup(label: 'text', extensions: ['txt']), + TypeGroup(label: 'image', extensions: ['jpg']), + ]), + true, + ); }); test('passes initialDirectory correctly', () async { @@ -425,18 +455,18 @@ void main() { ); await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - throwsArgumentError); + plugin.getSavePath(acceptedTypeGroups: [group]), + throwsArgumentError, + ); }); test('allows a wildcard group', () async { - const XTypeGroup group = XTypeGroup( - label: 'text', - ); + const XTypeGroup group = XTypeGroup(label: 'text'); await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - completes); + plugin.getSavePath(acceptedTypeGroups: [group]), + completes, + ); }); }); } diff --git a/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart b/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart index e673ab00d1e..5689a48369d 100644 --- a/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart +++ b/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart @@ -23,13 +23,8 @@ import 'test_api.g.dart' as _i3; class _FakeFileDialogResult_0 extends _i1.SmartFake implements _i2.FileDialogResult { - _FakeFileDialogResult_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFileDialogResult_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [TestFileSelectorApi]. @@ -48,26 +43,21 @@ class MockTestFileSelectorApi extends _i1.Mock String? confirmButtonText, ) => (super.noSuchMethod( - Invocation.method( - #showOpenDialog, - [ - options, - initialDirectory, - confirmButtonText, - ], - ), - returnValue: _FakeFileDialogResult_0( - this, - Invocation.method( - #showOpenDialog, - [ + Invocation.method(#showOpenDialog, [ options, initialDirectory, confirmButtonText, - ], - ), - ), - ) as _i2.FileDialogResult); + ]), + returnValue: _FakeFileDialogResult_0( + this, + Invocation.method(#showOpenDialog, [ + options, + initialDirectory, + confirmButtonText, + ]), + ), + ) + as _i2.FileDialogResult); @override _i2.FileDialogResult showSaveDialog( @@ -77,26 +67,21 @@ class MockTestFileSelectorApi extends _i1.Mock String? confirmButtonText, ) => (super.noSuchMethod( - Invocation.method( - #showSaveDialog, - [ - options, - initialDirectory, - suggestedName, - confirmButtonText, - ], - ), - returnValue: _FakeFileDialogResult_0( - this, - Invocation.method( - #showSaveDialog, - [ + Invocation.method(#showSaveDialog, [ options, initialDirectory, suggestedName, confirmButtonText, - ], - ), - ), - ) as _i2.FileDialogResult); + ]), + returnValue: _FakeFileDialogResult_0( + this, + Invocation.method(#showSaveDialog, [ + options, + initialDirectory, + suggestedName, + confirmButtonText, + ]), + ), + ) + as _i2.FileDialogResult); } diff --git a/packages/file_selector/file_selector_windows/test/test_api.g.dart b/packages/file_selector/file_selector_windows/test/test_api.g.dart index 018f425bf1d..7c1c86135bd 100644 --- a/packages/file_selector/file_selector_windows/test/test_api.g.dart +++ b/packages/file_selector/file_selector_windows/test/test_api.g.dart @@ -54,14 +54,18 @@ abstract class TestFileSelectorApi { TestDefaultBinaryMessengerBinding.instance; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); - FileDialogResult showOpenDialog(SelectionOptions options, - String? initialDirectory, String? confirmButtonText); + FileDialogResult showOpenDialog( + SelectionOptions options, + String? initialDirectory, + String? confirmButtonText, + ); FileDialogResult showSaveDialog( - SelectionOptions options, - String? initialDirectory, - String? suggestedName, - String? confirmButtonText); + SelectionOptions options, + String? initialDirectory, + String? suggestedName, + String? confirmButtonText, + ); static void setUp( TestFileSelectorApi? api, { @@ -71,74 +75,101 @@ abstract class TestFileSelectorApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog was null.'); - final List args = (message as List?)!; - final SelectionOptions? arg_options = (args[0] as SelectionOptions?); - assert(arg_options != null, - 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog was null, expected non-null SelectionOptions.'); - final String? arg_initialDirectory = (args[1] as String?); - final String? arg_confirmButtonText = (args[2] as String?); - try { - final FileDialogResult output = api.showOpenDialog( - arg_options!, arg_initialDirectory, arg_confirmButtonText); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog was null.', + ); + final List args = (message as List?)!; + final SelectionOptions? arg_options = + (args[0] as SelectionOptions?); + assert( + arg_options != null, + 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog was null, expected non-null SelectionOptions.', + ); + final String? arg_initialDirectory = (args[1] as String?); + final String? arg_confirmButtonText = (args[2] as String?); + try { + final FileDialogResult output = api.showOpenDialog( + arg_options!, + arg_initialDirectory, + arg_confirmButtonText, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog was null.'); - final List args = (message as List?)!; - final SelectionOptions? arg_options = (args[0] as SelectionOptions?); - assert(arg_options != null, - 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog was null, expected non-null SelectionOptions.'); - final String? arg_initialDirectory = (args[1] as String?); - final String? arg_suggestedName = (args[2] as String?); - final String? arg_confirmButtonText = (args[3] as String?); - try { - final FileDialogResult output = api.showSaveDialog(arg_options!, - arg_initialDirectory, arg_suggestedName, arg_confirmButtonText); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog was null.', + ); + final List args = (message as List?)!; + final SelectionOptions? arg_options = + (args[0] as SelectionOptions?); + assert( + arg_options != null, + 'Argument for dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog was null, expected non-null SelectionOptions.', + ); + final String? arg_initialDirectory = (args[1] as String?); + final String? arg_suggestedName = (args[2] as String?); + final String? arg_confirmButtonText = (args[3] as String?); + try { + final FileDialogResult output = api.showSaveDialog( + arg_options!, + arg_initialDirectory, + arg_suggestedName, + arg_confirmButtonText, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/packages/flutter_lints/CHANGELOG.md b/packages/flutter_lints/CHANGELOG.md index 169fe075179..04c2b8f0a4b 100644 --- a/packages/flutter_lints/CHANGELOG.md +++ b/packages/flutter_lints/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 6.0.0 * Updates `package:lints` dependency to version 6.0.0, with the following changes: diff --git a/packages/flutter_lints/example/pubspec.yaml b/packages/flutter_lints/example/pubspec.yaml index 249e5f59929..aa21898fdd2 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.6.0 + sdk: ^3.7.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_migrate/CHANGELOG.md b/packages/flutter_migrate/CHANGELOG.md index ba6da6c1996..1482a62df38 100644 --- a/packages/flutter_migrate/CHANGELOG.md +++ b/packages/flutter_migrate/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.0.1+4 diff --git a/packages/flutter_migrate/lib/executable.dart b/packages/flutter_migrate/lib/executable.dart index a8b91e07aed..e90b782ee9f 100644 --- a/packages/flutter_migrate/lib/executable.dart +++ b/packages/flutter_migrate/lib/executable.dart @@ -38,16 +38,18 @@ Future main(List args) async { processManager: baseDependencies.processManager, ), MigrateAbandonCommand( - logger: baseDependencies.logger, - fileSystem: baseDependencies.fileSystem, - terminal: baseDependencies.terminal, - processManager: baseDependencies.processManager), + logger: baseDependencies.logger, + fileSystem: baseDependencies.fileSystem, + terminal: baseDependencies.terminal, + processManager: baseDependencies.processManager, + ), MigrateApplyCommand( - verbose: verbose, - logger: baseDependencies.logger, - fileSystem: baseDependencies.fileSystem, - terminal: baseDependencies.terminal, - processManager: baseDependencies.processManager), + verbose: verbose, + logger: baseDependencies.logger, + fileSystem: baseDependencies.fileSystem, + terminal: baseDependencies.terminal, + processManager: baseDependencies.processManager, + ), ]; final MigrateCommandRunner runner = MigrateCommandRunner(); @@ -55,22 +57,24 @@ Future main(List args) async { commands.forEach(runner.addCommand); await runner.run(args); - await _exit(0, baseDependencies, - shutdownHooks: baseDependencies.fileSystem.shutdownHooks); + await _exit( + 0, + baseDependencies, + shutdownHooks: baseDependencies.fileSystem.shutdownHooks, + ); await baseDependencies.fileSystem.dispose(); } /// Simple extension of a CommandRunner to provide migrate specific global flags. class MigrateCommandRunner extends CommandRunner { MigrateCommandRunner() - : super( - 'flutter', - 'Migrates legacy flutter projects to modern versions.', - ) { - argParser.addFlag('verbose', - abbr: 'v', - negatable: false, - help: 'Noisy logging, including all shell commands executed.'); + : super('flutter', 'Migrates legacy flutter projects to modern versions.') { + argParser.addFlag( + 'verbose', + abbr: 'v', + negatable: false, + help: 'Noisy logging, including all shell commands executed.', + ); } @override @@ -78,8 +82,11 @@ class MigrateCommandRunner extends CommandRunner { final ArgParser _argParser = ArgParser(); } -Future _exit(int code, MigrateBaseDependencies baseDependencies, - {required ShutdownHooks shutdownHooks}) async { +Future _exit( + int code, + MigrateBaseDependencies baseDependencies, { + required ShutdownHooks shutdownHooks, +}) async { // Run shutdown hooks before flushing logs await shutdownHooks.runShutdownHooks(baseDependencies.logger); diff --git a/packages/flutter_migrate/lib/src/base/command.dart b/packages/flutter_migrate/lib/src/base/command.dart index 129cc454491..22fca4854c9 100644 --- a/packages/flutter_migrate/lib/src/base/command.dart +++ b/packages/flutter_migrate/lib/src/base/command.dart @@ -7,14 +7,10 @@ import 'package:args/command_runner.dart'; import 'logger.dart'; import 'project.dart'; -enum ExitStatus { - success, - warning, - fail, - killed, -} +enum ExitStatus { success, warning, fail, killed } -const String flutterNoPubspecMessage = 'Error: No pubspec.yaml file found.\n' +const String flutterNoPubspecMessage = + 'Error: No pubspec.yaml file found.\n' 'This command should be run from the root of your Flutter project.'; class CommandResult { diff --git a/packages/flutter_migrate/lib/src/base/common.dart b/packages/flutter_migrate/lib/src/base/common.dart index 1bf38431b52..21a9230d81b 100644 --- a/packages/flutter_migrate/lib/src/base/common.dart +++ b/packages/flutter_migrate/lib/src/base/common.dart @@ -110,16 +110,15 @@ String getEnumName(dynamic enumItem) { /// [onError] must have type `FutureOr Function(Object error)` or /// `FutureOr Function(Object error, StackTrace stackTrace)` otherwise an /// [ArgumentError] will be thrown synchronously. -Future asyncGuard( - Future Function() fn, { - Function? onError, -}) { +Future asyncGuard(Future Function() fn, {Function? onError}) { if (onError != null && onError is! _UnaryOnError && onError is! _BinaryOnError) { - throw ArgumentError('onError must be a unary function accepting an Object, ' - 'or a binary function accepting an Object and ' - 'StackTrace. onError must return a T'); + throw ArgumentError( + 'onError must be a unary function accepting an Object, ' + 'or a binary function accepting an Object and ' + 'StackTrace. onError must return a T', + ); } final Completer completer = Completer(); @@ -138,28 +137,31 @@ Future asyncGuard( } } - runZonedGuarded(() async { - try { - final T result = await fn(); - if (!completer.isCompleted) { - completer.complete(result); + runZonedGuarded( + () async { + try { + final T result = await fn(); + if (!completer.isCompleted) { + completer.complete(result); + } + // This catches all exceptions so that they can be propagated to the + // caller-supplied error handling or the completer. + } catch (e, s) { + // ignore: avoid_catches_without_on_clauses, forwards to Future + handleError(e, s); } - // This catches all exceptions so that they can be propagated to the - // caller-supplied error handling or the completer. - } catch (e, s) { - // ignore: avoid_catches_without_on_clauses, forwards to Future + }, + (Object e, StackTrace s) { handleError(e, s); - } - }, (Object e, StackTrace s) { - handleError(e, s); - }); + }, + ); return completer.future; } typedef _UnaryOnError = FutureOr Function(Object error); -typedef _BinaryOnError = FutureOr Function( - Object error, StackTrace stackTrace); +typedef _BinaryOnError = + FutureOr Function(Object error, StackTrace stackTrace); /// Whether the test is running in a web browser compiled to JavaScript. /// @@ -235,9 +237,7 @@ String? flutterRoot; /// /// If an exception is thrown during any of these checks, an error message is /// printed and `.` is returned by default (6). -String defaultFlutterRoot({ - required FileSystem fileSystem, -}) { +String defaultFlutterRoot({required FileSystem fileSystem}) { const String kFlutterRootEnvironmentVariableName = 'FLUTTER_ROOT'; // should point to //flutter/ (root of flutter/flutter repo) const String kSnapshotFileName = @@ -250,7 +250,8 @@ String defaultFlutterRoot({ if (Platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) { return normalize( - Platform.environment[kFlutterRootEnvironmentVariableName]!); + Platform.environment[kFlutterRootEnvironmentVariableName]!, + ); } try { if (Platform.script.scheme == 'data') { @@ -259,17 +260,14 @@ String defaultFlutterRoot({ final String Function(String) dirname = fileSystem.path.dirname; if (Platform.script.scheme == 'package') { - final String packageConfigPath = - Uri.parse(Platform.packageConfig!).toFilePath( - windows: isWindows, - ); + final String packageConfigPath = Uri.parse( + Platform.packageConfig!, + ).toFilePath(windows: isWindows); return normalize(dirname(dirname(dirname(packageConfigPath)))); } if (Platform.script.scheme == 'file') { - final String script = Platform.script.toFilePath( - windows: isWindows, - ); + final String script = Platform.script.toFilePath(windows: isWindows); if (fileSystem.path.basename(script) == kSnapshotFileName) { return normalize(dirname(dirname(fileSystem.path.dirname(script)))); } diff --git a/packages/flutter_migrate/lib/src/base/context.dart b/packages/flutter_migrate/lib/src/base/context.dart index 49e8943b346..6ef5db4f22f 100644 --- a/packages/flutter_migrate/lib/src/base/context.dart +++ b/packages/flutter_migrate/lib/src/base/context.dart @@ -98,7 +98,8 @@ class AppContext { if (index >= 0) { // We're already in the process of trying to generate this type. throw ContextDependencyCycleException._( - UnmodifiableListView(_reentrantChecks!.sublist(index))); + UnmodifiableListView(_reentrantChecks!.sublist(index)), + ); } _reentrantChecks!.add(type); diff --git a/packages/flutter_migrate/lib/src/base/file_system.dart b/packages/flutter_migrate/lib/src/base/file_system.dart index ee5eaf8b9f7..701ee99185e 100644 --- a/packages/flutter_migrate/lib/src/base/file_system.dart +++ b/packages/flutter_migrate/lib/src/base/file_system.dart @@ -86,27 +86,23 @@ class LocalFileSystem extends local_fs.LocalFileSystem { if (_systemTemp == null) { if (!superSystemTempDirectory.existsSync()) { throwToolExit( - 'Your system temp directory (${superSystemTempDirectory.path}) does not exist. ' - 'Did you set an invalid override in your environment? See issue https://github.com/flutter/flutter/issues/74042 for more context.'); + 'Your system temp directory (${superSystemTempDirectory.path}) does not exist. ' + 'Did you set an invalid override in your environment? See issue https://github.com/flutter/flutter/issues/74042 for more context.', + ); } _systemTemp = superSystemTempDirectory.createTempSync('flutter_tools.') ..createSync(recursive: true); // Make sure that the temporary directory is cleaned up if the tool is // killed by a signal. for (final ProcessSignal signal in _fatalSignals) { - final Object token = _signals.addHandler( - signal, - (ProcessSignal _) { - _tryToDeleteTemp(); - }, - ); + final Object token = _signals.addHandler(signal, (ProcessSignal _) { + _tryToDeleteTemp(); + }); _signalTokens[signal] = token; } // Make sure that the temporary directory is cleaned up when the tool // exits normally. - shutdownHooks.addShutdownHook( - _tryToDeleteTemp, - ); + shutdownHooks.addShutdownHook(_tryToDeleteTemp); } return _systemTemp!; } diff --git a/packages/flutter_migrate/lib/src/base/io.dart b/packages/flutter_migrate/lib/src/base/io.dart index 4d5834dd212..f8a89f5de34 100644 --- a/packages/flutter_migrate/lib/src/base/io.dart +++ b/packages/flutter_migrate/lib/src/base/io.dart @@ -32,7 +32,8 @@ // ignore_for_file: avoid_print import 'dart:async'; -import 'dart:io' as io +import 'dart:io' + as io show IOSink, Process, @@ -119,11 +120,9 @@ class Stdio { /// Tests can provide overrides to use instead of the stdout and stderr from /// dart:io. @visibleForTesting - Stdio.test({ - required io.Stdout stdout, - required io.IOSink stderr, - }) : _stdoutOverride = stdout, - _stderrOverride = stderr; + Stdio.test({required io.Stdout stdout, required io.IOSink stderr}) + : _stdoutOverride = stdout, + _stderrOverride = stderr; io.Stdout? _stdoutOverride; io.IOSink? _stderrOverride; @@ -221,10 +220,10 @@ class Stdio { fallback == null ? print(message) : fallback( - message, - const io.StdoutException('stderr is done'), - StackTrace.current, - ); + message, + const io.StdoutException('stderr is done'), + StackTrace.current, + ); } /// Writes [message] to [stdout], falling back on [fallback] if the write @@ -240,10 +239,10 @@ class Stdio { fallback == null ? print(message) : fallback( - message, - const io.StdoutException('stdout is done'), - StackTrace.current, - ); + message, + const io.StdoutException('stdout is done'), + StackTrace.current, + ); } // Helper for [stderrWrite] and [stdoutWrite]. @@ -252,15 +251,18 @@ class Stdio { String message, { void Function(String, dynamic, StackTrace)? fallback, }) { - asyncGuard(() async { - sink.write(message); - }, onError: (Object error, StackTrace stackTrace) { - if (fallback == null) { - print(message); - } else { - fallback(message, error, stackTrace); - } - }); + asyncGuard( + () async { + sink.write(message); + }, + onError: (Object error, StackTrace stackTrace) { + if (fallback == null) { + print(message); + } else { + fallback(message, error, stackTrace); + } + }, + ); } /// Adds [stream] to [stdout]. @@ -286,23 +288,27 @@ class ProcessSignal { @visibleForTesting const ProcessSignal(this._delegate); - static const ProcessSignal sigwinch = - PosixProcessSignal(io.ProcessSignal.sigwinch); - static const ProcessSignal sigterm = - PosixProcessSignal(io.ProcessSignal.sigterm); - static const ProcessSignal sigusr1 = - PosixProcessSignal(io.ProcessSignal.sigusr1); - static const ProcessSignal sigusr2 = - PosixProcessSignal(io.ProcessSignal.sigusr2); + static const ProcessSignal sigwinch = PosixProcessSignal( + io.ProcessSignal.sigwinch, + ); + static const ProcessSignal sigterm = PosixProcessSignal( + io.ProcessSignal.sigterm, + ); + static const ProcessSignal sigusr1 = PosixProcessSignal( + io.ProcessSignal.sigusr1, + ); + static const ProcessSignal sigusr2 = PosixProcessSignal( + io.ProcessSignal.sigusr2, + ); static const ProcessSignal sigint = ProcessSignal(io.ProcessSignal.sigint); static const ProcessSignal sigkill = ProcessSignal(io.ProcessSignal.sigkill); final io.ProcessSignal _delegate; Stream watch() { - return _delegate - .watch() - .map((io.ProcessSignal signal) => this); + return _delegate.watch().map( + (io.ProcessSignal signal) => this, + ); } /// Sends the signal to the given process (identified by pid). diff --git a/packages/flutter_migrate/lib/src/base/logger.dart b/packages/flutter_migrate/lib/src/base/logger.dart index 92ba372c611..a01103fa748 100644 --- a/packages/flutter_migrate/lib/src/base/logger.dart +++ b/packages/flutter_migrate/lib/src/base/logger.dart @@ -190,10 +190,7 @@ abstract class Logger { /// /// In the future, this output can be integrated with an IDE like VS Code to display a /// notification, and allow the user to trigger an action. e.g. run a migration. - void printBox( - String message, { - String? title, - }); + void printBox(String message, {String? title}); /// Use this for verbose tracing output. Users can turn this output on in order /// to help diagnose issues with the toolchain or with their setup. @@ -234,8 +231,9 @@ abstract class Logger { void checkForFatalLogs() { if (fatalWarnings && (hadWarningOutput || hadErrorOutput)) { throwToolExit( - 'Logger received ${hadErrorOutput ? 'error' : 'warning'} output ' - 'during the run, and "--fatal-warnings" is enabled.'); + 'Logger received ${hadErrorOutput ? 'error' : 'warning'} output ' + 'during the run, and "--fatal-warnings" is enabled.', + ); } } } @@ -246,9 +244,9 @@ class StdoutLogger extends Logger { required Stdio stdio, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), - }) : _stdio = stdio, - _outputPreferences = outputPreferences, - _stopwatchFactory = stopwatchFactory; + }) : _stdio = stdio, + _outputPreferences = outputPreferences, + _stopwatchFactory = stopwatchFactory; @override final Terminal terminal; @@ -355,10 +353,7 @@ class StdoutLogger extends Logger { } @override - void printBox( - String message, { - String? title, - }) { + void printBox(String message, {String? title}) { _status?.pause(); _generateBox( title: title, @@ -387,9 +382,8 @@ class StdoutLogger extends Logger { }) { if (_status != null) { // Ignore nested progresses; return a no-op status object. - return SilentStatus( - stopwatch: _stopwatchFactory.createStopwatch(), - )..start(); + return SilentStatus(stopwatch: _stopwatchFactory.createStopwatch()) + ..start(); } if (supportsColor) { _status = SpinnerStatus( @@ -470,17 +464,18 @@ class WindowsStdoutLogger extends StdoutLogger { @override void writeToStdOut(String message) { - final String windowsMessage = terminal.supportsEmoji - ? message - : message - .replaceAll('🔥', '') - .replaceAll('🖼️', '') - .replaceAll('✗', 'X') - .replaceAll('✓', '√') - .replaceAll('🔨', '') - .replaceAll('💪', '') - .replaceAll('⚠️', '!') - .replaceAll('✏️', ''); + final String windowsMessage = + terminal.supportsEmoji + ? message + : message + .replaceAll('🔥', '') + .replaceAll('🖼️', '') + .replaceAll('✗', 'X') + .replaceAll('✓', '√') + .replaceAll('🔨', '') + .replaceAll('💪', '') + .replaceAll('⚠️', '!') + .replaceAll('✏️', ''); _stdio.stdoutWrite(windowsMessage); } } @@ -511,13 +506,16 @@ void _generateBox({ const int kEdges = 2; final int maxTextWidthPerLine = wrapColumn - kEdges - kPaddingLeftRight * 2; - final List lines = - wrapText(message, shouldWrap: true, columnWidth: maxTextWidthPerLine) - .split('\n'); + final List lines = wrapText( + message, + shouldWrap: true, + columnWidth: maxTextWidthPerLine, + ).split('\n'); final List lineWidth = lines.map((String line) => _getColumnSize(line)).toList(); - final int maxColumnSize = - lineWidth.reduce((int currLen, int maxLen) => max(currLen, maxLen)); + final int maxColumnSize = lineWidth.reduce( + (int currLen, int maxLen) => max(currLen, maxLen), + ); final int textWidth = min(maxColumnSize, maxTextWidthPerLine); final int textWithPaddingWidth = textWidth + kPaddingLeftRight * 2; @@ -553,8 +551,9 @@ void _generateBox({ write('\n'); } -final RegExp _ansiEscapePattern = - RegExp('\x1B\\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]'); +final RegExp _ansiEscapePattern = RegExp( + '\x1B\\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]', +); int _getColumnSize(String line) { // Remove ANSI escape characters from the string. @@ -567,19 +566,19 @@ class BufferLogger extends Logger { required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), bool verbose = false, - }) : _outputPreferences = outputPreferences, - _stopwatchFactory = stopwatchFactory, - _verbose = verbose; + }) : _outputPreferences = outputPreferences, + _stopwatchFactory = stopwatchFactory, + _verbose = verbose; /// Create a [BufferLogger] with test preferences. BufferLogger.test({ Terminal? terminal, OutputPreferences? outputPreferences, bool verbose = false, - }) : terminal = terminal ?? Terminal.test(), - _outputPreferences = outputPreferences ?? OutputPreferences.test(), - _stopwatchFactory = const StopwatchFactory(), - _verbose = verbose; + }) : terminal = terminal ?? Terminal.test(), + _outputPreferences = outputPreferences ?? OutputPreferences.test(), + _stopwatchFactory = const StopwatchFactory(), + _verbose = verbose; final OutputPreferences _outputPreferences; @@ -622,16 +621,18 @@ class BufferLogger extends Logger { bool? wrap, }) { hadErrorOutput = true; - _error.writeln(terminal.color( - wrapText( - message, - indent: indent, - hangingIndent: hangingIndent, - shouldWrap: wrap ?? _outputPreferences.wrapText, - columnWidth: _outputPreferences.wrapColumn, + _error.writeln( + terminal.color( + wrapText( + message, + indent: indent, + hangingIndent: hangingIndent, + shouldWrap: wrap ?? _outputPreferences.wrapText, + columnWidth: _outputPreferences.wrapColumn, + ), + color ?? TerminalColor.red, ), - color ?? TerminalColor.red, - )); + ); } @override @@ -644,16 +645,18 @@ class BufferLogger extends Logger { bool? wrap, }) { hadWarningOutput = true; - _warning.writeln(terminal.color( - wrapText( - message, - indent: indent, - hangingIndent: hangingIndent, - shouldWrap: wrap ?? _outputPreferences.wrapText, - columnWidth: _outputPreferences.wrapColumn, + _warning.writeln( + terminal.color( + wrapText( + message, + indent: indent, + hangingIndent: hangingIndent, + shouldWrap: wrap ?? _outputPreferences.wrapText, + columnWidth: _outputPreferences.wrapColumn, + ), + color ?? TerminalColor.cyan, ), - color ?? TerminalColor.cyan, - )); + ); } @override @@ -667,29 +670,30 @@ class BufferLogger extends Logger { bool? wrap, }) { if (newline ?? true) { - _status.writeln(wrapText( - message, - indent: indent, - hangingIndent: hangingIndent, - shouldWrap: wrap ?? _outputPreferences.wrapText, - columnWidth: _outputPreferences.wrapColumn, - )); + _status.writeln( + wrapText( + message, + indent: indent, + hangingIndent: hangingIndent, + shouldWrap: wrap ?? _outputPreferences.wrapText, + columnWidth: _outputPreferences.wrapColumn, + ), + ); } else { - _status.write(wrapText( - message, - indent: indent, - hangingIndent: hangingIndent, - shouldWrap: wrap ?? _outputPreferences.wrapText, - columnWidth: _outputPreferences.wrapColumn, - )); + _status.write( + wrapText( + message, + indent: indent, + hangingIndent: hangingIndent, + shouldWrap: wrap ?? _outputPreferences.wrapText, + columnWidth: _outputPreferences.wrapColumn, + ), + ); } } @override - void printBox( - String message, { - String? title, - }) { + void printBox(String message, {String? title}) { _generateBox( title: title, message: message, @@ -709,9 +713,8 @@ class BufferLogger extends Logger { int progressIndicatorPadding = kDefaultStatusPadding, }) { printStatus(message); - return SilentStatus( - stopwatch: _stopwatchFactory.createStopwatch(), - )..start(); + return SilentStatus(stopwatch: _stopwatchFactory.createStopwatch()) + ..start(); } @override @@ -754,11 +757,8 @@ typedef SlowWarningCallback = String Function(); /// Generally, consider `logger.startProgress` instead of directly creating /// a [Status] or one of its subclasses. abstract class Status { - Status({ - this.onFinish, - required Stopwatch stopwatch, - this.timeout, - }) : _stopwatch = stopwatch; + Status({this.onFinish, required Stopwatch stopwatch, this.timeout}) + : _stopwatch = stopwatch; final VoidCallback? onFinish; final Duration? timeout; @@ -819,10 +819,7 @@ abstract class Status { /// A [Status] that shows nothing. class SilentStatus extends Status { - SilentStatus({ - required super.stopwatch, - super.onFinish, - }); + SilentStatus({required super.stopwatch, super.onFinish}); @override void finish() { @@ -903,9 +900,9 @@ class AnonymousSpinnerStatus extends Status { required Terminal terminal, this.slowWarningCallback, super.timeout, - }) : _stdio = stdio, - _terminal = terminal, - _animation = _selectAnimation(terminal); + }) : _stdio = stdio, + _terminal = terminal, + _animation = _selectAnimation(terminal); final Stdio _stdio; final Terminal _terminal; @@ -937,15 +934,12 @@ class AnonymousSpinnerStatus extends Status { '⢸⡯⠭⠅⢸⣇⣀⡀⢸⣇⣸⡇⠈⢹⡏⠁⠈⢹⡏⠁⢸⣯⣭⡅⢸⡯⢕⡂⠀⠀', // text crawl ]; - static const List _asciiAnimations = [ - r'-\|/', - ]; + static const List _asciiAnimations = [r'-\|/']; static List _selectAnimation(Terminal terminal) { final List animations = terminal.supportsEmoji ? _emojiAnimations : _asciiAnimations; - return animations[terminal.preferredStyle % animations.length] - .runes + return animations[terminal.preferredStyle % animations.length].runes .map((int scalar) => String.fromCharCode(scalar)) .toList(); } @@ -963,9 +957,11 @@ class AnonymousSpinnerStatus extends Status { void _writeToStdOut(String message) => _stdio.stdoutWrite(message); void _clear(int length) { - _writeToStdOut('${_backspaceChar * length}' - '${_clearChar * length}' - '${_backspaceChar * length}'); + _writeToStdOut( + '${_backspaceChar * length}' + '${_clearChar * length}' + '${_backspaceChar * length}', + ); } @override @@ -1154,8 +1150,10 @@ String wrapText( final List result = []; for (final String line in splitText) { String trimmedText = line.trimLeft(); - final String leadingWhitespace = - line.substring(0, line.length - trimmedText.length); + final String leadingWhitespace = line.substring( + 0, + line.length - trimmedText.length, + ); List notIndented; if (hangingIndent != 0) { // When we have a hanging indent, we want to wrap the first line at one @@ -1169,12 +1167,14 @@ String wrapText( notIndented = [firstLineWrap.removeAt(0)]; trimmedText = trimmedText.substring(notIndented[0].length).trimLeft(); if (trimmedText.isNotEmpty) { - notIndented.addAll(_wrapTextAsLines( - trimmedText, - columnWidth: - columnWidth - leadingWhitespace.length - indent - hangingIndent, - shouldWrap: shouldWrap, - )); + notIndented.addAll( + _wrapTextAsLines( + trimmedText, + columnWidth: + columnWidth - leadingWhitespace.length - indent - hangingIndent, + shouldWrap: shouldWrap, + ), + ); } } else { notIndented = _wrapTextAsLines( @@ -1185,8 +1185,8 @@ String wrapText( } String? hangingIndentString; final String indentString = ' ' * indent; - result.addAll(notIndented.map( - (String line) { + result.addAll( + notIndented.map((String line) { // Don't return any lines with just whitespace on them. if (line.isEmpty) { return ''; @@ -1195,13 +1195,15 @@ String wrapText( '$indentString${hangingIndentString ?? ''}$leadingWhitespace'; if (truncatedIndent.length > columnWidth - kMinColumnWidth) { truncatedIndent = truncatedIndent.substring( - 0, math.max(columnWidth - kMinColumnWidth, 0)); + 0, + math.max(columnWidth - kMinColumnWidth, 0), + ); } final String result = '$truncatedIndent$line'; hangingIndentString ??= ' ' * hangingIndent!; return result; - }, - )); + }), + ); } return result.join('\n'); } @@ -1240,8 +1242,10 @@ List _wrapTextAsLines( // reconstitute the original string. This is useful for manipulating "visible" // characters in the presence of ANSI control codes. List<_AnsiRun> splitWithCodes(String input) { - final RegExp characterOrCode = - RegExp('(\u001b\\[[0-9;]*m|.)', multiLine: true); + final RegExp characterOrCode = RegExp( + '(\u001b\\[[0-9;]*m|.)', + multiLine: true, + ); List<_AnsiRun> result = <_AnsiRun>[]; final StringBuffer current = StringBuffer(); for (final Match match in characterOrCode.allMatches(input)) { @@ -1359,10 +1363,10 @@ class LoggerFactory { required Stdio stdio, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), - }) : _terminal = terminal, - _stdio = stdio, - _stopwatchFactory = stopwatchFactory, - _outputPreferences = outputPreferences; + }) : _terminal = terminal, + _stdio = stdio, + _stopwatchFactory = stopwatchFactory, + _outputPreferences = outputPreferences; final Terminal _terminal; final Stdio _stdio; @@ -1370,9 +1374,7 @@ class LoggerFactory { final OutputPreferences _outputPreferences; /// Create the appropriate logger for the current platform and configuration. - Logger createLogger({ - required bool windows, - }) { + Logger createLogger({required bool windows}) { Logger logger; if (windows) { logger = WindowsStdoutLogger( @@ -1383,10 +1385,11 @@ class LoggerFactory { ); } else { logger = StdoutLogger( - terminal: _terminal, - stdio: _stdio, - outputPreferences: _outputPreferences, - stopwatchFactory: _stopwatchFactory); + terminal: _terminal, + stdio: _stdio, + outputPreferences: _outputPreferences, + stopwatchFactory: _stopwatchFactory, + ); } return logger; } diff --git a/packages/flutter_migrate/lib/src/base/project.dart b/packages/flutter_migrate/lib/src/base/project.dart index 9aa2cc67fe6..4b9385acb4b 100644 --- a/packages/flutter_migrate/lib/src/base/project.dart +++ b/packages/flutter_migrate/lib/src/base/project.dart @@ -8,15 +8,7 @@ import 'file_system.dart'; import 'logger.dart'; /// Emum for each officially supported platform. -enum SupportedPlatform { - android, - ios, - linux, - macos, - web, - windows, - fuchsia, -} +enum SupportedPlatform { android, ios, linux, macos, web, windows, fuchsia } class FlutterProjectFactory { FlutterProjectFactory(); @@ -44,8 +36,10 @@ class FlutterProject { /// Create a [FlutterProject] and bypass the project caching. @visibleForTesting - static FlutterProject fromDirectoryTest(Directory directory, - [Logger? logger]) { + static FlutterProject fromDirectoryTest( + Directory directory, [ + Logger? logger, + ]) { logger ??= BufferLogger.test(); return FlutterProject(directory); } diff --git a/packages/flutter_migrate/lib/src/base/signals.dart b/packages/flutter_migrate/lib/src/base/signals.dart index 265f00fae2e..968838433f1 100644 --- a/packages/flutter_migrate/lib/src/base/signals.dart +++ b/packages/flutter_migrate/lib/src/base/signals.dart @@ -19,8 +19,7 @@ abstract class Signals { @visibleForTesting factory Signals.test({ List exitSignals = defaultExitSignals, - }) => - LocalSignals._(exitSignals); + }) => LocalSignals._(exitSignals); // The default list of signals that should cause the process to exit. static const List defaultExitSignals = [ @@ -54,9 +53,7 @@ abstract class Signals { class LocalSignals implements Signals { LocalSignals._(this.exitSignals); - static LocalSignals instance = LocalSignals._( - Signals.defaultExitSignals, - ); + static LocalSignals instance = LocalSignals._(Signals.defaultExitSignals); final List exitSignals; @@ -71,8 +68,7 @@ class LocalSignals implements Signals { // A table mapping (signal) -> low-level signal event stream. final Map> - _streamSubscriptions = - >{}; + _streamSubscriptions = >{}; // The stream controller for errors coming from signal handlers. final StreamController _errorStreamController = diff --git a/packages/flutter_migrate/lib/src/base/terminal.dart b/packages/flutter_migrate/lib/src/base/terminal.dart index 8bb5480245f..442771609db 100644 --- a/packages/flutter_migrate/lib/src/base/terminal.dart +++ b/packages/flutter_migrate/lib/src/base/terminal.dart @@ -9,15 +9,7 @@ import 'common.dart'; import 'io.dart' as io; import 'logger.dart'; -enum TerminalColor { - red, - green, - blue, - cyan, - yellow, - magenta, - grey, -} +enum TerminalColor { red, green, blue, cyan, yellow, magenta, grey } /// A class that contains the context settings for command text output to the /// console. @@ -27,18 +19,18 @@ class OutputPreferences { int? wrapColumn, bool? showColor, io.Stdio? stdio, - }) : _stdio = stdio, - wrapText = wrapText ?? stdio?.hasTerminal ?? false, - _overrideWrapColumn = wrapColumn, - showColor = showColor ?? false; + }) : _stdio = stdio, + wrapText = wrapText ?? stdio?.hasTerminal ?? false, + _overrideWrapColumn = wrapColumn, + showColor = showColor ?? false; /// A version of this class for use in tests. - OutputPreferences.test( - {this.wrapText = false, - int wrapColumn = kDefaultTerminalColumns, - this.showColor = false}) - : _overrideWrapColumn = wrapColumn, - _stdio = null; + OutputPreferences.test({ + this.wrapText = false, + int wrapColumn = kDefaultTerminalColumns, + this.showColor = false, + }) : _overrideWrapColumn = wrapColumn, + _stdio = null; final io.Stdio? _stdio; @@ -160,11 +152,11 @@ class AnsiTerminal implements Terminal { AnsiTerminal({ required io.Stdio stdio, DateTime? - now, // Time used to determine preferredStyle. Defaults to 0001-01-01 00:00. + now, // Time used to determine preferredStyle. Defaults to 0001-01-01 00:00. bool? supportsColor, - }) : _stdio = stdio, - _now = now ?? DateTime(1), - _supportsColor = supportsColor; + }) : _stdio = stdio, + _now = now ?? DateTime(1), + _supportsColor = supportsColor; final io.Stdio _stdio; final DateTime _now; @@ -309,9 +301,10 @@ class AnsiTerminal implements Terminal { @override Stream get keystrokes { - return _broadcastStdInString ??= _stdio.stdin - .transform(const AsciiDecoder(allowInvalid: true)) - .asBroadcastStream(); + return _broadcastStdInString ??= + _stdio.stdin + .transform(const AsciiDecoder(allowInvalid: true)) + .asBroadcastStream(); } @override @@ -329,11 +322,14 @@ class AnsiTerminal implements Terminal { } List charactersToDisplay = acceptedCharacters; if (defaultChoiceIndex != null) { - assert(defaultChoiceIndex >= 0 && - defaultChoiceIndex < acceptedCharacters.length); + assert( + defaultChoiceIndex >= 0 && + defaultChoiceIndex < acceptedCharacters.length, + ); charactersToDisplay = List.of(charactersToDisplay); - charactersToDisplay[defaultChoiceIndex] = - bolden(charactersToDisplay[defaultChoiceIndex]); + charactersToDisplay[defaultChoiceIndex] = bolden( + charactersToDisplay[defaultChoiceIndex], + ); acceptedCharacters.add(''); } String? choice; @@ -344,8 +340,10 @@ class AnsiTerminal implements Terminal { if (prompt != null) { logger.printStatus(prompt, emphasis: true, newline: false); if (displayAcceptedCharacters) { - logger.printStatus(' [${charactersToDisplay.join("|")}]', - newline: false); + logger.printStatus( + ' [${charactersToDisplay.join("|")}]', + newline: false, + ); } // prompt ends with ': ' logger.printStatus(': ', emphasis: true, newline: false); @@ -388,7 +386,8 @@ class _TestTerminal implements Terminal { bool displayAcceptedCharacters = true, }) { throw UnsupportedError( - 'promptForCharInput not supported in the test terminal.'); + 'promptForCharInput not supported in the test terminal.', + ); } @override diff --git a/packages/flutter_migrate/lib/src/base_dependencies.dart b/packages/flutter_migrate/lib/src/base_dependencies.dart index 640f264de17..745084a57fd 100644 --- a/packages/flutter_migrate/lib/src/base_dependencies.dart +++ b/packages/flutter_migrate/lib/src/base_dependencies.dart @@ -18,7 +18,10 @@ class MigrateBaseDependencies { MigrateBaseDependencies() { processManager = const LocalProcessManager(); fileSystem = LocalFileSystem( - LocalSignals.instance, Signals.defaultExitSignals, ShutdownHooks()); + LocalSignals.instance, + Signals.defaultExitSignals, + ShutdownHooks(), + ); stdio = Stdio(); terminal = AnsiTerminal(stdio: stdio); @@ -32,9 +35,7 @@ class MigrateBaseDependencies { terminal: terminal, stdio: stdio, ); - logger = loggerFactory.createLogger( - windows: isWindows, - ); + logger = loggerFactory.createLogger(windows: isWindows); } late final ProcessManager processManager; @@ -53,10 +54,10 @@ class LoggerFactory { required Stdio stdio, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), - }) : _terminal = terminal, - _stdio = stdio, - _stopwatchFactory = stopwatchFactory, - _outputPreferences = outputPreferences; + }) : _terminal = terminal, + _stdio = stdio, + _stopwatchFactory = stopwatchFactory, + _outputPreferences = outputPreferences; final Terminal _terminal; final Stdio _stdio; @@ -64,9 +65,7 @@ class LoggerFactory { final OutputPreferences _outputPreferences; /// Create the appropriate logger for the current platform and configuration. - Logger createLogger({ - required bool windows, - }) { + Logger createLogger({required bool windows}) { Logger logger; if (windows) { logger = WindowsStdoutLogger( @@ -77,10 +76,11 @@ class LoggerFactory { ); } else { logger = StdoutLogger( - terminal: _terminal, - stdio: _stdio, - outputPreferences: _outputPreferences, - stopwatchFactory: _stopwatchFactory); + terminal: _terminal, + stdio: _stdio, + outputPreferences: _outputPreferences, + stopwatchFactory: _stopwatchFactory, + ); } return logger; } diff --git a/packages/flutter_migrate/lib/src/commands/abandon.dart b/packages/flutter_migrate/lib/src/commands/abandon.dart index 9f1f3bf6d03..2e266da8f2d 100644 --- a/packages/flutter_migrate/lib/src/commands/abandon.dart +++ b/packages/flutter_migrate/lib/src/commands/abandon.dart @@ -21,13 +21,14 @@ class MigrateAbandonCommand extends MigrateCommand { required ProcessManager processManager, this.standalone = false, }) : migrateUtils = MigrateUtils( - logger: logger, - fileSystem: fileSystem, - processManager: processManager, - ) { + logger: logger, + fileSystem: fileSystem, + processManager: processManager, + ) { argParser.addOption( 'staging-directory', - help: 'Specifies the custom migration working directory used to stage ' + help: + 'Specifies the custom migration working directory used to stage ' 'and edit proposed changes. This path can be absolute or relative ' 'to the flutter project root. This defaults to ' '`$kDefaultMigrateStagingDirectoryName`', @@ -35,7 +36,8 @@ class MigrateAbandonCommand extends MigrateCommand { ); argParser.addOption( 'project-directory', - help: 'The root directory of the flutter project. This defaults to the ' + help: + 'The root directory of the flutter project. This defaults to the ' 'current working directory if omitted.', valueHelp: 'path', ); @@ -74,42 +76,50 @@ class MigrateAbandonCommand extends MigrateCommand { Future runCommand() async { final String? projectDirectory = stringArg('project-directory'); final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(); - final FlutterProject project = projectDirectory == null - ? FlutterProject.current(fileSystem) - : flutterProjectFactory - .fromDirectory(fileSystem.directory(projectDirectory)); + final FlutterProject project = + projectDirectory == null + ? FlutterProject.current(fileSystem) + : flutterProjectFactory.fromDirectory( + fileSystem.directory(projectDirectory), + ); final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone; if (!validateWorkingDirectory(project, logger)) { return const CommandResult(ExitStatus.fail); } - Directory stagingDirectory = - project.directory.childDirectory(kDefaultMigrateStagingDirectoryName); + Directory stagingDirectory = project.directory.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); final String? customStagingDirectoryPath = stringArg('staging-directory'); if (customStagingDirectoryPath != null) { if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) { stagingDirectory = fileSystem.directory(customStagingDirectoryPath); } else { - stagingDirectory = - project.directory.childDirectory(customStagingDirectoryPath); + stagingDirectory = project.directory.childDirectory( + customStagingDirectoryPath, + ); } if (!stagingDirectory.existsSync()) { logger.printError( - 'Provided staging directory `$customStagingDirectoryPath` ' - 'does not exist or is not valid.'); + 'Provided staging directory `$customStagingDirectoryPath` ' + 'does not exist or is not valid.', + ); return const CommandResult(ExitStatus.fail); } } if (!stagingDirectory.existsSync()) { - logger - .printStatus('No migration in progress. Start a new migration with:'); + logger.printStatus( + 'No migration in progress. Start a new migration with:', + ); printCommandText('start', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } - logger.printStatus('\nAbandoning the existing migration will delete the ' - 'migration staging directory at ${stagingDirectory.path}'); + logger.printStatus( + '\nAbandoning the existing migration will delete the ' + 'migration staging directory at ${stagingDirectory.path}', + ); final bool force = boolArg('force') ?? false; if (!force) { String selection = 'y'; @@ -123,10 +133,7 @@ class MigrateAbandonCommand extends MigrateCommand { defaultChoiceIndex: 1, ); } on StateError catch (e) { - logger.printError( - e.message, - indent: 0, - ); + logger.printError(e.message, indent: 0); } if (selection != 'y') { return const CommandResult(ExitStatus.success); @@ -138,7 +145,8 @@ class MigrateAbandonCommand extends MigrateCommand { } on FileSystemException catch (e) { logger.printError('Deletion failed with: $e'); logger.printError( - 'Please manually delete the staging directory at `${stagingDirectory.path}`'); + 'Please manually delete the staging directory at `${stagingDirectory.path}`', + ); } logger.printStatus('\nAbandon complete. Start a new migration with:'); diff --git a/packages/flutter_migrate/lib/src/commands/apply.dart b/packages/flutter_migrate/lib/src/commands/apply.dart index 8b55b54eb4d..43ce7b6aefa 100644 --- a/packages/flutter_migrate/lib/src/commands/apply.dart +++ b/packages/flutter_migrate/lib/src/commands/apply.dart @@ -26,16 +26,17 @@ class MigrateApplyCommand extends MigrateCommand { required this.terminal, required ProcessManager processManager, this.standalone = false, - }) : _verbose = verbose, - _processManager = processManager, - migrateUtils = MigrateUtils( - logger: logger, - fileSystem: fileSystem, - processManager: processManager, - ) { + }) : _verbose = verbose, + _processManager = processManager, + migrateUtils = MigrateUtils( + logger: logger, + fileSystem: fileSystem, + processManager: processManager, + ) { argParser.addOption( 'staging-directory', - help: 'Specifies the custom migration working directory used to stage ' + help: + 'Specifies the custom migration working directory used to stage ' 'and edit proposed changes. This path can be absolute or relative ' 'to the flutter project root. This defaults to ' '`$kDefaultMigrateStagingDirectoryName`', @@ -43,14 +44,16 @@ class MigrateApplyCommand extends MigrateCommand { ); argParser.addOption( 'project-directory', - help: 'The root directory of the flutter project. This defaults to the ' + help: + 'The root directory of the flutter project. This defaults to the ' 'current working directory if omitted.', valueHelp: 'path', ); argParser.addFlag( 'force', abbr: 'f', - help: 'Ignore unresolved merge conflicts and uncommitted changes and ' + help: + 'Ignore unresolved merge conflicts and uncommitted changes and ' 'apply staged changes by force.', ); argParser.addFlag( @@ -83,7 +86,8 @@ class MigrateApplyCommand extends MigrateCommand { final String name = 'apply'; @override - final String description = r'Accepts the changes produced by `$ flutter ' + final String description = + r'Accepts the changes produced by `$ flutter ' 'migrate start` and copies the changed files into ' 'your project files. All merge conflicts should ' 'be resolved before apply will complete ' @@ -94,13 +98,17 @@ class MigrateApplyCommand extends MigrateCommand { Future runCommand() async { final String? projectDirectory = stringArg('project-directory'); final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(); - final FlutterProject project = projectDirectory == null - ? FlutterProject.current(fileSystem) - : flutterProjectFactory - .fromDirectory(fileSystem.directory(projectDirectory)); + final FlutterProject project = + projectDirectory == null + ? FlutterProject.current(fileSystem) + : flutterProjectFactory.fromDirectory( + fileSystem.directory(projectDirectory), + ); final FlutterToolsEnvironment environment = await FlutterToolsEnvironment.initializeFlutterToolsEnvironment( - _processManager, logger); + _processManager, + logger, + ); final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone; if (!validateWorkingDirectory(project, logger)) { @@ -108,47 +116,61 @@ class MigrateApplyCommand extends MigrateCommand { } if (!await gitRepoExists(project.directory.path, logger, migrateUtils)) { - logger.printStatus('No git repo found. Please run in a project with an ' - 'initialized git repo or initialize one with:'); + logger.printStatus( + 'No git repo found. Please run in a project with an ' + 'initialized git repo or initialize one with:', + ); printCommand('git init', logger); return const CommandResult(ExitStatus.fail); } final bool force = boolArg('force') ?? false; - Directory stagingDirectory = - project.directory.childDirectory(kDefaultMigrateStagingDirectoryName); + Directory stagingDirectory = project.directory.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); final String? customStagingDirectoryPath = stringArg('staging-directory'); if (customStagingDirectoryPath != null) { if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) { stagingDirectory = fileSystem.directory(customStagingDirectoryPath); } else { - stagingDirectory = - project.directory.childDirectory(customStagingDirectoryPath); + stagingDirectory = project.directory.childDirectory( + customStagingDirectoryPath, + ); } } if (!stagingDirectory.existsSync()) { logger.printStatus( - 'No migration in progress at $stagingDirectory. Please run:'); + 'No migration in progress at $stagingDirectory. Please run:', + ); printCommandText('start', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } - final File manifestFile = - MigrateManifest.getManifestFileFromDirectory(stagingDirectory); + final File manifestFile = MigrateManifest.getManifestFileFromDirectory( + stagingDirectory, + ); final MigrateManifest manifest = MigrateManifest.fromFile(manifestFile); - if (!checkAndPrintMigrateStatus(manifest, stagingDirectory, - warnConflict: true, logger: logger) && + if (!checkAndPrintMigrateStatus( + manifest, + stagingDirectory, + warnConflict: true, + logger: logger, + ) && !force) { logger.printStatus( - 'Conflicting files found. Resolve these conflicts and try again.'); + 'Conflicting files found. Resolve these conflicts and try again.', + ); logger.printStatus('Guided conflict resolution wizard:'); printCommandText('resolve-conflicts', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } if (await hasUncommittedChanges( - project.directory.path, logger, migrateUtils) && + project.directory.path, + logger, + migrateUtils, + ) && !force) { return const CommandResult(ExitStatus.fail); } @@ -160,8 +182,10 @@ class MigrateApplyCommand extends MigrateCommand { allFilesToCopy.addAll(manifest.conflictFiles); allFilesToCopy.addAll(manifest.addedFiles); if (allFilesToCopy.isNotEmpty && _verbose) { - logger.printStatus('Modifying ${allFilesToCopy.length} files.', - indent: 2); + logger.printStatus( + 'Modifying ${allFilesToCopy.length} files.', + indent: 2, + ); } for (final String localPath in allFilesToCopy) { if (_verbose) { @@ -177,16 +201,20 @@ class MigrateApplyCommand extends MigrateCommand { targetFile.createSync(recursive: true); } try { - targetFile.writeAsStringSync(workingFile.readAsStringSync(), - flush: true); + targetFile.writeAsStringSync( + workingFile.readAsStringSync(), + flush: true, + ); } on FileSystemException { targetFile.writeAsBytesSync(workingFile.readAsBytesSync(), flush: true); } } // Delete files slated for deletion. if (manifest.deletedFiles.isNotEmpty) { - logger.printStatus('Deleting ${manifest.deletedFiles.length} files.', - indent: 2); + logger.printStatus( + 'Deleting ${manifest.deletedFiles.length} files.', + indent: 2, + ); } for (final String localPath in manifest.deletedFiles) { final File targetFile = project.directory.childFile(localPath); @@ -198,7 +226,9 @@ class MigrateApplyCommand extends MigrateCommand { logger.printStatus('Updating .migrate_configs'); } final FlutterProjectMetadata metadata = FlutterProjectMetadata( - project.directory.childFile('.metadata'), logger); + project.directory.childFile('.metadata'), + logger, + ); final String currentGitHash = environment.getString('FlutterVersion.frameworkRevision') ?? ''; @@ -220,11 +250,19 @@ class MigrateApplyCommand extends MigrateCommand { // Detect gradle lockfiles in android directory. Delete lockfiles and regenerate with ./gradlew tasks (any gradle task that requires a build). await updateGradleDependencyLocking( - project, migrateUtils, logger, terminal, _verbose, fileSystem); + project, + migrateUtils, + logger, + terminal, + _verbose, + fileSystem, + ); - logger.printStatus('Migration complete. You may use commands like `git ' - 'status`, `git diff` and `git restore ` to continue ' - 'working with the migrated files.'); + logger.printStatus( + 'Migration complete. You may use commands like `git ' + 'status`, `git diff` and `git restore ` to continue ' + 'working with the migrated files.', + ); return const CommandResult(ExitStatus.success); } } diff --git a/packages/flutter_migrate/lib/src/commands/start.dart b/packages/flutter_migrate/lib/src/commands/start.dart index 34c4b5dc642..637b2d5e240 100644 --- a/packages/flutter_migrate/lib/src/commands/start.dart +++ b/packages/flutter_migrate/lib/src/commands/start.dart @@ -22,12 +22,12 @@ class MigrateStartCommand extends MigrateCommand { required this.fileSystem, required this.processManager, this.standalone = false, - }) : _verbose = verbose, - migrateUtils = MigrateUtils( - logger: logger, - fileSystem: fileSystem, - processManager: processManager, - ) { + }) : _verbose = verbose, + migrateUtils = MigrateUtils( + logger: logger, + fileSystem: fileSystem, + processManager: processManager, + ) { argParser.addOption( 'staging-directory', help: @@ -131,18 +131,23 @@ class MigrateStartCommand extends MigrateCommand { Future runCommand() async { final FlutterToolsEnvironment environment = await FlutterToolsEnvironment.initializeFlutterToolsEnvironment( - processManager, logger); + processManager, + logger, + ); if (!_validateEnvironment(environment)) { return const CommandResult(ExitStatus.fail); } - final String? projectRootDirPath = stringArg('project-directory') ?? + final String? projectRootDirPath = + stringArg('project-directory') ?? environment.getString('FlutterProject.directory'); final Directory projectRootDir = fileSystem.directory(projectRootDirPath); final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(); - final FlutterProject project = projectRootDirPath == null - ? FlutterProject.current(fileSystem) - : flutterProjectFactory - .fromDirectory(fileSystem.directory(projectRootDirPath)); + final FlutterProject project = + projectRootDirPath == null + ? FlutterProject.current(fileSystem) + : flutterProjectFactory.fromDirectory( + fileSystem.directory(projectRootDirPath), + ); if (!validateWorkingDirectory(project, logger)) { return CommandResult.fail(); @@ -154,7 +159,8 @@ class MigrateStartCommand extends MigrateCommand { environment.getBool('FlutterProject.isPlugin') ?? false; if (isModule || isPlugin) { logger.printError( - 'Migrate tool only supports app projects. This project is a ${isModule ? 'module' : 'plugin'}'); + 'Migrate tool only supports app projects. This project is a ${isModule ? 'module' : 'plugin'}', + ); return const CommandResult(ExitStatus.fail); } final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone; @@ -163,32 +169,40 @@ class MigrateStartCommand extends MigrateCommand { return const CommandResult(ExitStatus.fail); } - Directory stagingDirectory = - project.directory.childDirectory(kDefaultMigrateStagingDirectoryName); + Directory stagingDirectory = project.directory.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); final String? customStagingDirectoryPath = stringArg('staging-directory'); if (customStagingDirectoryPath != null) { if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) { stagingDirectory = fileSystem.directory(customStagingDirectoryPath); } else { - stagingDirectory = - project.directory.childDirectory(customStagingDirectoryPath); + stagingDirectory = project.directory.childDirectory( + customStagingDirectoryPath, + ); } } if (stagingDirectory.existsSync()) { logger.printStatus('Old migration already in progress.', emphasis: true); logger.printStatus( - 'Pending migration files exist in `${stagingDirectory.path}/$kDefaultMigrateStagingDirectoryName`'); + 'Pending migration files exist in `${stagingDirectory.path}/$kDefaultMigrateStagingDirectoryName`', + ); logger.printStatus( - 'Resolve merge conflicts and accept changes with by running:'); + 'Resolve merge conflicts and accept changes with by running:', + ); printCommandText('apply', logger, standalone: !isSubcommand); logger.printStatus( - 'You may also abandon the existing migration and start a new one with:'); + 'You may also abandon the existing migration and start a new one with:', + ); printCommandText('abandon', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } if (await hasUncommittedChanges( - project.directory.path, logger, migrateUtils)) { + project.directory.path, + logger, + migrateUtils, + )) { return const CommandResult(ExitStatus.fail); } @@ -197,9 +211,12 @@ class MigrateStartCommand extends MigrateCommand { platforms = []; for (String platformString in stringArg('platforms')!.split(',')) { platformString = platformString.trim(); - platforms.add(SupportedPlatform.values.firstWhere( + platforms.add( + SupportedPlatform.values.firstWhere( (SupportedPlatform val) => - val.toString() == 'SupportedPlatform.$platformString')); + val.toString() == 'SupportedPlatform.$platformString', + ), + ); } } @@ -228,8 +245,12 @@ class MigrateStartCommand extends MigrateCommand { return const CommandResult(ExitStatus.fail); } - await writeStagingDir(migrateResult, logger, - verbose: _verbose, projectRootDir: projectRootDir); + await writeStagingDir( + migrateResult, + logger, + verbose: _verbose, + projectRootDir: projectRootDir, + ); _deleteTempDirectories( paths: [], @@ -237,7 +258,8 @@ class MigrateStartCommand extends MigrateCommand { ); logger.printStatus( - 'The migrate tool has staged proposed changes in the migrate staging directory.\n'); + 'The migrate tool has staged proposed changes in the migrate staging directory.\n', + ); logger.printStatus('Guided conflict resolution wizard:'); printCommandText('resolve-conflicts', logger, standalone: !isSubcommand); logger.printStatus('Check the status and diffs of the migration with:'); @@ -245,22 +267,25 @@ class MigrateStartCommand extends MigrateCommand { logger.printStatus('Abandon the proposed migration with:'); printCommandText('abandon', logger, standalone: !isSubcommand); logger.printStatus( - 'Accept staged changes after resolving any merge conflicts with:'); + 'Accept staged changes after resolving any merge conflicts with:', + ); printCommandText('apply', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.success); } /// Deletes the files or directories at the provided paths. - void _deleteTempDirectories( - {List paths = const [], - List directories = const []}) { + void _deleteTempDirectories({ + List paths = const [], + List directories = const [], + }) { for (final Directory d in directories) { try { d.deleteSync(recursive: true); } on FileSystemException catch (e) { logger.printError( - 'Unabled to delete ${d.path} due to ${e.message}, please clean up manually.'); + 'Unabled to delete ${d.path} due to ${e.message}, please clean up manually.', + ); } } for (final String p in paths) { @@ -268,7 +293,8 @@ class MigrateStartCommand extends MigrateCommand { fileSystem.directory(p).deleteSync(recursive: true); } on FileSystemException catch (e) { logger.printError( - 'Unabled to delete $p due to ${e.message}, please clean up manually.'); + 'Unabled to delete $p due to ${e.message}, please clean up manually.', + ); } } } @@ -276,7 +302,8 @@ class MigrateStartCommand extends MigrateCommand { bool _validateEnvironment(FlutterToolsEnvironment environment) { if (environment.getString('FlutterProject.directory') == null) { logger.printError( - 'No valid flutter project found. This command must be run from a flutter project directory'); + 'No valid flutter project found. This command must be run from a flutter project directory', + ); return false; } if (environment.getString('FlutterProject.manifest.appname') == null) { @@ -286,26 +313,34 @@ class MigrateStartCommand extends MigrateCommand { if (!(environment.getBool('FlutterProject.android.exists') ?? false) && environment['FlutterProject.android.isKotlin'] == null) { logger.printError( - 'Could not detect if android project uses kotlin or java'); + 'Could not detect if android project uses kotlin or java', + ); return false; } if (!(environment.getBool('FlutterProject.ios.exists') ?? false) && environment['FlutterProject.ios.isSwift'] == null) { logger.printError( - 'Could not detect if iosProject uses swift or objective-c'); + 'Could not detect if iosProject uses swift or objective-c', + ); return false; } return true; } /// Writes the files into the working directory for the developer to review and resolve any conflicts. - Future writeStagingDir(MigrateResult migrateResult, Logger logger, - {bool verbose = false, required Directory projectRootDir}) async { - final Directory stagingDir = - projectRootDir.childDirectory(kDefaultMigrateStagingDirectoryName); + Future writeStagingDir( + MigrateResult migrateResult, + Logger logger, { + bool verbose = false, + required Directory projectRootDir, + }) async { + final Directory stagingDir = projectRootDir.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); if (verbose) { logger.printStatus( - 'Writing migrate staging directory at `${stagingDir.path}`'); + 'Writing migrate staging directory at `${stagingDir.path}`', + ); } // Write files in working dir for (final MergeResult result in migrateResult.mergeResults) { @@ -314,8 +349,10 @@ class MigrateStartCommand extends MigrateCommand { if (result is StringMergeResult) { file.writeAsStringSync(result.mergedString, flush: true); } else { - file.writeAsBytesSync((result as BinaryMergeResult).mergedBytes, - flush: true); + file.writeAsBytesSync( + (result as BinaryMergeResult).mergedBytes, + flush: true, + ); } } diff --git a/packages/flutter_migrate/lib/src/commands/status.dart b/packages/flutter_migrate/lib/src/commands/status.dart index 9228832ab2b..84dd99b17d9 100644 --- a/packages/flutter_migrate/lib/src/commands/status.dart +++ b/packages/flutter_migrate/lib/src/commands/status.dart @@ -21,15 +21,16 @@ class MigrateStatusCommand extends MigrateCommand { required this.fileSystem, required ProcessManager processManager, this.standalone = false, - }) : _verbose = verbose, - migrateUtils = MigrateUtils( - logger: logger, - fileSystem: fileSystem, - processManager: processManager, - ) { + }) : _verbose = verbose, + migrateUtils = MigrateUtils( + logger: logger, + fileSystem: fileSystem, + processManager: processManager, + ) { argParser.addOption( 'staging-directory', - help: 'Specifies the custom migration working directory used to stage ' + help: + 'Specifies the custom migration working directory used to stage ' 'and edit proposed changes. This path can be absolute or relative ' 'to the flutter project root. This defaults to ' '`$kDefaultMigrateStagingDirectoryName`', @@ -37,7 +38,8 @@ class MigrateStatusCommand extends MigrateCommand { ); argParser.addOption( 'project-directory', - help: 'The root directory of the flutter project. This defaults to the ' + help: + 'The root directory of the flutter project. This defaults to the ' 'current working directory if omitted.', valueHelp: 'path', ); @@ -85,40 +87,48 @@ class MigrateStatusCommand extends MigrateCommand { Future runCommand() async { final String? projectDirectory = stringArg('project-directory'); final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(); - final FlutterProject project = projectDirectory == null - ? FlutterProject.current(fileSystem) - : flutterProjectFactory - .fromDirectory(fileSystem.directory(projectDirectory)); + final FlutterProject project = + projectDirectory == null + ? FlutterProject.current(fileSystem) + : flutterProjectFactory.fromDirectory( + fileSystem.directory(projectDirectory), + ); final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone; if (!validateWorkingDirectory(project, logger)) { return CommandResult.fail(); } - Directory stagingDirectory = - project.directory.childDirectory(kDefaultMigrateStagingDirectoryName); + Directory stagingDirectory = project.directory.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); final String? customStagingDirectoryPath = stringArg('staging-directory'); if (customStagingDirectoryPath != null) { if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) { stagingDirectory = fileSystem.directory(customStagingDirectoryPath); } else { - stagingDirectory = - project.directory.childDirectory(customStagingDirectoryPath); + stagingDirectory = project.directory.childDirectory( + customStagingDirectoryPath, + ); } } if (!stagingDirectory.existsSync()) { logger.printStatus( - 'No migration in progress in $stagingDirectory. Start a new migration with:'); + 'No migration in progress in $stagingDirectory. Start a new migration with:', + ); printCommandText('start', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } - final File manifestFile = - MigrateManifest.getManifestFileFromDirectory(stagingDirectory); + final File manifestFile = MigrateManifest.getManifestFileFromDirectory( + stagingDirectory, + ); if (!manifestFile.existsSync()) { - logger.printError('No migrate manifest in the migrate working directory ' - 'at ${stagingDirectory.path}. Fix the working directory ' - 'or abandon and restart the migration.'); + logger.printError( + 'No migrate manifest in the migrate working directory ' + 'at ${stagingDirectory.path}. Fix the working directory ' + 'or abandon and restart the migration.', + ); return const CommandResult(ExitStatus.fail); } final MigrateManifest manifest = MigrateManifest.fromFile(manifestFile); @@ -131,11 +141,14 @@ class MigrateStatusCommand extends MigrateCommand { logger.printStatus('Newly added file at $localPath:\n'); try { logger.printStatus( - stagingDirectory.childFile(localPath).readAsStringSync(), - color: TerminalColor.green); + stagingDirectory.childFile(localPath).readAsStringSync(), + color: TerminalColor.green, + ); } on FileSystemException { - logger.printStatus('Contents are byte data\n', - color: TerminalColor.grey); + logger.printStatus( + 'Contents are byte data\n', + color: TerminalColor.grey, + ); } } } @@ -145,8 +158,9 @@ class MigrateStatusCommand extends MigrateCommand { files.addAll(manifest.remainingConflictFiles(stagingDirectory)); for (final String localPath in files) { final DiffResult result = await migrateUtils.diffFiles( - project.directory.childFile(localPath), - stagingDirectory.childFile(localPath)); + project.directory.childFile(localPath), + stagingDirectory.childFile(localPath), + ); if (result.diff != '' && result.diff != null) { // Print with different colors for better visibility. int lineNumber = -1; @@ -186,9 +200,10 @@ class MigrateStatusCommand extends MigrateCommand { logger.printStatus('Resolve conflicts and accept changes with:'); } else { logger.printStatus( - 'All conflicts resolved. Review changes above and ' - 'apply the migration with:', - color: TerminalColor.green); + 'All conflicts resolved. Review changes above and ' + 'apply the migration with:', + color: TerminalColor.green, + ); } printCommandText('apply', logger, standalone: !isSubcommand); diff --git a/packages/flutter_migrate/lib/src/compute.dart b/packages/flutter_migrate/lib/src/compute.dart index 1f37b3d7a7b..abf96e6e3e3 100644 --- a/packages/flutter_migrate/lib/src/compute.dart +++ b/packages/flutter_migrate/lib/src/compute.dart @@ -39,24 +39,31 @@ final Iterable canonicalizedSkippedFiles = _skippedFiles.map( // Returns true for paths relative to the project root that should be skipped // completely by the migrate tool. -bool _skipped(String localPath, FileSystem fileSystem, - {Set? skippedPrefixes}) { +bool _skipped( + String localPath, + FileSystem fileSystem, { + Set? skippedPrefixes, +}) { final String canonicalizedLocalPath = canonicalize(localPath); - final Iterable canonicalizedSkippedFiles = - _skippedFiles.map((String path) => canonicalize(path)); + final Iterable canonicalizedSkippedFiles = _skippedFiles.map( + (String path) => canonicalize(path), + ); if (canonicalizedSkippedFiles.contains(canonicalizedLocalPath)) { return true; } - final Iterable canonicalizedSkippedDirectories = - _skippedDirectories.map((String path) => canonicalize(path)); + final Iterable canonicalizedSkippedDirectories = _skippedDirectories + .map((String path) => canonicalize(path)); for (final String dir in canonicalizedSkippedDirectories) { if (canonicalizedLocalPath.startsWith('$dir${fileSystem.path.separator}')) { return true; } } if (skippedPrefixes != null) { - return skippedPrefixes.any((String prefix) => localPath.startsWith( - '${normalize(prefix.replaceAll(r'\', fileSystem.path.separator))}${fileSystem.path.separator}')); + return skippedPrefixes.any( + (String prefix) => localPath.startsWith( + '${normalize(prefix.replaceAll(r'\', fileSystem.path.separator))}${fileSystem.path.separator}', + ), + ); } return false; } @@ -219,8 +226,10 @@ Future computeMigration({ }) async { flutterProject ??= FlutterProject.current(fileSystem); - final MigrateLogger migrateLogger = - MigrateLogger(logger: logger, verbose: commandParameters.verbose); + final MigrateLogger migrateLogger = MigrateLogger( + logger: logger, + verbose: commandParameters.verbose, + ); migrateLogger.logStep('start'); // Find the path prefixes to ignore. This allows subdirectories of platforms // not part of the migration to be skipped. @@ -265,26 +274,34 @@ Future computeMigration({ // Generate the base templates final ReferenceProjects referenceProjects = await _generateBaseAndTargetReferenceProjects( - context: context, - result: result, - revisionConfig: revisionConfig, - platforms: platforms, - commandParameters: commandParameters, - ); + context: context, + result: result, + revisionConfig: revisionConfig, + platforms: platforms, + commandParameters: commandParameters, + ); // Generate diffs. These diffs are used to determine if a file is newly added, needs merging, // or deleted (rare). Only files with diffs between the base and target revisions need to be // migrated. If files are unchanged between base and target, then there are no changes to merge. migrateLogger.logStep('diff'); - result.diffMap.addAll(await referenceProjects.baseProject - .diff(context, referenceProjects.targetProject)); + result.diffMap.addAll( + await referenceProjects.baseProject.diff( + context, + referenceProjects.targetProject, + ), + ); // Check for any new files that were added in the target reference app that did not // exist in the base reference app. migrateLogger.logStep('new_files'); - result.addedFiles.addAll(await referenceProjects.baseProject - .computeNewlyAddedFiles( - context, result, referenceProjects.targetProject)); + result.addedFiles.addAll( + await referenceProjects.baseProject.computeNewlyAddedFiles( + context, + result, + referenceProjects.targetProject, + ), + ); // Merge any base->target changed files with the version in the developer's project. // Files that the developer left unchanged are fully updated to match the target reference. @@ -303,26 +320,32 @@ Future computeMigration({ // Clean up any temp directories generated by this tool. migrateLogger.logStep('cleaning'); _registerTempDirectoriesForCleaning( - commandParameters: commandParameters, - result: result, - referenceProjects: referenceProjects); + commandParameters: commandParameters, + result: result, + referenceProjects: referenceProjects, + ); migrateLogger.stop(); return result; } /// Returns a base revision to fallback to in case a true base revision is unknown. String _getFallbackBaseRevision( - bool allowFallbackBaseRevision, MigrateLogger migrateLogger) { + bool allowFallbackBaseRevision, + MigrateLogger migrateLogger, +) { if (!allowFallbackBaseRevision) { migrateLogger.stop(); migrateLogger.printError( - 'Could not determine base revision this app was created with:'); + 'Could not determine base revision this app was created with:', + ); migrateLogger.printError( - '.metadata file did not exist or did not contain a valid revision.', - indent: 2); + '.metadata file did not exist or did not contain a valid revision.', + indent: 2, + ); migrateLogger.printError( - 'Run this command again with the `--allow-fallback-base-revision` flag to use Flutter v1.0.0 as the base revision or manually pass a revision with `--base-revision=`', - indent: 2); + 'Run this command again with the `--allow-fallback-base-revision` flag to use Flutter v1.0.0 as the base revision or manually pass a revision with `--base-revision=`', + indent: 2, + ); throwToolExit('Failed to resolve base revision'); } // Earliest version of flutter with .metadata: c17099f474675d8066fec6984c242d8b409ae985 (2017) @@ -333,7 +356,8 @@ String _getFallbackBaseRevision( // // We fall back on flutter v1.0.0 if .metadata doesn't exist. migrateLogger.printIfVerbose( - 'Could not determine base revision, falling back on `v1.0.0`, revision 5391447fae6209bb21a89e6a5a6583cac1af9b4b'); + 'Could not determine base revision, falling back on `v1.0.0`, revision 5391447fae6209bb21a89e6a5a6583cac1af9b4b', + ); return '5391447fae6209bb21a89e6a5a6583cac1af9b4b'; } @@ -369,27 +393,33 @@ Future _generateBaseAndTargetReferenceProjects({ // Use user-provided projects if provided, if not, generate them internally. final bool customBaseProjectDir = commandParameters.baseAppPath != null; final bool customTargetProjectDir = commandParameters.targetAppPath != null; - Directory baseProjectDir = - context.fileSystem.systemTempDirectory.createTempSync('baseProject'); - Directory targetProjectDir = - context.fileSystem.systemTempDirectory.createTempSync('targetProject'); + Directory baseProjectDir = context.fileSystem.systemTempDirectory + .createTempSync('baseProject'); + Directory targetProjectDir = context.fileSystem.systemTempDirectory + .createTempSync('targetProject'); if (customBaseProjectDir) { - baseProjectDir = - context.fileSystem.directory(commandParameters.baseAppPath); + baseProjectDir = context.fileSystem.directory( + commandParameters.baseAppPath, + ); } else { - baseProjectDir = - context.fileSystem.systemTempDirectory.createTempSync('baseProject'); - context.migrateLogger - .printIfVerbose('Created temporary directory: ${baseProjectDir.path}'); + baseProjectDir = context.fileSystem.systemTempDirectory.createTempSync( + 'baseProject', + ); + context.migrateLogger.printIfVerbose( + 'Created temporary directory: ${baseProjectDir.path}', + ); } if (customTargetProjectDir) { - targetProjectDir = - context.fileSystem.directory(commandParameters.targetAppPath); + targetProjectDir = context.fileSystem.directory( + commandParameters.targetAppPath, + ); } else { - targetProjectDir = - context.fileSystem.systemTempDirectory.createTempSync('targetProject'); + targetProjectDir = context.fileSystem.systemTempDirectory.createTempSync( + 'targetProject', + ); context.migrateLogger.printIfVerbose( - 'Created temporary directory: ${targetProjectDir.path}'); + 'Created temporary directory: ${targetProjectDir.path}', + ); } // Git init to enable running further git commands on the reference projects. @@ -410,8 +440,9 @@ Future _generateBaseAndTargetReferenceProjects({ ? 'swift' : 'objc'; - final Directory targetFlutterDirectory = context.fileSystem - .directory(context.environment.getString('Cache.flutterRoot')); + final Directory targetFlutterDirectory = context.fileSystem.directory( + context.environment.getString('Cache.flutterRoot'), + ); // Create the base reference vanilla app. // @@ -435,7 +466,9 @@ Future _generateBaseAndTargetReferenceProjects({ commandParameters.baseRevision ?? revisionConfig.metadataRevision ?? _getFallbackBaseRevision( - commandParameters.allowFallbackBaseRevision, context.migrateLogger), + commandParameters.allowFallbackBaseRevision, + context.migrateLogger, + ), revisionConfig.targetRevision, targetFlutterDirectory, ); @@ -515,8 +548,9 @@ abstract class MigrateFlutterProject { MigrateFlutterProject other, ) async { final Map diffMap = {}; - final List thisFiles = - directory.listSync(recursive: true); + final List thisFiles = directory.listSync( + recursive: true, + ); int modifiedFilesCount = 0; for (final FileSystemEntity entity in thisFiles) { if (entity is! File) { @@ -524,24 +558,35 @@ abstract class MigrateFlutterProject { } final File thisFile = entity.absolute; final String localPath = getLocalPath( - thisFile.path, directory.absolute.path, context.fileSystem); - if (_skipped(localPath, context.fileSystem, - skippedPrefixes: context.skippedPrefixes)) { + thisFile.path, + directory.absolute.path, + context.fileSystem, + ); + if (_skipped( + localPath, + context.fileSystem, + skippedPrefixes: context.skippedPrefixes, + )) { continue; } - if (await context.migrateUtils - .isGitIgnored(thisFile.absolute.path, directory.absolute.path)) { + if (await context.migrateUtils.isGitIgnored( + thisFile.absolute.path, + directory.absolute.path, + )) { diffMap[localPath] = DiffResult(diffType: DiffType.ignored); } final File otherFile = other.directory.childFile(localPath); if (otherFile.existsSync()) { - final DiffResult diff = - await context.migrateUtils.diffFiles(thisFile, otherFile); + final DiffResult diff = await context.migrateUtils.diffFiles( + thisFile, + otherFile, + ); diffMap[localPath] = diff; if (diff.diff != '') { context.migrateLogger.printIfVerbose( - 'Found ${diff.exitCode} changes in $localPath', - indent: 4); + 'Found ${diff.exitCode} changes in $localPath', + indent: 4, + ); modifiedFilesCount++; } } else { @@ -551,7 +596,8 @@ abstract class MigrateFlutterProject { } } context.migrateLogger.printIfVerbose( - '$modifiedFilesCount files were modified between base and target apps.'); + '$modifiedFilesCount files were modified between base and target apps.', + ); return diffMap; } @@ -562,22 +608,31 @@ abstract class MigrateFlutterProject { MigrateFlutterProject other, ) async { final List addedFiles = []; - final List otherFiles = - other.directory.listSync(recursive: true); + final List otherFiles = other.directory.listSync( + recursive: true, + ); for (final FileSystemEntity entity in otherFiles) { if (entity is! File) { continue; } final File otherFile = entity.absolute; final String localPath = getLocalPath( - otherFile.path, other.directory.absolute.path, context.fileSystem); + otherFile.path, + other.directory.absolute.path, + context.fileSystem, + ); if (directory.childFile(localPath).existsSync() || - _skipped(localPath, context.fileSystem, - skippedPrefixes: context.skippedPrefixes)) { + _skipped( + localPath, + context.fileSystem, + skippedPrefixes: context.skippedPrefixes, + )) { continue; } if (await context.migrateUtils.isGitIgnored( - otherFile.absolute.path, other.directory.absolute.path)) { + otherFile.absolute.path, + other.directory.absolute.path, + )) { result.diffMap[localPath] = DiffResult(diffType: DiffType.ignored); } result.diffMap[localPath] = DiffResult(diffType: DiffType.addition); @@ -588,7 +643,8 @@ abstract class MigrateFlutterProject { addedFiles.add(FilePendingMigration(localPath, otherFile)); } context.migrateLogger.printIfVerbose( - '${addedFiles.length} files were newly added in the target app.'); + '${addedFiles.length} files were newly added in the target app.', + ); return addedFiles; } @@ -606,12 +662,13 @@ abstract class MigrateFlutterProject { MetadataCustomMerge(logger: context.migrateLogger.logger), ]; // For each existing file in the project, we attempt to 3 way merge if it is changed by the user. - final List currentFiles = - context.flutterProject.directory.listSync(recursive: true); + final List currentFiles = context.flutterProject.directory + .listSync(recursive: true); final String projectRootPath = context.flutterProject.directory.absolute.path; - final Set missingAlwaysMigrateFiles = - Set.of(_alwaysMigrateFiles); + final Set missingAlwaysMigrateFiles = Set.of( + _alwaysMigrateFiles, + ); for (final FileSystemEntity entity in currentFiles) { if (entity is! File) { continue; @@ -631,25 +688,38 @@ abstract class MigrateFlutterProject { final File currentFile = entity.absolute; // Diff the current file against the old generated template - final String localPath = - getLocalPath(currentFile.path, projectRootPath, context.fileSystem); + final String localPath = getLocalPath( + currentFile.path, + projectRootPath, + context.fileSystem, + ); missingAlwaysMigrateFiles.remove(localPath); if (result.diffMap.containsKey(localPath) && result.diffMap[localPath]!.diffType == DiffType.ignored || - await context.migrateUtils.isGitIgnored(currentFile.path, - context.flutterProject.directory.absolute.path) || - _skipped(localPath, context.fileSystem, - skippedPrefixes: context.skippedPrefixes) || + await context.migrateUtils.isGitIgnored( + currentFile.path, + context.flutterProject.directory.absolute.path, + ) || + _skipped( + localPath, + context.fileSystem, + skippedPrefixes: context.skippedPrefixes, + ) || !_mergable(localPath)) { continue; } final File baseTemplateFile = baseProject.directory.childFile(localPath); - final File targetTemplateFile = - targetProject.directory.childFile(localPath); - final DiffResult userDiff = - await context.migrateUtils.diffFiles(currentFile, baseTemplateFile); - final DiffResult targetDiff = - await context.migrateUtils.diffFiles(currentFile, targetTemplateFile); + final File targetTemplateFile = targetProject.directory.childFile( + localPath, + ); + final DiffResult userDiff = await context.migrateUtils.diffFiles( + currentFile, + baseTemplateFile, + ); + final DiffResult targetDiff = await context.migrateUtils.diffFiles( + currentFile, + targetTemplateFile, + ); if (targetDiff.exitCode == 0) { // current file is already the same as the target file. continue; @@ -664,8 +734,9 @@ abstract class MigrateFlutterProject { // File changed between base and target if (result.diffMap[localPath]!.diffType == DiffType.deletion) { // File is deleted in new template - result.deletedFiles - .add(FilePendingMigration(localPath, currentFile)); + result.deletedFiles.add( + FilePendingMigration(localPath, currentFile), + ); continue; } if (result.diffMap[localPath]!.exitCode != 0 || alwaysMigrate) { @@ -702,7 +773,10 @@ abstract class MigrateFlutterProject { for (final CustomMerge customMerge in customMerges) { if (customMerge.localPath == localPath) { mergeResult = customMerge.merge( - currentFile, baseTemplateFile, targetTemplateFile); + currentFile, + baseTemplateFile, + targetTemplateFile, + ); mergeType = MergeType.custom; break; } @@ -723,16 +797,22 @@ abstract class MigrateFlutterProject { basePath = currentFile.path; currentPath = currentFile.path; targetPath = context.fileSystem.path.join( - result.generatedTargetTemplateDirectory!.path, localPath); + result.generatedTargetTemplateDirectory!.path, + localPath, + ); break; } case MergeType.threeWay: { basePath = context.fileSystem.path.join( - result.generatedBaseTemplateDirectory!.path, localPath); + result.generatedBaseTemplateDirectory!.path, + localPath, + ); currentPath = currentFile.path; targetPath = context.fileSystem.path.join( - result.generatedTargetTemplateDirectory!.path, localPath); + result.generatedTargetTemplateDirectory!.path, + localPath, + ); break; } case MergeType.custom: @@ -753,8 +833,9 @@ abstract class MigrateFlutterProject { // Don't include if result is identical to the current file. if (mergeResult is StringMergeResult) { if (mergeResult.mergedString == currentFile.readAsStringSync()) { - context.migrateLogger - .printIfVerbose('$localPath was merged with a $mergeType.'); + context.migrateLogger.printIfVerbose( + '$localPath was merged with a $mergeType.', + ); continue; } } else { @@ -765,21 +846,26 @@ abstract class MigrateFlutterProject { } result.mergeResults.add(mergeResult); } - context.migrateLogger - .printStatus('$localPath was merged with a $mergeType.'); + context.migrateLogger.printStatus( + '$localPath was merged with a $mergeType.', + ); continue; } } // Add files that are in the target, marked as always migrate, and missing in the current project. for (final String localPath in missingAlwaysMigrateFiles) { - final File targetTemplateFile = - result.generatedTargetTemplateDirectory!.childFile(localPath); + final File targetTemplateFile = result.generatedTargetTemplateDirectory! + .childFile(localPath); if (targetTemplateFile.existsSync() && - !_skipped(localPath, context.fileSystem, - skippedPrefixes: context.skippedPrefixes)) { - result.addedFiles - .add(FilePendingMigration(localPath, targetTemplateFile)); + !_skipped( + localPath, + context.fileSystem, + skippedPrefixes: context.skippedPrefixes, + )) { + result.addedFiles.add( + FilePendingMigration(localPath, targetTemplateFile), + ); } } } @@ -845,12 +931,15 @@ class MigrateBaseFlutterProject extends MigrateFlutterProject { revisionToFlutterSdkDir[revision] = sdkDir; sdkAvailable = true; } else { - sdkDir = context.fileSystem.systemTempDirectory - .createTempSync('flutter_$activeRevision'); + sdkDir = context.fileSystem.systemTempDirectory.createTempSync( + 'flutter_$activeRevision', + ); result.sdkDirs[activeRevision] = sdkDir; context.migrateLogger.printStatus('Cloning SDK $activeRevision'); - sdkAvailable = await context.migrateUtils - .cloneFlutter(activeRevision, sdkDir.absolute.path); + sdkAvailable = await context.migrateUtils.cloneFlutter( + activeRevision, + sdkDir.absolute.path, + ); revisionToFlutterSdkDir[revision] = sdkDir; } } else { @@ -861,42 +950,49 @@ class MigrateBaseFlutterProject extends MigrateFlutterProject { } } while (!sdkAvailable); context.migrateLogger.printStatus( - 'Creating base app for $platforms with revision $revision.'); - final String newDirectoryPath = - await context.migrateUtils.createFromTemplates( - sdkDir.childDirectory('bin').absolute.path, - name: name, - androidLanguage: androidLanguage, - iosLanguage: iosLanguage, - outputDirectory: result.generatedBaseTemplateDirectory!.absolute.path, - platforms: platforms, + 'Creating base app for $platforms with revision $revision.', ); + final String newDirectoryPath = await context.migrateUtils + .createFromTemplates( + sdkDir.childDirectory('bin').absolute.path, + name: name, + androidLanguage: androidLanguage, + iosLanguage: iosLanguage, + outputDirectory: + result.generatedBaseTemplateDirectory!.absolute.path, + platforms: platforms, + ); if (newDirectoryPath != result.generatedBaseTemplateDirectory?.path) { - result.generatedBaseTemplateDirectory = - context.fileSystem.directory(newDirectoryPath); + result.generatedBaseTemplateDirectory = context.fileSystem.directory( + newDirectoryPath, + ); } // Determine merge type for each newly generated file. - final List generatedBaseFiles = - result.generatedBaseTemplateDirectory!.listSync(recursive: true); + final List generatedBaseFiles = result + .generatedBaseTemplateDirectory! + .listSync(recursive: true); for (final FileSystemEntity entity in generatedBaseFiles) { if (entity is! File) { continue; } final File baseTemplateFile = entity.absolute; final String localPath = getLocalPath( - baseTemplateFile.path, - result.generatedBaseTemplateDirectory!.absolute.path, - context.fileSystem); + baseTemplateFile.path, + result.generatedBaseTemplateDirectory!.absolute.path, + context.fileSystem, + ); if (!result.mergeTypeMap.containsKey(localPath)) { // Use two way merge when the base revision is the same as the target revision. - result.mergeTypeMap[localPath] = revision == targetRevision - ? MergeType.twoWay - : MergeType.threeWay; + result.mergeTypeMap[localPath] = + revision == targetRevision + ? MergeType.twoWay + : MergeType.threeWay; } } if (newDirectoryPath != result.generatedBaseTemplateDirectory?.path) { - result.generatedBaseTemplateDirectory = - context.fileSystem.directory(newDirectoryPath); + result.generatedBaseTemplateDirectory = context.fileSystem.directory( + newDirectoryPath, + ); break; // The create command is old and does not distinguish between platforms so it only needs to be called once. } } @@ -927,8 +1023,9 @@ class MigrateTargetFlutterProject extends MigrateFlutterProject { ) async { if (path == null) { // Create target - context.migrateLogger - .printStatus('Creating target app with revision $targetRevision.'); + context.migrateLogger.printStatus( + 'Creating target app with revision $targetRevision.', + ); context.migrateLogger.printIfVerbose('Creating target app.'); await context.migrateUtils.createFromTemplates( targetFlutterDirectory.childDirectory('bin').absolute.path, @@ -951,8 +1048,13 @@ class MigrateRevisions { required List platforms, required FlutterToolsEnvironment environment, }) { - _computeRevisions(context, baseRevision, allowFallbackBaseRevision, - platforms, environment); + _computeRevisions( + context, + baseRevision, + allowFallbackBaseRevision, + platforms, + environment, + ); } late List revisionsList; @@ -976,8 +1078,9 @@ class MigrateRevisions { } components.add(FlutterProjectComponent.root); final FlutterProjectMetadata metadata = FlutterProjectMetadata( - context.flutterProject.directory.childFile('.metadata'), - context.migrateLogger.logger); + context.flutterProject.directory.childFile('.metadata'), + context.migrateLogger.logger, + ); config = metadata.migrateConfig; // We call populate in case MigrateConfig is empty. If it is filled, populate should not do anything. @@ -998,11 +1101,14 @@ class MigrateRevisions { if (baseRevision == null) { for (final MigratePlatformConfig platform in config.platformConfigs.values) { - final String effectiveRevision = platform.baseRevision == null - ? metadataRevision ?? - _getFallbackBaseRevision( - allowFallbackBaseRevision, context.migrateLogger) - : platform.baseRevision!; + final String effectiveRevision = + platform.baseRevision == null + ? metadataRevision ?? + _getFallbackBaseRevision( + allowFallbackBaseRevision, + context.migrateLogger, + ) + : platform.baseRevision!; if (!components.contains(platform.component)) { continue; } @@ -1019,8 +1125,12 @@ class MigrateRevisions { rootBaseRevision = baseRevision; revisionToConfigs[baseRevision] = []; for (final FlutterProjectComponent component in components) { - revisionToConfigs[baseRevision]!.add(MigratePlatformConfig( - component: component, baseRevision: baseRevision)); + revisionToConfigs[baseRevision]!.add( + MigratePlatformConfig( + component: component, + baseRevision: baseRevision, + ), + ); } // revisionToConfigs[baseRevision]!.add( // MigratePlatformConfig(platform: null, baseRevision: baseRevision)); @@ -1031,15 +1141,17 @@ class MigrateRevisions { if (rootBaseRevision != '') { revisionsList.insert(0, rootBaseRevision); } - context.migrateLogger - .printIfVerbose('Potential base revisions: $revisionsList'); + context.migrateLogger.printIfVerbose( + 'Potential base revisions: $revisionsList', + ); fallbackRevision = _getFallbackBaseRevision(true, context.migrateLogger); if (revisionsList.contains(fallbackRevision) && baseRevision != fallbackRevision && metadataRevision != fallbackRevision) { context.migrateLogger.printStatus( - 'Using Flutter v1.0.0 ($fallbackRevision) as the base revision since a valid base revision could not be found in the .metadata file. This may result in more merge conflicts than normally expected.', - indent: 4); + 'Using Flutter v1.0.0 ($fallbackRevision) as the base revision since a valid base revision could not be found in the .metadata file. This may result in more merge conflicts than normally expected.', + indent: 4, + ); } } } diff --git a/packages/flutter_migrate/lib/src/custom_merge.dart b/packages/flutter_migrate/lib/src/custom_merge.dart index d1a3373d834..e0cb1175c6c 100644 --- a/packages/flutter_migrate/lib/src/custom_merge.dart +++ b/packages/flutter_migrate/lib/src/custom_merge.dart @@ -11,10 +11,7 @@ import 'utils.dart'; /// /// The `merge` method should be overridden to implement custom merging. abstract class CustomMerge { - CustomMerge({ - required this.logger, - required this.localPath, - }); + CustomMerge({required this.logger, required this.localPath}); /// The local path (with the project root as the root directory) of the file to merge. final String localPath; @@ -29,9 +26,7 @@ abstract class CustomMerge { /// /// See `FlutterProjectMetadata`. class MetadataCustomMerge extends CustomMerge { - MetadataCustomMerge({ - required super.logger, - }) : super(localPath: '.metadata'); + MetadataCustomMerge({required super.logger}) : super(localPath: '.metadata'); @override MergeResult merge(File current, File base, File target) { @@ -50,12 +45,14 @@ class MetadataCustomMerge extends CustomMerge { } FlutterProjectMetadata computeMerge( - FlutterProjectMetadata current, - FlutterProjectMetadata base, - FlutterProjectMetadata target, - Logger logger) { + FlutterProjectMetadata current, + FlutterProjectMetadata base, + FlutterProjectMetadata target, + Logger logger, + ) { // Prefer to update the version revision and channel to latest version. - final String? versionRevision = target.versionRevision ?? + final String? versionRevision = + target.versionRevision ?? current.versionRevision ?? base.versionRevision; final String? versionChannel = @@ -79,18 +76,21 @@ class MetadataCustomMerge extends CustomMerge { } MigrateConfig mergeMigrateConfig( - MigrateConfig current, MigrateConfig target) { + MigrateConfig current, + MigrateConfig target, + ) { // Create the superset of current and target platforms with baseRevision updated to be that of target. final Map - projectComponentConfigs = + projectComponentConfigs = {}; for (final MapEntry entry in current.platformConfigs.entries) { if (target.platformConfigs.containsKey(entry.key)) { projectComponentConfigs[entry.key] = MigratePlatformConfig( - component: entry.value.component, - createRevision: entry.value.createRevision, - baseRevision: target.platformConfigs[entry.key]?.baseRevision); + component: entry.value.component, + createRevision: entry.value.createRevision, + baseRevision: target.platformConfigs[entry.key]?.baseRevision, + ); } else { projectComponentConfigs[entry.key] = entry.value; } @@ -103,8 +103,9 @@ class MetadataCustomMerge extends CustomMerge { } // Ignore the base file list. - final List unmanagedFiles = - List.from(current.unmanagedFiles); + final List unmanagedFiles = List.from( + current.unmanagedFiles, + ); for (final String path in target.unmanagedFiles) { if (!unmanagedFiles.contains(path) && !MigrateConfig.kDefaultUnmanagedFiles.contains(path)) { diff --git a/packages/flutter_migrate/lib/src/environment.dart b/packages/flutter_migrate/lib/src/environment.dart index b3b25594671..38801d50450 100644 --- a/packages/flutter_migrate/lib/src/environment.dart +++ b/packages/flutter_migrate/lib/src/environment.dart @@ -22,32 +22,41 @@ class FlutterToolsEnvironment { /// Each key is the String URI-style description of a value in the Flutter tool /// and is mapped to a String or boolean value. The mapping should align with the /// JSON output of `flutter analyze --suggestions --machine`. - FlutterToolsEnvironment({ - required Map mapping, - }) : _mapping = mapping; + FlutterToolsEnvironment({required Map mapping}) + : _mapping = mapping; /// Creates a FlutterToolsEnvironment instance by calling `flutter analyze --suggestions --machine` /// and parsing its output. static Future initializeFlutterToolsEnvironment( - ProcessManager processManager, Logger logger) async { - final ProcessResult result = await processManager - .run(['flutter', 'analyze', '--suggestions', '--machine']); + ProcessManager processManager, + Logger logger, + ) async { + final ProcessResult result = await processManager.run([ + 'flutter', + 'analyze', + '--suggestions', + '--machine', + ]); if (result.exitCode != 0) { if ((result.stderr as String).contains( - 'The "--machine" flag is only valid with the "--version" flag.')) { + 'The "--machine" flag is only valid with the "--version" flag.', + )) { logger.printError( - 'The migrate tool is only compatible with flutter tools 3.4.0 or newer (git hash: 21861423f25ad03c2fdb33854b53f195bc117cb3).'); + 'The migrate tool is only compatible with flutter tools 3.4.0 or newer (git hash: 21861423f25ad03c2fdb33854b53f195bc117cb3).', + ); } throwToolExit( - 'Flutter tool exited while running `flutter analyze --suggestions --machine` with: ${result.stderr}'); + 'Flutter tool exited while running `flutter analyze --suggestions --machine` with: ${result.stderr}', + ); } String commandOutput = (result.stdout as String).trim(); Map mapping = {}; // minimally validate basic JSON format and trim away any accidental logging before. if (commandOutput.contains(RegExp(r'[\s\S]*{[\s\S]+}[\s\S]*'))) { commandOutput = commandOutput.substring(commandOutput.indexOf('{')); - mapping = jsonDecode(commandOutput.replaceAll(r'\', r'\\')) - as Map; + mapping = + jsonDecode(commandOutput.replaceAll(r'\', r'\\')) + as Map; } return FlutterToolsEnvironment(mapping: mapping); } diff --git a/packages/flutter_migrate/lib/src/flutter_project_metadata.dart b/packages/flutter_migrate/lib/src/flutter_project_metadata.dart index d8f4026ba11..3287a59cf94 100644 --- a/packages/flutter_migrate/lib/src/flutter_project_metadata.dart +++ b/packages/flutter_migrate/lib/src/flutter_project_metadata.dart @@ -28,8 +28,9 @@ extension SupportedPlatformExtension on SupportedPlatform { FlutterProjectComponent toFlutterProjectComponent() { final String platformName = toString().split('.').last; return FlutterProjectComponent.values.firstWhere( - (FlutterProjectComponent e) => - e.toString() == 'FlutterProjectComponent.$platformName'); + (FlutterProjectComponent e) => + e.toString() == 'FlutterProjectComponent.$platformName', + ); } } @@ -39,8 +40,10 @@ extension FlutterProjectComponentExtension on FlutterProjectComponent { if (platformName == 'root') { return null; } - return SupportedPlatform.values.firstWhere((SupportedPlatform e) => - e.toString() == 'SupportedPlatform.$platformName'); + return SupportedPlatform.values.firstWhere( + (SupportedPlatform e) => + e.toString() == 'SupportedPlatform.$platformName', + ); } } @@ -91,7 +94,10 @@ FlutterProjectType? stringToProjectType(String value) { /// Verifies the expected yaml keys are present in the file. bool _validateMetadataMap( - YamlMap map, Map validations, Logger logger) { + YamlMap map, + Map validations, + Logger logger, +) { bool isValid = true; for (final MapEntry entry in validations.entries) { if (!map.keys.contains(entry.key)) { @@ -103,7 +109,8 @@ bool _validateMetadataMap( if (metadataValue.runtimeType != entry.value) { isValid = false; logger.printTrace( - 'The value of key `${entry.key}` in .metadata was expected to be ${entry.value} but was ${metadataValue.runtimeType}'); + 'The value of key `${entry.key}` in .metadata was expected to be ${entry.value} but was ${metadataValue.runtimeType}', + ); break; } } @@ -114,8 +121,8 @@ bool _validateMetadataMap( class FlutterProjectMetadata { /// Creates a MigrateConfig by parsing an existing .migrate_config yaml file. FlutterProjectMetadata(this.file, Logger logger) - : _logger = logger, - migrateConfig = MigrateConfig() { + : _logger = logger, + migrateConfig = MigrateConfig() { if (!file.existsSync()) { _logger.printTrace('No .metadata file found at ${file.path}.'); // Create a default empty metadata. @@ -128,27 +135,27 @@ class FlutterProjectMetadata { // Handled in _validate below. } if (yamlRoot is! YamlMap) { - _logger - .printTrace('.metadata file at ${file.path} was empty or malformed.'); + _logger.printTrace( + '.metadata file at ${file.path} was empty or malformed.', + ); return; } - if (_validateMetadataMap( - yamlRoot, {'version': YamlMap}, _logger)) { + if (_validateMetadataMap(yamlRoot, { + 'version': YamlMap, + }, _logger)) { final Object? versionYamlMap = yamlRoot['version']; if (versionYamlMap is YamlMap && - _validateMetadataMap( - versionYamlMap, - { - 'revision': String, - 'channel': String, - }, - _logger)) { + _validateMetadataMap(versionYamlMap, { + 'revision': String, + 'channel': String, + }, _logger)) { _versionRevision = versionYamlMap['revision'] as String?; _versionChannel = versionYamlMap['channel'] as String?; } } - if (_validateMetadataMap( - yamlRoot, {'project_type': String}, _logger)) { + if (_validateMetadataMap(yamlRoot, { + 'project_type': String, + }, _logger)) { _projectType = stringToProjectType(yamlRoot['project_type'] as String); } final Object? migrationYaml = yamlRoot['migration']; @@ -165,10 +172,10 @@ class FlutterProjectMetadata { required FlutterProjectType? projectType, required this.migrateConfig, required Logger logger, - }) : _logger = logger, - _versionChannel = versionChannel, - _versionRevision = versionRevision, - _projectType = projectType; + }) : _logger = logger, + _versionChannel = versionChannel, + _versionRevision = versionRevision, + _projectType = projectType; /// The name of the config file. static const String kFileName = '.metadata'; @@ -254,11 +261,12 @@ ${migrateConfig.getOutputFileString()}'''; /// Each platform tracks a different set of revisions because flutter create can be /// used to add support for new platforms, so the base and create revision may not always be the same. class MigrateConfig { - MigrateConfig( - {Map? platformConfigs, - this.unmanagedFiles = kDefaultUnmanagedFiles}) - : platformConfigs = platformConfigs ?? - {}; + MigrateConfig({ + Map? platformConfigs, + this.unmanagedFiles = kDefaultUnmanagedFiles, + }) : platformConfigs = + platformConfigs ?? + {}; /// A mapping of the files that are unmanaged by defult for each platform. static const List kDefaultUnmanagedFiles = [ @@ -306,9 +314,10 @@ class MigrateConfig { } else { if (create) { platformConfigs[component] = MigratePlatformConfig( - component: component, - createRevision: createRevision, - baseRevision: currentRevision); + component: component, + createRevision: createRevision, + baseRevision: currentRevision, + ); } } } @@ -349,24 +358,23 @@ migration: /// Parses and validates the `migration` section of the .metadata file. void parseYaml(YamlMap map, Logger logger) { final Object? platformsYaml = map['platforms']; - if (_validateMetadataMap( - map, {'platforms': YamlList}, logger)) { + if (_validateMetadataMap(map, { + 'platforms': YamlList, + }, logger)) { if (platformsYaml is YamlList && platformsYaml.isNotEmpty) { for (final YamlMap platformYamlMap in platformsYaml.whereType()) { - if (_validateMetadataMap( - platformYamlMap, - { - 'platform': String, - 'create_revision': String, - 'base_revision': String, - }, - logger)) { - final FlutterProjectComponent component = FlutterProjectComponent - .values - .firstWhere((FlutterProjectComponent val) => - val.toString() == - 'FlutterProjectComponent.${platformYamlMap['platform'] as String}'); + if (_validateMetadataMap(platformYamlMap, { + 'platform': String, + 'create_revision': String, + 'base_revision': String, + }, logger)) { + final FlutterProjectComponent + component = FlutterProjectComponent.values.firstWhere( + (FlutterProjectComponent val) => + val.toString() == + 'FlutterProjectComponent.${platformYamlMap['platform'] as String}', + ); platformConfigs[component] = MigratePlatformConfig( component: component, createRevision: platformYamlMap['create_revision'] as String?, @@ -379,12 +387,14 @@ migration: } } } - if (_validateMetadataMap( - map, {'unmanaged_files': YamlList}, logger)) { + if (_validateMetadataMap(map, { + 'unmanaged_files': YamlList, + }, logger)) { final Object? unmanagedFilesYaml = map['unmanaged_files']; if (unmanagedFilesYaml is YamlList && unmanagedFilesYaml.isNotEmpty) { - unmanagedFiles = - List.from(unmanagedFilesYaml.value.cast()); + unmanagedFiles = List.from( + unmanagedFilesYaml.value.cast(), + ); } } } @@ -392,8 +402,11 @@ migration: /// Holds the revisions for a single platform for use by the flutter migrate command. class MigratePlatformConfig { - MigratePlatformConfig( - {required this.component, this.createRevision, this.baseRevision}); + MigratePlatformConfig({ + required this.component, + this.createRevision, + this.baseRevision, + }); /// The platform this config describes. FlutterProjectComponent component; diff --git a/packages/flutter_migrate/lib/src/manifest.dart b/packages/flutter_migrate/lib/src/manifest.dart index cef7ea42782..4b36cd0a5a5 100644 --- a/packages/flutter_migrate/lib/src/manifest.dart +++ b/packages/flutter_migrate/lib/src/manifest.dart @@ -22,28 +22,28 @@ const String _kDeletedFilesKey = 'deleted_files'; /// This manifest file is created with the MigrateResult of a computeMigration run. class MigrateManifest { /// Creates a new manifest from a MigrateResult. - MigrateManifest({ - required this.migrateRootDir, - required this.migrateResult, - }); + MigrateManifest({required this.migrateRootDir, required this.migrateResult}); /// Parses an existing migrate manifest. MigrateManifest.fromFile(File manifestFile) - : migrateResult = MigrateResult.empty(), - migrateRootDir = manifestFile.parent { + : migrateResult = MigrateResult.empty(), + migrateRootDir = manifestFile.parent { final Object? yamlContents = loadYaml(manifestFile.readAsStringSync()); if (yamlContents is! YamlMap) { throw Exception( - 'Invalid .migrate_manifest file in the migrate working directory. File is not a Yaml map.'); + 'Invalid .migrate_manifest file in the migrate working directory. File is not a Yaml map.', + ); } final YamlMap map = yamlContents; - bool valid = map.containsKey(_kMergedFilesKey) && + bool valid = + map.containsKey(_kMergedFilesKey) && map.containsKey(_kConflictFilesKey) && map.containsKey(_kAddedFilesKey) && map.containsKey(_kDeletedFilesKey); if (!valid) { throw Exception( - 'Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.'); + 'Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.', + ); } final Object? mergedFilesYaml = map[_kMergedFilesKey]; final Object? conflictFilesYaml = map[_kConflictFilesKey]; @@ -56,44 +56,59 @@ class MigrateManifest { valid = valid && (deletedFilesYaml is YamlList || deletedFilesYaml == null); if (!valid) { throw Exception( - 'Invalid .migrate_manifest file in the migrate working directory. Entry is not a Yaml list.'); + 'Invalid .migrate_manifest file in the migrate working directory. Entry is not a Yaml list.', + ); } if (mergedFilesYaml != null) { for (final Object? localPath in mergedFilesYaml as YamlList) { if (localPath is String) { // We can fill the maps with partially dummy data as not all properties are used by the manifest. - migrateResult.mergeResults.add(StringMergeResult.explicit( + migrateResult.mergeResults.add( + StringMergeResult.explicit( mergedString: '', hasConflict: false, exitCode: 0, - localPath: localPath)); + localPath: localPath, + ), + ); } } } if (conflictFilesYaml != null) { for (final Object? localPath in conflictFilesYaml as YamlList) { if (localPath is String) { - migrateResult.mergeResults.add(StringMergeResult.explicit( + migrateResult.mergeResults.add( + StringMergeResult.explicit( mergedString: '', hasConflict: true, exitCode: 1, - localPath: localPath)); + localPath: localPath, + ), + ); } } } if (addedFilesYaml != null) { for (final Object? localPath in addedFilesYaml as YamlList) { if (localPath is String) { - migrateResult.addedFiles.add(FilePendingMigration( - localPath, migrateRootDir.childFile(localPath))); + migrateResult.addedFiles.add( + FilePendingMigration( + localPath, + migrateRootDir.childFile(localPath), + ), + ); } } } if (deletedFilesYaml != null) { for (final Object? localPath in deletedFilesYaml as YamlList) { if (localPath is String) { - migrateResult.deletedFiles.add(FilePendingMigration( - localPath, migrateRootDir.childFile(localPath))); + migrateResult.deletedFiles.add( + FilePendingMigration( + localPath, + migrateRootDir.childFile(localPath), + ), + ); } } } @@ -118,7 +133,8 @@ class MigrateManifest { final List output = []; for (final String localPath in conflictFiles) { if (!_conflictsResolved( - workingDir.childFile(localPath).readAsStringSync())) { + workingDir.childFile(localPath).readAsStringSync(), + )) { output.add(localPath); } } @@ -130,7 +146,8 @@ class MigrateManifest { final List output = []; for (final String localPath in conflictFiles) { if (_conflictsResolved( - workingDir.childFile(localPath).readAsStringSync())) { + workingDir.childFile(localPath).readAsStringSync(), + )) { output.add(localPath); } } @@ -214,8 +231,12 @@ bool _conflictsResolved(String contents) { /// Returns true if the migration working directory has all conflicts resolved and prints the migration status. /// /// The migration status printout lists all added, deleted, merged, and conflicted files. -bool checkAndPrintMigrateStatus(MigrateManifest manifest, Directory workingDir, - {bool warnConflict = false, Logger? logger}) { +bool checkAndPrintMigrateStatus( + MigrateManifest manifest, + Directory workingDir, { + bool warnConflict = false, + Logger? logger, +}) { final StringBuffer printout = StringBuffer(); final StringBuffer redPrintout = StringBuffer(); bool result = true; @@ -223,7 +244,8 @@ bool checkAndPrintMigrateStatus(MigrateManifest manifest, Directory workingDir, final List mergedFiles = []; for (final String localPath in manifest.conflictFiles) { if (!_conflictsResolved( - workingDir.childFile(localPath).readAsStringSync())) { + workingDir.childFile(localPath).readAsStringSync(), + )) { remainingConflicts.add(localPath); } else { mergedFiles.add(localPath); @@ -252,7 +274,8 @@ bool checkAndPrintMigrateStatus(MigrateManifest manifest, Directory workingDir, if (remainingConflicts.isNotEmpty) { if (warnConflict) { printout.write( - 'Unable to apply migration. The following files in the migration working directory still have unresolved conflicts:'); + 'Unable to apply migration. The following files in the migration working directory still have unresolved conflicts:', + ); } else { printout.write('Merge conflicted files:'); } @@ -263,8 +286,11 @@ bool checkAndPrintMigrateStatus(MigrateManifest manifest, Directory workingDir, } if (logger != null) { logger.printStatus(printout.toString()); - logger.printStatus(redPrintout.toString(), - color: TerminalColor.red, newline: false); + logger.printStatus( + redPrintout.toString(), + color: TerminalColor.red, + newline: false, + ); } return result; } diff --git a/packages/flutter_migrate/lib/src/result.dart b/packages/flutter_migrate/lib/src/result.dart index 597fb927c13..a552a746a87 100644 --- a/packages/flutter_migrate/lib/src/result.dart +++ b/packages/flutter_migrate/lib/src/result.dart @@ -15,26 +15,27 @@ import 'utils.dart'; /// so this must be done manually afterwards. class MigrateResult { /// Explicitly initialize the MigrateResult. - MigrateResult( - {required this.mergeResults, - required this.addedFiles, - required this.deletedFiles, - required this.tempDirectories, - required this.sdkDirs, - required this.mergeTypeMap, - required this.diffMap, - this.generatedBaseTemplateDirectory, - this.generatedTargetTemplateDirectory}); + MigrateResult({ + required this.mergeResults, + required this.addedFiles, + required this.deletedFiles, + required this.tempDirectories, + required this.sdkDirs, + required this.mergeTypeMap, + required this.diffMap, + this.generatedBaseTemplateDirectory, + this.generatedTargetTemplateDirectory, + }); /// Creates a MigrateResult with all empty members. MigrateResult.empty() - : mergeResults = [], - addedFiles = [], - deletedFiles = [], - tempDirectories = [], - mergeTypeMap = {}, - diffMap = {}, - sdkDirs = {}; + : mergeResults = [], + addedFiles = [], + deletedFiles = [], + tempDirectories = [], + mergeTypeMap = {}, + diffMap = {}, + sdkDirs = {}; /// The results of merging existing files with the target files. final List mergeResults; diff --git a/packages/flutter_migrate/lib/src/update_locks.dart b/packages/flutter_migrate/lib/src/update_locks.dart index 8f34650a9f7..5c6022bca81 100644 --- a/packages/flutter_migrate/lib/src/update_locks.dart +++ b/packages/flutter_migrate/lib/src/update_locks.dart @@ -11,16 +11,20 @@ import 'utils.dart'; /// Checks if the project uses pubspec dependency locking and prompts if /// the pub upgrade should be run. -Future updatePubspecDependencies(FlutterProject flutterProject, - MigrateUtils migrateUtils, Logger logger, Terminal terminal, - {bool force = false}) async { +Future updatePubspecDependencies( + FlutterProject flutterProject, + MigrateUtils migrateUtils, + Logger logger, + Terminal terminal, { + bool force = false, +}) async { final File pubspecFile = flutterProject.directory.childFile('pubspec.yaml'); if (!pubspecFile.existsSync()) { return; } - if (!pubspecFile - .readAsStringSync() - .contains('# THIS LINE IS AUTOGENERATED')) { + if (!pubspecFile.readAsStringSync().contains( + '# THIS LINE IS AUTOGENERATED', + )) { return; } logger.printStatus('\nDart dependency locking detected in pubspec.yaml.'); @@ -52,8 +56,9 @@ Future updateGradleDependencyLocking( FileSystem fileSystem, { bool force = false, }) async { - final Directory androidDir = - flutterProject.directory.childDirectory('android'); + final Directory androidDir = flutterProject.directory.childDirectory( + 'android', + ); if (!androidDir.existsSync()) { return; } @@ -72,9 +77,10 @@ Future updateGradleDependencyLocking( try { // lockfiles generated by gradle start with this prefix. if (file.readAsStringSync().startsWith( - '# This is a Gradle generated file for dependency locking.\n# ' - 'Manual edits can break the build and are not advised.\n# This ' - 'file is expected to be part of source control.')) { + '# This is a Gradle generated file for dependency locking.\n# ' + 'Manual edits can break the build and are not advised.\n# This ' + 'file is expected to be part of source control.', + )) { lockfiles.add(file); } } on FileSystemException { @@ -85,9 +91,10 @@ Future updateGradleDependencyLocking( } if (lockfiles.isNotEmpty) { logger.printStatus('\nGradle dependency locking detected.'); - logger - .printStatus('Flutter can backup the lockfiles and regenerate updated ' - 'lockfiles.'); + logger.printStatus( + 'Flutter can backup the lockfiles and regenerate updated ' + 'lockfiles.', + ); terminal.usesTerminalUi = true; String selection = 'y'; if (!force) { @@ -115,7 +122,8 @@ Future updateGradleDependencyLocking( } // Runs `./gradlew tasks`in the project's android directory. await migrateUtils.gradlewTasks( - flutterProject.directory.childDirectory('android').path); + flutterProject.directory.childDirectory('android').path, + ); logger.printStatus('Old lockfiles renamed to:'); for (final String path in backedUpFilePaths) { logger.printStatus(path, color: TerminalColor.grey, indent: 2); diff --git a/packages/flutter_migrate/lib/src/utils.dart b/packages/flutter_migrate/lib/src/utils.dart index 84f70aa494f..0e6dfed8ce7 100644 --- a/packages/flutter_migrate/lib/src/utils.dart +++ b/packages/flutter_migrate/lib/src/utils.dart @@ -22,18 +22,24 @@ class MigrateUtils { required Logger logger, required FileSystem fileSystem, required ProcessManager processManager, - }) : _processManager = processManager, - _logger = logger, - _fileSystem = fileSystem; + }) : _processManager = processManager, + _logger = logger, + _fileSystem = fileSystem; final Logger _logger; final FileSystem _fileSystem; final ProcessManager _processManager; - Future _runCommand(List command, - {String? workingDirectory, bool runInShell = false}) { - return _processManager.run(command, - workingDirectory: workingDirectory, runInShell: runInShell); + Future _runCommand( + List command, { + String? workingDirectory, + bool runInShell = false, + }) { + return _processManager.run( + command, + workingDirectory: workingDirectory, + runInShell: runInShell, + ); } /// Calls `git diff` on two files and returns the diff as a DiffResult. @@ -49,18 +55,21 @@ class MigrateUtils { 'diff', '--no-index', one.absolute.path, - two.absolute.path + two.absolute.path, ]; final ProcessResult result = await _runCommand(cmdArgs); // diff exits with 1 if diffs are found. - checkForErrors(result, - allowedExitCodes: [0, 1], - commandDescription: 'git ${cmdArgs.join(' ')}'); + checkForErrors( + result, + allowedExitCodes: [0, 1], + commandDescription: 'git ${cmdArgs.join(' ')}', + ); return DiffResult( - diffType: DiffType.command, - diff: result.stdout as String, - exitCode: result.exitCode); + diffType: DiffType.command, + diff: result.stdout as String, + exitCode: result.exitCode, + ); } /// Clones a copy of the flutter repo into the destination directory. Returns false if unsuccessful. @@ -71,7 +80,7 @@ class MigrateUtils { 'clone', '--filter=blob:none', 'https://github.com/flutter/flutter.git', - destination + destination, ]; ProcessResult result = await _runCommand(cmdArgs); checkForErrors(result, commandDescription: cmdArgs.join(' ')); @@ -79,8 +88,11 @@ class MigrateUtils { cmdArgs.clear(); cmdArgs = ['git', 'reset', '--hard', revision]; result = await _runCommand(cmdArgs, workingDirectory: destination); - if (!checkForErrors(result, - commandDescription: cmdArgs.join(' '), exit: false)) { + if (!checkForErrors( + result, + commandDescription: cmdArgs.join(' '), + exit: false, + )) { return false; } return true; @@ -101,7 +113,8 @@ class MigrateUtils { // Limit the number of iterations this command is allowed to attempt to prevent infinite looping. if (iterationsAllowed <= 0) { _logger.printError( - 'Unable to `flutter create` with the version of flutter at $flutterBinPath'); + 'Unable to `flutter create` with the version of flutter at $flutterBinPath', + ); return outputDirectory; } @@ -127,8 +140,10 @@ class MigrateUtils { } else { cmdArgs.add(outputDirectory); } - final ProcessResult result = - await _runCommand(cmdArgs, workingDirectory: outputDirectory); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: outputDirectory, + ); final String error = result.stderr as String; // Catch errors due to parameters not existing. @@ -146,8 +161,9 @@ class MigrateUtils { ); } // Old versions of the tool does not include the project-name option. - if ((result.stderr as String) - .contains('Could not find an option named "project-name".')) { + if ((result.stderr as String).contains( + 'Could not find an option named "project-name".', + )) { return createFromTemplates( flutterBinPath, name: name, @@ -195,25 +211,32 @@ class MigrateUtils { '-p', current, base, - target + target, ]; final ProcessResult result = await _runCommand(cmdArgs); - checkForErrors(result, - allowedExitCodes: [-1], commandDescription: cmdArgs.join(' ')); + checkForErrors( + result, + allowedExitCodes: [-1], + commandDescription: cmdArgs.join(' '), + ); return StringMergeResult(result, localPath); } /// Calls `git init` on the workingDirectory. Future gitInit(String workingDirectory) async { final List cmdArgs = ['git', 'init']; - final ProcessResult result = - await _runCommand(cmdArgs, workingDirectory: workingDirectory); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: workingDirectory, + ); checkForErrors(result, commandDescription: cmdArgs.join(' ')); } /// Returns true if the workingDirectory git repo has any uncommited changes. - Future hasUncommittedChanges(String workingDirectory, - {String? migrateStagingDir}) async { + Future hasUncommittedChanges( + String workingDirectory, { + String? migrateStagingDir, + }) async { final List cmdArgs = [ 'git', 'ls-files', @@ -221,12 +244,17 @@ class MigrateUtils { '--modified', '--others', '--exclude-standard', - '--exclude=${migrateStagingDir ?? kDefaultMigrateStagingDirectoryName}' + '--exclude=${migrateStagingDir ?? kDefaultMigrateStagingDirectoryName}', ]; - final ProcessResult result = - await _runCommand(cmdArgs, workingDirectory: workingDirectory); - checkForErrors(result, - allowedExitCodes: [-1], commandDescription: cmdArgs.join(' ')); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: workingDirectory, + ); + checkForErrors( + result, + allowedExitCodes: [-1], + commandDescription: cmdArgs.join(' '), + ); if ((result.stdout as String).isEmpty) { return false; } @@ -238,12 +266,17 @@ class MigrateUtils { final List cmdArgs = [ 'git', 'rev-parse', - '--is-inside-work-tree' + '--is-inside-work-tree', ]; - final ProcessResult result = - await _runCommand(cmdArgs, workingDirectory: workingDirectory); - checkForErrors(result, - allowedExitCodes: [-1], commandDescription: cmdArgs.join(' ')); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: workingDirectory, + ); + checkForErrors( + result, + allowedExitCodes: [-1], + commandDescription: cmdArgs.join(' '), + ); if (result.exitCode == 0) { return true; } @@ -253,11 +286,15 @@ class MigrateUtils { /// Returns true if the file at `filePath` is covered by the `.gitignore` Future isGitIgnored(String filePath, String workingDirectory) async { final List cmdArgs = ['git', 'check-ignore', filePath]; - final ProcessResult result = - await _runCommand(cmdArgs, workingDirectory: workingDirectory); - checkForErrors(result, - allowedExitCodes: [0, 1, 128], - commandDescription: cmdArgs.join(' ')); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: workingDirectory, + ); + checkForErrors( + result, + allowedExitCodes: [0, 1, 128], + commandDescription: cmdArgs.join(' '), + ); return result.exitCode == 0; } @@ -267,10 +304,12 @@ class MigrateUtils { 'flutter', 'pub', 'upgrade', - '--major-versions' + '--major-versions', ]; - final ProcessResult result = - await _runCommand(cmdArgs, workingDirectory: workingDirectory); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: workingDirectory, + ); checkForErrors(result, commandDescription: cmdArgs.join(' ')); } @@ -278,8 +317,11 @@ class MigrateUtils { Future gradlewTasks(String workingDirectory) async { final String baseCommand = isWindows ? 'gradlew.bat' : './gradlew'; final List cmdArgs = [baseCommand, 'tasks']; - final ProcessResult result = await _runCommand(cmdArgs, - workingDirectory: workingDirectory, runInShell: isWindows); + final ProcessResult result = await _runCommand( + cmdArgs, + workingDirectory: workingDirectory, + runInShell: isWindows, + ); checkForErrors(result, commandDescription: cmdArgs.join(' ')); } @@ -288,18 +330,21 @@ class MigrateUtils { /// If an error is detected, the error can be optionally logged or exit the tool. /// /// Passing -1 in allowedExitCodes means all exit codes are valid. - bool checkForErrors(ProcessResult result, - {List allowedExitCodes = const [0], - String? commandDescription, - bool exit = true, - bool silent = false}) { + bool checkForErrors( + ProcessResult result, { + List allowedExitCodes = const [0], + String? commandDescription, + bool exit = true, + bool silent = false, + }) { if (allowedExitCodes.contains(result.exitCode) || allowedExitCodes.contains(-1)) { return true; } if (!silent) { _logger.printError( - 'Command encountered an error with exit code ${result.exitCode}.'); + 'Command encountered an error with exit code ${result.exitCode}.', + ); if (commandDescription != null) { _logger.printError('Command:'); _logger.printError(commandDescription, indent: 2); @@ -311,15 +356,17 @@ class MigrateUtils { } if (exit) { throwToolExit( - 'Command failed with exit code ${result.exitCode}: ${result.stderr}\n${result.stdout}', - exitCode: result.exitCode); + 'Command failed with exit code ${result.exitCode}: ${result.stderr}\n${result.stdout}', + exitCode: result.exitCode, + ); } return false; } /// Returns true if the file does not contain any git conflit markers. bool conflictsResolved(String contents) { - final bool hasMarker = contents.contains('>>>>>>>') || + final bool hasMarker = + contents.contains('>>>>>>>') || contents.contains('=======') || contents.contains('<<<<<<<'); return !hasMarker; @@ -327,21 +374,29 @@ class MigrateUtils { } Future gitRepoExists( - String projectDirectory, Logger logger, MigrateUtils migrateUtils) async { + String projectDirectory, + Logger logger, + MigrateUtils migrateUtils, +) async { if (await migrateUtils.isGitRepo(projectDirectory)) { return true; } logger.printStatus( - 'Project is not a git repo. Please initialize a git repo and try again.'); + 'Project is not a git repo. Please initialize a git repo and try again.', + ); printCommand('git init', logger); return false; } Future hasUncommittedChanges( - String projectDirectory, Logger logger, MigrateUtils migrateUtils) async { + String projectDirectory, + Logger logger, + MigrateUtils migrateUtils, +) async { if (await migrateUtils.hasUncommittedChanges(projectDirectory)) { logger.printStatus( - 'There are uncommitted changes in your project. Please git commit, abandon, or stash your changes before trying again.'); + 'There are uncommitted changes in your project. Please git commit, abandon, or stash your changes before trying again.', + ); logger.printStatus('You may commit your changes using'); printCommand('git add .', logger, newlineAfter: false); printCommand('git commit -m ""', logger); @@ -360,34 +415,32 @@ void printCommand(String command, Logger logger, {bool newlineAfter = true}) { } /// Prints a command to logger with appropriate formatting. -void printCommandText(String command, Logger logger, - {bool? standalone = true, bool newlineAfter = true}) { - final String prefix = standalone == null - ? '' - : (standalone - ? 'dart run ${Platform.pathSeparator}bin${Platform.pathSeparator}flutter_migrate.dart ' - : 'flutter migrate '); +void printCommandText( + String command, + Logger logger, { + bool? standalone = true, + bool newlineAfter = true, +}) { + final String prefix = + standalone == null + ? '' + : (standalone + ? 'dart run ${Platform.pathSeparator}bin${Platform.pathSeparator}flutter_migrate.dart ' + : 'flutter migrate '); printCommand('$prefix$command', logger, newlineAfter: newlineAfter); } /// Defines the classification of difference between files. -enum DiffType { - command, - addition, - deletion, - ignored, - none, -} +enum DiffType { command, addition, deletion, ignored, none } /// Tracks the output of a git diff command or any special cases such as addition of a new /// file or deletion of an existing file. class DiffResult { - DiffResult({ - required this.diffType, - this.diff, - this.exitCode, - }) : assert(diffType == DiffType.command && exitCode != null || - diffType != DiffType.command && exitCode == null); + DiffResult({required this.diffType, this.diff, this.exitCode}) + : assert( + diffType == DiffType.command && exitCode != null || + diffType != DiffType.command && exitCode == null, + ); /// The diff string output by git. final String? diff; @@ -404,8 +457,8 @@ class DiffResult { abstract class MergeResult { /// Initializes a MergeResult based off of a ProcessResult. MergeResult(ProcessResult result, this.localPath) - : hasConflict = result.exitCode != 0, - exitCode = result.exitCode; + : hasConflict = result.exitCode != 0, + exitCode = result.exitCode; /// Manually initializes a MergeResult with explicit values. MergeResult.explicit({ @@ -428,7 +481,7 @@ abstract class MergeResult { class StringMergeResult extends MergeResult { /// Initializes a BinaryMergeResult based off of a ProcessResult. StringMergeResult(super.result, super.localPath) - : mergedString = result.stdout as String; + : mergedString = result.stdout as String; /// Manually initializes a StringMergeResult with explicit values. StringMergeResult.explicit({ @@ -446,7 +499,7 @@ class StringMergeResult extends MergeResult { class BinaryMergeResult extends MergeResult { /// Initializes a BinaryMergeResult based off of a ProcessResult. BinaryMergeResult(super.result, super.localPath) - : mergedBytes = result.stdout as Uint8List; + : mergedBytes = result.stdout as Uint8List; /// Manually initializes a BinaryMergeResult with explicit values. BinaryMergeResult.explicit({ diff --git a/packages/flutter_migrate/pubspec.yaml b/packages/flutter_migrate/pubspec.yaml index 63328af7b4d..b6bbdf5690c 100644 --- a/packages/flutter_migrate/pubspec.yaml +++ b/packages/flutter_migrate/pubspec.yaml @@ -6,7 +6,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ publish_to: none environment: - sdk: ^3.6.0 + sdk: ^3.7.0 dependencies: args: ^2.3.1 diff --git a/packages/flutter_migrate/test/abandon_test.dart b/packages/flutter_migrate/test/abandon_test.dart index 8f38fbb91fb..58d95903c35 100644 --- a/packages/flutter_migrate/test/abandon_test.dart +++ b/packages/flutter_migrate/test/abandon_test.dart @@ -34,19 +34,22 @@ void main() { tryToDelete(appDir); }); - testUsingContext('abandon deletes staging directory', () async { - final MigrateAbandonCommand command = MigrateAbandonCommand( - logger: logger, - fileSystem: fileSystem, - terminal: terminal, - processManager: processManager, - ); - final Directory stagingDir = - appDir.childDirectory(kDefaultMigrateStagingDirectoryName); - appDir.childFile('lib/main.dart').createSync(recursive: true); - final File pubspecOriginal = appDir.childFile('pubspec.yaml'); - pubspecOriginal.createSync(); - pubspecOriginal.writeAsStringSync(''' + testUsingContext( + 'abandon deletes staging directory', + () async { + final MigrateAbandonCommand command = MigrateAbandonCommand( + logger: logger, + fileSystem: fileSystem, + terminal: terminal, + processManager: processManager, + ); + final Directory stagingDir = appDir.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); + appDir.childFile('lib/main.dart').createSync(recursive: true); + final File pubspecOriginal = appDir.childFile('pubspec.yaml'); + pubspecOriginal.createSync(); + pubspecOriginal.writeAsStringSync(''' name: originalname description: A new Flutter project. version: 1.0.0+1 @@ -60,29 +63,33 @@ dev_dependencies: sdk: flutter flutter: uses-material-design: true''', flush: true); - expect(stagingDir.existsSync(), false); - await createTestCommandRunner(command).run([ - 'abandon', - '--staging-directory=${stagingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect(logger.errorText, contains('Provided staging directory')); - expect(logger.errorText, - contains('migrate_staging_dir` does not exist or is not valid.')); + expect(stagingDir.existsSync(), false); + await createTestCommandRunner(command).run([ + 'abandon', + '--staging-directory=${stagingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect(logger.errorText, contains('Provided staging directory')); + expect( + logger.errorText, + contains('migrate_staging_dir` does not exist or is not valid.'), + ); - logger.clear(); - await createTestCommandRunner(command).run([ - 'abandon', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect(logger.statusText, - contains('No migration in progress. Start a new migration with:')); + logger.clear(); + await createTestCommandRunner(command).run([ + 'abandon', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect( + logger.statusText, + contains('No migration in progress. Start a new migration with:'), + ); - final File pubspecModified = stagingDir.childFile('pubspec.yaml'); - pubspecModified.createSync(recursive: true); - pubspecModified.writeAsStringSync(''' + final File pubspecModified = stagingDir.childFile('pubspec.yaml'); + pubspecModified.createSync(recursive: true); + pubspecModified.writeAsStringSync(''' name: newname description: new description of the test project version: 1.0.0+1 @@ -98,13 +105,13 @@ flutter: uses-material-design: false EXTRALINE''', flush: true); - final File addedFile = stagingDir.childFile('added.file'); - addedFile.createSync(recursive: true); - addedFile.writeAsStringSync('new file contents'); + final File addedFile = stagingDir.childFile('added.file'); + addedFile.createSync(recursive: true); + addedFile.writeAsStringSync('new file contents'); - final File manifestFile = stagingDir.childFile('.migrate_manifest'); - manifestFile.createSync(recursive: true); - manifestFile.writeAsStringSync(''' + final File manifestFile = stagingDir.childFile('.migrate_manifest'); + manifestFile.createSync(recursive: true); + manifestFile.writeAsStringSync(''' merged_files: - pubspec.yaml conflict_files: @@ -113,22 +120,26 @@ added_files: deleted_files: '''); - expect(appDir.childFile('lib/main.dart').existsSync(), true); + expect(appDir.childFile('lib/main.dart').existsSync(), true); - expect(stagingDir.existsSync(), true); - logger.clear(); - await createTestCommandRunner(command).run([ - 'abandon', - '--staging-directory=${stagingDir.path}', - '--project-directory=${appDir.path}', - '--force', - '--flutter-subcommand', - ]); - expect(logger.statusText, - contains('Abandon complete. Start a new migration with:')); - expect(stagingDir.existsSync(), false); - }, overrides: { - FileSystem: () => fileSystem, - ProcessManager: () => processManager, - }); + expect(stagingDir.existsSync(), true); + logger.clear(); + await createTestCommandRunner(command).run([ + 'abandon', + '--staging-directory=${stagingDir.path}', + '--project-directory=${appDir.path}', + '--force', + '--flutter-subcommand', + ]); + expect( + logger.statusText, + contains('Abandon complete. Start a new migration with:'), + ); + expect(stagingDir.existsSync(), false); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }, + ); } diff --git a/packages/flutter_migrate/test/apply_test.dart b/packages/flutter_migrate/test/apply_test.dart index 6f2bb8aa5b3..5aa86982e5d 100644 --- a/packages/flutter_migrate/test/apply_test.dart +++ b/packages/flutter_migrate/test/apply_test.dart @@ -35,31 +35,38 @@ void main() { tryToDelete(appDir); }); - testUsingContext('Apply produces all outputs', () async { - final ProcessResult result = await processManager - .run(['flutter', '--version'], workingDirectory: appDir.path); - final String versionOutput = result.stdout as String; - final List versionSplit = versionOutput.substring(8, 14).split('.'); - expect(versionSplit.length >= 2, true); - if (!(int.parse(versionSplit[0]) > 3 || - int.parse(versionSplit[0]) == 3 && int.parse(versionSplit[1]) > 3)) { - // Apply not supported on stable version 3.3 and below - return; - } - - final MigrateApplyCommand command = MigrateApplyCommand( - verbose: true, - logger: logger, - fileSystem: fileSystem, - terminal: terminal, - processManager: processManager, - ); - final Directory workingDir = - appDir.childDirectory(kDefaultMigrateStagingDirectoryName); - appDir.childFile('lib/main.dart').createSync(recursive: true); - final File pubspecOriginal = appDir.childFile('pubspec.yaml'); - pubspecOriginal.createSync(); - pubspecOriginal.writeAsStringSync(''' + testUsingContext( + 'Apply produces all outputs', + () async { + final ProcessResult result = await processManager.run([ + 'flutter', + '--version', + ], workingDirectory: appDir.path); + final String versionOutput = result.stdout as String; + final List versionSplit = versionOutput + .substring(8, 14) + .split('.'); + expect(versionSplit.length >= 2, true); + if (!(int.parse(versionSplit[0]) > 3 || + int.parse(versionSplit[0]) == 3 && int.parse(versionSplit[1]) > 3)) { + // Apply not supported on stable version 3.3 and below + return; + } + + final MigrateApplyCommand command = MigrateApplyCommand( + verbose: true, + logger: logger, + fileSystem: fileSystem, + terminal: terminal, + processManager: processManager, + ); + final Directory workingDir = appDir.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); + appDir.childFile('lib/main.dart').createSync(recursive: true); + final File pubspecOriginal = appDir.childFile('pubspec.yaml'); + pubspecOriginal.createSync(); + pubspecOriginal.writeAsStringSync(''' name: originalname description: A new Flutter project. version: 1.0.0+1 @@ -74,38 +81,44 @@ dev_dependencies: flutter: uses-material-design: true''', flush: true); - final File gitignore = appDir.childFile('.gitignore'); - gitignore.createSync(); - gitignore.writeAsStringSync(kDefaultMigrateStagingDirectoryName, - flush: true); - - logger.clear(); - await createTestCommandRunner(command).run([ - 'apply', - '--staging-directory=${workingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect( + final File gitignore = appDir.childFile('.gitignore'); + gitignore.createSync(); + gitignore.writeAsStringSync( + kDefaultMigrateStagingDirectoryName, + flush: true, + ); + + logger.clear(); + await createTestCommandRunner(command).run([ + 'apply', + '--staging-directory=${workingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect( logger.statusText, contains( - 'Project is not a git repo. Please initialize a git repo and try again.')); - - await processManager - .run(['git', 'init'], workingDirectory: appDir.path); - - logger.clear(); - await createTestCommandRunner(command).run([ - 'apply', - '--staging-directory=${workingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect(logger.statusText, contains('No migration in progress')); - - final File pubspecModified = workingDir.childFile('pubspec.yaml'); - pubspecModified.createSync(recursive: true); - pubspecModified.writeAsStringSync(''' + 'Project is not a git repo. Please initialize a git repo and try again.', + ), + ); + + await processManager.run([ + 'git', + 'init', + ], workingDirectory: appDir.path); + + logger.clear(); + await createTestCommandRunner(command).run([ + 'apply', + '--staging-directory=${workingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect(logger.statusText, contains('No migration in progress')); + + final File pubspecModified = workingDir.childFile('pubspec.yaml'); + pubspecModified.createSync(recursive: true); + pubspecModified.writeAsStringSync(''' name: newname description: new description of the test project version: 1.0.0+1 @@ -121,13 +134,13 @@ flutter: uses-material-design: false # EXTRALINE:''', flush: true); - final File addedFile = workingDir.childFile('added.file'); - addedFile.createSync(recursive: true); - addedFile.writeAsStringSync('new file contents'); + final File addedFile = workingDir.childFile('added.file'); + addedFile.createSync(recursive: true); + addedFile.writeAsStringSync('new file contents'); - final File manifestFile = workingDir.childFile('.migrate_manifest'); - manifestFile.createSync(recursive: true); - manifestFile.writeAsStringSync(''' + final File manifestFile = workingDir.childFile('.migrate_manifest'); + manifestFile.createSync(recursive: true); + manifestFile.writeAsStringSync(''' merged_files: - pubspec.yaml conflict_files: @@ -137,11 +150,12 @@ added_files: deleted_files: '''); - // Add conflict file - final File conflictFile = - workingDir.childDirectory('conflict').childFile('conflict.file'); - conflictFile.createSync(recursive: true); - conflictFile.writeAsStringSync(''' + // Add conflict file + final File conflictFile = workingDir + .childDirectory('conflict') + .childFile('conflict.file'); + conflictFile.createSync(recursive: true); + conflictFile.writeAsStringSync(''' line1 <<<<<<< /conflcit/conflict.file line2 @@ -151,23 +165,26 @@ linetwo line3 ''', flush: true); - final File conflictFileOriginal = - appDir.childDirectory('conflict').childFile('conflict.file'); - conflictFileOriginal.createSync(recursive: true); - conflictFileOriginal.writeAsStringSync(''' + final File conflictFileOriginal = appDir + .childDirectory('conflict') + .childFile('conflict.file'); + conflictFileOriginal.createSync(recursive: true); + conflictFileOriginal.writeAsStringSync(''' line1 line2 line3 ''', flush: true); - logger.clear(); - await createTestCommandRunner(command).run([ - 'apply', - '--staging-directory=${workingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect(logger.statusText, contains(r''' + logger.clear(); + await createTestCommandRunner(command).run([ + 'apply', + '--staging-directory=${workingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect( + logger.statusText, + contains(r''' Added files: - added.file Modified files: @@ -177,39 +194,52 @@ Unable to apply migration. The following files in the migration working director Conflicting files found. Resolve these conflicts and try again. Guided conflict resolution wizard: - $ flutter migrate resolve-conflicts''')); + $ flutter migrate resolve-conflicts'''), + ); - conflictFile.writeAsStringSync(''' + conflictFile.writeAsStringSync(''' line1 linetwo line3 ''', flush: true); - logger.clear(); - await createTestCommandRunner(command).run([ - 'apply', - '--staging-directory=${workingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect( + logger.clear(); + await createTestCommandRunner(command).run([ + 'apply', + '--staging-directory=${workingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect( logger.statusText, contains( - 'There are uncommitted changes in your project. Please git commit, abandon, or stash your changes before trying again.')); - - await processManager - .run(['git', 'add', '.'], workingDirectory: appDir.path); - await processManager.run(['git', 'commit', '-m', 'Initial commit'], - workingDirectory: appDir.path); - - logger.clear(); - await createTestCommandRunner(command).run([ - 'apply', - '--staging-directory=${workingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - expect(logger.statusText, contains(r''' + 'There are uncommitted changes in your project. Please git commit, abandon, or stash your changes before trying again.', + ), + ); + + await processManager.run([ + 'git', + 'add', + '.', + ], workingDirectory: appDir.path); + await processManager.run([ + 'git', + 'commit', + '-m', + 'Initial commit', + ], workingDirectory: appDir.path); + + logger.clear(); + await createTestCommandRunner(command).run([ + 'apply', + '--staging-directory=${workingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + expect( + logger.statusText, + contains( + r''' Added files: - added.file Modified files: @@ -222,15 +252,21 @@ Writing pubspec.yaml Writing conflict/conflict.file Writing added.file Updating .migrate_configs -Migration complete. You may use commands like `git status`, `git diff` and `git restore ` to continue working with the migrated files.''')); - - expect(pubspecOriginal.readAsStringSync(), contains('# EXTRALINE')); - expect(conflictFileOriginal.readAsStringSync(), contains('linetwo')); - expect(appDir.childFile('added.file').existsSync(), true); - expect(appDir.childFile('added.file').readAsStringSync(), - contains('new file contents')); - }, overrides: { - FileSystem: () => fileSystem, - ProcessManager: () => processManager, - }); +Migration complete. You may use commands like `git status`, `git diff` and `git restore ` to continue working with the migrated files.''', + ), + ); + + expect(pubspecOriginal.readAsStringSync(), contains('# EXTRALINE')); + expect(conflictFileOriginal.readAsStringSync(), contains('linetwo')); + expect(appDir.childFile('added.file').existsSync(), true); + expect( + appDir.childFile('added.file').readAsStringSync(), + contains('new file contents'), + ); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }, + ); } diff --git a/packages/flutter_migrate/test/base/context_test.dart b/packages/flutter_migrate/test/base/context_test.dart index 53f8e8f691a..551838e701d 100644 --- a/packages/flutter_migrate/test/base/context_test.dart +++ b/packages/flutter_migrate/test/base/context_test.dart @@ -22,88 +22,93 @@ void main() { }); test( - 'returns root context in child of root zone if zone was manually created', - () { - final Zone rootZone = Zone.current; - final AppContext rootContext = context; - runZoned(() { - expect(Zone.current, isNot(rootZone)); - expect(Zone.current.parent, rootZone); - expect(context, rootContext); - called = true; - }); - expect(called, isTrue); - }); + 'returns root context in child of root zone if zone was manually created', + () { + final Zone rootZone = Zone.current; + final AppContext rootContext = context; + runZoned(() { + expect(Zone.current, isNot(rootZone)); + expect(Zone.current.parent, rootZone); + expect(context, rootContext); + called = true; + }); + expect(called, isTrue); + }, + ); test('returns child context after run', () async { final AppContext rootContext = context; await rootContext.run( - name: 'child', - body: () { - expect(context, isNot(rootContext)); - expect(context.name, 'child'); - called = true; - }); + name: 'child', + body: () { + expect(context, isNot(rootContext)); + expect(context.name, 'child'); + called = true; + }, + ); expect(called, isTrue); }); test('returns grandchild context after nested run', () async { final AppContext rootContext = context; await rootContext.run( - name: 'child', - body: () async { - final AppContext childContext = context; - await childContext.run( - name: 'grandchild', - body: () { - expect(context, isNot(rootContext)); - expect(context, isNot(childContext)); - expect(context.name, 'grandchild'); - called = true; - }); - }); + name: 'child', + body: () async { + final AppContext childContext = context; + await childContext.run( + name: 'grandchild', + body: () { + expect(context, isNot(rootContext)); + expect(context, isNot(childContext)); + expect(context.name, 'grandchild'); + called = true; + }, + ); + }, + ); expect(called, isTrue); }); test('scans up zone hierarchy for first context', () async { final AppContext rootContext = context; await rootContext.run( - name: 'child', - body: () { - final AppContext childContext = context; - runZoned(() { - expect(context, isNot(rootContext)); - expect(context, same(childContext)); - expect(context.name, 'child'); - called = true; - }); + name: 'child', + body: () { + final AppContext childContext = context; + runZoned(() { + expect(context, isNot(rootContext)); + expect(context, same(childContext)); + expect(context.name, 'child'); + called = true; }); + }, + ); expect(called, isTrue); }); }); group('operator[]', () { - test('still finds values if async code runs after body has finished', - () async { - final Completer outer = Completer(); - final Completer inner = Completer(); - String? value; - await context.run( - body: () { - outer.future.then((_) { - value = context.get(); - inner.complete(); - }); - }, - fallbacks: { - String: () => 'value', - }, - ); - expect(value, isNull); - outer.complete(); - await inner.future; - expect(value, 'value'); - }); + test( + 'still finds values if async code runs after body has finished', + () async { + final Completer outer = Completer(); + final Completer inner = Completer(); + String? value; + await context.run( + body: () { + outer.future.then((_) { + value = context.get(); + inner.complete(); + }); + }, + fallbacks: {String: () => 'value'}, + ); + expect(value, isNull); + outer.complete(); + await inner.future; + expect(value, 'value'); + }, + ); test('caches generated override values', () async { int consultationCount = 0; @@ -112,9 +117,11 @@ void main() { body: () async { final StringBuffer buf = StringBuffer(context.get()!); buf.write(context.get()); - await context.run(body: () { - buf.write(context.get()); - }); + await context.run( + body: () { + buf.write(context.get()); + }, + ); value = buf.toString(); }, overrides: { @@ -135,9 +142,11 @@ void main() { body: () async { final StringBuffer buf = StringBuffer(context.get()!); buf.write(context.get()); - await context.run(body: () { - buf.write(context.get()); - }); + await context.run( + body: () { + buf.write(context.get()); + }, + ); value = buf.toString(); }, fallbacks: { @@ -154,9 +163,7 @@ void main() { test('returns null if generated value is null', () async { final String? value = await context.run( body: () => context.get(), - overrides: { - String: () => null, - }, + overrides: {String: () => null}, ); expect(value, isNull); }); @@ -175,14 +182,17 @@ void main() { expect( () => value, throwsA( - isA().having( - (ContextDependencyCycleException error) => error.cycle, - 'cycle', - [String, double, int]).having( - (ContextDependencyCycleException error) => error.toString(), - 'toString()', - 'Dependency cycle detected: String -> double -> int', - ), + isA() + .having( + (ContextDependencyCycleException error) => error.cycle, + 'cycle', + [String, double, int], + ) + .having( + (ContextDependencyCycleException error) => error.toString(), + 'toString()', + 'Dependency cycle detected: String -> double -> int', + ), ), ); }); @@ -197,10 +207,11 @@ void main() { test('passes name to child context', () async { await context.run( - name: 'child', - body: () { - expect(context.name, 'child'); - }); + name: 'child', + body: () { + expect(context.name, 'child'); + }, + ); }); group('fallbacks', () { @@ -218,9 +229,7 @@ void main() { called = true; return context.get(); }, - fallbacks: { - String: () => 'child', - }, + fallbacks: {String: () => 'child'}, ); }, ); @@ -245,9 +254,7 @@ void main() { }, ); }, - fallbacks: { - String: () => 'parent', - }, + fallbacks: {String: () => 'parent'}, ); expect(called, isTrue); expect(value, 'parent'); @@ -275,9 +282,7 @@ void main() { body: () { return context.run( body: () => context.get(), - overrides: { - String: () => 'child', - }, + overrides: {String: () => 'child'}, ); }, fallbacks: { diff --git a/packages/flutter_migrate/test/base/file_system_test.dart b/packages/flutter_migrate/test/base/file_system_test.dart index 191a13101b2..a1538e19c6e 100644 --- a/packages/flutter_migrate/test/base/file_system_test.dart +++ b/packages/flutter_migrate/test/base/file_system_test.dart @@ -30,32 +30,41 @@ void main() { setUp(() { fs = MemoryFileSystem.test(); - fsUtils = FileSystemUtils( - fileSystem: fs, - ); + fsUtils = FileSystemUtils(fileSystem: fs); }); testWithoutContext('getUniqueFile creates a unique file name', () async { final File fileA = fsUtils.getUniqueFile( - fs.currentDirectory, 'foo', 'json') - ..createSync(); - final File fileB = - fsUtils.getUniqueFile(fs.currentDirectory, 'foo', 'json'); + fs.currentDirectory, + 'foo', + 'json', + )..createSync(); + final File fileB = fsUtils.getUniqueFile( + fs.currentDirectory, + 'foo', + 'json', + ); expect(fileA.path, '/foo_01.json'); expect(fileB.path, '/foo_02.json'); }); - testWithoutContext('getUniqueDirectory creates a unique directory name', - () async { - final Directory directoryA = - fsUtils.getUniqueDirectory(fs.currentDirectory, 'foo')..createSync(); - final Directory directoryB = - fsUtils.getUniqueDirectory(fs.currentDirectory, 'foo'); - - expect(directoryA.path, '/foo_01'); - expect(directoryB.path, '/foo_02'); - }); + testWithoutContext( + 'getUniqueDirectory creates a unique directory name', + () async { + final Directory directoryA = fsUtils.getUniqueDirectory( + fs.currentDirectory, + 'foo', + )..createSync(); + final Directory directoryB = fsUtils.getUniqueDirectory( + fs.currentDirectory, + 'foo', + ); + + expect(directoryA.path, '/foo_01'); + expect(directoryB.path, '/foo_02'); + }, + ); }); group('copyDirectorySync', () { @@ -64,8 +73,9 @@ void main() { testWithoutContext('test directory copy', () async { final MemoryFileSystem sourceMemoryFs = MemoryFileSystem.test(); const String sourcePath = '/some/origin'; - final Directory sourceDirectory = - await sourceMemoryFs.directory(sourcePath).create(recursive: true); + final Directory sourceDirectory = await sourceMemoryFs + .directory(sourcePath) + .create(recursive: true); sourceMemoryFs.currentDirectory = sourcePath; final File sourceFile1 = sourceMemoryFs.file('some_file.txt') ..writeAsStringSync('bleh'); @@ -86,12 +96,16 @@ void main() { targetMemoryFs.currentDirectory = targetPath; expect(targetMemoryFs.directory('empty_directory').existsSync(), true); expect( - targetMemoryFs.file('sub_dir/another_file.txt').existsSync(), true); + targetMemoryFs.file('sub_dir/another_file.txt').existsSync(), + true, + ); expect(targetMemoryFs.file('some_file.txt').readAsStringSync(), 'bleh'); // Assert that the copy operation hasn't modified the original file in some way. expect( - sourceMemoryFs.file('some_file.txt').lastModifiedSync(), writeTime); + sourceMemoryFs.file('some_file.txt').lastModifiedSync(), + writeTime, + ); // There's still 3 things in the original directory as there were initially. expect(sourceMemoryFs.directory(sourcePath).listSync().length, 3); }); @@ -112,50 +126,62 @@ void main() { .writeAsStringSync('irrelevant'); final Directory destination = fileSystem.directory('/destination'); - copyDirectory(origin, destination, - shouldCopyFile: (File origin, File dest) { - return origin.basename == 'b.txt'; - }); + copyDirectory( + origin, + destination, + shouldCopyFile: (File origin, File dest) { + return origin.basename == 'b.txt'; + }, + ); expect(destination.existsSync(), isTrue); expect(destination.childDirectory('nested').existsSync(), isTrue); expect( - destination.childDirectory('nested').childFile('b.txt').existsSync(), - isTrue); + destination.childDirectory('nested').childFile('b.txt').existsSync(), + isTrue, + ); expect(destination.childFile('a.txt').existsSync(), isFalse); expect( - destination.childDirectory('nested').childFile('a.txt').existsSync(), - isFalse); + destination.childDirectory('nested').childFile('a.txt').existsSync(), + isFalse, + ); }); - testWithoutContext('Skip directories if shouldCopyDirectory returns false', - () { - final MemoryFileSystem fileSystem = MemoryFileSystem.test(); - final Directory origin = fileSystem.directory('/origin'); - origin.createSync(); - fileSystem - .file(fileSystem.path.join('origin', 'a.txt')) - .writeAsStringSync('irrelevant'); - fileSystem.directory('/origin/nested').createSync(); - fileSystem - .file(fileSystem.path.join('origin', 'nested', 'a.txt')) - .writeAsStringSync('irrelevant'); - fileSystem - .file(fileSystem.path.join('origin', 'nested', 'b.txt')) - .writeAsStringSync('irrelevant'); - - final Directory destination = fileSystem.directory('/destination'); - copyDirectory(origin, destination, + testWithoutContext( + 'Skip directories if shouldCopyDirectory returns false', + () { + final MemoryFileSystem fileSystem = MemoryFileSystem.test(); + final Directory origin = fileSystem.directory('/origin'); + origin.createSync(); + fileSystem + .file(fileSystem.path.join('origin', 'a.txt')) + .writeAsStringSync('irrelevant'); + fileSystem.directory('/origin/nested').createSync(); + fileSystem + .file(fileSystem.path.join('origin', 'nested', 'a.txt')) + .writeAsStringSync('irrelevant'); + fileSystem + .file(fileSystem.path.join('origin', 'nested', 'b.txt')) + .writeAsStringSync('irrelevant'); + + final Directory destination = fileSystem.directory('/destination'); + copyDirectory( + origin, + destination, shouldCopyDirectory: (Directory directory) { - return !directory.path.endsWith('nested'); - }); + return !directory.path.endsWith('nested'); + }, + ); - expect(destination, exists); - expect(destination.childDirectory('nested'), isNot(exists)); - expect(destination.childDirectory('nested').childFile('b.txt'), - isNot(exists)); - }); + expect(destination, exists); + expect(destination.childDirectory('nested'), isNot(exists)); + expect( + destination.childDirectory('nested').childFile('b.txt'), + isNot(exists), + ); + }, + ); }); group('LocalFileSystem', () { @@ -214,10 +240,11 @@ void main() { fail('expected tool exit'); } on ToolExit catch (e) { expect( - e.message, - 'Your system temp directory (/does_not_exist) does not exist. ' - 'Did you set an invalid override in your environment? ' - 'See issue https://github.com/flutter/flutter/issues/74042 for more context.'); + e.message, + 'Your system temp directory (/does_not_exist) does not exist. ' + 'Did you set an invalid override in your environment? ' + 'See issue https://github.com/flutter/flutter/issues/74042 for more context.', + ); } }); }); @@ -233,9 +260,7 @@ class FakeProcessSignal extends Fake implements io.ProcessSignal { /// Various convenience file system methods. class FileSystemUtils { - FileSystemUtils({ - required FileSystem fileSystem, - }) : _fileSystem = fileSystem; + FileSystemUtils({required FileSystem fileSystem}) : _fileSystem = fileSystem; final FileSystem _fileSystem; @@ -270,8 +295,9 @@ class FileSystemUtils { while (true) { final String name = '${baseName}_${i.toString().padLeft(2, '0')}'; - final Directory directory = - fs.directory(_fileSystem.path.join(dir.path, name)); + final Directory directory = fs.directory( + _fileSystem.path.join(dir.path, name), + ); if (!directory.existsSync()) { return directory; } @@ -295,7 +321,8 @@ void copyDirectory( }) { if (!srcDir.existsSync()) { throw Exception( - 'Source directory "${srcDir.path}" does not exist, nothing to copy'); + 'Source directory "${srcDir.path}" does not exist, nothing to copy', + ); } if (!destDir.existsSync()) { @@ -303,8 +330,10 @@ void copyDirectory( } for (final FileSystemEntity entity in srcDir.listSync()) { - final String newPath = - destDir.fileSystem.path.join(destDir.path, entity.basename); + final String newPath = destDir.fileSystem.path.join( + destDir.path, + entity.basename, + ); if (entity is Link) { final Link newLink = destDir.fileSystem.link(newPath); newLink.createSync(entity.targetSync()); @@ -327,7 +356,8 @@ void copyDirectory( ); } else { throw Exception( - '${entity.path} is neither File nor Directory, was ${entity.runtimeType}'); + '${entity.path} is neither File nor Directory, was ${entity.runtimeType}', + ); } } } diff --git a/packages/flutter_migrate/test/base/io_test.dart b/packages/flutter_migrate/test/base/io_test.dart index 608715e497c..28b954ce3d0 100644 --- a/packages/flutter_migrate/test/base/io_test.dart +++ b/packages/flutter_migrate/test/base/io_test.dart @@ -15,14 +15,19 @@ import '../src/io.dart'; void main() { testWithoutContext('IOOverrides can inject a memory file system', () async { final MemoryFileSystem memoryFileSystem = MemoryFileSystem.test(); - final FlutterIOOverrides flutterIOOverrides = - FlutterIOOverrides(fileSystem: memoryFileSystem); + final FlutterIOOverrides flutterIOOverrides = FlutterIOOverrides( + fileSystem: memoryFileSystem, + ); await io.IOOverrides.runWithIOOverrides(() async { // statics delegate correctly. - expect(io.FileSystemEntity.isWatchSupported, - memoryFileSystem.isWatchSupported); - expect(io.Directory.systemTemp.path, - memoryFileSystem.systemTempDirectory.path); + expect( + io.FileSystemEntity.isWatchSupported, + memoryFileSystem.isWatchSupported, + ); + expect( + io.Directory.systemTemp.path, + memoryFileSystem.systemTempDirectory.path, + ); // can create and write to files/directories sync. final io.File file = io.File('abc'); @@ -52,10 +57,14 @@ void main() { await linkA.create('jjj'); linkB.createSync('lll'); - expect(await memoryFileSystem.link('hhh').resolveSymbolicLinks(), - await linkA.resolveSymbolicLinks()); - expect(memoryFileSystem.link('ggg').resolveSymbolicLinksSync(), - linkB.resolveSymbolicLinksSync()); + expect( + await memoryFileSystem.link('hhh').resolveSymbolicLinks(), + await linkA.resolveSymbolicLinks(), + ); + expect( + memoryFileSystem.link('ggg').resolveSymbolicLinksSync(), + linkB.resolveSymbolicLinksSync(), + ); }, flutterIOOverrides); }); diff --git a/packages/flutter_migrate/test/base/logger_test.dart b/packages/flutter_migrate/test/base/logger_test.dart index efc988b2c40..b0cd9636129 100644 --- a/packages/flutter_migrate/test/base/logger_test.dart +++ b/packages/flutter_migrate/test/base/logger_test.dart @@ -20,104 +20,104 @@ void main() { outputPreferences: OutputPreferences.test(), ); + expect(loggerFactory.createLogger(windows: false), isA()); expect( - loggerFactory.createLogger( - windows: false, - ), - isA()); - expect( - loggerFactory.createLogger( - windows: true, - ), - isA()); + loggerFactory.createLogger(windows: true), + isA(), + ); }); testWithoutContext( - 'WindowsStdoutLogger rewrites emojis when terminal does not support emoji', - () { - final FakeStdio stdio = FakeStdio(); - final WindowsStdoutLogger logger = WindowsStdoutLogger( - outputPreferences: OutputPreferences.test(), - stdio: stdio, - terminal: Terminal.test(), - ); + 'WindowsStdoutLogger rewrites emojis when terminal does not support emoji', + () { + final FakeStdio stdio = FakeStdio(); + final WindowsStdoutLogger logger = WindowsStdoutLogger( + outputPreferences: OutputPreferences.test(), + stdio: stdio, + terminal: Terminal.test(), + ); - logger.printStatus('🔥🖼️✗✓🔨💪✏️'); + logger.printStatus('🔥🖼️✗✓🔨💪✏️'); - expect(stdio.writtenToStdout, ['X√\n']); - }); + expect(stdio.writtenToStdout, ['X√\n']); + }, + ); testWithoutContext( - 'WindowsStdoutLogger does not rewrite emojis when terminal does support emoji', - () { - final FakeStdio stdio = FakeStdio(); - final WindowsStdoutLogger logger = WindowsStdoutLogger( - outputPreferences: OutputPreferences.test(), - stdio: stdio, - terminal: Terminal.test(supportsColor: true, supportsEmoji: true), - ); + 'WindowsStdoutLogger does not rewrite emojis when terminal does support emoji', + () { + final FakeStdio stdio = FakeStdio(); + final WindowsStdoutLogger logger = WindowsStdoutLogger( + outputPreferences: OutputPreferences.test(), + stdio: stdio, + terminal: Terminal.test(supportsColor: true, supportsEmoji: true), + ); - logger.printStatus('🔥🖼️✗✓🔨💪✏️'); + logger.printStatus('🔥🖼️✗✓🔨💪✏️'); - expect(stdio.writtenToStdout, ['🔥🖼️✗✓🔨💪✏️\n']); - }); + expect(stdio.writtenToStdout, ['🔥🖼️✗✓🔨💪✏️\n']); + }, + ); testWithoutContext( - 'Logger does not throw when stdio write throws synchronously', () async { - final FakeStdout stdout = FakeStdout(syncError: true); - final FakeStdout stderr = FakeStdout(syncError: true); - final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr); - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Logger does not throw when stdio write throws synchronously', + () async { + final FakeStdout stdout = FakeStdout(syncError: true); + final FakeStdout stderr = FakeStdout(syncError: true); + final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr); + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: stdio), stdio: stdio, - ), - stdio: stdio, - outputPreferences: OutputPreferences.test(), - ); + outputPreferences: OutputPreferences.test(), + ); - logger.printStatus('message'); - logger.printError('error message'); - }); + logger.printStatus('message'); + logger.printError('error message'); + }, + ); testWithoutContext( - 'Logger does not throw when stdio write throws asynchronously', () async { - final FakeStdout stdout = FakeStdout(syncError: false); - final FakeStdout stderr = FakeStdout(syncError: false); - final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr); - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Logger does not throw when stdio write throws asynchronously', + () async { + final FakeStdout stdout = FakeStdout(syncError: false); + final FakeStdout stderr = FakeStdout(syncError: false); + final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr); + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: stdio), stdio: stdio, - ), - stdio: stdio, - outputPreferences: OutputPreferences.test(), - ); - logger.printStatus('message'); - logger.printError('error message'); + outputPreferences: OutputPreferences.test(), + ); + logger.printStatus('message'); + logger.printError('error message'); - await stdout.done; - await stderr.done; - }); + await stdout.done; + await stderr.done; + }, + ); testWithoutContext( - 'Logger does not throw when stdio completes done with an error', - () async { - final FakeStdout stdout = - FakeStdout(syncError: false, completeWithError: true); - final FakeStdout stderr = - FakeStdout(syncError: false, completeWithError: true); - final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr); - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Logger does not throw when stdio completes done with an error', + () async { + final FakeStdout stdout = FakeStdout( + syncError: false, + completeWithError: true, + ); + final FakeStdout stderr = FakeStdout( + syncError: false, + completeWithError: true, + ); + final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr); + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: stdio), stdio: stdio, - ), - stdio: stdio, - outputPreferences: OutputPreferences.test(), - ); - logger.printStatus('message'); - logger.printError('error message'); + outputPreferences: OutputPreferences.test(), + ); + logger.printStatus('message'); + logger.printError('error message'); - expect(() async => stdout.done, throwsException); - expect(() async => stderr.done, throwsException); - }); + expect(() async => stdout.done, throwsException); + expect(() async => stderr.done, throwsException); + }, + ); group('Output format', () { late FakeStdio fakeStdio; @@ -141,12 +141,12 @@ void main() { testWithoutContext('Error logs are wrapped', () async { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), ); logger.printError('0123456789' * 15); final List lines = outputStderr(); @@ -161,12 +161,12 @@ void main() { testWithoutContext('Error logs are wrapped and can be indented.', () async { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), ); logger.printError('0123456789' * 15, indent: 5); final List lines = outputStderr(); @@ -182,63 +182,66 @@ void main() { expect(lines[5], isEmpty); }); - testWithoutContext('Error logs are wrapped and can have hanging indent.', - () async { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + testWithoutContext( + 'Error logs are wrapped and can have hanging indent.', + () async { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), - ); - logger.printError('0123456789' * 15, hangingIndent: 5); - final List lines = outputStderr(); - - expect(outputStdout().length, equals(1)); - expect(outputStdout().first, isEmpty); - expect(lines.length, equals(6)); - expect(lines[0], equals('0123456789012345678901234567890123456789')); - expect(lines[1], equals(' 01234567890123456789012345678901234')); - expect(lines[2], equals(' 56789012345678901234567890123456789')); - expect(lines[3], equals(' 01234567890123456789012345678901234')); - expect(lines[4], equals(' 56789')); - expect(lines[5], isEmpty); - }); + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), + ); + logger.printError('0123456789' * 15, hangingIndent: 5); + final List lines = outputStderr(); + + expect(outputStdout().length, equals(1)); + expect(outputStdout().first, isEmpty); + expect(lines.length, equals(6)); + expect(lines[0], equals('0123456789012345678901234567890123456789')); + expect(lines[1], equals(' 01234567890123456789012345678901234')); + expect(lines[2], equals(' 56789012345678901234567890123456789')); + expect(lines[3], equals(' 01234567890123456789012345678901234')); + expect(lines[4], equals(' 56789')); + expect(lines[5], isEmpty); + }, + ); testWithoutContext( - 'Error logs are wrapped, indented, and can have hanging indent.', - () async { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Error logs are wrapped, indented, and can have hanging indent.', + () async { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), - ); - logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5); - final List lines = outputStderr(); - - expect(outputStdout().length, equals(1)); - expect(outputStdout().first, isEmpty); - expect(lines.length, equals(6)); - expect(lines[0], equals(' 012345678901234567890123456789012345')); - expect(lines[1], equals(' 6789012345678901234567890123456')); - expect(lines[2], equals(' 7890123456789012345678901234567')); - expect(lines[3], equals(' 8901234567890123456789012345678')); - expect(lines[4], equals(' 901234567890123456789')); - expect(lines[5], isEmpty); - }); + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), + ); + logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5); + final List lines = outputStderr(); + + expect(outputStdout().length, equals(1)); + expect(outputStdout().first, isEmpty); + expect(lines.length, equals(6)); + expect(lines[0], equals(' 012345678901234567890123456789012345')); + expect(lines[1], equals(' 6789012345678901234567890123456')); + expect(lines[2], equals(' 7890123456789012345678901234567')); + expect(lines[3], equals(' 8901234567890123456789012345678')); + expect(lines[4], equals(' 901234567890123456789')); + expect(lines[5], isEmpty); + }, + ); testWithoutContext('Stdout logs are wrapped', () async { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), ); logger.printStatus('0123456789' * 15); final List lines = outputStdout(); @@ -251,84 +254,87 @@ void main() { expect(lines[3], equals('0123456789' * 3)); }); - testWithoutContext('Stdout logs are wrapped and can be indented.', - () async { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + testWithoutContext( + 'Stdout logs are wrapped and can be indented.', + () async { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), - ); - logger.printStatus('0123456789' * 15, indent: 5); - final List lines = outputStdout(); - - expect(outputStderr().length, equals(1)); - expect(outputStderr().first, isEmpty); - expect(lines.length, equals(6)); - expect(lines[0], equals(' 01234567890123456789012345678901234')); - expect(lines[1], equals(' 56789012345678901234567890123456789')); - expect(lines[2], equals(' 01234567890123456789012345678901234')); - expect(lines[3], equals(' 56789012345678901234567890123456789')); - expect(lines[4], equals(' 0123456789')); - expect(lines[5], isEmpty); - }); - - testWithoutContext('Stdout logs are wrapped and can have hanging indent.', - () async { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40)); - logger.printStatus('0123456789' * 15, hangingIndent: 5); - final List lines = outputStdout(); - - expect(outputStderr().length, equals(1)); - expect(outputStderr().first, isEmpty); - expect(lines.length, equals(6)); - expect(lines[0], equals('0123456789012345678901234567890123456789')); - expect(lines[1], equals(' 01234567890123456789012345678901234')); - expect(lines[2], equals(' 56789012345678901234567890123456789')); - expect(lines[3], equals(' 01234567890123456789012345678901234')); - expect(lines[4], equals(' 56789')); - expect(lines[5], isEmpty); - }); + ); + logger.printStatus('0123456789' * 15, indent: 5); + final List lines = outputStdout(); + + expect(outputStderr().length, equals(1)); + expect(outputStderr().first, isEmpty); + expect(lines.length, equals(6)); + expect(lines[0], equals(' 01234567890123456789012345678901234')); + expect(lines[1], equals(' 56789012345678901234567890123456789')); + expect(lines[2], equals(' 01234567890123456789012345678901234')); + expect(lines[3], equals(' 56789012345678901234567890123456789')); + expect(lines[4], equals(' 0123456789')); + expect(lines[5], isEmpty); + }, + ); testWithoutContext( - 'Stdout logs are wrapped, indented, and can have hanging indent.', - () async { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Stdout logs are wrapped and can have hanging indent.', + () async { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), - ); - logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5); - final List lines = outputStdout(); + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), + ); + logger.printStatus('0123456789' * 15, hangingIndent: 5); + final List lines = outputStdout(); + + expect(outputStderr().length, equals(1)); + expect(outputStderr().first, isEmpty); + expect(lines.length, equals(6)); + expect(lines[0], equals('0123456789012345678901234567890123456789')); + expect(lines[1], equals(' 01234567890123456789012345678901234')); + expect(lines[2], equals(' 56789012345678901234567890123456789')); + expect(lines[3], equals(' 01234567890123456789012345678901234')); + expect(lines[4], equals(' 56789')); + expect(lines[5], isEmpty); + }, + ); - expect(outputStderr().length, equals(1)); - expect(outputStderr().first, isEmpty); - expect(lines.length, equals(6)); - expect(lines[0], equals(' 012345678901234567890123456789012345')); - expect(lines[1], equals(' 6789012345678901234567890123456')); - expect(lines[2], equals(' 7890123456789012345678901234567')); - expect(lines[3], equals(' 8901234567890123456789012345678')); - expect(lines[4], equals(' 901234567890123456789')); - expect(lines[5], isEmpty); - }); + testWithoutContext( + 'Stdout logs are wrapped, indented, and can have hanging indent.', + () async { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), + stdio: fakeStdio, + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), + ); + logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5); + final List lines = outputStdout(); + + expect(outputStderr().length, equals(1)); + expect(outputStderr().first, isEmpty); + expect(lines.length, equals(6)); + expect(lines[0], equals(' 012345678901234567890123456789012345')); + expect(lines[1], equals(' 6789012345678901234567890123456')); + expect(lines[2], equals(' 7890123456789012345678901234567')); + expect(lines[3], equals(' 8901234567890123456789012345678')); + expect(lines[4], equals(' 901234567890123456789')); + expect(lines[5], isEmpty); + }, + ); testWithoutContext('Error logs are red', () async { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - supportsColor: true, - ), + terminal: AnsiTerminal(stdio: fakeStdio, supportsColor: true), stdio: fakeStdio, outputPreferences: OutputPreferences.test(showColor: true), ); @@ -338,16 +344,14 @@ void main() { expect(outputStdout().length, equals(1)); expect(outputStdout().first, isEmpty); expect( - lines[0], - equals( - '${AnsiTerminal.red}Pants on fire!${AnsiTerminal.resetColor}')); + lines[0], + equals('${AnsiTerminal.red}Pants on fire!${AnsiTerminal.resetColor}'), + ); }); testWithoutContext('Stdout logs are not colored', () async { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, outputPreferences: OutputPreferences.test(showColor: true), ); @@ -361,9 +365,7 @@ void main() { testWithoutContext('Stdout printBox puts content inside a box', () { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, outputPreferences: OutputPreferences.test(showColor: true), ); @@ -371,18 +373,18 @@ void main() { final String stdout = fakeStdio.writtenToStdout.join(); expect( stdout, - contains('\n' - '┌─ Test title ┐\n' - '│ Hello world │\n' - '└─────────────┘\n'), + contains( + '\n' + '┌─ Test title ┐\n' + '│ Hello world │\n' + '└─────────────┘\n', + ), ); }); testWithoutContext('Stdout printBox does not require title', () { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, outputPreferences: OutputPreferences.test(showColor: true), ); @@ -390,18 +392,18 @@ void main() { final String stdout = fakeStdio.writtenToStdout.join(); expect( stdout, - contains('\n' - '┌─────────────┐\n' - '│ Hello world │\n' - '└─────────────┘\n'), + contains( + '\n' + '┌─────────────┐\n' + '│ Hello world │\n' + '└─────────────┘\n', + ), ); }); testWithoutContext('Stdout printBox handles new lines', () { final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, outputPreferences: OutputPreferences.test(showColor: true), ); @@ -409,48 +411,54 @@ void main() { final String stdout = fakeStdio.writtenToStdout.join(); expect( stdout, - contains('\n' - '┌─ Test title ───────┐\n' - '│ Hello world │\n' - '│ This is a new line │\n' - '└────────────────────┘\n'), + contains( + '\n' + '┌─ Test title ───────┐\n' + '│ Hello world │\n' + '│ This is a new line │\n' + '└────────────────────┘\n', + ), ); }); testWithoutContext( - 'Stdout printBox handles content with ANSI escape characters', () { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Stdout printBox handles content with ANSI escape characters', + () { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: OutputPreferences.test(showColor: true), - ); - const String bold = '\u001B[1m'; - const String clear = '\u001B[2J\u001B[H'; - logger.printBox('${bold}Hello world$clear', title: 'Test title'); - final String stdout = fakeStdio.writtenToStdout.join(); - expect( - stdout, - contains('\n' + outputPreferences: OutputPreferences.test(showColor: true), + ); + const String bold = '\u001B[1m'; + const String clear = '\u001B[2J\u001B[H'; + logger.printBox('${bold}Hello world$clear', title: 'Test title'); + final String stdout = fakeStdio.writtenToStdout.join(); + expect( + stdout, + contains( + '\n' '┌─ Test title ┐\n' '│ ${bold}Hello world$clear │\n' - '└─────────────┘\n'), - ); - }); + '└─────────────┘\n', + ), + ); + }, + ); testWithoutContext('Stdout printBox handles column limit', () { const int columnLimit = 14; final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(showColor: true, wrapColumn: columnLimit), + outputPreferences: OutputPreferences.test( + showColor: true, + wrapColumn: columnLimit, + ), + ); + logger.printBox( + 'This line is longer than $columnLimit characters', + title: 'Test', ); - logger.printBox('This line is longer than $columnLimit characters', - title: 'Test'); final String stdout = fakeStdio.writtenToStdout.join(); final List stdoutLines = stdout.split('\n'); @@ -458,37 +466,43 @@ void main() { expect(stdoutLines[1].length, equals(columnLimit)); expect( stdout, - contains('\n' - '┌─ Test ─────┐\n' - '│ This line │\n' - '│ is longer │\n' - '│ than 14 │\n' - '│ characters │\n' - '└────────────┘\n'), + contains( + '\n' + '┌─ Test ─────┐\n' + '│ This line │\n' + '│ is longer │\n' + '│ than 14 │\n' + '│ characters │\n' + '└────────────┘\n', + ), ); }); testWithoutContext( - 'Stdout printBox handles column limit and respects new lines', () { - const int columnLimit = 14; - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Stdout printBox handles column limit and respects new lines', + () { + const int columnLimit = 14; + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(showColor: true, wrapColumn: columnLimit), - ); - logger.printBox('This\nline is longer than\n\n$columnLimit characters', - title: 'Test'); - final String stdout = fakeStdio.writtenToStdout.join(); - final List stdoutLines = stdout.split('\n'); - - expect(stdoutLines.length, greaterThan(1)); - expect(stdoutLines[1].length, equals(columnLimit)); - expect( - stdout, - contains('\n' + outputPreferences: OutputPreferences.test( + showColor: true, + wrapColumn: columnLimit, + ), + ); + logger.printBox( + 'This\nline is longer than\n\n$columnLimit characters', + title: 'Test', + ); + final String stdout = fakeStdio.writtenToStdout.join(); + final List stdoutLines = stdout.split('\n'); + + expect(stdoutLines.length, greaterThan(1)); + expect(stdoutLines[1].length, equals(columnLimit)); + expect( + stdout, + contains( + '\n' '┌─ Test ─────┐\n' '│ This │\n' '│ line is │\n' @@ -497,46 +511,52 @@ void main() { '│ │\n' '│ 14 │\n' '│ characters │\n' - '└────────────┘\n'), - ); - }); + '└────────────┘\n', + ), + ); + }, + ); testWithoutContext( - 'Stdout printBox breaks long words that exceed the column limit', () { - const int columnLimit = 14; - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( + 'Stdout printBox breaks long words that exceed the column limit', + () { + const int columnLimit = 14; + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: - OutputPreferences.test(showColor: true, wrapColumn: columnLimit), - ); - logger.printBox('Thiswordislongerthan${columnLimit}characters', - title: 'Test'); - final String stdout = fakeStdio.writtenToStdout.join(); - final List stdoutLines = stdout.split('\n'); - - expect(stdoutLines.length, greaterThan(1)); - expect(stdoutLines[1].length, equals(columnLimit)); - expect( - stdout, - contains('\n' + outputPreferences: OutputPreferences.test( + showColor: true, + wrapColumn: columnLimit, + ), + ); + logger.printBox( + 'Thiswordislongerthan${columnLimit}characters', + title: 'Test', + ); + final String stdout = fakeStdio.writtenToStdout.join(); + final List stdoutLines = stdout.split('\n'); + + expect(stdoutLines.length, greaterThan(1)); + expect(stdoutLines[1].length, equals(columnLimit)); + expect( + stdout, + contains( + '\n' '┌─ Test ─────┐\n' '│ Thiswordis │\n' '│ longerthan │\n' '│ 14characte │\n' '│ rs │\n' - '└────────────┘\n'), - ); - }); + '└────────────┘\n', + ), + ); + }, + ); testWithoutContext('Stdout startProgress on non-color terminal', () async { final FakeStopwatch fakeStopwatch = FakeStopwatch(); final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, outputPreferences: OutputPreferences.test(), stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopwatch), @@ -573,10 +593,7 @@ void main() { // Verify a cancel does _not_ print the time and prints a newline. summaryStatus.cancel(); - expect(outputStdout(), [ - 'Hello world ', - '', - ]); + expect(outputStdout(), ['Hello world ', '']); // Verify that stopping or canceling multiple times throws. expect(summaryStatus.cancel, throwsAssertionError); @@ -591,51 +608,48 @@ void main() { // Verify a stop prints the time. summaryStatus.stop(); - expect(outputStdout(), [ - 'Hello world 0ms', - '', - ]); + expect(outputStdout(), ['Hello world 0ms', '']); // Verify that stopping or canceling multiple times throws. expect(summaryStatus.stop, throwsAssertionError); expect(summaryStatus.cancel, throwsAssertionError); }); - testWithoutContext('sequential startProgress calls with StdoutLogger', - () async { - final Logger logger = StdoutLogger( - terminal: AnsiTerminal( - stdio: fakeStdio, - ), - stdio: fakeStdio, - outputPreferences: OutputPreferences.test(), - ); - logger.startProgress('AAA').stop(); - logger.startProgress('BBB').stop(); - final List output = outputStdout(); - - expect(output.length, equals(3)); - - // There's 61 spaces at the start: 59 (padding default) - 3 (length of AAA) + 5 (margin). - // Then there's a left-padded "0ms" 8 characters wide, so 5 spaces then "0ms" - // (except sometimes it's randomly slow so we handle up to "99,999ms"). - expect(output[0], matches(RegExp(r'AAA[ ]{61}[\d, ]{5}[\d]ms'))); - expect(output[1], matches(RegExp(r'BBB[ ]{61}[\d, ]{5}[\d]ms'))); - }); - - testWithoutContext('sequential startProgress calls with BufferLogger', - () async { - final BufferLogger logger = BufferLogger( - terminal: AnsiTerminal( + testWithoutContext( + 'sequential startProgress calls with StdoutLogger', + () async { + final Logger logger = StdoutLogger( + terminal: AnsiTerminal(stdio: fakeStdio), stdio: fakeStdio, - ), - outputPreferences: OutputPreferences.test(), - ); - logger.startProgress('AAA').stop(); - logger.startProgress('BBB').stop(); + outputPreferences: OutputPreferences.test(), + ); + logger.startProgress('AAA').stop(); + logger.startProgress('BBB').stop(); + final List output = outputStdout(); + + expect(output.length, equals(3)); + + // There's 61 spaces at the start: 59 (padding default) - 3 (length of AAA) + 5 (margin). + // Then there's a left-padded "0ms" 8 characters wide, so 5 spaces then "0ms" + // (except sometimes it's randomly slow so we handle up to "99,999ms"). + expect(output[0], matches(RegExp(r'AAA[ ]{61}[\d, ]{5}[\d]ms'))); + expect(output[1], matches(RegExp(r'BBB[ ]{61}[\d, ]{5}[\d]ms'))); + }, + ); - expect(logger.statusText, 'AAA\nBBB\n'); - }); + testWithoutContext( + 'sequential startProgress calls with BufferLogger', + () async { + final BufferLogger logger = BufferLogger( + terminal: AnsiTerminal(stdio: fakeStdio), + outputPreferences: OutputPreferences.test(), + ); + logger.startProgress('AAA').stop(); + logger.startProgress('BBB').stop(); + + expect(logger.statusText, 'AAA\nBBB\n'); + }, + ); }); } diff --git a/packages/flutter_migrate/test/base/signals_test.dart b/packages/flutter_migrate/test/base/signals_test.dart index 87f0d04155b..0283fc3a9b8 100644 --- a/packages/flutter_migrate/test/base/signals_test.dart +++ b/packages/flutter_migrate/test/base/signals_test.dart @@ -55,21 +55,22 @@ void main() { }); testWithoutContext( - 'signal handlers do not cause concurrent modification errors when removing handlers in a signal callback', - () async { - final Completer completer = Completer(); - late Object token; - Future handle(ProcessSignal s) async { - expect(s, signalUnderTest); - expect(await signals.removeHandler(signalUnderTest, token), true); - completer.complete(); - } + 'signal handlers do not cause concurrent modification errors when removing handlers in a signal callback', + () async { + final Completer completer = Completer(); + late Object token; + Future handle(ProcessSignal s) async { + expect(s, signalUnderTest); + expect(await signals.removeHandler(signalUnderTest, token), true); + completer.complete(); + } - token = signals.addHandler(signalUnderTest, handle); + token = signals.addHandler(signalUnderTest, handle); - fakeSignal.controller.add(fakeSignal); - await completer.future; - }); + fakeSignal.controller.add(fakeSignal); + await completer.future; + }, + ); testWithoutContext('signal handler error goes on error stream', () async { final Exception exn = Exception('Error'); @@ -79,12 +80,12 @@ void main() { final Completer completer = Completer(); final List errList = []; - final StreamSubscription errSub = signals.errors.listen( - (Object err) { - errList.add(err); - completer.complete(); - }, - ); + final StreamSubscription errSub = signals.errors.listen(( + Object err, + ) { + errList.add(err); + completer.complete(); + }); fakeSignal.controller.add(fakeSignal); await completer.future; @@ -93,21 +94,20 @@ void main() { }); testWithoutContext('removed signal handler does not run', () async { - final Object token = signals.addHandler( - signalUnderTest, - (ProcessSignal s) async { - fail('Signal handler should have been removed.'); - }, - ); + final Object token = signals.addHandler(signalUnderTest, ( + ProcessSignal s, + ) async { + fail('Signal handler should have been removed.'); + }); await signals.removeHandler(signalUnderTest, token); final List errList = []; - final StreamSubscription errSub = signals.errors.listen( - (Object err) { - errList.add(err); - }, - ); + final StreamSubscription errSub = signals.errors.listen(( + Object err, + ) { + errList.add(err); + }); fakeSignal.controller.add(fakeSignal); @@ -122,20 +122,19 @@ void main() { completer.complete(); }); - final Object token = signals.addHandler( - signalUnderTest, - (ProcessSignal s) async { - fail('Signal handler should have been removed.'); - }, - ); + final Object token = signals.addHandler(signalUnderTest, ( + ProcessSignal s, + ) async { + fail('Signal handler should have been removed.'); + }); await signals.removeHandler(signalUnderTest, token); final List errList = []; - final StreamSubscription errSub = signals.errors.listen( - (Object err) { - errList.add(err); - }, - ); + final StreamSubscription errSub = signals.errors.listen(( + Object err, + ) { + errList.add(err); + }); fakeSignal.controller.add(fakeSignal); await completer.future; @@ -158,11 +157,11 @@ void main() { }); final List errList = []; - final StreamSubscription errSub = signals.errors.listen( - (Object err) { - errList.add(err); - }, - ); + final StreamSubscription errSub = signals.errors.listen(( + Object err, + ) { + errList.add(err); + }); fakeSignal.controller.add(fakeSignal); await completer.future; diff --git a/packages/flutter_migrate/test/base/terminal_test.dart b/packages/flutter_migrate/test/base/terminal_test.dart index 6dec484d59b..a61913c907d 100644 --- a/packages/flutter_migrate/test/base/terminal_test.dart +++ b/packages/flutter_migrate/test/base/terminal_test.dart @@ -13,8 +13,10 @@ void main() { group('output preferences', () { testWithoutContext('can wrap output', () async { final BufferLogger bufferLogger = BufferLogger( - outputPreferences: - OutputPreferences.test(wrapText: true, wrapColumn: 40), + outputPreferences: OutputPreferences.test( + wrapText: true, + wrapColumn: 40, + ), terminal: TestTerminal(), ); bufferLogger.printStatus('0123456789' * 8); @@ -49,7 +51,8 @@ void main() { expect( terminal.color('output', color), equals( - '${AnsiTerminal.colorCode(color)}output${AnsiTerminal.resetColor}'), + '${AnsiTerminal.colorCode(color)}output${AnsiTerminal.resetColor}', + ), ); } }); @@ -65,13 +68,17 @@ void main() { expect( terminal.color(terminal.bolden('output'), TerminalColor.blue), equals( - '${AnsiTerminal.blue}${AnsiTerminal.bold}output${AnsiTerminal.resetBold}${AnsiTerminal.resetColor}'), + '${AnsiTerminal.blue}${AnsiTerminal.bold}output${AnsiTerminal.resetBold}${AnsiTerminal.resetColor}', + ), ); expect( - terminal.color('non-bold ${terminal.bolden('output')} also non-bold', - TerminalColor.blue), + terminal.color( + 'non-bold ${terminal.bolden('output')} also non-bold', + TerminalColor.blue, + ), equals( - '${AnsiTerminal.blue}non-bold ${AnsiTerminal.bold}output${AnsiTerminal.resetBold} also non-bold${AnsiTerminal.resetColor}'), + '${AnsiTerminal.blue}non-bold ${AnsiTerminal.bold}output${AnsiTerminal.resetBold} also non-bold${AnsiTerminal.resetColor}', + ), ); }); @@ -79,29 +86,37 @@ void main() { expect( terminal.bolden(terminal.color('output', TerminalColor.blue)), equals( - '${AnsiTerminal.bold}${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.resetBold}'), + '${AnsiTerminal.bold}${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.resetBold}', + ), ); expect( terminal.bolden( - 'non-color ${terminal.color('output', TerminalColor.blue)} also non-color'), + 'non-color ${terminal.color('output', TerminalColor.blue)} also non-color', + ), equals( - '${AnsiTerminal.bold}non-color ${AnsiTerminal.blue}output${AnsiTerminal.resetColor} also non-color${AnsiTerminal.resetBold}'), + '${AnsiTerminal.bold}non-color ${AnsiTerminal.blue}output${AnsiTerminal.resetColor} also non-color${AnsiTerminal.resetBold}', + ), ); }); testWithoutContext('nesting color within color works', () { expect( - terminal.color(terminal.color('output', TerminalColor.blue), - TerminalColor.magenta), + terminal.color( + terminal.color('output', TerminalColor.blue), + TerminalColor.magenta, + ), equals( - '${AnsiTerminal.magenta}${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.magenta}${AnsiTerminal.resetColor}'), + '${AnsiTerminal.magenta}${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.magenta}${AnsiTerminal.resetColor}', + ), ); expect( terminal.color( - 'magenta ${terminal.color('output', TerminalColor.blue)} also magenta', - TerminalColor.magenta), + 'magenta ${terminal.color('output', TerminalColor.blue)} also magenta', + TerminalColor.magenta, + ), equals( - '${AnsiTerminal.magenta}magenta ${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.magenta} also magenta${AnsiTerminal.resetColor}'), + '${AnsiTerminal.magenta}magenta ${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.magenta} also magenta${AnsiTerminal.resetColor}', + ), ); }); @@ -113,7 +128,8 @@ void main() { expect( terminal.bolden('bold ${terminal.bolden('output')} still bold'), equals( - '${AnsiTerminal.bold}bold output still bold${AnsiTerminal.resetBold}'), + '${AnsiTerminal.bold}bold output still bold${AnsiTerminal.resetBold}', + ), ); }); }); @@ -125,16 +141,19 @@ void main() { terminalUnderTest = TestTerminal(stdio: FakeStdio()); }); - testWithoutContext('character prompt throws if usesTerminalUi is false', - () async { - expect( + testWithoutContext( + 'character prompt throws if usesTerminalUi is false', + () async { + expect( terminalUnderTest.promptForCharInput( ['a', 'b', 'c'], prompt: 'Please choose something', logger: BufferLogger.test(), ), - throwsStateError); - }); + throwsStateError, + ); + }, + ); testWithoutContext('character prompt', () async { final BufferLogger bufferLogger = BufferLogger( @@ -142,11 +161,12 @@ void main() { outputPreferences: OutputPreferences.test(), ); terminalUnderTest.usesTerminalUi = true; - mockStdInStream = Stream.fromFutures(>[ - Future.value('d'), // Not in accepted list. - Future.value('\n'), // Not in accepted list - Future.value('b'), - ]).asBroadcastStream(); + mockStdInStream = + Stream.fromFutures(>[ + Future.value('d'), // Not in accepted list. + Future.value('\n'), // Not in accepted list + Future.value('b'), + ]).asBroadcastStream(); final String choice = await terminalUnderTest.promptForCharInput( ['a', 'b', 'c'], prompt: 'Please choose something', @@ -154,164 +174,195 @@ void main() { ); expect(choice, 'b'); expect( - bufferLogger.statusText, - 'Please choose something [a|b|c]: d\n' - 'Please choose something [a|b|c]: \n' - 'Please choose something [a|b|c]: b\n'); + bufferLogger.statusText, + 'Please choose something [a|b|c]: d\n' + 'Please choose something [a|b|c]: \n' + 'Please choose something [a|b|c]: b\n', + ); }); testWithoutContext( - 'default character choice without displayAcceptedCharacters', () async { - final BufferLogger bufferLogger = BufferLogger( - terminal: terminalUnderTest, - outputPreferences: OutputPreferences.test(), - ); - terminalUnderTest.usesTerminalUi = true; - mockStdInStream = Stream.fromFutures(>[ - Future.value('\n'), // Not in accepted list - ]).asBroadcastStream(); - final String choice = await terminalUnderTest.promptForCharInput( - ['a', 'b', 'c'], - prompt: 'Please choose something', - displayAcceptedCharacters: false, - defaultChoiceIndex: 1, // which is b. - logger: bufferLogger, - ); + 'default character choice without displayAcceptedCharacters', + () async { + final BufferLogger bufferLogger = BufferLogger( + terminal: terminalUnderTest, + outputPreferences: OutputPreferences.test(), + ); + terminalUnderTest.usesTerminalUi = true; + mockStdInStream = + Stream.fromFutures(>[ + Future.value('\n'), // Not in accepted list + ]).asBroadcastStream(); + final String choice = await terminalUnderTest.promptForCharInput( + ['a', 'b', 'c'], + prompt: 'Please choose something', + displayAcceptedCharacters: false, + defaultChoiceIndex: 1, // which is b. + logger: bufferLogger, + ); - expect(choice, 'b'); - expect(bufferLogger.statusText, 'Please choose something: \n'); - }); + expect(choice, 'b'); + expect(bufferLogger.statusText, 'Please choose something: \n'); + }, + ); testWithoutContext( - 'Does not set single char mode when a terminal is not attached', () { - final Stdio stdio = FakeStdio()..stdinHasTerminal = false; - final AnsiTerminal ansiTerminal = AnsiTerminal( - stdio: stdio, - ); - - expect(() => ansiTerminal.singleCharMode = true, returnsNormally); - }); + 'Does not set single char mode when a terminal is not attached', + () { + final Stdio stdio = FakeStdio()..stdinHasTerminal = false; + final AnsiTerminal ansiTerminal = AnsiTerminal(stdio: stdio); + + expect(() => ansiTerminal.singleCharMode = true, returnsNormally); + }, + ); }); testWithoutContext('AnsiTerminal.preferredStyle', () { final Stdio stdio = FakeStdio(); - expect(AnsiTerminal(stdio: stdio).preferredStyle, - 0); // Defaults to 0 for backwards compatibility. + expect( + AnsiTerminal(stdio: stdio).preferredStyle, + 0, + ); // Defaults to 0 for backwards compatibility. expect(AnsiTerminal(stdio: stdio, now: DateTime(2018)).preferredStyle, 0); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2)).preferredStyle, - 1); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3)).preferredStyle, - 2); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4)).preferredStyle, - 3); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5)).preferredStyle, - 4); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6)).preferredStyle, - 5); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7)).preferredStyle, - 5); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8)).preferredStyle, - 0); - expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9)).preferredStyle, - 1); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10)).preferredStyle, - 2); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2)).preferredStyle, + 1, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3)).preferredStyle, + 2, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4)).preferredStyle, + 3, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5)).preferredStyle, + 4, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6)).preferredStyle, + 5, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7)).preferredStyle, + 5, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8)).preferredStyle, + 0, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9)).preferredStyle, + 1, + ); + expect( + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10)).preferredStyle, + 2, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11)).preferredStyle, - 3); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11)).preferredStyle, + 3, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 1, 1)).preferredStyle, - 0); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 1, 1)).preferredStyle, + 0, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2, 1)).preferredStyle, - 1); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2, 1)).preferredStyle, + 1, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3, 1)).preferredStyle, - 2); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3, 1)).preferredStyle, + 2, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4, 1)).preferredStyle, - 3); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4, 1)).preferredStyle, + 3, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5, 1)).preferredStyle, - 4); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5, 1)).preferredStyle, + 4, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6, 1)).preferredStyle, - 6); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6, 1)).preferredStyle, + 6, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7, 1)).preferredStyle, - 6); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7, 1)).preferredStyle, + 6, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8, 1)).preferredStyle, - 0); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8, 1)).preferredStyle, + 0, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9, 1)).preferredStyle, - 1); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9, 1)).preferredStyle, + 1, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10, 1)) - .preferredStyle, - 2); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10, 1)).preferredStyle, + 2, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11, 1)) - .preferredStyle, - 3); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11, 1)).preferredStyle, + 3, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 1, 23)) - .preferredStyle, - 0); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 1, 23)).preferredStyle, + 0, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2, 23)) - .preferredStyle, - 1); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2, 23)).preferredStyle, + 1, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3, 23)) - .preferredStyle, - 2); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3, 23)).preferredStyle, + 2, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4, 23)) - .preferredStyle, - 3); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4, 23)).preferredStyle, + 3, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5, 23)) - .preferredStyle, - 4); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5, 23)).preferredStyle, + 4, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6, 23)) - .preferredStyle, - 28); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6, 23)).preferredStyle, + 28, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7, 23)) - .preferredStyle, - 28); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7, 23)).preferredStyle, + 28, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8, 23)) - .preferredStyle, - 0); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8, 23)).preferredStyle, + 0, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9, 23)) - .preferredStyle, - 1); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9, 23)).preferredStyle, + 1, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10, 23)) - .preferredStyle, - 2); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10, 23)).preferredStyle, + 2, + ); expect( - AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11, 23)) - .preferredStyle, - 3); + AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11, 23)).preferredStyle, + 3, + ); }); } late Stream mockStdInStream; class TestTerminal extends AnsiTerminal { - TestTerminal({ - Stdio? stdio, - DateTime? now, - }) : super(stdio: stdio ?? Stdio(), now: now ?? DateTime(2018)); + TestTerminal({Stdio? stdio, DateTime? now}) + : super(stdio: stdio ?? Stdio(), now: now ?? DateTime(2018)); @override Stream get keystrokes { diff --git a/packages/flutter_migrate/test/compute_test.dart b/packages/flutter_migrate/test/compute_test.dart index 523162cad38..925881ab204 100644 --- a/packages/flutter_migrate/test/compute_test.dart +++ b/packages/flutter_migrate/test/compute_test.dart @@ -51,11 +51,14 @@ void main() { ); await MigrateProject.installProject('version:1.22.6_stable', currentDir); final FlutterProjectFactory flutterFactory = FlutterProjectFactory(); - final FlutterProject flutterProject = - flutterFactory.fromDirectory(currentDir); + final FlutterProject flutterProject = flutterFactory.fromDirectory( + currentDir, + ); result = MigrateResult.empty(); - final MigrateLogger migrateLogger = - MigrateLogger(logger: logger, verbose: true); + final MigrateLogger migrateLogger = MigrateLogger( + logger: logger, + verbose: true, + ); migrateLogger.start(); separator = isWindows ? r'\\' : '/'; envProcessManager = FakeProcessManager(''' @@ -87,7 +90,9 @@ void main() { '''); environment = await FlutterToolsEnvironment.initializeFlutterToolsEnvironment( - envProcessManager, logger); + envProcessManager, + logger, + ); context = MigrateContext( flutterProject: flutterProject, skippedPrefixes: {}, @@ -96,239 +101,295 @@ void main() { migrateUtils: utils, environment: environment, ); - targetFlutterDirectory = - createResolvedTempDirectorySync('targetFlutterDir.'); - newerTargetFlutterDirectory = - createResolvedTempDirectorySync('newerTargetFlutterDir.'); - await context.migrateUtils - .cloneFlutter(oldSdkRevision, targetFlutterDirectory.absolute.path); + targetFlutterDirectory = createResolvedTempDirectorySync( + 'targetFlutterDir.', + ); + newerTargetFlutterDirectory = createResolvedTempDirectorySync( + 'newerTargetFlutterDir.', + ); + await context.migrateUtils.cloneFlutter( + oldSdkRevision, + targetFlutterDirectory.absolute.path, + ); await context.migrateUtils.cloneFlutter( - newSdkRevision, newerTargetFlutterDirectory.absolute.path); + newSdkRevision, + newerTargetFlutterDirectory.absolute.path, + ); } - group('MigrateFlutterProject', () { - setUp(() async { - await setUpFullEnv(); - }); - - tearDown(() async { - tryToDelete(targetFlutterDirectory); - tryToDelete(newerTargetFlutterDirectory); - }); - - testUsingContext('MigrateTargetFlutterProject creates', () async { - final Directory workingDir = - createResolvedTempDirectorySync('migrate_working_dir.'); - final Directory targetDir = - createResolvedTempDirectorySync('target_dir.'); - result.generatedTargetTemplateDirectory = targetDir; - workingDir.createSync(recursive: true); - final MigrateTargetFlutterProject targetProject = - MigrateTargetFlutterProject( - path: null, - directory: targetDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', - ); + group( + 'MigrateFlutterProject', + () { + setUp(() async { + await setUpFullEnv(); + }); - await targetProject.createProject( - context, - result, - oldSdkRevision, //targetRevision - targetFlutterDirectory, //targetFlutterDirectory - ); + tearDown(() async { + tryToDelete(targetFlutterDirectory); + tryToDelete(newerTargetFlutterDirectory); + }); - expect(targetDir.childFile('pubspec.yaml').existsSync(), true); - expect( - targetDir - .childDirectory('android') - .childFile('build.gradle') - .existsSync(), - true); - }, timeout: const Timeout(Duration(seconds: 500))); - - testUsingContext('MigrateBaseFlutterProject creates', () async { - final Directory workingDir = - createResolvedTempDirectorySync('migrate_working_dir.'); - final Directory baseDir = createResolvedTempDirectorySync('base_dir.'); - result.generatedBaseTemplateDirectory = baseDir; - workingDir.createSync(recursive: true); - final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject( - path: null, - directory: baseDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', + testUsingContext( + 'MigrateTargetFlutterProject creates', + () async { + final Directory workingDir = createResolvedTempDirectorySync( + 'migrate_working_dir.', + ); + final Directory targetDir = createResolvedTempDirectorySync( + 'target_dir.', + ); + result.generatedTargetTemplateDirectory = targetDir; + workingDir.createSync(recursive: true); + final MigrateTargetFlutterProject targetProject = + MigrateTargetFlutterProject( + path: null, + directory: targetDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + + await targetProject.createProject( + context, + result, + oldSdkRevision, //targetRevision + targetFlutterDirectory, //targetFlutterDirectory + ); + + expect(targetDir.childFile('pubspec.yaml').existsSync(), true); + expect( + targetDir + .childDirectory('android') + .childFile('build.gradle') + .existsSync(), + true, + ); + }, + timeout: const Timeout(Duration(seconds: 500)), ); - await baseProject.createProject( - context, - result, - [oldSdkRevision], //revisionsList - >{ - oldSdkRevision: [ - MigratePlatformConfig(component: FlutterProjectComponent.android), - MigratePlatformConfig(component: FlutterProjectComponent.ios) - ], - }, //revisionToConfigs - oldSdkRevision, //fallbackRevision - oldSdkRevision, //targetRevision - targetFlutterDirectory, //targetFlutterDirectory + testUsingContext( + 'MigrateBaseFlutterProject creates', + () async { + final Directory workingDir = createResolvedTempDirectorySync( + 'migrate_working_dir.', + ); + final Directory baseDir = createResolvedTempDirectorySync( + 'base_dir.', + ); + result.generatedBaseTemplateDirectory = baseDir; + workingDir.createSync(recursive: true); + final MigrateBaseFlutterProject baseProject = + MigrateBaseFlutterProject( + path: null, + directory: baseDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + + await baseProject.createProject( + context, + result, + [oldSdkRevision], //revisionsList + >{ + oldSdkRevision: [ + MigratePlatformConfig( + component: FlutterProjectComponent.android, + ), + MigratePlatformConfig(component: FlutterProjectComponent.ios), + ], + }, //revisionToConfigs + oldSdkRevision, //fallbackRevision + oldSdkRevision, //targetRevision + targetFlutterDirectory, //targetFlutterDirectory + ); + + expect(baseDir.childFile('pubspec.yaml').existsSync(), true); + expect( + baseDir + .childDirectory('android') + .childFile('build.gradle') + .existsSync(), + true, + ); + }, + timeout: const Timeout(Duration(seconds: 500)), ); - expect(baseDir.childFile('pubspec.yaml').existsSync(), true); - expect( - baseDir - .childDirectory('android') - .childFile('build.gradle') - .existsSync(), - true); - }, timeout: const Timeout(Duration(seconds: 500))); - - testUsingContext('Migrate___FlutterProject skips when path exists', + testUsingContext( + 'Migrate___FlutterProject skips when path exists', () async { - final Directory workingDir = - createResolvedTempDirectorySync('migrate_working_dir.'); - final Directory targetDir = - createResolvedTempDirectorySync('target_dir.'); - final Directory baseDir = createResolvedTempDirectorySync('base_dir.'); - result.generatedTargetTemplateDirectory = targetDir; - result.generatedBaseTemplateDirectory = baseDir; - workingDir.createSync(recursive: true); - - final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject( - path: 'some_existing_base_path', - directory: baseDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', - ); - final MigrateTargetFlutterProject targetProject = - MigrateTargetFlutterProject( - path: 'some_existing_target_path', - directory: targetDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', + final Directory workingDir = createResolvedTempDirectorySync( + 'migrate_working_dir.', + ); + final Directory targetDir = createResolvedTempDirectorySync( + 'target_dir.', + ); + final Directory baseDir = createResolvedTempDirectorySync( + 'base_dir.', + ); + result.generatedTargetTemplateDirectory = targetDir; + result.generatedBaseTemplateDirectory = baseDir; + workingDir.createSync(recursive: true); + + final MigrateBaseFlutterProject baseProject = + MigrateBaseFlutterProject( + path: 'some_existing_base_path', + directory: baseDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + final MigrateTargetFlutterProject targetProject = + MigrateTargetFlutterProject( + path: 'some_existing_target_path', + directory: targetDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + + await baseProject.createProject( + context, + result, + [oldSdkRevision], //revisionsList + >{ + oldSdkRevision: [ + MigratePlatformConfig( + component: FlutterProjectComponent.android, + ), + MigratePlatformConfig(component: FlutterProjectComponent.ios), + ], + }, //revisionToConfigs + oldSdkRevision, //fallbackRevision + oldSdkRevision, //targetRevision + targetFlutterDirectory, //targetFlutterDirectory + ); + + expect(baseDir.childFile('pubspec.yaml').existsSync(), false); + expect( + baseDir + .childDirectory('android') + .childFile('build.gradle') + .existsSync(), + false, + ); + + await targetProject.createProject( + context, + result, + oldSdkRevision, //revisionsList + targetFlutterDirectory, //targetFlutterDirectory + ); + + expect(targetDir.childFile('pubspec.yaml').existsSync(), false); + expect( + targetDir + .childDirectory('android') + .childFile('build.gradle') + .existsSync(), + false, + ); + }, + timeout: const Timeout(Duration(seconds: 500)), ); - - await baseProject.createProject( - context, - result, - [oldSdkRevision], //revisionsList - >{ - oldSdkRevision: [ - MigratePlatformConfig(component: FlutterProjectComponent.android), - MigratePlatformConfig(component: FlutterProjectComponent.ios) + }, + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: 'TODO: Speed up, or move to another type of test', + ); + + group( + 'MigrateRevisions', + () { + setUp(() async { + fileSystem = LocalFileSystem.test(signals: LocalSignals.instance); + currentDir = createResolvedTempDirectorySync('current_app.'); + logger = BufferLogger.test(); + utils = MigrateUtils( + logger: logger, + fileSystem: fileSystem, + processManager: const LocalProcessManager(), + ); + await MigrateProject.installProject( + 'version:1.22.6_stable', + currentDir, + ); + final FlutterProjectFactory flutterFactory = FlutterProjectFactory(); + final FlutterProject flutterProject = flutterFactory.fromDirectory( + currentDir, + ); + result = MigrateResult.empty(); + final MigrateLogger migrateLogger = MigrateLogger( + logger: logger, + verbose: true, + ); + migrateLogger.start(); + context = MigrateContext( + flutterProject: flutterProject, + skippedPrefixes: {}, + fileSystem: fileSystem, + migrateLogger: migrateLogger, + migrateUtils: utils, + environment: environment, + ); + }); + + testUsingContext('extracts revisions underpopulated metadata', () async { + final MigrateRevisions revisions = MigrateRevisions( + context: context, + baseRevision: oldSdkRevision, + allowFallbackBaseRevision: true, + platforms: [ + SupportedPlatform.android, + SupportedPlatform.ios, ], - }, //revisionToConfigs - oldSdkRevision, //fallbackRevision - oldSdkRevision, //targetRevision - targetFlutterDirectory, //targetFlutterDirectory - ); + environment: environment, + ); - expect(baseDir.childFile('pubspec.yaml').existsSync(), false); - expect( - baseDir - .childDirectory('android') - .childFile('build.gradle') - .existsSync(), - false); - - await targetProject.createProject( - context, - result, - oldSdkRevision, //revisionsList - targetFlutterDirectory, //targetFlutterDirectory - ); - - expect(targetDir.childFile('pubspec.yaml').existsSync(), false); - expect( - targetDir - .childDirectory('android') - .childFile('build.gradle') - .existsSync(), - false); - }, timeout: const Timeout(Duration(seconds: 500))); - }, - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: 'TODO: Speed up, or move to another type of test'); - - group('MigrateRevisions', () { - setUp(() async { - fileSystem = LocalFileSystem.test(signals: LocalSignals.instance); - currentDir = createResolvedTempDirectorySync('current_app.'); - logger = BufferLogger.test(); - utils = MigrateUtils( - logger: logger, - fileSystem: fileSystem, - processManager: const LocalProcessManager(), - ); - await MigrateProject.installProject('version:1.22.6_stable', currentDir); - final FlutterProjectFactory flutterFactory = FlutterProjectFactory(); - final FlutterProject flutterProject = - flutterFactory.fromDirectory(currentDir); - result = MigrateResult.empty(); - final MigrateLogger migrateLogger = - MigrateLogger(logger: logger, verbose: true); - migrateLogger.start(); - context = MigrateContext( - flutterProject: flutterProject, - skippedPrefixes: {}, - fileSystem: fileSystem, - migrateLogger: migrateLogger, - migrateUtils: utils, - environment: environment, - ); - }); - - testUsingContext('extracts revisions underpopulated metadata', () async { - final MigrateRevisions revisions = MigrateRevisions( - context: context, - baseRevision: oldSdkRevision, - allowFallbackBaseRevision: true, - platforms: [ - SupportedPlatform.android, - SupportedPlatform.ios - ], - environment: environment, - ); - - expect(revisions.revisionsList, [oldSdkRevision]); - expect(revisions.fallbackRevision, oldSdkRevision); - expect(revisions.metadataRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect(revisions.config.unmanagedFiles.isEmpty, false); - expect(revisions.config.platformConfigs.isEmpty, false); - expect(revisions.config.platformConfigs.length, 3); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.root), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.android), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.ios), - true); - }); - - testUsingContext('extracts revisions full metadata', () async { - final File metadataFile = - context.flutterProject.directory.childFile('.metadata'); - if (metadataFile.existsSync()) { - if (!tryToDelete(metadataFile)) { - // TODO(garyq): Inaccessible .metadata on windows. - // Skip test for now. We should reneable. - return; + expect(revisions.revisionsList, [oldSdkRevision]); + expect(revisions.fallbackRevision, oldSdkRevision); + expect( + revisions.metadataRevision, + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect(revisions.config.unmanagedFiles.isEmpty, false); + expect(revisions.config.platformConfigs.isEmpty, false); + expect(revisions.config.platformConfigs.length, 3); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.root, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.android, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.ios, + ), + true, + ); + }); + + testUsingContext('extracts revisions full metadata', () async { + final File metadataFile = context.flutterProject.directory.childFile( + '.metadata', + ); + if (metadataFile.existsSync()) { + if (!tryToDelete(metadataFile)) { + // TODO(garyq): Inaccessible .metadata on windows. + // Skip test for now. We should reneable. + return; + } } - } - metadataFile.createSync(recursive: true); - metadataFile.writeAsStringSync(''' + metadataFile.createSync(recursive: true); + metadataFile.writeAsStringSync(''' # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # @@ -377,279 +438,349 @@ migration: - 'ios/Runner.xcodeproj/project.pbxproj' ''', flush: true); - final MigrateRevisions revisions = MigrateRevisions( - context: context, - baseRevision: oldSdkRevision, - allowFallbackBaseRevision: true, - platforms: [ - SupportedPlatform.android, - SupportedPlatform.ios - ], - environment: environment, - ); + final MigrateRevisions revisions = MigrateRevisions( + context: context, + baseRevision: oldSdkRevision, + allowFallbackBaseRevision: true, + platforms: [ + SupportedPlatform.android, + SupportedPlatform.ios, + ], + environment: environment, + ); + + expect(revisions.revisionsList, [oldSdkRevision]); + expect(revisions.fallbackRevision, oldSdkRevision); + expect( + revisions.metadataRevision, + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect(revisions.config.unmanagedFiles.isEmpty, false); + expect(revisions.config.unmanagedFiles.length, 3); + expect(revisions.config.unmanagedFiles.contains('lib/main.dart'), true); + expect(revisions.config.unmanagedFiles.contains('blah.dart'), true); + expect( + revisions.config.unmanagedFiles.contains( + 'ios/Runner.xcodeproj/project.pbxproj', + ), + true, + ); + + expect(revisions.config.platformConfigs.length, 7); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.root, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.android, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.ios, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.linux, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.macos, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.web, + ), + true, + ); + expect( + revisions.config.platformConfigs.containsKey( + FlutterProjectComponent.windows, + ), + true, + ); - expect(revisions.revisionsList, [oldSdkRevision]); - expect(revisions.fallbackRevision, oldSdkRevision); - expect(revisions.metadataRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect(revisions.config.unmanagedFiles.isEmpty, false); - expect(revisions.config.unmanagedFiles.length, 3); - expect(revisions.config.unmanagedFiles.contains('lib/main.dart'), true); - expect(revisions.config.unmanagedFiles.contains('blah.dart'), true); - expect( - revisions.config.unmanagedFiles - .contains('ios/Runner.xcodeproj/project.pbxproj'), - true); - - expect(revisions.config.platformConfigs.length, 7); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.root), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.android), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.ios), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.linux), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.macos), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.web), - true); - expect( - revisions.config.platformConfigs - .containsKey(FlutterProjectComponent.windows), - true); - - expect( - revisions.config.platformConfigs[FlutterProjectComponent.root]! + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.root]! .createRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.android]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.android]! .createRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.ios]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.ios]! .createRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.linux]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.linux]! .createRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.macos]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.macos]! .createRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.web]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.web]! .createRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.windows]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.windows]! .createRevision, - '36427af29421f406ac95ff55ea31d1dc49a45b5f'); + '36427af29421f406ac95ff55ea31d1dc49a45b5f', + ); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.root]! + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.root]! .baseRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.android]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.android]! .baseRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.ios]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.ios]! .baseRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.linux]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.linux]! .baseRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.macos]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.macos]! .baseRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.web]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.web]! .baseRevision, - '9b2d32b605630f28625709ebd9d78ab3016b2bf6'); - expect( - revisions.config.platformConfigs[FlutterProjectComponent.windows]! + '9b2d32b605630f28625709ebd9d78ab3016b2bf6', + ); + expect( + revisions + .config + .platformConfigs[FlutterProjectComponent.windows]! .baseRevision, - '36427af29421f406ac95ff55ea31d1dc49a45b5f'); - }); - }, - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: 'TODO: Speed up, or move to another type of test'); - - group('project operations', () { - setUp(() async { - await setUpFullEnv(); - }); - - tearDown(() async { - tryToDelete(targetFlutterDirectory); - tryToDelete(newerTargetFlutterDirectory); - }); - - testUsingContext('diff base and target', () async { - final Directory workingDir = - createResolvedTempDirectorySync('migrate_working_dir.'); - final Directory targetDir = - createResolvedTempDirectorySync('target_dir.'); - final Directory baseDir = createResolvedTempDirectorySync('base_dir.'); - result.generatedTargetTemplateDirectory = targetDir; - result.generatedBaseTemplateDirectory = baseDir; - workingDir.createSync(recursive: true); - - final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject( - path: null, - directory: baseDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', - ); - final MigrateTargetFlutterProject targetProject = - MigrateTargetFlutterProject( - path: null, - directory: targetDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', - ); - - await baseProject.createProject( - context, - result, - [oldSdkRevision], //revisionsList - >{ - oldSdkRevision: [ - MigratePlatformConfig(component: FlutterProjectComponent.android), - MigratePlatformConfig(component: FlutterProjectComponent.ios) - ], - }, //revisionToConfigs - oldSdkRevision, //fallbackRevision - oldSdkRevision, //targetRevision - targetFlutterDirectory, //targetFlutterDirectory - ); - - expect(baseDir.childFile('pubspec.yaml').existsSync(), true); - expect( + '36427af29421f406ac95ff55ea31d1dc49a45b5f', + ); + }); + }, + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: 'TODO: Speed up, or move to another type of test', + ); + + group( + 'project operations', + () { + setUp(() async { + await setUpFullEnv(); + }); + + tearDown(() async { + tryToDelete(targetFlutterDirectory); + tryToDelete(newerTargetFlutterDirectory); + }); + + testUsingContext('diff base and target', () async { + final Directory workingDir = createResolvedTempDirectorySync( + 'migrate_working_dir.', + ); + final Directory targetDir = createResolvedTempDirectorySync( + 'target_dir.', + ); + final Directory baseDir = createResolvedTempDirectorySync('base_dir.'); + result.generatedTargetTemplateDirectory = targetDir; + result.generatedBaseTemplateDirectory = baseDir; + workingDir.createSync(recursive: true); + + final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject( + path: null, + directory: baseDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + final MigrateTargetFlutterProject targetProject = + MigrateTargetFlutterProject( + path: null, + directory: targetDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + + await baseProject.createProject( + context, + result, + [oldSdkRevision], //revisionsList + >{ + oldSdkRevision: [ + MigratePlatformConfig(component: FlutterProjectComponent.android), + MigratePlatformConfig(component: FlutterProjectComponent.ios), + ], + }, //revisionToConfigs + oldSdkRevision, //fallbackRevision + oldSdkRevision, //targetRevision + targetFlutterDirectory, //targetFlutterDirectory + ); + + expect(baseDir.childFile('pubspec.yaml').existsSync(), true); + expect( baseDir .childDirectory('android') .childFile('build.gradle') .existsSync(), - true); + true, + ); - await targetProject.createProject( - context, - result, - newSdkRevision, //revisionsList - newerTargetFlutterDirectory, //targetFlutterDirectory - ); + await targetProject.createProject( + context, + result, + newSdkRevision, //revisionsList + newerTargetFlutterDirectory, //targetFlutterDirectory + ); - expect(targetDir.childFile('pubspec.yaml').existsSync(), true); - expect( + expect(targetDir.childFile('pubspec.yaml').existsSync(), true); + expect( targetDir .childDirectory('android') .childFile('build.gradle') .existsSync(), - true); - - final Map diffResults = - await baseProject.diff(context, targetProject); - final Map canonicalizedDiffResults = - {}; - for (final MapEntry entry in diffResults.entries) { - canonicalizedDiffResults[canonicalize(entry.key)] = entry.value; - } - result.diffMap.addAll(diffResults); - - List expectedFiles = [ - '.metadata', - 'ios/Runner.xcworkspace/contents.xcworkspacedata', - 'ios/Runner/AppDelegate.h', - 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png', - 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png', - 'ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md', - 'ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json', - 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png', - 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png', - 'ios/Runner/Base.lproj/LaunchScreen.storyboard', - 'ios/Runner/Base.lproj/Main.storyboard', - 'ios/Runner/main.m', - 'ios/Runner/AppDelegate.m', - 'ios/Runner/Info.plist', - 'ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata', - 'ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', - 'ios/Flutter/Debug.xcconfig', - 'ios/Flutter/Release.xcconfig', - 'ios/Flutter/AppFrameworkInfo.plist', - 'pubspec.yaml', - '.gitignore', - 'android/base_android.iml', - 'android/app/build.gradle', - 'android/app/src/main/res/mipmap-mdpi/ic_launcher.png', - 'android/app/src/main/res/mipmap-hdpi/ic_launcher.png', - 'android/app/src/main/res/drawable/launch_background.xml', - 'android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png', - 'android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png', - 'android/app/src/main/res/values/styles.xml', - 'android/app/src/main/res/mipmap-xhdpi/ic_launcher.png', - 'android/app/src/main/AndroidManifest.xml', - 'android/app/src/main/java/com/example/base/MainActivity.java', - 'android/local.properties', - 'android/gradle/wrapper/gradle-wrapper.jar', - 'android/gradle/wrapper/gradle-wrapper.properties', - 'android/gradlew', - 'android/build.gradle', - 'android/gradle.properties', - 'android/gradlew.bat', - 'android/settings.gradle', - 'base.iml', - '.idea/runConfigurations/main_dart.xml', - '.idea/libraries/Dart_SDK.xml', - '.idea/libraries/KotlinJavaRuntime.xml', - '.idea/libraries/Flutter_for_Android.xml', - '.idea/workspace.xml', - '.idea/modules.xml', - ]; - expectedFiles = - List.from(expectedFiles.map((String e) => canonicalize(e))); - expect(diffResults.length, 62); - expect(expectedFiles.length, 62); - for (final String diffResultPath in canonicalizedDiffResults.keys) { - expect(expectedFiles.contains(diffResultPath), true); - } - // Spot check diffs on key files: - expect( + true, + ); + + final Map diffResults = await baseProject.diff( + context, + targetProject, + ); + final Map canonicalizedDiffResults = + {}; + for (final MapEntry entry in diffResults.entries) { + canonicalizedDiffResults[canonicalize(entry.key)] = entry.value; + } + result.diffMap.addAll(diffResults); + + List expectedFiles = [ + '.metadata', + 'ios/Runner.xcworkspace/contents.xcworkspacedata', + 'ios/Runner/AppDelegate.h', + 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png', + 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png', + 'ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md', + 'ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json', + 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png', + 'ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png', + 'ios/Runner/Base.lproj/LaunchScreen.storyboard', + 'ios/Runner/Base.lproj/Main.storyboard', + 'ios/Runner/main.m', + 'ios/Runner/AppDelegate.m', + 'ios/Runner/Info.plist', + 'ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata', + 'ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', + 'ios/Flutter/Debug.xcconfig', + 'ios/Flutter/Release.xcconfig', + 'ios/Flutter/AppFrameworkInfo.plist', + 'pubspec.yaml', + '.gitignore', + 'android/base_android.iml', + 'android/app/build.gradle', + 'android/app/src/main/res/mipmap-mdpi/ic_launcher.png', + 'android/app/src/main/res/mipmap-hdpi/ic_launcher.png', + 'android/app/src/main/res/drawable/launch_background.xml', + 'android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png', + 'android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png', + 'android/app/src/main/res/values/styles.xml', + 'android/app/src/main/res/mipmap-xhdpi/ic_launcher.png', + 'android/app/src/main/AndroidManifest.xml', + 'android/app/src/main/java/com/example/base/MainActivity.java', + 'android/local.properties', + 'android/gradle/wrapper/gradle-wrapper.jar', + 'android/gradle/wrapper/gradle-wrapper.properties', + 'android/gradlew', + 'android/build.gradle', + 'android/gradle.properties', + 'android/gradlew.bat', + 'android/settings.gradle', + 'base.iml', + '.idea/runConfigurations/main_dart.xml', + '.idea/libraries/Dart_SDK.xml', + '.idea/libraries/KotlinJavaRuntime.xml', + '.idea/libraries/Flutter_for_Android.xml', + '.idea/workspace.xml', + '.idea/modules.xml', + ]; + expectedFiles = List.from( + expectedFiles.map((String e) => canonicalize(e)), + ); + expect(diffResults.length, 62); + expect(expectedFiles.length, 62); + for (final String diffResultPath in canonicalizedDiffResults.keys) { + expect(expectedFiles.contains(diffResultPath), true); + } + // Spot check diffs on key files: + expect( canonicalizedDiffResults[canonicalize('android/build.gradle')]!.diff, contains(r''' @@ -1,18 +1,20 @@ @@ -659,8 +790,9 @@ migration: google() - jcenter() + mavenCentral() - }''')); - expect( + }'''), + ); + expect( canonicalizedDiffResults[canonicalize('android/build.gradle')]!.diff, contains(r''' dependencies { @@ -668,8 +800,9 @@ migration: + classpath 'com.android.tools.build:gradle:7.1.2' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } - }''')); - expect( + }'''), + ); + expect( canonicalizedDiffResults[canonicalize('android/build.gradle')]!.diff, contains(r''' allprojects { @@ -678,10 +811,12 @@ migration: - jcenter() + mavenCentral() } - }''')); - expect( - canonicalizedDiffResults[ - canonicalize('android/app/src/main/AndroidManifest.xml')]! + }'''), + ); + expect( + canonicalizedDiffResults[canonicalize( + 'android/app/src/main/AndroidManifest.xml', + )]! .diff, contains(r''' @@ -1,39 +1,34 @@ @@ -739,140 +874,148 @@ migration: + android:name="flutterEmbedding" + android:value="2" /> - ''')); - }, timeout: const Timeout(Duration(seconds: 500))); - - testUsingContext('Merge succeeds', () async { - final Directory workingDir = - createResolvedTempDirectorySync('migrate_working_dir.'); - final Directory targetDir = - createResolvedTempDirectorySync('target_dir.'); - final Directory baseDir = createResolvedTempDirectorySync('base_dir.'); - result.generatedTargetTemplateDirectory = targetDir; - result.generatedBaseTemplateDirectory = baseDir; - workingDir.createSync(recursive: true); - - final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject( - path: null, - directory: baseDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', - ); - final MigrateTargetFlutterProject targetProject = - MigrateTargetFlutterProject( - path: null, - directory: targetDir, - name: 'base', - androidLanguage: 'java', - iosLanguage: 'objc', - ); - - await baseProject.createProject( - context, - result, - [oldSdkRevision], //revisionsList - >{ - oldSdkRevision: [ - MigratePlatformConfig(component: FlutterProjectComponent.android), - MigratePlatformConfig(component: FlutterProjectComponent.ios) - ], - }, //revisionToConfigs - oldSdkRevision, //fallbackRevision - oldSdkRevision, //targetRevision - targetFlutterDirectory, //targetFlutterDirectory - ); - - expect(baseDir.childFile('pubspec.yaml').existsSync(), true); - expect(baseDir.childFile('.metadata').existsSync(), true); - expect( + '''), + ); + }, timeout: const Timeout(Duration(seconds: 500))); + + testUsingContext('Merge succeeds', () async { + final Directory workingDir = createResolvedTempDirectorySync( + 'migrate_working_dir.', + ); + final Directory targetDir = createResolvedTempDirectorySync( + 'target_dir.', + ); + final Directory baseDir = createResolvedTempDirectorySync('base_dir.'); + result.generatedTargetTemplateDirectory = targetDir; + result.generatedBaseTemplateDirectory = baseDir; + workingDir.createSync(recursive: true); + + final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject( + path: null, + directory: baseDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + final MigrateTargetFlutterProject targetProject = + MigrateTargetFlutterProject( + path: null, + directory: targetDir, + name: 'base', + androidLanguage: 'java', + iosLanguage: 'objc', + ); + + await baseProject.createProject( + context, + result, + [oldSdkRevision], //revisionsList + >{ + oldSdkRevision: [ + MigratePlatformConfig(component: FlutterProjectComponent.android), + MigratePlatformConfig(component: FlutterProjectComponent.ios), + ], + }, //revisionToConfigs + oldSdkRevision, //fallbackRevision + oldSdkRevision, //targetRevision + targetFlutterDirectory, //targetFlutterDirectory + ); + + expect(baseDir.childFile('pubspec.yaml').existsSync(), true); + expect(baseDir.childFile('.metadata').existsSync(), true); + expect( baseDir .childDirectory('android') .childFile('build.gradle') .existsSync(), - true); - - await targetProject.createProject( - context, - result, - newSdkRevision, //revisionsList - newerTargetFlutterDirectory, //targetFlutterDirectory - ); - - expect(targetDir.childFile('pubspec.yaml').existsSync(), true); - expect(targetDir.childFile('.metadata').existsSync(), true); - expect( + true, + ); + + await targetProject.createProject( + context, + result, + newSdkRevision, //revisionsList + newerTargetFlutterDirectory, //targetFlutterDirectory + ); + + expect(targetDir.childFile('pubspec.yaml').existsSync(), true); + expect(targetDir.childFile('.metadata').existsSync(), true); + expect( targetDir .childDirectory('android') .childFile('build.gradle') .existsSync(), - true); - - result.diffMap.addAll(await baseProject.diff(context, targetProject)); - - await MigrateFlutterProject.merge( - context, - result, - baseProject, - targetProject, - [], // unmanagedFiles - [], // unmanagedDirectories - false, // preferTwoWayMerge - ); - - List expectedMergedPaths = [ - '.metadata', - 'ios/Runner/Info.plist', - 'ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata', - 'ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', - 'ios/Flutter/AppFrameworkInfo.plist', - 'pubspec.yaml', - '.gitignore', - 'android/app/build.gradle', - 'android/app/src/main/res/values/styles.xml', - 'android/app/src/main/AndroidManifest.xml', - 'android/gradle/wrapper/gradle-wrapper.properties', - 'android/build.gradle', - ]; - expectedMergedPaths = List.from( - expectedMergedPaths.map((String e) => canonicalize(e))); - expect(result.mergeResults.length, 12); - expect(expectedMergedPaths.length, 12); - - for (final MergeResult mergeResult in result.mergeResults) { - expect( + true, + ); + + result.diffMap.addAll(await baseProject.diff(context, targetProject)); + + await MigrateFlutterProject.merge( + context, + result, + baseProject, + targetProject, + [], // unmanagedFiles + [], // unmanagedDirectories + false, // preferTwoWayMerge + ); + + List expectedMergedPaths = [ + '.metadata', + 'ios/Runner/Info.plist', + 'ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata', + 'ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', + 'ios/Flutter/AppFrameworkInfo.plist', + 'pubspec.yaml', + '.gitignore', + 'android/app/build.gradle', + 'android/app/src/main/res/values/styles.xml', + 'android/app/src/main/AndroidManifest.xml', + 'android/gradle/wrapper/gradle-wrapper.properties', + 'android/build.gradle', + ]; + expectedMergedPaths = List.from( + expectedMergedPaths.map((String e) => canonicalize(e)), + ); + expect(result.mergeResults.length, 12); + expect(expectedMergedPaths.length, 12); + + for (final MergeResult mergeResult in result.mergeResults) { + expect( expectedMergedPaths.contains(canonicalize(mergeResult.localPath)), - true); - } - - expect(result.mergeResults[0].exitCode, 0); - expect(result.mergeResults[1].exitCode, 0); - expect(result.mergeResults[2].exitCode, 0); - expect(result.mergeResults[3].exitCode, 0); - expect(result.mergeResults[4].exitCode, 0); - expect(result.mergeResults[5].exitCode, 0); - expect(result.mergeResults[6].exitCode, 0); - expect(result.mergeResults[7].exitCode, 0); - expect(result.mergeResults[8].exitCode, 0); - expect(result.mergeResults[9].exitCode, 0); - expect(result.mergeResults[10].exitCode, 0); - expect(result.mergeResults[11].exitCode, 0); - - expect(result.mergeResults[0].hasConflict, false); - expect(result.mergeResults[1].hasConflict, false); - expect(result.mergeResults[2].hasConflict, false); - expect(result.mergeResults[3].hasConflict, false); - expect(result.mergeResults[4].hasConflict, false); - expect(result.mergeResults[5].hasConflict, false); - expect(result.mergeResults[6].hasConflict, false); - expect(result.mergeResults[7].hasConflict, false); - expect(result.mergeResults[8].hasConflict, false); - expect(result.mergeResults[9].hasConflict, false); - expect(result.mergeResults[10].hasConflict, false); - expect(result.mergeResults[11].hasConflict, false); - }, timeout: const Timeout(Duration(seconds: 500))); - }, - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: 'TODO: Speed up, or move to another type of test'); + true, + ); + } + + expect(result.mergeResults[0].exitCode, 0); + expect(result.mergeResults[1].exitCode, 0); + expect(result.mergeResults[2].exitCode, 0); + expect(result.mergeResults[3].exitCode, 0); + expect(result.mergeResults[4].exitCode, 0); + expect(result.mergeResults[5].exitCode, 0); + expect(result.mergeResults[6].exitCode, 0); + expect(result.mergeResults[7].exitCode, 0); + expect(result.mergeResults[8].exitCode, 0); + expect(result.mergeResults[9].exitCode, 0); + expect(result.mergeResults[10].exitCode, 0); + expect(result.mergeResults[11].exitCode, 0); + + expect(result.mergeResults[0].hasConflict, false); + expect(result.mergeResults[1].hasConflict, false); + expect(result.mergeResults[2].hasConflict, false); + expect(result.mergeResults[3].hasConflict, false); + expect(result.mergeResults[4].hasConflict, false); + expect(result.mergeResults[5].hasConflict, false); + expect(result.mergeResults[6].hasConflict, false); + expect(result.mergeResults[7].hasConflict, false); + expect(result.mergeResults[8].hasConflict, false); + expect(result.mergeResults[9].hasConflict, false); + expect(result.mergeResults[10].hasConflict, false); + expect(result.mergeResults[11].hasConflict, false); + }, timeout: const Timeout(Duration(seconds: 500))); + }, + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: 'TODO: Speed up, or move to another type of test', + ); } diff --git a/packages/flutter_migrate/test/custom_merge_test.dart b/packages/flutter_migrate/test/custom_merge_test.dart index 142e7f54cd1..4dd683afad4 100644 --- a/packages/flutter_migrate/test/custom_merge_test.dart +++ b/packages/flutter_migrate/test/custom_merge_test.dart @@ -48,8 +48,8 @@ void main() { final StringMergeResult result = merger.merge(currentFile, baseFile, targetFile) as StringMergeResult; expect( - result.mergedString, - ''' + result.mergedString, + ''' # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # @@ -60,7 +60,7 @@ version: channel: null project_type: ''' - ''' + ''' # Tracks metadata for the flutter migrate command @@ -76,7 +76,8 @@ migration: unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj' -'''); +''', + ); }); testWithoutContext('merge adds migration section', () async { diff --git a/packages/flutter_migrate/test/environment_test.dart b/packages/flutter_migrate/test/environment_test.dart index a2d20e50d00..e38351eb832 100644 --- a/packages/flutter_migrate/test/environment_test.dart +++ b/packages/flutter_migrate/test/environment_test.dart @@ -61,42 +61,52 @@ void main() { tryToDelete(appDir); }); - testUsingContext('Environment initialization', () async { - final FlutterToolsEnvironment env = - await FlutterToolsEnvironment.initializeFlutterToolsEnvironment( - processManager, logger); - expect(env.getString('invalid key') == null, true); - expect(env.getBool('invalid key') == null, true); + testUsingContext( + 'Environment initialization', + () async { + final FlutterToolsEnvironment env = + await FlutterToolsEnvironment.initializeFlutterToolsEnvironment( + processManager, + logger, + ); + expect(env.getString('invalid key') == null, true); + expect(env.getBool('invalid key') == null, true); - expect(env.getString('FlutterProject.directory'), '/Users/test/flutter'); - expect(env.getString('FlutterProject.metadataFile'), - '/Users/test/flutter/.metadata'); - expect(env.getBool('FlutterProject.android.exists'), false); - expect(env.getBool('FlutterProject.ios.exists'), false); - expect(env.getBool('FlutterProject.web.exists'), false); - expect(env.getBool('FlutterProject.macos.exists'), false); - expect(env.getBool('FlutterProject.linux.exists'), false); - expect(env.getBool('FlutterProject.windows.exists'), false); - expect(env.getBool('FlutterProject.fuchsia.exists'), false); - expect(env.getBool('FlutterProject.android.isKotlin'), false); - expect(env.getBool('FlutterProject.ios.isSwift'), false); - expect(env.getBool('FlutterProject.isModule'), false); - expect(env.getBool('FlutterProject.isPlugin'), false); - expect(env.getString('FlutterProject.manifest.appname'), 'test_app_name'); - expect(env.getString('FlutterVersion.frameworkRevision'), - '4e181f012c717777681862e4771af5a941774bb9'); - expect(env.getString('Platform.operatingSystem'), 'macos'); - expect(env.getBool('Platform.isAndroid'), true); - expect(env.getBool('Platform.isIOS'), false); - expect(env.getBool('Platform.isWindows'), isWindows); - expect(env.getBool('Platform.isMacOS'), isMacOS); - expect(env.getBool('Platform.isFuchsia'), false); - expect(env.getString('Platform.pathSeparator'), separator); - expect(env.getString('Cache.flutterRoot'), '/Users/test/flutter'); - }, overrides: { - FileSystem: () => fileSystem, - ProcessManager: () => processManager, - }); + expect(env.getString('FlutterProject.directory'), '/Users/test/flutter'); + expect( + env.getString('FlutterProject.metadataFile'), + '/Users/test/flutter/.metadata', + ); + expect(env.getBool('FlutterProject.android.exists'), false); + expect(env.getBool('FlutterProject.ios.exists'), false); + expect(env.getBool('FlutterProject.web.exists'), false); + expect(env.getBool('FlutterProject.macos.exists'), false); + expect(env.getBool('FlutterProject.linux.exists'), false); + expect(env.getBool('FlutterProject.windows.exists'), false); + expect(env.getBool('FlutterProject.fuchsia.exists'), false); + expect(env.getBool('FlutterProject.android.isKotlin'), false); + expect(env.getBool('FlutterProject.ios.isSwift'), false); + expect(env.getBool('FlutterProject.isModule'), false); + expect(env.getBool('FlutterProject.isPlugin'), false); + expect(env.getString('FlutterProject.manifest.appname'), 'test_app_name'); + expect( + env.getString('FlutterVersion.frameworkRevision'), + '4e181f012c717777681862e4771af5a941774bb9', + ); + expect(env.getString('Platform.operatingSystem'), 'macos'); + expect(env.getBool('Platform.isAndroid'), true); + expect(env.getBool('Platform.isIOS'), false); + expect(env.getBool('Platform.isWindows'), isWindows); + expect(env.getBool('Platform.isMacOS'), isMacOS); + expect(env.getBool('Platform.isFuchsia'), false); + expect(env.getString('Platform.pathSeparator'), separator); + expect(env.getString('Cache.flutterRoot'), '/Users/test/flutter'); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }, + ); } class FakeProcessManager extends LocalProcessManager { @@ -105,13 +115,15 @@ class FakeProcessManager extends LocalProcessManager { final String runResult; @override - Future run(List command, - {String? workingDirectory, - Map? environment, - bool includeParentEnvironment = true, - bool runInShell = false, - covariant Encoding? stdoutEncoding = systemEncoding, - covariant Encoding? stderrEncoding = systemEncoding}) async { + Future run( + List command, { + String? workingDirectory, + Map? environment, + bool includeParentEnvironment = true, + bool runInShell = false, + covariant Encoding? stdoutEncoding = systemEncoding, + covariant Encoding? stderrEncoding = systemEncoding, + }) async { return ProcessResult(0, 0, runResult, ''); } } diff --git a/packages/flutter_migrate/test/flutter_project_metadata_test.dart b/packages/flutter_migrate/test/flutter_project_metadata_test.dart index 8d4e5328060..6b3bef6c38e 100644 --- a/packages/flutter_migrate/test/flutter_project_metadata_test.dart +++ b/packages/flutter_migrate/test/flutter_project_metadata_test.dart @@ -21,41 +21,60 @@ void main() { }); testWithoutContext( - 'project metadata fields are empty when file does not exist', () { - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); - expect(projectMetadata.projectType, isNull); - expect(projectMetadata.versionChannel, isNull); - expect(projectMetadata.versionRevision, isNull); + 'project metadata fields are empty when file does not exist', + () { + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); + expect(projectMetadata.projectType, isNull); + expect(projectMetadata.versionChannel, isNull); + expect(projectMetadata.versionRevision, isNull); - expect(logger.traceText, contains('No .metadata file found at .metadata')); - }); + expect( + logger.traceText, + contains('No .metadata file found at .metadata'), + ); + }, + ); - testWithoutContext('project metadata fields are empty when file is empty', - () { - metadataFile.createSync(); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); - expect(projectMetadata.projectType, isNull); - expect(projectMetadata.versionChannel, isNull); - expect(projectMetadata.versionRevision, isNull); + testWithoutContext( + 'project metadata fields are empty when file is empty', + () { + metadataFile.createSync(); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); + expect(projectMetadata.projectType, isNull); + expect(projectMetadata.versionChannel, isNull); + expect(projectMetadata.versionRevision, isNull); - expect(logger.traceText, - contains('.metadata file at .metadata was empty or malformed.')); - }); + expect( + logger.traceText, + contains('.metadata file at .metadata was empty or malformed.'), + ); + }, + ); testWithoutContext( - 'project metadata fields are empty when file is not valid yaml', () { - metadataFile.writeAsStringSync(' channel: @something'); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); - expect(projectMetadata.projectType, isNull); - expect(projectMetadata.versionChannel, isNull); - expect(projectMetadata.versionRevision, isNull); + 'project metadata fields are empty when file is not valid yaml', + () { + metadataFile.writeAsStringSync(' channel: @something'); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); + expect(projectMetadata.projectType, isNull); + expect(projectMetadata.versionChannel, isNull); + expect(projectMetadata.versionRevision, isNull); - expect(logger.traceText, - contains('.metadata file at .metadata was empty or malformed.')); - }); + expect( + logger.traceText, + contains('.metadata file at .metadata was empty or malformed.'), + ); + }, + ); testWithoutContext('projectType is populated when version is null', () { metadataFile @@ -64,16 +83,20 @@ void main() { version: project_type: plugin '''); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); expect(projectMetadata.projectType, FlutterProjectType.plugin); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect( - logger.traceText, - contains( - 'The value of key `version` in .metadata was expected to be YamlMap but was Null')); + logger.traceText, + contains( + 'The value of key `version` in .metadata was expected to be YamlMap but was Null', + ), + ); }); testWithoutContext('projectType is populated when version is malformed', () { @@ -83,16 +106,20 @@ project_type: plugin version: STRING INSTEAD OF MAP project_type: plugin '''); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); expect(projectMetadata.projectType, FlutterProjectType.plugin); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect( - logger.traceText, - contains( - 'The value of key `version` in .metadata was expected to be YamlMap but was String')); + logger.traceText, + contains( + 'The value of key `version` in .metadata was expected to be YamlMap but was String', + ), + ); }); testWithoutContext('version is populated when projectType is malformed', () { @@ -104,21 +131,26 @@ version: channel: stable project_type: {} '''); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, 'stable'); - expect(projectMetadata.versionRevision, - 'b59b226a49391949247e3d6122e34bb001049ae4'); + expect( + projectMetadata.versionRevision, + 'b59b226a49391949247e3d6122e34bb001049ae4', + ); expect( - logger.traceText, - contains( - 'The value of key `project_type` in .metadata was expected to be String but was YamlMap')); + logger.traceText, + contains( + 'The value of key `project_type` in .metadata was expected to be String but was YamlMap', + ), + ); }); - testWithoutContext('migrate config is populated when version is malformed', - () { + testWithoutContext('migrate config is populated when version is malformed', () { metadataFile ..createSync() ..writeAsStringSync(''' @@ -134,34 +166,47 @@ migration: unmanaged_files: - 'file1' '''); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); expect(projectMetadata.projectType, isNull); expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.root]?.createRevision, - 'abcdefg'); + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.root] + ?.createRevision, + 'abcdefg', + ); expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.root]?.baseRevision, - 'baserevision'); + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.root] + ?.baseRevision, + 'baserevision', + ); expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'file1'); expect( - logger.traceText, - contains( - 'The value of key `version` in .metadata was expected to be YamlMap but was String')); + logger.traceText, + contains( + 'The value of key `version` in .metadata was expected to be YamlMap but was String', + ), + ); expect( - logger.traceText, - contains( - 'The value of key `project_type` in .metadata was expected to be String but was YamlMap')); + logger.traceText, + contains( + 'The value of key `project_type` in .metadata was expected to be String but was YamlMap', + ), + ); }); testWithoutContext( - 'migrate config is populated when unmanaged_files is malformed', () { - metadataFile - ..createSync() - ..writeAsStringSync(''' + 'migrate config is populated when unmanaged_files is malformed', + () { + metadataFile + ..createSync() + ..writeAsStringSync(''' version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stable @@ -175,25 +220,36 @@ migration: unmanaged_files: {} '''); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); - expect(projectMetadata.projectType, FlutterProjectType.app); - expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.root]?.createRevision, - 'abcdefg'); - expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.root]?.baseRevision, - 'baserevision'); - // Tool uses default unamanged files list when malformed. - expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'lib/main.dart'); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); + expect(projectMetadata.projectType, FlutterProjectType.app); + expect( + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.root] + ?.createRevision, + 'abcdefg', + ); + expect( + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.root] + ?.baseRevision, + 'baserevision', + ); + // Tool uses default unamanged files list when malformed. + expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'lib/main.dart'); - expect( + expect( logger.traceText, contains( - 'The value of key `unmanaged_files` in .metadata was expected to be YamlList but was YamlMap')); - }); + 'The value of key `unmanaged_files` in .metadata was expected to be YamlList but was YamlMap', + ), + ); + }, + ); testWithoutContext('platforms is populated with a malformed entry', () { metadataFile @@ -218,32 +274,50 @@ migration: unmanaged_files: - 'file1' '''); - final FlutterProjectMetadata projectMetadata = - FlutterProjectMetadata(metadataFile, logger); + final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata( + metadataFile, + logger, + ); expect(projectMetadata.projectType, FlutterProjectType.app); expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.root]?.createRevision, - 'abcdefg'); + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.root] + ?.createRevision, + 'abcdefg', + ); expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.root]?.baseRevision, - 'baserevision'); + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.root] + ?.baseRevision, + 'baserevision', + ); expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.ios]?.createRevision, - 'abcdefg'); + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.ios] + ?.createRevision, + 'abcdefg', + ); expect( - projectMetadata.migrateConfig - .platformConfigs[FlutterProjectComponent.ios]?.baseRevision, - 'baserevision'); + projectMetadata + .migrateConfig + .platformConfigs[FlutterProjectComponent.ios] + ?.baseRevision, + 'baserevision', + ); expect( - projectMetadata.migrateConfig.platformConfigs - .containsKey(FlutterProjectComponent.android), - false); + projectMetadata.migrateConfig.platformConfigs.containsKey( + FlutterProjectComponent.android, + ), + false, + ); expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'file1'); expect( - logger.traceText, contains('The key `create_revision` was not found')); + logger.traceText, + contains('The key `create_revision` was not found'), + ); }); } diff --git a/packages/flutter_migrate/test/manifest_test.dart b/packages/flutter_migrate/test/manifest_test.dart index 4a77289a6e4..90658b093ae 100644 --- a/packages/flutter_migrate/test/manifest_test.dart +++ b/packages/flutter_migrate/test/manifest_test.dart @@ -27,28 +27,36 @@ void main() { final Directory workingDir = fileSystem.directory('migrate_working_dir'); workingDir.createSync(recursive: true); final MigrateManifest manifest = MigrateManifest( - migrateRootDir: workingDir, - migrateResult: MigrateResult( - mergeResults: [], - addedFiles: [], - deletedFiles: [], - mergeTypeMap: {}, - diffMap: {}, - tempDirectories: [], - sdkDirs: {}, - )); - - checkAndPrintMigrateStatus(manifest, workingDir, - warnConflict: true, logger: logger); + migrateRootDir: workingDir, + migrateResult: MigrateResult( + mergeResults: [], + addedFiles: [], + deletedFiles: [], + mergeTypeMap: {}, + diffMap: {}, + tempDirectories: [], + sdkDirs: {}, + ), + ); + + checkAndPrintMigrateStatus( + manifest, + workingDir, + warnConflict: true, + logger: logger, + ); expect(logger.statusText, contains('\n')); }); - testWithoutContext('populated MigrateResult produces correct output', - () async { - final Directory workingDir = fileSystem.directory('migrate_working_dir'); - workingDir.createSync(recursive: true); - final MigrateManifest manifest = MigrateManifest( + testWithoutContext( + 'populated MigrateResult produces correct output', + () async { + final Directory workingDir = fileSystem.directory( + 'migrate_working_dir', + ); + workingDir.createSync(recursive: true); + final MigrateManifest manifest = MigrateManifest( migrateRootDir: workingDir, migrateResult: MigrateResult( mergeResults: [ @@ -67,28 +75,38 @@ void main() { ), ], addedFiles: [ - FilePendingMigration('added_file', fileSystem.file('added_file')) + FilePendingMigration('added_file', fileSystem.file('added_file')), ], deletedFiles: [ FilePendingMigration( - 'deleted_file', fileSystem.file('deleted_file')) + 'deleted_file', + fileSystem.file('deleted_file'), + ), ], // The following are ignored by the manifest. mergeTypeMap: {'test': MergeType.threeWay}, diffMap: {}, tempDirectories: [], sdkDirs: {}, - )); + ), + ); - final File conflictFile = workingDir.childFile('conflict_file'); - conflictFile.writeAsStringSync( + final File conflictFile = workingDir.childFile('conflict_file'); + conflictFile.writeAsStringSync( 'hello\nwow a bunch of lines\n<<<<<<<\n=======\n<<<<<<<\nhi\n', - flush: true); - - checkAndPrintMigrateStatus(manifest, workingDir, - warnConflict: true, logger: logger); - - expect(logger.statusText, contains(''' + flush: true, + ); + + checkAndPrintMigrateStatus( + manifest, + workingDir, + warnConflict: true, + logger: logger, + ); + + expect( + logger.statusText, + contains(''' Added files: - added_file Deleted files: @@ -96,14 +114,19 @@ Deleted files: Modified files: - conflict_file - merged_file -''')); - }); - - testWithoutContext('populated MigrateResult detects fixed conflict', - () async { - final Directory workingDir = fileSystem.directory('migrate_working_dir'); - workingDir.createSync(recursive: true); - final MigrateManifest manifest = MigrateManifest( +'''), + ); + }, + ); + + testWithoutContext( + 'populated MigrateResult detects fixed conflict', + () async { + final Directory workingDir = fileSystem.directory( + 'migrate_working_dir', + ); + workingDir.createSync(recursive: true); + final MigrateManifest manifest = MigrateManifest( migrateRootDir: workingDir, migrateResult: MigrateResult( mergeResults: [ @@ -122,26 +145,37 @@ Modified files: ), ], addedFiles: [ - FilePendingMigration('added_file', fileSystem.file('added_file')) + FilePendingMigration('added_file', fileSystem.file('added_file')), ], deletedFiles: [ FilePendingMigration( - 'deleted_file', fileSystem.file('deleted_file')) + 'deleted_file', + fileSystem.file('deleted_file'), + ), ], // The following are ignored by the manifest. mergeTypeMap: {'test': MergeType.threeWay}, diffMap: {}, tempDirectories: [], sdkDirs: {}, - )); - - final File conflictFile = workingDir.childFile('conflict_file'); - conflictFile.writeAsStringSync('hello\nwow a bunch of lines\nhi\n', - flush: true); - - checkAndPrintMigrateStatus(manifest, workingDir, - warnConflict: true, logger: logger); - expect(logger.statusText, contains(''' + ), + ); + + final File conflictFile = workingDir.childFile('conflict_file'); + conflictFile.writeAsStringSync( + 'hello\nwow a bunch of lines\nhi\n', + flush: true, + ); + + checkAndPrintMigrateStatus( + manifest, + workingDir, + warnConflict: true, + logger: logger, + ); + expect( + logger.statusText, + contains(''' Added files: - added_file Deleted files: @@ -149,8 +183,10 @@ Deleted files: Modified files: - conflict_file - merged_file -''')); - }); +'''), + ); + }, + ); }); group('manifest file parsing', () { @@ -161,8 +197,10 @@ Modified files: MigrateManifest.fromFile(manifestFile); } on Exception catch (e) { exceptionFound = true; - expect(e.toString(), - 'Exception: Invalid .migrate_manifest file in the migrate working directory. File is not a Yaml map.'); + expect( + e.toString(), + 'Exception: Invalid .migrate_manifest file in the migrate working directory. File is not a Yaml map.', + ); } expect(exceptionFound, true); }); @@ -179,8 +217,10 @@ Modified files: MigrateManifest.fromFile(manifestFile); } on Exception catch (e) { exceptionFound = true; - expect(e.toString(), - 'Exception: Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.'); + expect( + e.toString(), + 'Exception: Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.', + ); } expect(exceptionFound, true); }); @@ -196,8 +236,10 @@ Modified files: MigrateManifest.fromFile(manifestFile); } on Exception catch (e) { exceptionFound = true; - expect(e.toString(), - 'Exception: Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.'); + expect( + e.toString(), + 'Exception: Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.', + ); } expect(exceptionFound, true); }); @@ -215,8 +257,10 @@ Modified files: MigrateManifest.fromFile(manifestFile); } on Exception catch (e) { exceptionFound = true; - expect(e.toString(), - 'Exception: Invalid .migrate_manifest file in the migrate working directory. Entry is not a Yaml list.'); + expect( + e.toString(), + 'Exception: Invalid .migrate_manifest file in the migrate working directory. Entry is not a Yaml list.', + ); } expect(exceptionFound, true); }); @@ -309,16 +353,17 @@ Modified files: group('manifest MigrateResult creation', () { testWithoutContext('empty MigrateResult', () async { final MigrateManifest manifest = MigrateManifest( - migrateRootDir: fileSystem.directory('root'), - migrateResult: MigrateResult( - mergeResults: [], - addedFiles: [], - deletedFiles: [], - mergeTypeMap: {}, - diffMap: {}, - tempDirectories: [], - sdkDirs: {}, - )); + migrateRootDir: fileSystem.directory('root'), + migrateResult: MigrateResult( + mergeResults: [], + addedFiles: [], + deletedFiles: [], + mergeTypeMap: {}, + diffMap: {}, + tempDirectories: [], + sdkDirs: {}, + ), + ); expect(manifest.mergedFiles.isEmpty, true); expect(manifest.conflictFiles.isEmpty, true); expect(manifest.addedFiles.isEmpty, true); @@ -327,35 +372,38 @@ Modified files: testWithoutContext('simple MigrateResult', () async { final MigrateManifest manifest = MigrateManifest( - migrateRootDir: fileSystem.directory('root'), - migrateResult: MigrateResult( - mergeResults: [ - StringMergeResult.explicit( - localPath: 'merged_file', - mergedString: 'str', - hasConflict: false, - exitCode: 0, - ), - StringMergeResult.explicit( - localPath: 'conflict_file', - mergedString: '<<<<<<<<<<<', - hasConflict: true, - exitCode: 1, - ), - ], - addedFiles: [ - FilePendingMigration('added_file', fileSystem.file('added_file')) - ], - deletedFiles: [ - FilePendingMigration( - 'deleted_file', fileSystem.file('deleted_file')) - ], - // The following are ignored by the manifest. - mergeTypeMap: {'test': MergeType.threeWay}, - diffMap: {}, - tempDirectories: [], - sdkDirs: {}, - )); + migrateRootDir: fileSystem.directory('root'), + migrateResult: MigrateResult( + mergeResults: [ + StringMergeResult.explicit( + localPath: 'merged_file', + mergedString: 'str', + hasConflict: false, + exitCode: 0, + ), + StringMergeResult.explicit( + localPath: 'conflict_file', + mergedString: '<<<<<<<<<<<', + hasConflict: true, + exitCode: 1, + ), + ], + addedFiles: [ + FilePendingMigration('added_file', fileSystem.file('added_file')), + ], + deletedFiles: [ + FilePendingMigration( + 'deleted_file', + fileSystem.file('deleted_file'), + ), + ], + // The following are ignored by the manifest. + mergeTypeMap: {'test': MergeType.threeWay}, + diffMap: {}, + tempDirectories: [], + sdkDirs: {}, + ), + ); expect(manifest.mergedFiles.isEmpty, false); expect(manifest.conflictFiles.isEmpty, false); expect(manifest.addedFiles.isEmpty, false); diff --git a/packages/flutter_migrate/test/migrate_test.dart b/packages/flutter_migrate/test/migrate_test.dart index f07085bfbd5..e580e214f58 100644 --- a/packages/flutter_migrate/test/migrate_test.dart +++ b/packages/flutter_migrate/test/migrate_test.dart @@ -36,10 +36,16 @@ void main() { Future hasFlutterEnvironment() async { final String flutterRoot = getFlutterRoot(); - final String flutterExecutable = fileSystem.path - .join(flutterRoot, 'bin', 'flutter${isWindows ? '.bat' : ''}'); - final ProcessResult result = await Process.run( - flutterExecutable, ['analyze', '--suggestions', '--machine']); + final String flutterExecutable = fileSystem.path.join( + flutterRoot, + 'bin', + 'flutter${isWindows ? '.bat' : ''}', + ); + final ProcessResult result = await Process.run(flutterExecutable, [ + 'analyze', + '--suggestions', + '--machine', + ]); if (result.exitCode != 0) { return false; } @@ -47,21 +53,26 @@ void main() { } // Migrates a clean untouched app generated with flutter create - testUsingContext('vanilla migrate process succeeds', () async { - // This tool does not support old versions of flutter that dont include - // `flutter analyze --suggestions --machine` command - if (!await hasFlutterEnvironment()) { - return; - } - // Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6 - await MigrateProject.installProject('version:1.22.6_stable', tempDir); - - ProcessResult result = await runMigrateCommand([ - 'start', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.stdout.toString(), contains('Staging directory created at')); - const String linesToMatch = ''' + testUsingContext( + 'vanilla migrate process succeeds', + () async { + // This tool does not support old versions of flutter that dont include + // `flutter analyze --suggestions --machine` command + if (!await hasFlutterEnvironment()) { + return; + } + // Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6 + await MigrateProject.installProject('version:1.22.6_stable', tempDir); + + ProcessResult result = await runMigrateCommand([ + 'start', + '--verbose', + ], workingDirectory: tempDir.path); + expect( + result.stdout.toString(), + contains('Staging directory created at'), + ); + const String linesToMatch = ''' Added files: - android/app/src/main/res/values-night/styles.xml - android/app/src/main/res/drawable-v21/launch_background.xml @@ -83,44 +94,52 @@ Modified files: - android/gradle/wrapper/gradle-wrapper.properties - android/.gitignore - android/build.gradle'''; - for (final String line in linesToMatch.split('\n')) { - expect(result.stdout.toString(), contains(line)); - } - - result = await runMigrateCommand([ - 'apply', - '--verbose', - ], workingDirectory: tempDir.path); - logger.printStatus('${result.exitCode}', color: TerminalColor.blue); - logger.printStatus(result.stdout as String, color: TerminalColor.green); - logger.printStatus(result.stderr as String, color: TerminalColor.red); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Migration complete')); - - expect(tempDir.childFile('.metadata').readAsStringSync(), - contains('migration:\n platforms:\n - platform: root\n')); - - expect( + for (final String line in linesToMatch.split('\n')) { + expect(result.stdout.toString(), contains(line)); + } + + result = await runMigrateCommand([ + 'apply', + '--verbose', + ], workingDirectory: tempDir.path); + logger.printStatus('${result.exitCode}', color: TerminalColor.blue); + logger.printStatus(result.stdout as String, color: TerminalColor.green); + logger.printStatus(result.stderr as String, color: TerminalColor.red); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('Migration complete')); + + expect( + tempDir.childFile('.metadata').readAsStringSync(), + contains('migration:\n platforms:\n - platform: root\n'), + ); + + expect( tempDir .childFile('android/app/src/main/res/values-night/styles.xml') .existsSync(), - true); - expect(tempDir.childFile('analysis_options.yaml').existsSync(), true); - }, - timeout: const Timeout(Duration(seconds: 500)), - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: true); + true, + ); + expect(tempDir.childFile('analysis_options.yaml').existsSync(), true); + }, + timeout: const Timeout(Duration(seconds: 500)), + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: true, + ); // Migrates a clean untouched app generated with flutter create - testUsingContext('vanilla migrate builds', () async { - // This tool does not support old versions of flutter that dont include - // `flutter analyze --suggestions --machine` command - if (!await hasFlutterEnvironment()) { - return; - } - // Flutter Stable 2.0.0 hash: 60bd88df915880d23877bfc1602e8ddcf4c4dd2a - await MigrateProject.installProject('version:2.0.0_stable', tempDir, + testUsingContext( + 'vanilla migrate builds', + () async { + // This tool does not support old versions of flutter that dont include + // `flutter analyze --suggestions --machine` command + if (!await hasFlutterEnvironment()) { + return; + } + // Flutter Stable 2.0.0 hash: 60bd88df915880d23877bfc1602e8ddcf4c4dd2a + await MigrateProject.installProject( + 'version:2.0.0_stable', + tempDir, main: ''' import 'package:flutter/material.dart'; @@ -143,118 +162,139 @@ class MyApp extends StatelessWidget { ); } } -'''); - ProcessResult result = await runMigrateCommand([ - 'start', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.stdout.toString(), contains('Staging directory created at')); - - result = await runMigrateCommand([ - 'apply', - '--verbose', - ], workingDirectory: tempDir.path); - logger.printStatus('${result.exitCode}', color: TerminalColor.blue); - logger.printStatus(result.stdout as String, color: TerminalColor.green); - logger.printStatus(result.stderr as String, color: TerminalColor.red); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Migration complete')); - - result = await processManager.run([ - 'flutter', - 'build', - 'apk', - '--debug', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('app-debug.apk')); - // Skipped due to being flaky, the build completes successfully, but sometimes - // Gradle crashes due to resources on the bot. We should fine tune this to - // make it stable. - }, - timeout: const Timeout(Duration(seconds: 900)), - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: true); - - testUsingContext('migrate abandon', () async { - // Abandon in an empty dir fails. - ProcessResult result = await runMigrateCommand([ - 'abandon', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stderr.toString(), - contains('Error: No pubspec.yaml file found')); - expect( +''', + ); + ProcessResult result = await runMigrateCommand([ + 'start', + '--verbose', + ], workingDirectory: tempDir.path); + expect( + result.stdout.toString(), + contains('Staging directory created at'), + ); + + result = await runMigrateCommand([ + 'apply', + '--verbose', + ], workingDirectory: tempDir.path); + logger.printStatus('${result.exitCode}', color: TerminalColor.blue); + logger.printStatus(result.stdout as String, color: TerminalColor.green); + logger.printStatus(result.stderr as String, color: TerminalColor.red); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('Migration complete')); + + result = await processManager.run([ + 'flutter', + 'build', + 'apk', + '--debug', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('app-debug.apk')); + // Skipped due to being flaky, the build completes successfully, but sometimes + // Gradle crashes due to resources on the bot. We should fine tune this to + // make it stable. + }, + timeout: const Timeout(Duration(seconds: 900)), + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: true, + ); + + testUsingContext( + 'migrate abandon', + () async { + // Abandon in an empty dir fails. + ProcessResult result = await runMigrateCommand([ + 'abandon', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect( + result.stderr.toString(), + contains('Error: No pubspec.yaml file found'), + ); + expect( result.stderr.toString(), contains( - 'This command should be run from the root of your Flutter project')); - - final File manifestFile = - tempDir.childFile('migrate_staging_dir/.migrate_manifest'); - expect(manifestFile.existsSync(), false); - - // Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6 - await MigrateProject.installProject('version:1.22.6_stable', tempDir); - - // Initialized repo fails. - result = await runMigrateCommand([ - 'abandon', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('No migration in progress')); - - // Create migration. - manifestFile.createSync(recursive: true); - - // Directory with manifest_staging_dir succeeds. - result = await runMigrateCommand([ - 'abandon', - '--verbose', - '--force', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Abandon complete')); - }, - timeout: const Timeout(Duration(seconds: 300)), - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: true); + 'This command should be run from the root of your Flutter project', + ), + ); + + final File manifestFile = tempDir.childFile( + 'migrate_staging_dir/.migrate_manifest', + ); + expect(manifestFile.existsSync(), false); + + // Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6 + await MigrateProject.installProject('version:1.22.6_stable', tempDir); + + // Initialized repo fails. + result = await runMigrateCommand([ + 'abandon', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('No migration in progress')); + + // Create migration. + manifestFile.createSync(recursive: true); + + // Directory with manifest_staging_dir succeeds. + result = await runMigrateCommand([ + 'abandon', + '--verbose', + '--force', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('Abandon complete')); + }, + timeout: const Timeout(Duration(seconds: 300)), + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: true, + ); // Migrates a user-modified app - testUsingContext('modified migrate process succeeds', () async { - // This tool does not support old versions of flutter that dont include - // `flutter analyze --suggestions --machine` command - if (!await hasFlutterEnvironment()) { - return; - } - // Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6 - await MigrateProject.installProject('version:1.22.6_stable', tempDir, - vanilla: false); - - ProcessResult result = await runMigrateCommand([ - 'apply', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('No migration')); - - result = await runMigrateCommand([ - 'status', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('No migration')); - - result = await runMigrateCommand([ - 'start', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Staging directory created at')); - const String linesToMatch = ''' + testUsingContext( + 'modified migrate process succeeds', + () async { + // This tool does not support old versions of flutter that dont include + // `flutter analyze --suggestions --machine` command + if (!await hasFlutterEnvironment()) { + return; + } + // Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6 + await MigrateProject.installProject( + 'version:1.22.6_stable', + tempDir, + vanilla: false, + ); + + ProcessResult result = await runMigrateCommand([ + 'apply', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('No migration')); + + result = await runMigrateCommand([ + 'status', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('No migration')); + + result = await runMigrateCommand([ + 'start', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect( + result.stdout.toString(), + contains('Staging directory created at'), + ); + const String linesToMatch = ''' Modified files: - .metadata - ios/Runner/Info.plist @@ -273,35 +313,38 @@ Modified files: - android/build.gradle Merge conflicted files: - pubspec.yaml'''; - for (final String line in linesToMatch.split('\n')) { - expect(result.stdout.toString(), contains(line)); - } - - // Call apply with conflicts remaining. Should fail. - result = await runMigrateCommand([ - 'apply', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect( + for (final String line in linesToMatch.split('\n')) { + expect(result.stdout.toString(), contains(line)); + } + + // Call apply with conflicts remaining. Should fail. + result = await runMigrateCommand([ + 'apply', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect( result.stdout.toString(), contains( - 'Conflicting files found. Resolve these conflicts and try again.')); - expect(result.stdout.toString(), contains('- pubspec.yaml')); - - result = await runMigrateCommand([ - 'status', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Modified files')); - expect(result.stdout.toString(), contains('Merge conflicted files')); - - // Manually resolve conflics. The correct contents for resolution may change over time, - // but it shouldnt matter for this test. - final File metadataFile = - tempDir.childFile('migrate_staging_dir/.metadata'); - metadataFile.writeAsStringSync(''' + 'Conflicting files found. Resolve these conflicts and try again.', + ), + ); + expect(result.stdout.toString(), contains('- pubspec.yaml')); + + result = await runMigrateCommand([ + 'status', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('Modified files')); + expect(result.stdout.toString(), contains('Merge conflicted files')); + + // Manually resolve conflics. The correct contents for resolution may change over time, + // but it shouldnt matter for this test. + final File metadataFile = tempDir.childFile( + 'migrate_staging_dir/.metadata', + ); + metadataFile.writeAsStringSync(''' # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # @@ -314,9 +357,10 @@ version: project_type: app ''', flush: true); - final File pubspecYamlFile = - tempDir.childFile('migrate_staging_dir/pubspec.yaml'); - pubspecYamlFile.writeAsStringSync(''' + final File pubspecYamlFile = tempDir.childFile( + 'migrate_staging_dir/pubspec.yaml', + ); + pubspecYamlFile.writeAsStringSync(''' name: vanilla_app_1_22_6_stable description: This is a modified description from the default. @@ -409,48 +453,65 @@ flutter: ''', flush: true); - result = await runMigrateCommand([ - 'status', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Modified files')); - expect(result.stdout.toString(), contains('diff --git')); - expect(result.stdout.toString(), contains('@@')); - expect(result.stdout.toString(), isNot(contains('Merge conflicted files'))); - - result = await runMigrateCommand([ - 'apply', - '--verbose', - ], workingDirectory: tempDir.path); - expect(result.exitCode, 0); - expect(result.stdout.toString(), contains('Migration complete')); - - expect(tempDir.childFile('.metadata').readAsStringSync(), - contains('e96a72392696df66755ca246ff291dfc6ca6c4ad')); - expect(tempDir.childFile('pubspec.yaml').readAsStringSync(), - isNot(contains('">=2.6.0 <3.0.0"'))); - expect(tempDir.childFile('pubspec.yaml').readAsStringSync(), - contains('">=2.17.0-79.0.dev <3.0.0"')); - expect( + result = await runMigrateCommand([ + 'status', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('Modified files')); + expect(result.stdout.toString(), contains('diff --git')); + expect(result.stdout.toString(), contains('@@')); + expect( + result.stdout.toString(), + isNot(contains('Merge conflicted files')), + ); + + result = await runMigrateCommand([ + 'apply', + '--verbose', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + expect(result.stdout.toString(), contains('Migration complete')); + + expect( + tempDir.childFile('.metadata').readAsStringSync(), + contains('e96a72392696df66755ca246ff291dfc6ca6c4ad'), + ); + expect( + tempDir.childFile('pubspec.yaml').readAsStringSync(), + isNot(contains('">=2.6.0 <3.0.0"')), + ); + expect( + tempDir.childFile('pubspec.yaml').readAsStringSync(), + contains('">=2.17.0-79.0.dev <3.0.0"'), + ); + expect( tempDir.childFile('pubspec.yaml').readAsStringSync(), contains( - 'description: This is a modified description from the default.')); - expect(tempDir.childFile('lib/main.dart').readAsStringSync(), - contains('OtherWidget()')); - expect(tempDir.childFile('lib/other.dart').existsSync(), true); - expect(tempDir.childFile('lib/other.dart').readAsStringSync(), - contains('class OtherWidget')); - - expect( + 'description: This is a modified description from the default.', + ), + ); + expect( + tempDir.childFile('lib/main.dart').readAsStringSync(), + contains('OtherWidget()'), + ); + expect(tempDir.childFile('lib/other.dart').existsSync(), true); + expect( + tempDir.childFile('lib/other.dart').readAsStringSync(), + contains('class OtherWidget'), + ); + + expect( tempDir .childFile('android/app/src/main/res/values-night/styles.xml') .existsSync(), - true); - expect(tempDir.childFile('analysis_options.yaml').existsSync(), true); - }, - timeout: const Timeout(Duration(seconds: 500)), - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: true); + true, + ); + expect(tempDir.childFile('analysis_options.yaml').existsSync(), true); + }, + timeout: const Timeout(Duration(seconds: 500)), + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: true, + ); } diff --git a/packages/flutter_migrate/test/src/common.dart b/packages/flutter_migrate/test/src/common.dart index a354020d47a..6abed2fff34 100644 --- a/packages/flutter_migrate/test/src/common.dart +++ b/packages/flutter_migrate/test/src/common.dart @@ -46,7 +46,8 @@ String getFlutterRoot() { } Error invalidScript() => StateError( - 'Could not determine flutter_tools/ path from script URL (${io.Platform.script}); consider setting FLUTTER_ROOT explicitly.'); + 'Could not determine flutter_tools/ path from script URL (${io.Platform.script}); consider setting FLUTTER_ROOT explicitly.', + ); Uri scriptUri; switch (io.Platform.script.scheme) { @@ -54,10 +55,12 @@ String getFlutterRoot() { scriptUri = io.Platform.script; case 'data': final RegExp flutterTools = RegExp( - r'(file://[^"]*[/\\]flutter_tools[/\\][^"]+\.dart)', - multiLine: true); - final Match? match = - flutterTools.firstMatch(Uri.decodeFull(io.Platform.script.path)); + r'(file://[^"]*[/\\]flutter_tools[/\\][^"]+\.dart)', + multiLine: true, + ); + final Match? match = flutterTools.firstMatch( + Uri.decodeFull(io.Platform.script.path), + ); if (match == null) { throw invalidScript(); } @@ -80,12 +83,17 @@ String getMigratePackageRoot() { } String getMigrateMain() { - return fileSystem.path - .join(getMigratePackageRoot(), 'bin', 'flutter_migrate.dart'); + return fileSystem.path.join( + getMigratePackageRoot(), + 'bin', + 'flutter_migrate.dart', + ); } -Future runMigrateCommand(List args, - {String? workingDirectory}) { +Future runMigrateCommand( + List args, { + String? workingDirectory, +}) { final List commandArgs = ['dart', 'run', getMigrateMain()]; commandArgs.addAll(args); return processManager.run(commandArgs, workingDirectory: workingDirectory); @@ -148,9 +156,10 @@ void testWithoutContext( return test( description, () async { - return runZoned(body, zoneValues: { - contextKey: const _NoContext(), - }); + return runZoned( + body, + zoneValues: {contextKey: const _NoContext()}, + ); }, skip: skip, tags: tags, @@ -173,9 +182,11 @@ class _NoContext implements AppContext { @override T get() { - throw UnsupportedError('context.get<$T> is not supported in test methods. ' - 'Use Testbed or testUsingContext if accessing Zone injected ' - 'values.'); + throw UnsupportedError( + 'context.get<$T> is not supported in test methods. ' + 'Use Testbed or testUsingContext if accessing Zone injected ' + 'values.', + ); } @override diff --git a/packages/flutter_migrate/test/src/context.dart b/packages/flutter_migrate/test/src/context.dart index 961d6d3537f..680fa9dd4b0 100644 --- a/packages/flutter_migrate/test/src/context.dart +++ b/packages/flutter_migrate/test/src/context.dart @@ -26,13 +26,14 @@ void testUsingContext( String? testOn, Timeout? timeout, bool? - skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this + skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this }) { if (overrides[FileSystem] != null && overrides[ProcessManager] == null) { throw StateError( - 'If you override the FileSystem context you must also provide a ProcessManager, ' - 'otherwise the processes you launch will not be dealing with the same file system ' - 'that you are dealing with in your test.'); + 'If you override the FileSystem context you must also provide a ProcessManager, ' + 'otherwise the processes you launch will not be dealing with the same file system ' + 'that you are dealing with in your test.', + ); } // Ensure we don't rely on the default [Config] constructor which will @@ -45,50 +46,59 @@ void testUsingContext( } }); - test(description, () async { - await runInContext(() { - return context.run( - name: 'mocks', - overrides: { - AnsiTerminal: () => AnsiTerminal(stdio: FakeStdio()), - OutputPreferences: () => OutputPreferences.test(), - Logger: () => BufferLogger.test(), - ProcessManager: () => const LocalProcessManager(), - }, - body: () { - return runZonedGuarded>(() { - try { - return context.run( - // Apply the overrides to the test context in the zone since their - // instantiation may reference items already stored on the context. - overrides: overrides, - name: 'test-specific overrides', - body: () async { - if (initializeFlutterRoot) { - // Provide a sane default for the flutterRoot directory. Individual - // tests can override this either in the test or during setup. - // Cache.flutterRoot ??= flutterRoot; - } - return await testMethod(); - }, - ); - // This catch rethrows, so doesn't need to catch only Exception. - } catch (error) { - // ignore: avoid_catches_without_on_clauses - _printBufferedErrors(context); - rethrow; - } - }, (Object error, StackTrace stackTrace) { - // When things fail, it's ok to print to the console! - print(error); // ignore: avoid_print - print(stackTrace); // ignore: avoid_print - _printBufferedErrors(context); - throw error; //ignore: only_throw_errors - }); - }, - ); - }, overrides: {}); - }, testOn: testOn, skip: skip, timeout: timeout); + test( + description, + () async { + await runInContext(() { + return context.run( + name: 'mocks', + overrides: { + AnsiTerminal: () => AnsiTerminal(stdio: FakeStdio()), + OutputPreferences: () => OutputPreferences.test(), + Logger: () => BufferLogger.test(), + ProcessManager: () => const LocalProcessManager(), + }, + body: () { + return runZonedGuarded>( + () { + try { + return context.run( + // Apply the overrides to the test context in the zone since their + // instantiation may reference items already stored on the context. + overrides: overrides, + name: 'test-specific overrides', + body: () async { + if (initializeFlutterRoot) { + // Provide a sane default for the flutterRoot directory. Individual + // tests can override this either in the test or during setup. + // Cache.flutterRoot ??= flutterRoot; + } + return await testMethod(); + }, + ); + // This catch rethrows, so doesn't need to catch only Exception. + } catch (error) { + // ignore: avoid_catches_without_on_clauses + _printBufferedErrors(context); + rethrow; + } + }, + (Object error, StackTrace stackTrace) { + // When things fail, it's ok to print to the console! + print(error); // ignore: avoid_print + print(stackTrace); // ignore: avoid_print + _printBufferedErrors(context); + throw error; //ignore: only_throw_errors + }, + ); + }, + ); + }, overrides: {}); + }, + testOn: testOn, + skip: skip, + timeout: timeout, + ); } void _printBufferedErrors(AppContext testContext) { @@ -116,8 +126,9 @@ Future runInContext( } return context.run( - name: 'global fallbacks', - body: runnerWrapper, - overrides: overrides, - fallbacks: {}); + name: 'global fallbacks', + body: runnerWrapper, + overrides: overrides, + fallbacks: {}, + ); } diff --git a/packages/flutter_migrate/test/src/fakes.dart b/packages/flutter_migrate/test/src/fakes.dart index fda5a28879b..e8dcd5439e7 100644 --- a/packages/flutter_migrate/test/src/fakes.dart +++ b/packages/flutter_migrate/test/src/fakes.dart @@ -12,9 +12,7 @@ import 'package:test/fake.dart'; /// An IOSink that completes a future with the first line written to it. class CompleterIOSink extends MemoryIOSink { - CompleterIOSink({ - this.throwOnAdd = false, - }); + CompleterIOSink({this.throwOnAdd = false}); final bool throwOnAdd; @@ -116,8 +114,9 @@ class MemoryIOSink implements IOSink { } String getAndClear() { - final String result = - utf8.decode(writes.expand((List l) => l).toList()); + final String result = utf8.decode( + writes.expand((List l) => l).toList(), + ); clear(); return result; } @@ -276,12 +275,13 @@ class FakeStopwatch implements Stopwatch { } class FakeStopwatchFactory implements StopwatchFactory { - FakeStopwatchFactory( - {Stopwatch? stopwatch, Map? stopwatches}) - : stopwatches = { - if (stopwatches != null) ...stopwatches, - if (stopwatch != null) '': stopwatch, - }; + FakeStopwatchFactory({ + Stopwatch? stopwatch, + Map? stopwatches, + }) : stopwatches = { + if (stopwatches != null) ...stopwatches, + if (stopwatch != null) '': stopwatch, + }; Map stopwatches; diff --git a/packages/flutter_migrate/test/src/io.dart b/packages/flutter_migrate/test/src/io.dart index daabe43367c..fab7ca1d54c 100644 --- a/packages/flutter_migrate/test/src/io.dart +++ b/packages/flutter_migrate/test/src/io.dart @@ -18,7 +18,7 @@ import 'package:flutter_migrate/src/base/file_system.dart'; /// like the [MemoryFileSystem]. final class FlutterIOOverrides extends io.IOOverrides { FlutterIOOverrides({FileSystem? fileSystem}) - : _fileSystemDelegate = fileSystem; + : _fileSystemDelegate = fileSystem; final FileSystem? _fileSystemDelegate; diff --git a/packages/flutter_migrate/test/src/test_flutter_command_runner.dart b/packages/flutter_migrate/test/src/test_flutter_command_runner.dart index 9f4731dada0..fceaa322362 100644 --- a/packages/flutter_migrate/test/src/test_flutter_command_runner.dart +++ b/packages/flutter_migrate/test/src/test_flutter_command_runner.dart @@ -17,16 +17,16 @@ CommandRunner createTestCommandRunner([MigrateCommand? command]) { class TestCommandRunner extends CommandRunner { TestCommandRunner() - : super( - 'flutter', - 'Manage your Flutter app development.\n' - '\n' - 'Common commands:\n' - '\n' - ' flutter create \n' - ' Create a new Flutter project in the specified directory.\n' - '\n' - ' flutter run [options]\n' - ' Run your Flutter application on an attached device or in an emulator.', - ); + : super( + 'flutter', + 'Manage your Flutter app development.\n' + '\n' + 'Common commands:\n' + '\n' + ' flutter create \n' + ' Create a new Flutter project in the specified directory.\n' + '\n' + ' flutter run [options]\n' + ' Run your Flutter application on an attached device or in an emulator.', + ); } diff --git a/packages/flutter_migrate/test/src/test_utils.dart b/packages/flutter_migrate/test/src/test_utils.dart index b51e127a912..83399eaada2 100644 --- a/packages/flutter_migrate/test/src/test_utils.dart +++ b/packages/flutter_migrate/test/src/test_utils.dart @@ -12,8 +12,9 @@ import 'package:process/process.dart'; import 'common.dart'; /// The [FileSystem] for the integration test environment. -LocalFileSystem fileSystem = - LocalFileSystem.test(signals: LocalSignals.instance); +LocalFileSystem fileSystem = LocalFileSystem.test( + signals: LocalSignals.instance, +); /// The [ProcessManager] for the integration test environment. const ProcessManager processManager = LocalProcessManager(); @@ -23,16 +24,21 @@ const ProcessManager processManager = LocalProcessManager(); /// https://github.com/flutter/flutter/pull/21741 Directory createResolvedTempDirectorySync(String prefix) { assert(prefix.endsWith('.')); - final Directory tempDirectory = - fileSystem.systemTempDirectory.createTempSync('flutter_$prefix'); + final Directory tempDirectory = fileSystem.systemTempDirectory.createTempSync( + 'flutter_$prefix', + ); return fileSystem.directory(tempDirectory.resolveSymbolicLinksSync()); } -void writeFile(String path, String content, - {bool writeFutureModifiedDate = false}) { - final File file = fileSystem.file(path) - ..createSync(recursive: true) - ..writeAsStringSync(content, flush: true); +void writeFile( + String path, + String content, { + bool writeFutureModifiedDate = false, +}) { + final File file = + fileSystem.file(path) + ..createSync(recursive: true) + ..writeAsStringSync(content, flush: true); // Some integration tests on Windows to not see this file as being modified // recently enough for the hot reload to pick this change up unless the // modified time is written in the future. @@ -53,10 +59,13 @@ Future getPackages(String folder) async { 'pub', 'get', ]; - final ProcessResult result = - await processManager.run(command, workingDirectory: folder); + final ProcessResult result = await processManager.run( + command, + workingDirectory: folder, + ); if (result.exitCode != 0) { throw Exception( - 'flutter pub get failed: ${result.stderr}\n${result.stdout}'); + 'flutter pub get failed: ${result.stderr}\n${result.stdout}', + ); } } diff --git a/packages/flutter_migrate/test/status_test.dart b/packages/flutter_migrate/test/status_test.dart index 8cb546d5796..42624f90e01 100644 --- a/packages/flutter_migrate/test/status_test.dart +++ b/packages/flutter_migrate/test/status_test.dart @@ -31,18 +31,21 @@ void main() { tryToDelete(appDir); }); - testUsingContext('Status produces all outputs', () async { - final MigrateStatusCommand command = MigrateStatusCommand( - verbose: true, - logger: logger, - fileSystem: fileSystem, - processManager: processManager, - ); - final Directory stagingDir = - appDir.childDirectory(kDefaultMigrateStagingDirectoryName); - final File pubspecOriginal = appDir.childFile('pubspec.yaml'); - pubspecOriginal.createSync(); - pubspecOriginal.writeAsStringSync(''' + testUsingContext( + 'Status produces all outputs', + () async { + final MigrateStatusCommand command = MigrateStatusCommand( + verbose: true, + logger: logger, + fileSystem: fileSystem, + processManager: processManager, + ); + final Directory stagingDir = appDir.childDirectory( + kDefaultMigrateStagingDirectoryName, + ); + final File pubspecOriginal = appDir.childFile('pubspec.yaml'); + pubspecOriginal.createSync(); + pubspecOriginal.writeAsStringSync(''' name: originalname description: A new Flutter project. version: 1.0.0+1 @@ -57,9 +60,9 @@ dev_dependencies: flutter: uses-material-design: true''', flush: true); - final File pubspecModified = stagingDir.childFile('pubspec.yaml'); - pubspecModified.createSync(recursive: true); - pubspecModified.writeAsStringSync(''' + final File pubspecModified = stagingDir.childFile('pubspec.yaml'); + pubspecModified.createSync(recursive: true); + pubspecModified.writeAsStringSync(''' name: newname description: new description of the test project version: 1.0.0+1 @@ -75,13 +78,13 @@ flutter: uses-material-design: false EXTRALINE''', flush: true); - final File addedFile = stagingDir.childFile('added.file'); - addedFile.createSync(recursive: true); - addedFile.writeAsStringSync('new file contents'); + final File addedFile = stagingDir.childFile('added.file'); + addedFile.createSync(recursive: true); + addedFile.writeAsStringSync('new file contents'); - final File manifestFile = stagingDir.childFile('.migrate_manifest'); - manifestFile.createSync(recursive: true); - manifestFile.writeAsStringSync(''' + final File manifestFile = stagingDir.childFile('.migrate_manifest'); + manifestFile.createSync(recursive: true); + manifestFile.writeAsStringSync(''' merged_files: - pubspec.yaml conflict_files: @@ -90,18 +93,23 @@ added_files: deleted_files: '''); - await createTestCommandRunner(command).run([ - 'status', - '--staging-directory=${stagingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); + await createTestCommandRunner(command).run([ + 'status', + '--staging-directory=${stagingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); - expect(logger.statusText, contains(''' + expect( + logger.statusText, + contains(''' Newly added file at added.file: -new file contents''')); - expect(logger.statusText, contains(r''' +new file contents'''), + ); + expect( + logger.statusText, + contains(r''' Added files: - added.file Modified files: @@ -110,9 +118,12 @@ Modified files: All conflicts resolved. Review changes above and apply the migration with: $ flutter migrate apply -''')); +'''), + ); - expect(logger.statusText, contains(r''' + expect( + logger.statusText, + contains(r''' @@ -1,5 +1,5 @@ -name: originalname -description: A new Flutter project. @@ -128,13 +139,15 @@ All conflicts resolved. Review changes above and apply the migration with: - uses-material-design: true \ No newline at end of file + uses-material-design: false -+ EXTRALINE''')); - - // Add conflict file - final File conflictFile = - stagingDir.childDirectory('conflict').childFile('conflict.file'); - conflictFile.createSync(recursive: true); - conflictFile.writeAsStringSync(''' ++ EXTRALINE'''), + ); + + // Add conflict file + final File conflictFile = stagingDir + .childDirectory('conflict') + .childFile('conflict.file'); + conflictFile.createSync(recursive: true); + conflictFile.writeAsStringSync(''' line1 <<<<<<< /conflcit/conflict.file line2 @@ -143,16 +156,17 @@ linetwo >>>>>>> /var/folders/md/gm0zgfcj07vcsj6jkh_mp_wh00ff02/T/flutter_tools.4Xdep8/generatedTargetTemplatetlN44S/conflict/conflict.file line3 ''', flush: true); - final File conflictFileOriginal = - appDir.childDirectory('conflict').childFile('conflict.file'); - conflictFileOriginal.createSync(recursive: true); - conflictFileOriginal.writeAsStringSync(''' + final File conflictFileOriginal = appDir + .childDirectory('conflict') + .childFile('conflict.file'); + conflictFileOriginal.createSync(recursive: true); + conflictFileOriginal.writeAsStringSync(''' line1 line2 line3 ''', flush: true); - manifestFile.writeAsStringSync(''' + manifestFile.writeAsStringSync(''' merged_files: - pubspec.yaml conflict_files: @@ -162,24 +176,29 @@ added_files: deleted_files: '''); - logger.clear(); - await createTestCommandRunner(command).run([ - 'status', - '--staging-directory=${stagingDir.path}', - '--project-directory=${appDir.path}', - '--flutter-subcommand', - ]); - - expect(logger.statusText, contains(''' + logger.clear(); + await createTestCommandRunner(command).run([ + 'status', + '--staging-directory=${stagingDir.path}', + '--project-directory=${appDir.path}', + '--flutter-subcommand', + ]); + + expect( + logger.statusText, + contains(''' @@ -1,3 +1,7 @@ line1 +<<<<<<< /conflcit/conflict.file line2 +======= +linetwo -+>>>>>>>''')); - }, overrides: { - FileSystem: () => fileSystem, - ProcessManager: () => processManager, - }); ++>>>>>>>'''), + ); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }, + ); } diff --git a/packages/flutter_migrate/test/test_data/migrate_project.dart b/packages/flutter_migrate/test/test_data/migrate_project.dart index 2590834a4c5..36a41769c8b 100644 --- a/packages/flutter_migrate/test/test_data/migrate_project.dart +++ b/packages/flutter_migrate/test/test_data/migrate_project.dart @@ -27,10 +27,17 @@ class MigrateProject extends Project { late String _appPath; - static Future installProject(String verison, Directory dir, - {bool vanilla = true, String? main}) async { - final MigrateProject project = - MigrateProject(verison, vanilla: vanilla, main: main); + static Future installProject( + String verison, + Directory dir, { + bool vanilla = true, + String? main, + }) async { + final MigrateProject project = MigrateProject( + verison, + vanilla: vanilla, + main: main, + ); await project.setUpIn(dir); // Init a git repo to test uncommitted changes checks @@ -68,11 +75,14 @@ class MigrateProject extends Project { }) async { this.dir = dir; _appPath = dir.path; - writeFile(fileSystem.path.join(dir.path, 'android', 'local.properties'), - androidLocalProperties); + writeFile( + fileSystem.path.join(dir.path, 'android', 'local.properties'), + androidLocalProperties, + ); final Directory tempDir = createResolvedTempDirectorySync('cipd_dest.'); - final Directory depotToolsDir = - createResolvedTempDirectorySync('depot_tools.'); + final Directory depotToolsDir = createResolvedTempDirectorySync( + 'depot_tools.', + ); await processManager.run([ 'git', @@ -81,8 +91,9 @@ class MigrateProject extends Project { depotToolsDir.path, ], workingDirectory: dir.path); - final File cipdFile = - depotToolsDir.childFile(Platform.isWindows ? 'cipd.bat' : 'cipd'); + final File cipdFile = depotToolsDir.childFile( + Platform.isWindows ? 'cipd.bat' : 'cipd', + ); await processManager.run([ cipdFile.path, 'init', @@ -111,12 +122,7 @@ class MigrateProject extends Project { ]); // Robocopy exit code 1 means some files were copied. 0 means no files were copied. assert(res.exitCode == 1); - res = await processManager.run([ - 'takeown', - '/f', - dir.path, - '/r', - ]); + res = await processManager.run(['takeown', '/f', dir.path, '/r']); res = await processManager.run([ 'takeown', '/f', @@ -183,9 +189,10 @@ class MigrateProject extends Project { // Maintain the same pubspec as the configured app. @override - String get pubspec => fileSystem - .file(fileSystem.path.join(_appPath, 'pubspec.yaml')) - .readAsStringSync(); + String get pubspec => + fileSystem + .file(fileSystem.path.join(_appPath, 'pubspec.yaml')) + .readAsStringSync(); String get androidLocalProperties => ''' flutter.sdk=${getFlutterRoot()} diff --git a/packages/flutter_migrate/test/test_data/project.dart b/packages/flutter_migrate/test/test_data/project.dart index 5182f50c9fe..00894442883 100644 --- a/packages/flutter_migrate/test/test_data/project.dart +++ b/packages/flutter_migrate/test/test_data/project.dart @@ -41,19 +41,27 @@ abstract class Project { final String? generatedFile = this.generatedFile; if (generatedFile != null) { writeFile( - fileSystem.path - .join(dir.path, '.dart_tool', 'flutter_gen', 'flutter_gen.dart'), - generatedFile); + fileSystem.path.join( + dir.path, + '.dart_tool', + 'flutter_gen', + 'flutter_gen.dart', + ), + generatedFile, + ); } writeFile( - fileSystem.path.join(dir.path, 'web', 'index.html'), _kDefaultHtml); + fileSystem.path.join(dir.path, 'web', 'index.html'), + _kDefaultHtml, + ); writePackages(dir.path); await getPackages(dir.path); } int lineContaining(String contents, String search) { - final int index = - contents.split('\n').indexWhere((String l) => l.contains(search)); + final int index = contents + .split('\n') + .indexWhere((String l) => l.contains(search)); if (index == -1) { throw Exception("Did not find '$search' inside the file"); } diff --git a/packages/flutter_migrate/test/update_locks_test.dart b/packages/flutter_migrate/test/update_locks_test.dart index 94fa8d95e89..675ac79e9a7 100644 --- a/packages/flutter_migrate/test/update_locks_test.dart +++ b/packages/flutter_migrate/test/update_locks_test.dart @@ -49,7 +49,7 @@ void main() { 'flutter', 'create', currentDir.absolute.path, - '--project-name=testproject' + '--project-name=testproject', ]); expect(result.exitCode, 0); final File pubspec = currentDir.childFile('pubspec.yaml'); @@ -77,59 +77,75 @@ flutter: # PUBSPEC CHECKSUM: 1b91 ''', flush: true); - await updatePubspecDependencies(flutterProject, utils, logger, terminal, - force: true); + await updatePubspecDependencies( + flutterProject, + utils, + logger, + terminal, + force: true, + ); final YamlMap pubspecYaml = loadYaml(pubspec.readAsStringSync()) as YamlMap; final YamlMap dependenciesMap = pubspecYaml['dependencies'] as YamlMap; expect( - _VersionCode.fromString(dependenciesMap['characters'] as String) > - _VersionCode.fromString('1.2.0'), - true); + _VersionCode.fromString(dependenciesMap['characters'] as String) > + _VersionCode.fromString('1.2.0'), + true, + ); expect( - _VersionCode.fromString(dependenciesMap['collection'] as String) > - _VersionCode.fromString('1.15.0'), - true); + _VersionCode.fromString(dependenciesMap['collection'] as String) > + _VersionCode.fromString('1.15.0'), + true, + ); expect( - _VersionCode.fromString(dependenciesMap['js'] as String) > - _VersionCode.fromString('0.6.3'), - true); + _VersionCode.fromString(dependenciesMap['js'] as String) > + _VersionCode.fromString('0.6.3'), + true, + ); expect( - _VersionCode.fromString( - dependenciesMap['material_color_utilities'] as String) > - _VersionCode.fromString('0.1.0'), - true); + _VersionCode.fromString( + dependenciesMap['material_color_utilities'] as String, + ) > + _VersionCode.fromString('0.1.0'), + true, + ); expect( - _VersionCode.fromString(dependenciesMap['meta'] as String) > - _VersionCode.fromString('1.7.0'), - true); + _VersionCode.fromString(dependenciesMap['meta'] as String) > + _VersionCode.fromString('1.7.0'), + true, + ); }); - testWithoutContext('updates gradle locks', () async { - final ProcessResult result = await processManager.run([ - 'flutter', - 'create', - currentDir.absolute.path, - '--project-name=testproject' - ]); - expect(result.exitCode, 0); - final File projectAppLock = - currentDir.childDirectory('android').childFile('project-app.lockfile'); - final File buildGradle = - currentDir.childDirectory('android').childFile('build.gradle'); - final File gradleProperties = - currentDir.childDirectory('android').childFile('gradle.properties'); - gradleProperties.writeAsStringSync(''' + testWithoutContext( + 'updates gradle locks', + () async { + final ProcessResult result = await processManager.run([ + 'flutter', + 'create', + currentDir.absolute.path, + '--project-name=testproject', + ]); + expect(result.exitCode, 0); + final File projectAppLock = currentDir + .childDirectory('android') + .childFile('project-app.lockfile'); + final File buildGradle = currentDir + .childDirectory('android') + .childFile('build.gradle'); + final File gradleProperties = currentDir + .childDirectory('android') + .childFile('gradle.properties'); + gradleProperties.writeAsStringSync(''' org.gradle.daemon=false org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true ''', flush: true); - final File projectAppLockBackup = currentDir - .childDirectory('android') - .childFile('project-app.lockfile_backup_0'); - expect(projectAppLockBackup.existsSync(), false); - projectAppLock.createSync(recursive: true); - projectAppLock.writeAsStringSync(''' + final File projectAppLockBackup = currentDir + .childDirectory('android') + .childFile('project-app.lockfile_backup_0'); + expect(projectAppLockBackup.existsSync(), false); + projectAppLock.createSync(recursive: true); + projectAppLock.writeAsStringSync(''' # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. @@ -138,7 +154,7 @@ androidx.annotation:annotation-experimental:1.1.0=debugAndroidTestCompileClasspa androidx.annotation:annotation:1.2.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath ''', flush: true); - buildGradle.writeAsStringSync(r''' + buildGradle.writeAsStringSync(r''' buildscript { ext.kotlin_version = '1.5.31' repositories { @@ -180,36 +196,53 @@ subprojects { } ''', flush: true); - expect( + expect( currentDir .childDirectory('android') .childFile('gradlew.bat') .existsSync(), - true); - final Directory dotGradle = - currentDir.childDirectory('android').childDirectory('.gradle'); - tryToDelete(dotGradle); - await updateGradleDependencyLocking( - flutterProject, utils, logger, terminal, true, fileSystem, - force: true); - expect(projectAppLockBackup.existsSync(), true); - expect(projectAppLock.existsSync(), true); - expect(projectAppLock.readAsStringSync(), - contains('# This is a Gradle generated file for dependency locking.')); - expect(projectAppLock.readAsStringSync(), - contains('# Manual edits can break the build and are not advised.')); - expect(projectAppLock.readAsStringSync(), - contains('# This file is expected to be part of source control.')); - }, timeout: const Timeout(Duration(seconds: 500)), skip: true); + true, + ); + final Directory dotGradle = currentDir + .childDirectory('android') + .childDirectory('.gradle'); + tryToDelete(dotGradle); + await updateGradleDependencyLocking( + flutterProject, + utils, + logger, + terminal, + true, + fileSystem, + force: true, + ); + expect(projectAppLockBackup.existsSync(), true); + expect(projectAppLock.existsSync(), true); + expect( + projectAppLock.readAsStringSync(), + contains('# This is a Gradle generated file for dependency locking.'), + ); + expect( + projectAppLock.readAsStringSync(), + contains('# Manual edits can break the build and are not advised.'), + ); + expect( + projectAppLock.readAsStringSync(), + contains('# This file is expected to be part of source control.'), + ); + }, + timeout: const Timeout(Duration(seconds: 500)), + skip: true, + ); } class _VersionCode implements Comparable<_VersionCode> { _VersionCode(this.first, this.second, this.third, this.caret); _VersionCode.fromString(String str) - : first = 0, - second = 0, - third = 0, - caret = 0 { + : first = 0, + second = 0, + third = 0, + caret = 0 { caret = str.contains('^') ? 1 : 0; str = str.replaceAll('^', ''); final List splits = str.split('.'); diff --git a/packages/flutter_migrate/test/utils_test.dart b/packages/flutter_migrate/test/utils_test.dart index 4c52156d9a6..bed6746f6c8 100644 --- a/packages/flutter_migrate/test/utils_test.dart +++ b/packages/flutter_migrate/test/utils_test.dart @@ -33,8 +33,9 @@ void main() { group('git', () { setUp(() async { - projectRoot = fileSystem.systemTempDirectory - .createTempSync('flutter_migrate_utils_test'); + projectRoot = fileSystem.systemTempDirectory.createTempSync( + 'flutter_migrate_utils_test', + ); projectRoot.createSync(recursive: true); projectRootPath = projectRoot.path; }); @@ -61,9 +62,13 @@ void main() { ..writeAsStringSync('ignored_file.dart', flush: true); expect( - await utils.isGitIgnored('ignored_file.dart', projectRootPath), true); + await utils.isGitIgnored('ignored_file.dart', projectRootPath), + true, + ); expect( - await utils.isGitIgnored('other_file.dart', projectRootPath), false); + await utils.isGitIgnored('other_file.dart', projectRootPath), + false, + ); }); testWithoutContext('isGitRepo', () async { @@ -88,10 +93,15 @@ void main() { ..createSync() ..writeAsStringSync('ignored_file.dart', flush: true); - await Process.run('git', ['add', '.'], - workingDirectory: projectRootPath); - await Process.run('git', ['commit', '-m', 'Initial commit'], - workingDirectory: projectRootPath); + await Process.run('git', [ + 'add', + '.', + ], workingDirectory: projectRootPath); + await Process.run('git', [ + 'commit', + '-m', + 'Initial commit', + ], workingDirectory: projectRootPath); expect(await utils.hasUncommittedChanges(projectRootPath), false); }); @@ -109,19 +119,24 @@ void main() { expect(await utils.hasUncommittedChanges(projectRootPath), true); }); - testWithoutContext('logging hasUncommittedChanges true on dirty repo', - () async { - expect(projectRoot.existsSync(), true); - expect(projectRoot.childDirectory('.git').existsSync(), false); - await utils.gitInit(projectRootPath); - expect(projectRoot.childDirectory('.git').existsSync(), true); - - projectRoot.childFile('some_file.dart') - ..createSync() - ..writeAsStringSync('void main() {}', flush: true); - - expect(await hasUncommittedChanges(projectRootPath, logger, utils), true); - }); + testWithoutContext( + 'logging hasUncommittedChanges true on dirty repo', + () async { + expect(projectRoot.existsSync(), true); + expect(projectRoot.childDirectory('.git').existsSync(), false); + await utils.gitInit(projectRootPath); + expect(projectRoot.childDirectory('.git').existsSync(), true); + + projectRoot.childFile('some_file.dart') + ..createSync() + ..writeAsStringSync('void main() {}', flush: true); + + expect( + await hasUncommittedChanges(projectRootPath, logger, utils), + true, + ); + }, + ); testWithoutContext('diffFiles', () async { expect(projectRoot.existsSync(), true); @@ -129,9 +144,10 @@ void main() { await utils.gitInit(projectRootPath); expect(projectRoot.childDirectory('.git').existsSync(), true); - final File file1 = projectRoot.childFile('some_file.dart') - ..createSync() - ..writeAsStringSync('void main() {}\n', flush: true); + final File file1 = + projectRoot.childFile('some_file.dart') + ..createSync() + ..writeAsStringSync('void main() {}\n', flush: true); final File file2 = projectRoot.childFile('some_other_file.dart'); @@ -153,14 +169,18 @@ void main() { expect(result.diffType, DiffType.command); expect(result.exitCode, 0); - file2.writeAsStringSync('void main() {}\na second line\na third line\n', - flush: true); + file2.writeAsStringSync( + 'void main() {}\na second line\na third line\n', + flush: true, + ); result = await utils.diffFiles(file1, file2); expect( - result.diff, - contains( - '@@ -1 +1,3 @@\n void main() {}\n+a second line\n+a third line')); + result.diff, + contains( + '@@ -1 +1,3 @@\n void main() {}\n+a second line\n+a third line', + ), + ); expect(result.diffType, DiffType.command); expect(result.exitCode, 1); }); @@ -174,56 +194,73 @@ void main() { final File file1 = projectRoot.childFile('some_file.dart'); file1.createSync(); file1.writeAsStringSync( - 'void main() {}\n\nline1\nline2\nline3\nline4\nline5\n', - flush: true); + 'void main() {}\n\nline1\nline2\nline3\nline4\nline5\n', + flush: true, + ); final File file2 = projectRoot.childFile('some_other_file.dart'); file2.createSync(); file2.writeAsStringSync( - 'void main() {}\n\nline1\nline2\nline3.0\nline3.5\nline4\nline5\n', - flush: true); + 'void main() {}\n\nline1\nline2\nline3.0\nline3.5\nline4\nline5\n', + flush: true, + ); final File file3 = projectRoot.childFile('some_other_third_file.dart'); file3.createSync(); - file3.writeAsStringSync('void main() {}\n\nline2\nline3\nline4\nline5\n', - flush: true); - - StringMergeResult result = await utils.gitMergeFile( - base: file1.path, - current: file2.path, - target: file3.path, - localPath: 'some_file.dart', - ) as StringMergeResult; - - expect(result.mergedString, - 'void main() {}\n\nline2\nline3.0\nline3.5\nline4\nline5\n'); + file3.writeAsStringSync( + 'void main() {}\n\nline2\nline3\nline4\nline5\n', + flush: true, + ); + + StringMergeResult result = + await utils.gitMergeFile( + base: file1.path, + current: file2.path, + target: file3.path, + localPath: 'some_file.dart', + ) + as StringMergeResult; + + expect( + result.mergedString, + 'void main() {}\n\nline2\nline3.0\nline3.5\nline4\nline5\n', + ); expect(result.hasConflict, false); expect(result.exitCode, 0); file3.writeAsStringSync( - 'void main() {}\n\nline1\nline2\nline3.1\nline3.5\nline4\nline5\n', - flush: true); + 'void main() {}\n\nline1\nline2\nline3.1\nline3.5\nline4\nline5\n', + flush: true, + ); - result = await utils.gitMergeFile( - base: file1.path, - current: file2.path, - target: file3.path, - localPath: 'some_file.dart', - ) as StringMergeResult; + result = + await utils.gitMergeFile( + base: file1.path, + current: file2.path, + target: file3.path, + localPath: 'some_file.dart', + ) + as StringMergeResult; expect( - result.mergedString, contains('line3.0\n=======\nline3.1\n>>>>>>>')); + result.mergedString, + contains('line3.0\n=======\nline3.1\n>>>>>>>'), + ); expect(result.hasConflict, true); expect(result.exitCode, 1); // Two way merge - result = await utils.gitMergeFile( - base: file1.path, - current: file1.path, - target: file3.path, - localPath: 'some_file.dart', - ) as StringMergeResult; - - expect(result.mergedString, - 'void main() {}\n\nline1\nline2\nline3.1\nline3.5\nline4\nline5\n'); + result = + await utils.gitMergeFile( + base: file1.path, + current: file1.path, + target: file3.path, + localPath: 'some_file.dart', + ) + as StringMergeResult; + + expect( + result.mergedString, + 'void main() {}\n\nline1\nline2\nline3.1\nline3.5\nline4\nline5\n', + ); expect(result.hasConflict, false); expect(result.exitCode, 0); }); @@ -241,70 +278,88 @@ void main() { printCommandText('fullstandalone', logger); if (isWindows) { expect( - logger.statusText, - contains( - r'dart run \bin\flutter_migrate.dart fullstandalone')); + logger.statusText, + contains( + r'dart run \bin\flutter_migrate.dart fullstandalone', + ), + ); } else { expect( - logger.statusText, - contains( - 'dart run /bin/flutter_migrate.dart fullstandalone')); + logger.statusText, + contains( + 'dart run /bin/flutter_migrate.dart fullstandalone', + ), + ); } logger.clear(); }); - group('legacy app creation', () { - testWithoutContext('clone and create', () async { - projectRoot = - fileSystem.systemTempDirectory.createTempSync('flutter_sdk_test'); - const String revision = '5391447fae6209bb21a89e6a5a6583cac1af9b4b'; - - expect(await utils.cloneFlutter(revision, projectRoot.path), true); - expect(projectRoot.childFile('README.md').existsSync(), true); - - final Directory appDir = - fileSystem.systemTempDirectory.createTempSync('flutter_app'); - await utils.createFromTemplates( - projectRoot.childDirectory('bin').path, - name: 'testapp', - androidLanguage: 'java', - iosLanguage: 'objc', - outputDirectory: appDir.path, - ); - expect(appDir.childFile('pubspec.yaml').existsSync(), true); - expect(appDir.childFile('.metadata').existsSync(), true); - expect( - appDir.childFile('.metadata').readAsStringSync(), contains(revision)); - expect(appDir.childDirectory('android').existsSync(), true); - expect(appDir.childDirectory('ios').existsSync(), true); - expect(appDir.childDirectory('web').existsSync(), false); - - projectRoot.deleteSync(recursive: true); - }); - }, - timeout: const Timeout(Duration(seconds: 500)), - // TODO(stuartmorgan): These should not be unit tests, see - // https://github.com/flutter/flutter/issues/121257. - skip: 'TODO: Speed up, or move to another type of test'); + group( + 'legacy app creation', + () { + testWithoutContext('clone and create', () async { + projectRoot = fileSystem.systemTempDirectory.createTempSync( + 'flutter_sdk_test', + ); + const String revision = '5391447fae6209bb21a89e6a5a6583cac1af9b4b'; + + expect(await utils.cloneFlutter(revision, projectRoot.path), true); + expect(projectRoot.childFile('README.md').existsSync(), true); + + final Directory appDir = fileSystem.systemTempDirectory.createTempSync( + 'flutter_app', + ); + await utils.createFromTemplates( + projectRoot.childDirectory('bin').path, + name: 'testapp', + androidLanguage: 'java', + iosLanguage: 'objc', + outputDirectory: appDir.path, + ); + expect(appDir.childFile('pubspec.yaml').existsSync(), true); + expect(appDir.childFile('.metadata').existsSync(), true); + expect( + appDir.childFile('.metadata').readAsStringSync(), + contains(revision), + ); + expect(appDir.childDirectory('android').existsSync(), true); + expect(appDir.childDirectory('ios').existsSync(), true); + expect(appDir.childDirectory('web').existsSync(), false); + + projectRoot.deleteSync(recursive: true); + }); + }, + timeout: const Timeout(Duration(seconds: 500)), + // TODO(stuartmorgan): These should not be unit tests, see + // https://github.com/flutter/flutter/issues/121257. + skip: 'TODO: Speed up, or move to another type of test', + ); testWithoutContext('conflictsResolved', () async { expect(utils.conflictsResolved(''), true); expect(utils.conflictsResolved('hello'), true); expect(utils.conflictsResolved('hello\n'), true); expect( - utils.conflictsResolved('hello\nwow a bunch of lines\n\nhi\n'), true); + utils.conflictsResolved('hello\nwow a bunch of lines\n\nhi\n'), + true, + ); expect( - utils.conflictsResolved('hello\nwow a bunch of lines\n>>>>>>>\nhi\n'), - false); + utils.conflictsResolved('hello\nwow a bunch of lines\n>>>>>>>\nhi\n'), + false, + ); expect( - utils.conflictsResolved('hello\nwow a bunch of lines\n=======\nhi\n'), - false); + utils.conflictsResolved('hello\nwow a bunch of lines\n=======\nhi\n'), + false, + ); expect( - utils.conflictsResolved('hello\nwow a bunch of lines\n<<<<<<<\nhi\n'), - false); + utils.conflictsResolved('hello\nwow a bunch of lines\n<<<<<<<\nhi\n'), + false, + ); expect( - utils.conflictsResolved( - 'hello\nwow a bunch of lines\n<<<<<<<\n=======\n<<<<<<<\nhi\n'), - false); + utils.conflictsResolved( + 'hello\nwow a bunch of lines\n<<<<<<<\n=======\n<<<<<<<\nhi\n', + ), + false, + ); }); } diff --git a/packages/flutter_plugin_android_lifecycle/CHANGELOG.md b/packages/flutter_plugin_android_lifecycle/CHANGELOG.md index a4d5f7993ab..eae3f557c05 100644 --- a/packages/flutter_plugin_android_lifecycle/CHANGELOG.md +++ b/packages/flutter_plugin_android_lifecycle/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 2.0.29 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/flutter_plugin_android_lifecycle/example/lib/main.dart b/packages/flutter_plugin_android_lifecycle/example/lib/main.dart index 0ec602550d5..d54b115668b 100644 --- a/packages/flutter_plugin_android_lifecycle/example/lib/main.dart +++ b/packages/flutter_plugin_android_lifecycle/example/lib/main.dart @@ -19,8 +19,10 @@ class MyApp extends StatelessWidget { title: const Text('Sample flutter_plugin_android_lifecycle usage'), ), body: const Center( - child: Text( - 'This plugin only provides Android Lifecycle API\n for other Android plugins.')), + child: Text( + 'This plugin only provides Android Lifecycle API\n for other Android plugins.', + ), + ), ), ); } diff --git a/packages/flutter_plugin_android_lifecycle/example/pubspec.yaml b/packages/flutter_plugin_android_lifecycle/example/pubspec.yaml index e5f6299afb1..bf925f75018 100644 --- a/packages/flutter_plugin_android_lifecycle/example/pubspec.yaml +++ b/packages/flutter_plugin_android_lifecycle/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the flutter_plugin_android_lifecycle plugin publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/flutter_plugin_android_lifecycle/pubspec.yaml b/packages/flutter_plugin_android_lifecycle/pubspec.yaml index 666074f7d9c..18291c0ffe6 100644 --- a/packages/flutter_plugin_android_lifecycle/pubspec.yaml +++ b/packages/flutter_plugin_android_lifecycle/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.0.29 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/flutter_template_images/CHANGELOG.md b/packages/flutter_template_images/CHANGELOG.md index 210fa5c11c2..8f08f288a92 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 5.0.0 diff --git a/packages/flutter_template_images/pubspec.yaml b/packages/flutter_template_images/pubspec.yaml index 22e3e827df0..3b7a32bde2b 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.6.0 + sdk: ^3.7.0 topics: - assets diff --git a/packages/go_router/CHANGELOG.md b/packages/go_router/CHANGELOG.md index 51885216ad8..413efb10461 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.29/Dart 3.7. + ## 16.1.0 - Adds annotation for go_router_builder that enable custom string encoder/decoder [#110781](https://github.com/flutter/flutter/issues/110781). **Requires go_router_builder >= 3.1.0**. diff --git a/packages/go_router/doc/configuration.md b/packages/go_router/doc/configuration.md index eb927805c9e..81be3be03d7 100644 --- a/packages/go_router/doc/configuration.md +++ b/packages/go_router/doc/configuration.md @@ -178,16 +178,18 @@ 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'), ), ], ), @@ -205,8 +207,11 @@ which is passed as the last argument to the builder function. Example: ```dart StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell 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 diff --git a/packages/go_router/example/lib/async_redirection.dart b/packages/go_router/example/lib/async_redirection.dart index f84c14e8afc..e5101017556 100644 --- a/packages/go_router/example/lib/async_redirection.dart +++ b/packages/go_router/example/lib/async_redirection.dart @@ -30,22 +30,22 @@ class App extends StatelessWidget { // add the login info into the tree as app state that can change over time @override Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ); + routerConfig: _router, + title: title, + debugShowCheckedModeBanner: false, + ); late final GoRouter _router = GoRouter( 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(), ), ], @@ -93,8 +93,8 @@ class _LoginScreenState extends State vsync: this, duration: const Duration(seconds: 1), )..addListener(() { - setState(() {}); - }); + setState(() {}); + }); controller.repeat(); } @@ -106,26 +106,26 @@ class _LoginScreenState extends State @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - if (loggingIn) CircularProgressIndicator(value: controller.value), - if (!loggingIn) - ElevatedButton( - onPressed: () { - StreamAuthScope.of(context).signIn('test-user'); - setState(() { - loggingIn = true; - }); - }, - child: const Text('Login'), - ), - ], - ), - ), - ); + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (loggingIn) CircularProgressIndicator(value: controller.value), + if (!loggingIn) + ElevatedButton( + onPressed: () { + StreamAuthScope.of(context).signIn('test-user'); + setState(() { + loggingIn = true; + }); + }, + child: const Text('Login'), + ), + ], + ), + ), + ); } /// The home screen. @@ -145,12 +145,10 @@ class HomeScreen extends StatelessWidget { onPressed: () => info.signOut(), tooltip: 'Logout: ${info.currentUser}', icon: const Icon(Icons.logout), - ) + ), ], ), - body: const Center( - child: Text('HomeScreen'), - ), + body: const Center(child: Text('HomeScreen')), ); } } @@ -158,12 +156,8 @@ class HomeScreen extends StatelessWidget { /// A scope that provides [StreamAuth] for the subtree. class StreamAuthScope extends InheritedNotifier { /// Creates a [StreamAuthScope] sign in scope. - StreamAuthScope({ - super.key, - required super.child, - }) : super( - notifier: StreamAuthNotifier(), - ); + StreamAuthScope({super.key, required super.child}) + : super(notifier: StreamAuthNotifier()); /// Gets the [StreamAuth]. static StreamAuth of(BuildContext context) { @@ -195,7 +189,7 @@ class StreamAuth { /// Creates an [StreamAuth] that clear the current user session in /// [refeshInterval] second. StreamAuth({this.refreshInterval = 20}) - : _userStreamController = StreamController.broadcast() { + : _userStreamController = StreamController.broadcast() { _userStreamController.stream.listen((String? currentUser) { _currentUser = currentUser; }); diff --git a/packages/go_router/example/lib/books/main.dart b/packages/go_router/example/lib/books/main.dart index eb757e3de4f..acfcac8d401 100644 --- a/packages/go_router/example/lib/books/main.dart +++ b/packages/go_router/example/lib/books/main.dart @@ -29,52 +29,46 @@ class Bookstore extends StatelessWidget { @override Widget build(BuildContext context) => BookstoreAuthScope( - notifier: _auth, - child: MaterialApp.router( - routerConfig: _router, - ), - ); + notifier: _auth, + child: MaterialApp.router(routerConfig: _router), + ); final BookstoreAuth _auth = BookstoreAuth(); late final GoRouter _router = GoRouter( routes: [ - GoRoute( - path: '/', - redirect: (_, __) => '/books', - ), + GoRoute(path: '/', redirect: (_, __) => '/books'), GoRoute( path: '/signin', - pageBuilder: (BuildContext context, GoRouterState state) => - FadeTransitionPage( - key: state.pageKey, - child: SignInScreen( - onSignIn: (Credentials credentials) { - BookstoreAuthScope.of(context) - .signIn(credentials.username, credentials.password); - }, - ), - ), - ), - GoRoute( - path: '/books', - redirect: (_, __) => '/books/popular', + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( + key: state.pageKey, + child: SignInScreen( + onSignIn: (Credentials credentials) { + BookstoreAuthScope.of( + context, + ).signIn(credentials.username, credentials.password); + }, + ), + ), ), + 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( - key: _scaffoldKey, - child: BookstoreScaffold( - selectedTab: ScaffoldTab.books, - child: BooksScreen(state.pathParameters['kind']!), - ), - ), + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( + key: _scaffoldKey, + child: BookstoreScaffold( + selectedTab: ScaffoldTab.books, + child: BooksScreen(state.pathParameters['kind']!), + ), + ), routes: [ GoRoute( path: ':bookId', @@ -90,19 +84,20 @@ 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( - key: _scaffoldKey, - child: const BookstoreScaffold( - selectedTab: ScaffoldTab.authors, - child: AuthorsScreen(), - ), - ), + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( + key: _scaffoldKey, + child: const BookstoreScaffold( + selectedTab: ScaffoldTab.authors, + child: AuthorsScreen(), + ), + ), routes: [ GoRoute( path: ':authorId', @@ -118,14 +113,14 @@ class Bookstore extends StatelessWidget { ), GoRoute( path: '/settings', - pageBuilder: (BuildContext context, GoRouterState state) => - FadeTransitionPage( - key: _scaffoldKey, - child: const BookstoreScaffold( - selectedTab: ScaffoldTab.settings, - child: SettingsScreen(), - ), - ), + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( + key: _scaffoldKey, + child: const BookstoreScaffold( + selectedTab: ScaffoldTab.settings, + child: SettingsScreen(), + ), + ), ), ], redirect: _guard, @@ -154,18 +149,19 @@ class Bookstore extends StatelessWidget { /// A page that fades in an out. class FadeTransitionPage extends CustomTransitionPage { /// Creates a [FadeTransitionPage]. - FadeTransitionPage({ - required LocalKey super.key, - required super.child, - }) : super( - transitionsBuilder: (BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child) => - FadeTransition( - opacity: animation.drive(_curveTween), - child: child, - )); + FadeTransitionPage({required LocalKey super.key, required super.child}) + : super( + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => FadeTransition( + opacity: animation.drive(_curveTween), + child: child, + ), + ); static final CurveTween _curveTween = CurveTween(curve: Curves.easeIn); } diff --git a/packages/go_router/example/lib/books/src/auth.dart b/packages/go_router/example/lib/books/src/auth.dart index b9c353c1573..6abc89c800d 100644 --- a/packages/go_router/example/lib/books/src/auth.dart +++ b/packages/go_router/example/lib/books/src/auth.dart @@ -40,7 +40,8 @@ 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/author.dart b/packages/go_router/example/lib/books/src/data/author.dart index b58db11d8cf..e776a5b79b1 100644 --- a/packages/go_router/example/lib/books/src/data/author.dart +++ b/packages/go_router/example/lib/books/src/data/author.dart @@ -7,10 +7,7 @@ import 'book.dart'; /// Author data class. class Author { /// Creates an author data object. - Author({ - required this.id, - required this.name, - }); + Author({required this.id, required this.name}); /// The id of the author. final int id; 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 075b825b473..6cd1c763699 100644 --- a/packages/go_router/example/lib/books/src/data/library.dart +++ b/packages/go_router/example/lib/books/src/data/library.dart @@ -6,27 +6,32 @@ 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 { @@ -66,11 +71,11 @@ class Library { /// The list of popular books in the library. List get popularBooks => [ - ...allBooks.where((Book book) => book.isPopular), - ]; + ...allBooks.where((Book book) => book.isPopular), + ]; /// The list of new books in the library. List get newBooks => [ - ...allBooks.where((Book book) => book.isNew), - ]; + ...allBooks.where((Book book) => book.isNew), + ]; } diff --git a/packages/go_router/example/lib/books/src/screens/author_details.dart b/packages/go_router/example/lib/books/src/screens/author_details.dart index 3aff898cff9..87acd4af2bd 100644 --- a/packages/go_router/example/lib/books/src/screens/author_details.dart +++ b/packages/go_router/example/lib/books/src/screens/author_details.dart @@ -11,10 +11,7 @@ import '../widgets/book_list.dart'; /// The author detail screen. class AuthorDetailsScreen extends StatelessWidget { /// Creates an author detail screen. - const AuthorDetailsScreen({ - required this.author, - super.key, - }); + const AuthorDetailsScreen({required this.author, super.key}); /// The author to be displayed. final Author? author; @@ -22,16 +19,10 @@ class AuthorDetailsScreen extends StatelessWidget { @override Widget build(BuildContext context) { if (author == null) { - return const Scaffold( - body: Center( - child: Text('No author found.'), - ), - ); + return const Scaffold(body: Center(child: Text('No author found.'))); } return Scaffold( - appBar: AppBar( - title: Text(author!.name), - ), + appBar: AppBar(title: Text(author!.name)), body: Center( child: Column( children: [ diff --git a/packages/go_router/example/lib/books/src/screens/authors.dart b/packages/go_router/example/lib/books/src/screens/authors.dart index 0eeb1c338b4..d85ce499064 100644 --- a/packages/go_router/example/lib/books/src/screens/authors.dart +++ b/packages/go_router/example/lib/books/src/screens/authors.dart @@ -18,14 +18,12 @@ class AuthorsScreen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar( - title: const Text(title), - ), - body: AuthorList( - authors: libraryInstance.allAuthors, - onTap: (Author author) { - context.go('/author/${author.id}'); - }, - ), - ); + appBar: AppBar(title: const Text(title)), + body: AuthorList( + authors: libraryInstance.allAuthors, + onTap: (Author author) { + context.go('/author/${author.id}'); + }, + ), + ); } 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 9a51a8342ad..cbefcec5d8c 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 @@ -12,10 +12,7 @@ import 'author_details.dart'; /// A screen to display book details. class BookDetailsScreen extends StatelessWidget { /// Creates a [BookDetailsScreen]. - const BookDetailsScreen({ - super.key, - this.book, - }); + const BookDetailsScreen({super.key, this.book}); /// The book to be displayed. final Book? book; @@ -23,16 +20,10 @@ class BookDetailsScreen extends StatelessWidget { @override Widget build(BuildContext context) { if (book == null) { - return const Scaffold( - body: Center( - child: Text('No book found.'), - ), - ); + return const Scaffold(body: Center(child: Text('No book found.'))); } return Scaffold( - appBar: AppBar( - title: Text(book!.title), - ), + appBar: AppBar(title: Text(book!.title)), body: Center( child: Column( children: [ @@ -48,8 +39,9 @@ class BookDetailsScreen extends StatelessWidget { onPressed: () { Navigator.of(context).push( MaterialPageRoute( - builder: (BuildContext context) => - AuthorDetailsScreen(author: book!.author), + builder: + (BuildContext context) => + AuthorDetailsScreen(author: book!.author), ), ); }, @@ -57,11 +49,11 @@ class BookDetailsScreen extends StatelessWidget { ), Link( uri: Uri.parse('/author/${book!.author.id}'), - builder: (BuildContext context, FollowLink? followLink) => - TextButton( - onPressed: followLink, - child: const Text('View author (Link)'), - ), + builder: + (BuildContext context, FollowLink? followLink) => TextButton( + onPressed: followLink, + child: const Text('View author (Link)'), + ), ), TextButton( onPressed: () { diff --git a/packages/go_router/example/lib/books/src/screens/books.dart b/packages/go_router/example/lib/books/src/screens/books.dart index 57fb60f645e..8c1ad88db36 100644 --- a/packages/go_router/example/lib/books/src/screens/books.dart +++ b/packages/go_router/example/lib/books/src/screens/books.dart @@ -54,45 +54,27 @@ class _BooksScreenState extends State @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar( - title: const Text('Books'), - bottom: TabBar( - controller: _tabController, - onTap: _handleTabTapped, - tabs: const [ - Tab( - text: 'Popular', - icon: Icon(Icons.people), - ), - Tab( - text: 'New', - icon: Icon(Icons.new_releases), - ), - Tab( - text: 'All', - icon: Icon(Icons.list), - ), - ], - ), - ), - body: TabBarView( - controller: _tabController, - children: [ - BookList( - books: libraryInstance.popularBooks, - onTap: _handleBookTapped, - ), - BookList( - books: libraryInstance.newBooks, - onTap: _handleBookTapped, - ), - BookList( - books: libraryInstance.allBooks, - onTap: _handleBookTapped, - ), - ], - ), - ); + appBar: AppBar( + title: const Text('Books'), + bottom: TabBar( + controller: _tabController, + onTap: _handleTabTapped, + tabs: const [ + Tab(text: 'Popular', icon: Icon(Icons.people)), + Tab(text: 'New', icon: Icon(Icons.new_releases)), + Tab(text: 'All', icon: Icon(Icons.list)), + ], + ), + ), + body: TabBarView( + controller: _tabController, + children: [ + BookList(books: libraryInstance.popularBooks, onTap: _handleBookTapped), + BookList(books: libraryInstance.newBooks, onTap: _handleBookTapped), + BookList(books: libraryInstance.allBooks, onTap: _handleBookTapped), + ], + ), + ); void _handleBookTapped(Book book) { context.go('/book/${book.id}'); diff --git a/packages/go_router/example/lib/books/src/screens/scaffold.dart b/packages/go_router/example/lib/books/src/screens/scaffold.dart index 7e26fe28e4e..fc06d47e406 100644 --- a/packages/go_router/example/lib/books/src/screens/scaffold.dart +++ b/packages/go_router/example/lib/books/src/screens/scaffold.dart @@ -16,7 +16,7 @@ enum ScaffoldTab { authors, /// The settings tab. - settings + settings, } /// The scaffold for the book store. @@ -36,33 +36,24 @@ class BookstoreScaffold extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - body: AdaptiveNavigationScaffold( - selectedIndex: selectedTab.index, - body: child, - onDestinationSelected: (int idx) { - switch (ScaffoldTab.values[idx]) { - case ScaffoldTab.books: - context.go('/books'); - case ScaffoldTab.authors: - context.go('/authors'); - case ScaffoldTab.settings: - context.go('/settings'); - } - }, - destinations: const [ - AdaptiveScaffoldDestination( - title: 'Books', - icon: Icons.book, - ), - AdaptiveScaffoldDestination( - title: 'Authors', - icon: Icons.person, - ), - AdaptiveScaffoldDestination( - title: 'Settings', - icon: Icons.settings, - ), - ], - ), - ); + body: AdaptiveNavigationScaffold( + selectedIndex: selectedTab.index, + body: child, + onDestinationSelected: (int idx) { + switch (ScaffoldTab.values[idx]) { + case ScaffoldTab.books: + context.go('/books'); + case ScaffoldTab.authors: + context.go('/authors'); + case ScaffoldTab.settings: + context.go('/settings'); + } + }, + destinations: const [ + AdaptiveScaffoldDestination(title: 'Books', icon: Icons.book), + AdaptiveScaffoldDestination(title: 'Authors', icon: Icons.person), + AdaptiveScaffoldDestination(title: 'Settings', icon: Icons.settings), + ], + ), + ); } 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 a098e3046d1..070fde10c11 100644 --- a/packages/go_router/example/lib/books/src/screens/settings.dart +++ b/packages/go_router/example/lib/books/src/screens/settings.dart @@ -20,82 +20,80 @@ class SettingsScreen extends StatefulWidget { class _SettingsScreenState extends State { @override Widget build(BuildContext context) => Scaffold( - body: SafeArea( - child: SingleChildScrollView( - child: Align( - alignment: Alignment.topCenter, - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 400), - child: const Card( - child: Padding( - padding: EdgeInsets.symmetric(vertical: 18, horizontal: 12), - child: SettingsContent(), - ), - ), + body: SafeArea( + child: SingleChildScrollView( + child: Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: const Card( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 18, horizontal: 12), + child: SettingsContent(), ), ), ), ), - ); + ), + ), + ); } /// The content of a [SettingsScreen]. class SettingsContent extends StatelessWidget { /// Creates a [SettingsContent]. - const SettingsContent({ - super.key, - }); + const SettingsContent({super.key}); @override Widget build(BuildContext context) => Column( - children: [ - ...[ - Text( - 'Settings', - style: Theme.of(context).textTheme.headlineMedium, - ), - ElevatedButton( - onPressed: () { - BookstoreAuthScope.of(context).signOut(); - }, - child: const Text('Sign out'), - ), - Link( - uri: Uri.parse('/book/0'), - builder: (BuildContext context, FollowLink? followLink) => - TextButton( + children: [ + ...[ + Text('Settings', style: Theme.of(context).textTheme.headlineMedium), + ElevatedButton( + onPressed: () { + BookstoreAuthScope.of(context).signOut(); + }, + child: const Text('Sign out'), + ), + Link( + uri: Uri.parse('/book/0'), + builder: + (BuildContext context, FollowLink? followLink) => TextButton( onPressed: followLink, child: const Text('Go directly to /book/0 (Link)'), ), - ), - TextButton( - onPressed: () { - context.go('/book/0'); - }, - child: const Text('Go directly to /book/0 (GoRouter)'), - ), - ].map((Widget w) => - Padding(padding: const EdgeInsets.all(8), child: w)), - TextButton( - onPressed: () => showDialog( + ), + TextButton( + onPressed: () { + context.go('/book/0'); + }, + child: const Text('Go directly to /book/0 (GoRouter)'), + ), + ].map( + (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'), + 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'), + ), + ], ), - TextButton( - onPressed: () => Navigator.pop(context, 'OK'), - child: const Text('OK'), - ), - ], - ), ), - child: const Text('Show Dialog'), - ) - ], - ); + child: const Text('Show Dialog'), + ), + ], + ); } diff --git a/packages/go_router/example/lib/books/src/screens/sign_in.dart b/packages/go_router/example/lib/books/src/screens/sign_in.dart index e02c870ba7c..e60ceda84c7 100644 --- a/packages/go_router/example/lib/books/src/screens/sign_in.dart +++ b/packages/go_router/example/lib/books/src/screens/sign_in.dart @@ -19,10 +19,7 @@ class Credentials { /// The sign-in screen. class SignInScreen extends StatefulWidget { /// Creates a sign-in screen. - const SignInScreen({ - required this.onSignIn, - super.key, - }); + const SignInScreen({required this.onSignIn, super.key}); /// Called when users sign in with [Credentials]. final ValueChanged onSignIn; @@ -37,41 +34,46 @@ class _SignInScreenState extends State { @override Widget build(BuildContext context) => Scaffold( - body: Center( - child: Card( - child: Container( - constraints: BoxConstraints.loose(const Size(600, 600)), - padding: const EdgeInsets.all(8), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Text('Sign in', - style: Theme.of(context).textTheme.headlineMedium), - TextField( - decoration: const InputDecoration(labelText: 'Username'), - controller: _usernameController, - ), - TextField( - decoration: const InputDecoration(labelText: 'Password'), - obscureText: true, - controller: _passwordController, - ), - Padding( - padding: const EdgeInsets.all(16), - child: TextButton( - onPressed: () async { - widget.onSignIn(Credentials( - _usernameController.value.text, - _passwordController.value.text)); - }, - child: const Text('Sign in'), - ), - ), - ], + body: Center( + child: Card( + child: Container( + constraints: BoxConstraints.loose(const Size(600, 600)), + padding: const EdgeInsets.all(8), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Sign in', + style: Theme.of(context).textTheme.headlineMedium, ), - ), + TextField( + decoration: const InputDecoration(labelText: 'Username'), + controller: _usernameController, + ), + TextField( + decoration: const InputDecoration(labelText: 'Password'), + obscureText: true, + controller: _passwordController, + ), + Padding( + padding: const EdgeInsets.all(16), + child: TextButton( + onPressed: () async { + widget.onSignIn( + Credentials( + _usernameController.value.text, + _passwordController.value.text, + ), + ); + }, + child: const Text('Sign in'), + ), + ), + ], ), ), - ); + ), + ), + ); } 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 371e30a10cd..d22e9dd2bd8 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 @@ -9,11 +9,7 @@ import '../data.dart'; /// The author list view. class AuthorList extends StatelessWidget { /// Creates an [AuthorList]. - const AuthorList({ - required this.authors, - this.onTap, - super.key, - }); + const AuthorList({required this.authors, this.onTap, super.key}); /// The list of authors to be shown. final List authors; @@ -23,15 +19,12 @@ 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', - ), + 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, ), - ); + ); } 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 3e2761fcb2c..5acf6de894c 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 @@ -9,11 +9,7 @@ import '../data.dart'; /// The book list view. class BookList extends StatelessWidget { /// Creates an [BookList]. - const BookList({ - required this.books, - this.onTap, - super.key, - }); + const BookList({required this.books, this.onTap, super.key}); /// The list of books to be displayed. final List books; @@ -23,15 +19,12 @@ 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, - ), + 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, ), - ); + ); } diff --git a/packages/go_router/example/lib/exception_handling.dart b/packages/go_router/example/lib/exception_handling.dart index 82c10e332f6..18b13416d55 100644 --- a/packages/go_router/example/lib/exception_handling.dart +++ b/packages/go_router/example/lib/exception_handling.dart @@ -42,9 +42,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - ); + return MaterialApp.router(routerConfig: _router); } } @@ -79,9 +77,7 @@ class NotFoundScreen extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Page Not Found')), - body: Center( - child: Text("Can't find a page for: $uri"), - ), + body: Center(child: Text("Can't find a page for: $uri")), ); } } diff --git a/packages/go_router/example/lib/extra_codec.dart b/packages/go_router/example/lib/extra_codec.dart index 389afe4063b..5f79539c653 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(), @@ -29,9 +29,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - ); + return MaterialApp.router(routerConfig: _router); } } @@ -49,9 +47,11 @@ class HomeScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( - "If running in web, use the browser's backward and forward button to test extra codec after setting extra several times."), + "If running in web, use the browser's backward and forward button to test extra codec after setting extra several times.", + ), Text( - 'The extra for this page is: ${GoRouterState.of(context).extra}'), + 'The extra for this page is: ${GoRouterState.of(context).extra}', + ), ElevatedButton( onPressed: () => context.go('/', extra: ComplexData1('data')), child: const Text('Set extra to ComplexData1'), diff --git a/packages/go_router/example/lib/go_relative.dart b/packages/go_router/example/lib/go_relative.dart index 72076dcbea0..98e13f3596d 100644 --- a/packages/go_router/example/lib/go_relative.dart +++ b/packages/go_router/example/lib/go_relative.dart @@ -15,9 +15,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - ); + return MaterialApp.router(routerConfig: _router); } } diff --git a/packages/go_router/example/lib/main.dart b/packages/go_router/example/lib/main.dart index d1596485034..03eda41d0ba 100644 --- a/packages/go_router/example/lib/main.dart +++ b/packages/go_router/example/lib/main.dart @@ -42,9 +42,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - ); + return MaterialApp.router(routerConfig: _router); } } diff --git a/packages/go_router/example/lib/named_routes.dart b/packages/go_router/example/lib/named_routes.dart index 9685fc4a874..6d5c5c25de5 100644 --- a/packages/go_router/example/lib/named_routes.dart +++ b/packages/go_router/example/lib/named_routes.dart @@ -66,10 +66,10 @@ class App extends StatelessWidget { @override Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ); + routerConfig: _router, + title: title, + debugShowCheckedModeBanner: false, + ); late final GoRouter _router = GoRouter( debugLogDiagnostics: true, @@ -77,22 +77,24 @@ 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', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { return PersonScreen( - fid: state.pathParameters['fid']!, - pid: state.pathParameters['pid']!); + fid: state.pathParameters['fid']!, + pid: state.pathParameters['pid']!, + ); }, ), ], @@ -111,17 +113,20 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text(App.title), - ), + appBar: AppBar(title: const Text(App.title)), body: ListView( children: [ 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}, + ), + ), + ), ], ), ); @@ -146,11 +151,17 @@ 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/on_exit.dart b/packages/go_router/example/lib/on_exit.dart index bf397efedd3..c2284d09b7f 100644 --- a/packages/go_router/example/lib/on_exit.dart +++ b/packages/go_router/example/lib/on_exit.dart @@ -22,10 +22,7 @@ final GoRouter _router = GoRouter( builder: (BuildContext context, GoRouterState state) { return const DetailsScreen(); }, - onExit: ( - BuildContext context, - GoRouterState state, - ) async { + onExit: (BuildContext context, GoRouterState state) async { final bool? confirmed = await showDialog( context: context, builder: (_) { @@ -65,9 +62,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - ); + return MaterialApp.router(routerConfig: _router); } } @@ -105,22 +100,23 @@ class DetailsScreen extends StatelessWidget { return Scaffold( appBar: AppBar(title: const Text('Details Screen')), body: Center( - child: Column( - children: [ - TextButton( - onPressed: () { - context.pop(); - }, - child: const Text('go back'), - ), - TextButton( - onPressed: () { - context.go('/settings'); - }, - child: const Text('go to settings'), - ), - ], - )), + child: Column( + children: [ + TextButton( + onPressed: () { + context.pop(); + }, + child: const Text('go back'), + ), + TextButton( + onPressed: () { + context.go('/settings'); + }, + child: const Text('go to settings'), + ), + ], + ), + ), ); } } @@ -134,9 +130,7 @@ class SettingsScreen extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Settings Screen')), - body: const Center( - child: Text('Settings'), - ), + body: const Center(child: Text('Settings')), ); } } 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 dfacac830f3..33e3366a457 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 @@ -7,16 +7,21 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = - GlobalKey(debugLabel: 'root'); -final GlobalKey _tabANavigatorKey = - GlobalKey(debugLabel: 'tabANav'); -final GlobalKey _tabBNavigatorKey = - GlobalKey(debugLabel: 'tabBNav'); -final GlobalKey _tabB1NavigatorKey = - GlobalKey(debugLabel: 'tabB1Nav'); -final GlobalKey _tabB2NavigatorKey = - GlobalKey(debugLabel: 'tabB2Nav'); +final GlobalKey _rootNavigatorKey = GlobalKey( + debugLabel: 'root', +); +final GlobalKey _tabANavigatorKey = GlobalKey( + debugLabel: 'tabANav', +); +final GlobalKey _tabBNavigatorKey = GlobalKey( + debugLabel: 'tabBNav', +); +final GlobalKey _tabB1NavigatorKey = GlobalKey( + debugLabel: 'tabB1Nav', +); +final GlobalKey _tabB2NavigatorKey = GlobalKey( + debugLabel: 'tabB2Nav', +); @visibleForTesting // ignore: public_member_api_docs @@ -45,8 +50,11 @@ class NestedTabNavigationExampleApp extends StatelessWidget { initialLocation: '/a', routes: [ StatefulShellRoute( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + 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 @@ -55,15 +63,20 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // customize the container for the branch Navigators. return navigationShell; }, - navigatorContainerBuilder: (BuildContext context, - StatefulNavigationShell navigationShell, List children) { + 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); + navigationShell: navigationShell, + children: children, + ); // NOTE: To use a Cupertino version of ScaffoldWithNavBar, replace // ScaffoldWithNavBar above with CupertinoScaffoldWithNavBar. }, @@ -76,16 +89,18 @@ 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'), ), ], ), @@ -105,15 +120,20 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // defaultLocation: '/b1', routes: [ StatefulShellRoute( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + 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) { + navigatorContainerBuilder: ( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ) { // Returning a customized container for the branch // Navigators (i.e. the `List children` argument). // @@ -131,52 +151,58 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // top TabBar. branches: [ StatefulShellBranch( - navigatorKey: _tabB1NavigatorKey, - routes: [ - GoRoute( - path: '/b1', - builder: - (BuildContext context, GoRouterState state) => - const TabScreen( - label: 'B1', detailsPath: '/b1/details'), - routes: [ - GoRoute( - path: 'details', - builder: - (BuildContext context, GoRouterState state) => - const DetailsScreen( - label: 'B1', - withScaffold: false, - ), - ), - ], - ), - ]), + navigatorKey: _tabB1NavigatorKey, + routes: [ + GoRoute( + path: '/b1', + builder: + (BuildContext context, GoRouterState state) => + const TabScreen( + label: 'B1', + detailsPath: '/b1/details', + ), + routes: [ + GoRoute( + path: 'details', + builder: + (BuildContext context, GoRouterState state) => + const DetailsScreen( + label: 'B1', + withScaffold: false, + ), + ), + ], + ), + ], + ), StatefulShellBranch( - navigatorKey: _tabB2NavigatorKey, - // To enable preloading for all nested branches, set - // `preload` to `true` (`false` is default). - preload: true, - routes: [ - GoRoute( - path: '/b2', - builder: - (BuildContext context, GoRouterState state) => - const TabScreen( - label: 'B2', detailsPath: '/b2/details'), - routes: [ - GoRoute( - path: 'details', - builder: - (BuildContext context, GoRouterState state) => - const DetailsScreen( - label: 'B2', - withScaffold: false, - ), - ), - ], - ), - ]), + navigatorKey: _tabB2NavigatorKey, + // To enable preloading for all nested branches, set + // `preload` to `true` (`false` is default). + preload: true, + routes: [ + GoRoute( + path: '/b2', + builder: + (BuildContext context, GoRouterState state) => + const TabScreen( + label: 'B2', + detailsPath: '/b2/details', + ), + routes: [ + GoRoute( + path: 'details', + builder: + (BuildContext context, GoRouterState state) => + const DetailsScreen( + label: 'B2', + withScaffold: false, + ), + ), + ], + ), + ], + ), ], ), ], @@ -190,9 +216,7 @@ class NestedTabNavigationExampleApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp.router( title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), routerConfig: _router, ); } @@ -280,8 +304,9 @@ class CupertinoScaffoldWithNavBar extends StatefulWidget { class _CupertinoScaffoldWithNavBarState extends State { - late final CupertinoTabController tabController = - CupertinoTabController(initialIndex: widget.navigationShell.currentIndex); + late final CupertinoTabController tabController = CupertinoTabController( + initialIndex: widget.navigationShell.currentIndex, + ); @override void dispose() { @@ -322,8 +347,11 @@ class _CupertinoScaffoldWithNavBarState /// when switching branches. class AnimatedBranchContainer extends StatelessWidget { /// Creates a AnimatedBranchContainer - const AnimatedBranchContainer( - {super.key, required this.currentIndex, required this.children}); + const AnimatedBranchContainer({ + super.key, + required this.currentIndex, + required this.children, + }); /// The index (in [children]) of the branch Navigator to display. final int currentIndex; @@ -334,28 +362,25 @@ 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(), + ); } Widget _branchNavigatorWrapper(int index, Widget navigator) => IgnorePointer( - ignoring: index != currentIndex, - child: TickerMode( - enabled: index == currentIndex, - child: navigator, - ), - ); + ignoring: index != currentIndex, + child: TickerMode(enabled: index == currentIndex, child: navigator), + ); } /// Widget for the root page for the first section of the bottom navigation bar. @@ -366,9 +391,7 @@ class RootScreenA extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Section A root'), - ), + appBar: AppBar(title: const Text('Section A root')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, @@ -419,9 +442,7 @@ class DetailsScreenState extends State { Widget build(BuildContext context) { if (widget.withScaffold) { return Scaffold( - appBar: AppBar( - title: Text('Details Screen - ${widget.label}'), - ), + appBar: AppBar(title: Text('Details Screen - ${widget.label}')), body: _build(context), ); } else { @@ -437,8 +458,10 @@ class DetailsScreenState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text('Details for ${widget.label} - Counter: $_counter', - style: Theme.of(context).textTheme.titleLarge), + Text( + 'Details for ${widget.label} - Counter: $_counter', + style: Theme.of(context).textTheme.titleLarge, + ), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { @@ -450,8 +473,10 @@ class DetailsScreenState extends State { ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) - Text('Parameter: ${widget.param!}', - style: Theme.of(context).textTheme.titleMedium), + Text( + 'Parameter: ${widget.param!}', + style: Theme.of(context).textTheme.titleMedium, + ), const Padding(padding: EdgeInsets.all(8)), if (!widget.withScaffold) ...[ const Padding(padding: EdgeInsets.all(16)), @@ -459,10 +484,12 @@ class DetailsScreenState extends State { onPressed: () { GoRouter.of(context).pop(); }, - child: const Text('< Back', - style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)), + child: const Text( + '< Back', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + ), ), - ] + ], ], ), ); @@ -472,8 +499,11 @@ class DetailsScreenState extends State { /// Builds a nested shell using a [TabBar] and [TabBarView]. class TabbedRootScreen extends StatefulWidget { /// Constructs a TabbedRootScreen - const TabbedRootScreen( - {required this.navigationShell, required this.children, super.key}); + const TabbedRootScreen({ + required this.navigationShell, + required this.children, + super.key, + }); /// The current state of the parent StatefulShellRoute. final StatefulNavigationShell navigationShell; @@ -492,9 +522,10 @@ class TabbedRootScreenState extends State @visibleForTesting // ignore: public_member_api_docs late final TabController tabController = TabController( - length: widget.children.length, - vsync: this, - initialIndex: widget.navigationShell.currentIndex); + length: widget.children.length, + vsync: this, + initialIndex: widget.navigationShell.currentIndex, + ); void _switchedTab() { if (tabController.index != widget.navigationShell.currentIndex) { @@ -523,23 +554,23 @@ 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( - title: Text( - 'Section B root (tab: ${widget.navigationShell.currentIndex + 1})'), - bottom: TabBar( - controller: tabController, - tabs: tabs, - onTap: (int tappedIndex) => _onTabTap(context, tappedIndex), - )), - body: TabBarView( - controller: tabController, - children: widget.children, + title: Text( + 'Section B root (tab: ${widget.navigationShell.currentIndex + 1})', + ), + bottom: TabBar( + controller: tabController, + tabs: tabs, + onTap: (int tappedIndex) => _onTabTap(context, tappedIndex), + ), ), + body: TabBarView(controller: tabController, children: widget.children), ); } @@ -554,8 +585,11 @@ class TabbedRootScreenState extends State class PagedRootScreen extends StatefulWidget { /// Constructs a PagedRootScreen // ignore: unreachable_from_main - const PagedRootScreen( - {required this.navigationShell, required this.children, super.key}); + const PagedRootScreen({ + required this.navigationShell, + required this.children, + super.key, + }); /// The current state of the parent StatefulShellRoute. // ignore: unreachable_from_main @@ -587,22 +621,24 @@ class _PagedRootScreenState extends State { return Scaffold( appBar: AppBar( title: Text( - 'Section B root (tab ${widget.navigationShell.currentIndex + 1})'), + 'Section B root (tab ${widget.navigationShell.currentIndex + 1})', + ), ), body: Column( children: [ Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - ElevatedButton( - onPressed: () => _animateToPage(0), - child: const Text('Tab 1'), - ), - ElevatedButton( - onPressed: () => _animateToPage(1), - child: const Text('Tab 2'), - ), - ]), + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + ElevatedButton( + onPressed: () => _animateToPage(0), + child: const Text('Tab 1'), + ), + ElevatedButton( + onPressed: () => _animateToPage(1), + child: const Text('Tab 2'), + ), + ], + ), Expanded( child: PageView( onPageChanged: (int i) => widget.navigationShell.goBranch(i), diff --git a/packages/go_router/example/lib/others/error_screen.dart b/packages/go_router/example/lib/others/error_screen.dart index 5c071fc03e4..dc40aee5ee1 100644 --- a/packages/go_router/example/lib/others/error_screen.dart +++ b/packages/go_router/example/lib/others/error_screen.dart @@ -16,26 +16,25 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Custom Error Screen'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( 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!), ); } @@ -46,19 +45,19 @@ class Page1Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/page2'), + child: const Text('Go to page 2'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the second page. @@ -68,19 +67,19 @@ class Page2Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/'), + child: const Text('Go to home page'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the error page. @@ -93,18 +92,18 @@ class ErrorScreen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text('My "Page Not Found" Screen')), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SelectableText(error.toString()), - TextButton( - onPressed: () => context.go('/'), - child: const Text('Home'), - ), - ], + appBar: AppBar(title: const Text('My "Page Not Found" Screen')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SelectableText(error.toString()), + TextButton( + onPressed: () => context.go('/'), + child: const Text('Home'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/example/lib/others/extra_param.dart b/packages/go_router/example/lib/others/extra_param.dart index 6cb1c39fcb5..96b9aced6cc 100644 --- a/packages/go_router/example/lib/others/extra_param.dart +++ b/packages/go_router/example/lib/others/extra_param.dart @@ -54,18 +54,16 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Extra Parameter'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); late final GoRouter _router = GoRouter( routes: [ GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', @@ -90,18 +88,21 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: ListView( - children: [ - for (final MapEntry entry in _families.entries) - ListTile( - title: Text(entry.value.name), - onTap: () => context.goNamed('family', - extra: {'fid': entry.key}), - ) - ], - ), - ); + appBar: AppBar(title: const Text(App.title)), + body: ListView( + children: [ + for (final MapEntry entry in _families.entries) + ListTile( + title: Text(entry.value.name), + onTap: + () => context.goNamed( + 'family', + extra: {'fid': entry.key}, + ), + ), + ], + ), + ); } /// The screen that shows a list of persons in a family. @@ -119,10 +120,7 @@ class FamilyScreen extends StatelessWidget { appBar: AppBar(title: Text(_families[fid]!.name)), body: ListView( children: [ - for (final Person p in people.values) - ListTile( - title: Text(p.name), - ), + for (final Person p in people.values) ListTile(title: Text(p.name)), ], ), ); diff --git a/packages/go_router/example/lib/others/init_loc.dart b/packages/go_router/example/lib/others/init_loc.dart index 4f61b006f6e..f16178da11b 100644 --- a/packages/go_router/example/lib/others/init_loc.dart +++ b/packages/go_router/example/lib/others/init_loc.dart @@ -16,28 +16,26 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Initial Location'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( initialLocation: '/page3', 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(), ), ], ); @@ -50,19 +48,19 @@ class Page1Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/page2'), + child: const Text('Go to page 2'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the second page. @@ -72,19 +70,19 @@ class Page2Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/'), + child: const Text('Go to home page'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the third page. @@ -94,17 +92,17 @@ class Page3Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/page2'), + child: const Text('Go to page 2'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/example/lib/others/nav_observer.dart b/packages/go_router/example/lib/others/nav_observer.dart index 038d337c08b..878ba6b7545 100644 --- a/packages/go_router/example/lib/others/nav_observer.dart +++ b/packages/go_router/example/lib/others/nav_observer.dart @@ -17,10 +17,8 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Navigator Observer'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( observers: [MyNavObserver()], @@ -28,20 +26,22 @@ 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(), ), ], ), @@ -81,9 +81,10 @@ class MyNavObserver extends NavigatorObserver { void didStartUserGesture( Route route, Route? previousRoute, - ) => - log.info('didStartUserGesture: ${route.str}, ' - 'previousRoute= ${previousRoute?.str}'); + ) => log.info( + 'didStartUserGesture: ${route.str}, ' + 'previousRoute= ${previousRoute?.str}', + ); @override void didStopUserGesture() => log.info('didStopUserGesture'); @@ -100,23 +101,24 @@ class Page1Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.goNamed( + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: + () => context.goNamed( 'page2', pathParameters: {'p1': 'pv1'}, queryParameters: {'q1': 'qv1'}, ), - child: const Text('Go to page 2'), - ), - ], + child: const Text('Go to page 2'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the second page. @@ -126,22 +128,23 @@ class Page2Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.goNamed( + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: + () => context.goNamed( 'page3', pathParameters: {'p1': 'pv2'}, ), - child: const Text('Go to page 3'), - ), - ], + child: const Text('Go to page 3'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the third page. @@ -151,17 +154,17 @@ class Page3Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/'), + child: const Text('Go to home page'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/example/lib/others/push.dart b/packages/go_router/example/lib/others/push.dart index 0cea8942cb9..d78419ec72c 100644 --- a/packages/go_router/example/lib/others/push.dart +++ b/packages/go_router/example/lib/others/push.dart @@ -16,24 +16,23 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Push'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); late final GoRouter _router = GoRouter( 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( - int.parse(state.uri.queryParameters['push-count']!), - ), + builder: + (BuildContext context, GoRouterState state) => Page2ScreenWithPush( + int.parse(state.uri.queryParameters['push-count']!), + ), ), ], ); @@ -46,19 +45,19 @@ class Page1ScreenWithPush extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text('${App.title}: page 1')), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.push('/page2?push-count=1'), - child: const Text('Push page 2'), - ), - ], + appBar: AppBar(title: const Text('${App.title}: page 1')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.push('/page2?push-count=1'), + child: const Text('Push page 2'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the second page. @@ -71,31 +70,30 @@ class Page2ScreenWithPush extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar( - title: Text('${App.title}: page 2 w/ push count $pushCount'), - ), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Padding( - padding: const EdgeInsets.all(8), - child: ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), - ), - Padding( - padding: const EdgeInsets.all(8), - child: ElevatedButton( - onPressed: () => context.push( - '/page2?push-count=${pushCount + 1}', - ), - child: const Text('Push page 2 (again)'), - ), - ), - ], + appBar: AppBar( + title: Text('${App.title}: page 2 w/ push count $pushCount'), + ), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: ElevatedButton( + onPressed: () => context.go('/'), + child: const Text('Go to home page'), + ), + ), + Padding( + padding: const EdgeInsets.all(8), + child: ElevatedButton( + 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 6660f0ee270..a5dd81e3852 100644 --- a/packages/go_router/example/lib/others/router_neglect.dart +++ b/packages/go_router/example/lib/others/router_neglect.dart @@ -16,10 +16,8 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Router neglect'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( // To turn off history tracking in the browser for the entire application, @@ -28,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(), ), ], ); @@ -47,30 +45,28 @@ class Page1Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), - const SizedBox(height: 8), - ElevatedButton( - // 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'), - ), - child: const Text('Push page 2'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/page2'), + child: const Text('Go to page 2'), ), - ), - ); + const SizedBox(height: 8), + ElevatedButton( + // 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')), + child: const Text('Push page 2'), + ), + ], + ), + ), + ); } /// The screen of the second page. @@ -80,17 +76,17 @@ class Page2Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/'), + child: const Text('Go to home page'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/example/lib/others/state_restoration.dart b/packages/go_router/example/lib/others/state_restoration.dart index 93e8aca12ad..8ad22c8ec17 100644 --- a/packages/go_router/example/lib/others/state_restoration.dart +++ b/packages/go_router/example/lib/others/state_restoration.dart @@ -5,9 +5,8 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -void main() => runApp( - const RootRestorationScope(restorationId: 'root', child: App()), - ); +void main() => + runApp(const RootRestorationScope(restorationId: 'root', child: App())); /// The main app. class App extends StatefulWidget { @@ -32,25 +31,25 @@ class _AppState extends State with RestorationMixin { @override Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: App.title, - restorationScopeId: 'app', - ); + routerConfig: _router, + title: App.title, + restorationScopeId: 'app', + ); final GoRouter _router = GoRouter( routes: [ // restorationId set for the route automatically GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: + (BuildContext context, GoRouterState state) => const Page1Screen(), ), // restorationId set for the route automatically GoRoute( path: '/page2', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: + (BuildContext context, GoRouterState state) => const Page2Screen(), ), ], restorationScopeId: 'router', @@ -64,19 +63,19 @@ class Page1Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/page2'), + child: const Text('Go to page 2'), ), - ), - ); + ], + ), + ), + ); } /// The screen of the second page. @@ -86,17 +85,17 @@ class Page2Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), - ], + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/'), + child: const Text('Go to home page'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/example/lib/others/stateful_shell_state_restoration.dart b/packages/go_router/example/lib/others/stateful_shell_state_restoration.dart index aeecd115590..8811ac72313 100644 --- a/packages/go_router/example/lib/others/stateful_shell_state_restoration.dart +++ b/packages/go_router/example/lib/others/stateful_shell_state_restoration.dart @@ -19,11 +19,15 @@ class RestorableStatefulShellRouteExampleApp extends StatelessWidget { routes: [ StatefulShellRoute.indexedStack( restorationScopeId: 'shell1', - pageBuilder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { return MaterialPage( - restorationId: 'shellWidget1', - child: ScaffoldWithNavBar(navigationShell: navigationShell)); + restorationId: 'shellWidget1', + child: ScaffoldWithNavBar(navigationShell: navigationShell), + ); }, branches: [ // The route branch for the first tab of the bottom navigation bar. @@ -34,21 +38,27 @@ class RestorableStatefulShellRouteExampleApp extends StatelessWidget { // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', - pageBuilder: (BuildContext context, GoRouterState state) => - const MaterialPage( - restorationId: 'screenA', - child: - RootScreen(label: 'A', detailsPath: '/a/details')), + pageBuilder: + (BuildContext context, GoRouterState state) => + const MaterialPage( + restorationId: 'screenA', + child: 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', - pageBuilder: (BuildContext context, GoRouterState state) => - const MaterialPage( - restorationId: 'screenADetail', - child: DetailsScreen(label: 'A')), + pageBuilder: + (BuildContext context, GoRouterState state) => + const MaterialPage( + restorationId: 'screenADetail', + child: DetailsScreen(label: 'A'), + ), ), ], ), @@ -62,21 +72,27 @@ class RestorableStatefulShellRouteExampleApp extends StatelessWidget { // The screen to display as the root in the second tab of the // bottom navigation bar. path: '/b', - pageBuilder: (BuildContext context, GoRouterState state) => - const MaterialPage( - restorationId: 'screenB', - child: - RootScreen(label: 'B', detailsPath: '/b/details')), + pageBuilder: + (BuildContext context, GoRouterState state) => + const MaterialPage( + restorationId: 'screenB', + child: RootScreen( + label: 'B', + detailsPath: '/b/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', - pageBuilder: (BuildContext context, GoRouterState state) => - const MaterialPage( - restorationId: 'screenBDetail', - child: DetailsScreen(label: 'B')), + pageBuilder: + (BuildContext context, GoRouterState state) => + const MaterialPage( + restorationId: 'screenBDetail', + child: DetailsScreen(label: 'B'), + ), ), ], ), @@ -92,9 +108,7 @@ class RestorableStatefulShellRouteExampleApp extends StatelessWidget { return MaterialApp.router( restorationScopeId: 'app', title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), routerConfig: _router, ); } @@ -104,10 +118,8 @@ class RestorableStatefulShellRouteExampleApp extends StatelessWidget { /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. - const ScaffoldWithNavBar({ - required this.navigationShell, - Key? key, - }) : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); + const ScaffoldWithNavBar({required this.navigationShell, Key? key}) + : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; @@ -131,11 +143,7 @@ class ScaffoldWithNavBar extends StatelessWidget { /// Widget for the root/initial pages in the bottom navigation bar. class RootScreen extends StatelessWidget { /// Creates a RootScreen - const RootScreen({ - required this.label, - required this.detailsPath, - super.key, - }); + const RootScreen({required this.label, required this.detailsPath, super.key}); /// The label final String label; @@ -146,15 +154,15 @@ class RootScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text('Root of section $label'), - ), + appBar: AppBar(title: Text('Root of section $label')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text('Screen $label', - style: Theme.of(context).textTheme.titleLarge), + Text( + 'Screen $label', + style: Theme.of(context).textTheme.titleLarge, + ), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { @@ -172,10 +180,7 @@ class RootScreen extends StatelessWidget { /// The details screen for either the A or B screen. class DetailsScreen extends StatefulWidget { /// Constructs a [DetailsScreen]. - const DetailsScreen({ - required this.label, - super.key, - }); + const DetailsScreen({required this.label, super.key}); /// The label to display in the center of the screen. final String label; @@ -205,9 +210,7 @@ class DetailsScreenState extends State with RestorationMixin { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text('Details Screen - ${widget.label}'), - ), + appBar: AppBar(title: Text('Details Screen - ${widget.label}')), body: _build(context), ); } @@ -217,8 +220,10 @@ class DetailsScreenState extends State with RestorationMixin { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text('Details for ${widget.label} - Counter: ${_counter.value}', - style: Theme.of(context).textTheme.titleLarge), + Text( + 'Details for ${widget.label} - Counter: ${_counter.value}', + style: Theme.of(context).textTheme.titleLarge, + ), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { diff --git a/packages/go_router/example/lib/others/transitions.dart b/packages/go_router/example/lib/others/transitions.dart index f2559521a19..1ecd3438c18 100644 --- a/packages/go_router/example/lib/others/transitions.dart +++ b/packages/go_router/example/lib/others/transitions.dart @@ -16,99 +16,107 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Custom Transitions'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( routes: [ - GoRoute( - path: '/', - redirect: (_, __) => '/none', - ), + 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, - ), - 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, - ), - ), + 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, + ), + ), ), 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, + ), + ), ), ], ); @@ -129,7 +137,7 @@ class ExampleTransitionsScreen extends StatelessWidget { 'scale', 'slide', 'rotation', - 'none' + 'none', ]; /// The color of the container. @@ -140,24 +148,24 @@ class ExampleTransitionsScreen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: Text('${App.title}: $kind')), - body: ColoredBox( - color: color, - child: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - for (final String kind in kinds) - Padding( - padding: const EdgeInsets.all(8), - child: ElevatedButton( - onPressed: () => context.go('/$kind'), - child: Text('$kind transition'), - ), - ) - ], - ), - ), + appBar: AppBar(title: Text('${App.title}: $kind')), + body: ColoredBox( + color: color, + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (final String kind in kinds) + Padding( + padding: const EdgeInsets.all(8), + child: ElevatedButton( + onPressed: () => context.go('/$kind'), + child: Text('$kind transition'), + ), + ), + ], ), - ); + ), + ), + ); } 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 42d3b15d261..fde3b2be199 100755 --- a/packages/go_router/example/lib/path_and_query_parameters.dart +++ b/packages/go_router/example/lib/path_and_query_parameters.dart @@ -64,27 +64,28 @@ class App extends StatelessWidget { // add the login info into the tree as app state that can change over time @override Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ); + routerConfig: _router, + title: title, + debugShowCheckedModeBanner: false, + ); late final GoRouter _router = GoRouter( routes: [ GoRoute( 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) { - return FamilyScreen( - fid: state.pathParameters['fid']!, - asc: state.uri.queryParameters['sort'] == 'asc', - ); - }), + name: 'family', + path: 'family/:fid', + builder: (BuildContext context, GoRouterState state) { + return FamilyScreen( + fid: state.pathParameters['fid']!, + asc: state.uri.queryParameters['sort'] == 'asc', + ); + }, + ), ], ), ], @@ -99,16 +100,14 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text(App.title), - ), + appBar: AppBar(title: const Text(App.title)), body: ListView( children: [ for (final MapEntry entry in _families.entries) ListTile( title: Text(entry.value.name), onTap: () => context.go('/family/${entry.key}'), - ) + ), ], ), ); @@ -129,11 +128,10 @@ 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'}; @@ -145,20 +143,21 @@ 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), - ) + ), ], ), body: ListView( children: [ for (final String name in asc ? names : names.reversed) - ListTile( - title: Text(name), - ), + ListTile(title: Text(name)), ], ), ); 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 d26fb104294..3ecf3a13417 100644 --- a/packages/go_router/example/lib/push_with_shell_route.dart +++ b/packages/go_router/example/lib/push_with_shell_route.dart @@ -38,11 +38,10 @@ 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')), + ), ), ], ), @@ -62,9 +61,7 @@ class PushWithShellRouteExampleApp extends StatelessWidget { GoRoute( path: '/regular-route', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Center(child: Text('regular route')), - ); + return const Scaffold(body: Center(child: Text('regular route'))); }, ), ], @@ -74,9 +71,7 @@ class PushWithShellRouteExampleApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp.router( title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), routerConfig: _router, ); } @@ -85,10 +80,7 @@ class PushWithShellRouteExampleApp extends StatelessWidget { /// Builds the "shell" for /shell1 class ScaffoldForShell1 extends StatelessWidget { /// Constructs an [ScaffoldForShell1]. - const ScaffoldForShell1({ - required this.child, - super.key, - }); + const ScaffoldForShell1({required this.child, super.key}); /// The widget to display in the body of the Scaffold. /// In this sample, it is a Navigator. @@ -96,20 +88,14 @@ 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); } } /// Builds the "shell" for /shell1 class ScaffoldForShell2 extends StatelessWidget { /// Constructs an [ScaffoldForShell1]. - const ScaffoldForShell2({ - required this.child, - super.key, - }); + const ScaffoldForShell2({required this.child, super.key}); /// The widget to display in the body of the Scaffold. /// In this sample, it is a Navigator. @@ -117,10 +103,7 @@ 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 aded4b759b4..4d8fb92db9b 100644 --- a/packages/go_router/example/lib/redirection.dart +++ b/packages/go_router/example/lib/redirection.dart @@ -49,25 +49,25 @@ class App extends StatelessWidget { // add the login info into the tree as app state that can change over time @override Widget build(BuildContext context) => ChangeNotifierProvider.value( - value: _loginInfo, - child: MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ), - ); + value: _loginInfo, + child: MaterialApp.router( + routerConfig: _router, + title: title, + debugShowCheckedModeBanner: false, + ), + ); late final GoRouter _router = GoRouter( 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(), ), ], @@ -102,20 +102,20 @@ class LoginScreen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text(App.title)), - body: Center( - child: ElevatedButton( - onPressed: () { - // log a user in, letting all the listeners know - context.read().login('test-user'); - - // router will automatically redirect from /login to / using - // refreshListenable - }, - child: const Text('Login'), - ), - ), - ); + appBar: AppBar(title: const Text(App.title)), + body: Center( + child: ElevatedButton( + onPressed: () { + // log a user in, letting all the listeners know + context.read().login('test-user'); + + // router will automatically redirect from /login to / using + // refreshListenable + }, + child: const Text('Login'), + ), + ), + ); } /// The home screen. @@ -135,12 +135,10 @@ class HomeScreen extends StatelessWidget { onPressed: info.logout, tooltip: 'Logout: ${info.userName}', icon: const Icon(Icons.logout), - ) + ), ], ), - body: const Center( - child: Text('HomeScreen'), - ), + body: const Center(child: Text('HomeScreen')), ); } } diff --git a/packages/go_router/example/lib/routing_config.dart b/packages/go_router/example/lib/routing_config.dart index 85acf20c918..8632e9a754b 100644 --- a/packages/go_router/example/lib/routing_config.dart +++ b/packages/go_router/example/lib/routing_config.dart @@ -24,20 +24,24 @@ class _MyAppState extends State { ValueNotifier(_generateRoutingConfig()); late final GoRouter router = GoRouter.routingConfig( - routingConfig: myConfig, - errorBuilder: (_, GoRouterState state) => Scaffold( - appBar: AppBar(title: const Text('Page not found')), - body: Center( - child: Column( + 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')), + onPressed: () => router.go('/'), + child: const Text('Go to home'), + ), ], - )), - )); + ), + ), + ), + ); RoutingConfig _generateRoutingConfig() { return RoutingConfig( @@ -52,25 +56,27 @@ 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: () { router.go('/new-route'); }, child: const Text('Try going to /new-route'), - ) + ), ], ), ), @@ -84,14 +90,16 @@ class _MyAppState extends State { return Scaffold( appBar: AppBar(title: const Text('A new Route')), body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( onPressed: () => router.go('/'), - child: const Text('Go to home')), - ], - )), + child: const Text('Go to home'), + ), + ], + ), + ), ); }, ), @@ -101,8 +109,6 @@ class _MyAppState extends State { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: router, - ); + return MaterialApp.router(routerConfig: router); } } diff --git a/packages/go_router/example/lib/shell_route.dart b/packages/go_router/example/lib/shell_route.dart index 7ffc474b0fd..14057f255a8 100644 --- a/packages/go_router/example/lib/shell_route.dart +++ b/packages/go_router/example/lib/shell_route.dart @@ -5,10 +5,12 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = - GlobalKey(debugLabel: 'root'); -final GlobalKey _shellNavigatorKey = - GlobalKey(debugLabel: 'shell'); +final GlobalKey _rootNavigatorKey = GlobalKey( + debugLabel: 'root', +); +final GlobalKey _shellNavigatorKey = GlobalKey( + debugLabel: 'shell', +); // This scenario demonstrates how to set up nested navigation using ShellRoute, // which is a pattern where an additional Navigator is placed in the widget tree @@ -105,9 +107,7 @@ class ShellRouteExampleApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp.router( title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), routerConfig: _router, ); } @@ -117,10 +117,7 @@ class ShellRouteExampleApp extends StatelessWidget { /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. - const ScaffoldWithNavBar({ - required this.child, - super.key, - }); + const ScaffoldWithNavBar({required this.child, super.key}); /// The widget to display in the body of the Scaffold. /// In this sample, it is a Navigator. @@ -132,10 +129,7 @@ class ScaffoldWithNavBar extends StatelessWidget { body: child, bottomNavigationBar: BottomNavigationBar( items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.home), - label: 'A Screen', - ), + BottomNavigationBarItem(icon: Icon(Icons.home), label: 'A Screen'), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'B Screen', @@ -261,10 +255,7 @@ class ScreenC extends StatelessWidget { /// The details screen for either the A, B or C screen. class DetailsScreen extends StatelessWidget { /// Constructs a [DetailsScreen]. - const DetailsScreen({ - required this.label, - super.key, - }); + const DetailsScreen({required this.label, super.key}); /// The label to display in the center of the screen. final String label; @@ -272,9 +263,7 @@ class DetailsScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Details Screen'), - ), + appBar: AppBar(title: const Text('Details Screen')), body: Center( child: Text( 'Details for $label', 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 ce6128a559d..6c9def14fac 100644 --- a/packages/go_router/example/lib/shell_route_top_route.dart +++ b/packages/go_router/example/lib/shell_route_top_route.dart @@ -5,10 +5,12 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = - GlobalKey(debugLabel: 'root'); -final GlobalKey _shellNavigatorKey = - GlobalKey(debugLabel: 'shell'); +final GlobalKey _rootNavigatorKey = GlobalKey( + debugLabel: 'root', +); +final GlobalKey _shellNavigatorKey = GlobalKey( + debugLabel: 'shell', +); // This scenario demonstrates how to set up nested navigation using ShellRoute, // which is a pattern where an additional Navigator is placed in the widget tree @@ -125,9 +127,7 @@ class ShellRouteExampleApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp.router( title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), routerConfig: _router, ); } @@ -154,16 +154,10 @@ class ScaffoldWithNavBar extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( body: child, - appBar: AppBar( - title: Text(title), - leading: _buildLeadingButton(context), - ), + appBar: AppBar(title: Text(title), leading: _buildLeadingButton(context)), bottomNavigationBar: BottomNavigationBar( items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.home), - label: 'A Screen', - ), + BottomNavigationBarItem(icon: Icon(Icons.home), label: 'A Screen'), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'B Screen', @@ -187,9 +181,10 @@ class ScaffoldWithNavBar extends StatelessWidget { 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; } @@ -283,10 +278,7 @@ class ScreenC extends StatelessWidget { /// The details screen for either the A, B or C screen. class DetailsScreen extends StatelessWidget { /// Constructs a [DetailsScreen]. - const DetailsScreen({ - required this.label, - super.key, - }); + const DetailsScreen({required this.label, super.key}); /// The label to display in the center of the screen. final String label; diff --git a/packages/go_router/example/lib/stateful_shell_route.dart b/packages/go_router/example/lib/stateful_shell_route.dart index 96671556b03..277f19ab391 100644 --- a/packages/go_router/example/lib/stateful_shell_route.dart +++ b/packages/go_router/example/lib/stateful_shell_route.dart @@ -5,8 +5,9 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = - GlobalKey(debugLabel: 'root'); +final GlobalKey _rootNavigatorKey = GlobalKey( + debugLabel: 'root', +); final GlobalKey _sectionANavigatorKey = GlobalKey(debugLabel: 'sectionANav'); @@ -30,8 +31,11 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ // #docregion configuration-builder StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell 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 @@ -49,16 +53,18 @@ 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'), ), ], ), @@ -77,20 +83,22 @@ 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'], + ), ), ], ), @@ -104,19 +112,15 @@ 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), ), ], ), @@ -131,9 +135,7 @@ class NestedTabNavigationExampleApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp.router( title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), routerConfig: _router, ); } @@ -143,10 +145,8 @@ class NestedTabNavigationExampleApp extends StatelessWidget { /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. - const ScaffoldWithNavBar({ - required this.navigationShell, - Key? key, - }) : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); + const ScaffoldWithNavBar({required this.navigationShell, Key? key}) + : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; @@ -218,15 +218,15 @@ class RootScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text('Root of section $label'), - ), + appBar: AppBar(title: Text('Root of section $label')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text('Screen $label', - style: Theme.of(context).textTheme.titleLarge), + Text( + 'Screen $label', + style: Theme.of(context).textTheme.titleLarge, + ), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { @@ -284,9 +284,7 @@ class DetailsScreenState extends State { Widget build(BuildContext context) { if (widget.withScaffold) { return Scaffold( - appBar: AppBar( - title: Text('Details Screen - ${widget.label}'), - ), + appBar: AppBar(title: Text('Details Screen - ${widget.label}')), body: _build(context), ); } else { @@ -302,8 +300,10 @@ class DetailsScreenState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text('Details for ${widget.label} - Counter: $_counter', - style: Theme.of(context).textTheme.titleLarge), + Text( + 'Details for ${widget.label} - Counter: $_counter', + style: Theme.of(context).textTheme.titleLarge, + ), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { @@ -315,22 +315,28 @@ class DetailsScreenState extends State { ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) - Text('Parameter: ${widget.param!}', - style: Theme.of(context).textTheme.titleMedium), + Text( + 'Parameter: ${widget.param!}', + style: Theme.of(context).textTheme.titleMedium, + ), const Padding(padding: EdgeInsets.all(8)), if (widget.extra != null) - Text('Extra: ${widget.extra!}', - style: Theme.of(context).textTheme.titleMedium), + Text( + 'Extra: ${widget.extra!}', + style: Theme.of(context).textTheme.titleMedium, + ), if (!widget.withScaffold) ...[ const Padding(padding: EdgeInsets.all(16)), TextButton( onPressed: () { GoRouter.of(context).pop(); }, - child: const Text('< Back', - style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)), + child: const Text( + '< Back', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + ), ), - ] + ], ], ), ); diff --git a/packages/go_router/example/lib/transition_animations.dart b/packages/go_router/example/lib/transition_animations.dart index f245719d5e1..5d986b8f1d8 100644 --- a/packages/go_router/example/lib/transition_animations.dart +++ b/packages/go_router/example/lib/transition_animations.dart @@ -29,15 +29,18 @@ final GoRouter _router = GoRouter( key: state.pageKey, child: const DetailsScreen(), transitionDuration: const Duration(milliseconds: 150), - transitionsBuilder: (BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget 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), + opacity: CurveTween( + curve: Curves.easeInOut, + ).animate(animation), child: child, ); }, @@ -69,14 +72,13 @@ 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); }, ); }, @@ -93,9 +95,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - ); + return MaterialApp.router(routerConfig: _router); } } @@ -123,8 +123,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 20229b50082..056e9de8271 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: adaptive_navigation: ^0.0.4 diff --git a/packages/go_router/example/test/custom_stateful_shell_route_test.dart b/packages/go_router/example/test/custom_stateful_shell_route_test.dart index 4a001a9dc56..bf0ffd135d7 100644 --- a/packages/go_router/example/test/custom_stateful_shell_route_test.dart +++ b/packages/go_router/example/test/custom_stateful_shell_route_test.dart @@ -8,25 +8,26 @@ import 'package:go_router_examples/others/custom_stateful_shell_route.dart'; void main() { testWidgets( - 'Changing active tab in TabController of TabbedRootScreen (root screen ' - 'of branch/section B) correctly navigates to appropriate screen', - (WidgetTester tester) async { - await tester.pumpWidget(NestedTabNavigationExampleApp()); - expect(find.text('Screen A'), findsOneWidget); + 'Changing active tab in TabController of TabbedRootScreen (root screen ' + 'of branch/section B) correctly navigates to appropriate screen', + (WidgetTester tester) async { + await tester.pumpWidget(NestedTabNavigationExampleApp()); + expect(find.text('Screen A'), findsOneWidget); - // navigate to ScreenB - await tester.tap(find.text('Section B')); - await tester.pumpAndSettle(); - expect(find.text('Screen B1'), findsOneWidget); + // navigate to ScreenB + await tester.tap(find.text('Section B')); + await tester.pumpAndSettle(); + expect(find.text('Screen B1'), findsOneWidget); - // Get TabController from TabbedRootScreen (root screen of branch/section B) - final TabController? tabController = - tabbedRootScreenKey.currentState?.tabController; - expect(tabController, isNotNull); + // Get TabController from TabbedRootScreen (root screen of branch/section B) + final TabController? tabController = + tabbedRootScreenKey.currentState?.tabController; + expect(tabController, isNotNull); - // Simulate swiping TabView to change active tab in TabController - tabbedRootScreenKey.currentState?.tabController.index = 1; - await tester.pumpAndSettle(); - expect(find.text('Screen B2'), findsOneWidget); - }); + // Simulate swiping TabView to change active tab in TabController + tabbedRootScreenKey.currentState?.tabController.index = 1; + await tester.pumpAndSettle(); + expect(find.text('Screen B2'), findsOneWidget); + }, + ); } diff --git a/packages/go_router/example/test/exception_handling_test.dart b/packages/go_router/example/test/exception_handling_test.dart index 68a731032c7..5253da2ce4b 100644 --- a/packages/go_router/example/test/exception_handling_test.dart +++ b/packages/go_router/example/test/exception_handling_test.dart @@ -12,7 +12,9 @@ void main() { await tester.tap(find.text('Simulates user entering unknown url')); await tester.pumpAndSettle(); - expect(find.text("Can't find a page for: /some-unknown-route"), - findsOneWidget); + expect( + find.text("Can't find a page for: /some-unknown-route"), + findsOneWidget, + ); }); } diff --git a/packages/go_router/example/test/extra_codec_test.dart b/packages/go_router/example/test/extra_codec_test.dart index e42b19ddb3b..f4bd40d221c 100644 --- a/packages/go_router/example/test/extra_codec_test.dart +++ b/packages/go_router/example/test/extra_codec_test.dart @@ -12,13 +12,17 @@ void main() { await tester.tap(find.text('Set extra to ComplexData1')); await tester.pumpAndSettle(); - expect(find.text('The extra for this page is: ComplexData1(data: data)'), - findsOneWidget); + expect( + find.text('The extra for this page is: ComplexData1(data: data)'), + findsOneWidget, + ); await tester.tap(find.text('Set extra to ComplexData2')); await tester.pumpAndSettle(); - expect(find.text('The extra for this page is: ComplexData2(data: data)'), - findsOneWidget); + expect( + find.text('The extra for this page is: ComplexData2(data: data)'), + findsOneWidget, + ); }); test('invalid extra throws', () { diff --git a/packages/go_router/example/test/path_and_query_params_test.dart b/packages/go_router/example/test/path_and_query_params_test.dart index e4af48b7bae..c27718a9405 100644 --- a/packages/go_router/example/test/path_and_query_params_test.dart +++ b/packages/go_router/example/test/path_and_query_params_test.dart @@ -18,15 +18,19 @@ void main() { ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); // 'Chris' should be higher than 'Tom'. expect( - tester.getCenter(find.text('Jane')).dy < - tester.getCenter(find.text('John')).dy, - isTrue); + tester.getCenter(find.text('Jane')).dy < + tester.getCenter(find.text('John')).dy, + isTrue, + ); testRouteInformation = { 'location': '/family/f1?privacy=false', @@ -34,14 +38,18 @@ void main() { message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); // 'Chris' should be lower than 'Tom'. expect( - tester.getCenter(find.text('Jane')).dy > - tester.getCenter(find.text('John')).dy, - isTrue); + tester.getCenter(find.text('Jane')).dy > + tester.getCenter(find.text('John')).dy, + isTrue, + ); }); } diff --git a/packages/go_router/example/test/redirection_test.dart b/packages/go_router/example/test/redirection_test.dart index 2d0e286ed3b..d7b43cac456 100644 --- a/packages/go_router/example/test/redirection_test.dart +++ b/packages/go_router/example/test/redirection_test.dart @@ -19,8 +19,11 @@ void main() { ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); // Still show login page due to redirection @@ -30,14 +33,15 @@ void main() { await tester.pumpAndSettle(); expect(find.text('HomeScreen'), findsOneWidget); - testRouteInformation = { - 'location': '/login', - }; + testRouteInformation = {'location': '/login'}; message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); // Got redirected back to home page. diff --git a/packages/go_router/lib/src/builder.dart b/packages/go_router/lib/src/builder.dart index 7d238f8ae03..2811247f576 100644 --- a/packages/go_router/lib/src/builder.dart +++ b/packages/go_router/lib/src/builder.dart @@ -17,23 +17,20 @@ import 'route_data.dart'; import 'state.dart'; /// Signature of a go router builder function with navigator. -typedef GoRouterBuilderWithNav = Widget Function( - BuildContext context, - Widget child, -); - -typedef _PageBuilderForAppType = Page Function({ - required LocalKey key, - required String? name, - required Object? arguments, - required String restorationId, - required Widget child, -}); - -typedef _ErrorBuilderForAppType = Widget Function( - BuildContext context, - GoRouterState state, -); +typedef GoRouterBuilderWithNav = + Widget Function(BuildContext context, Widget child); + +typedef _PageBuilderForAppType = + Page Function({ + required LocalKey key, + required String? name, + required Object? arguments, + required String restorationId, + required Widget child, + }); + +typedef _ErrorBuilderForAppType = + Widget Function(BuildContext context, GoRouterState state); /// Signature for a function that takes in a `route` to be popped with /// the `result` and returns a boolean decision on whether the pop @@ -43,8 +40,8 @@ typedef _ErrorBuilderForAppType = Widget Function( /// associates with. /// /// Used by of [RouteBuilder.onPopPageWithRouteMatch]. -typedef PopPageWithRouteMatchCallback = bool Function( - Route route, dynamic result, RouteMatchBase match); +typedef PopPageWithRouteMatchCallback = + bool Function(Route route, dynamic result, RouteMatchBase match); /// Builds the top-level Navigator for GoRouter. class RouteBuilder { @@ -128,18 +125,19 @@ class RouteBuilder { } class _CustomNavigator extends StatefulWidget { - const _CustomNavigator( - {super.key, - required this.navigatorKey, - required this.observers, - required this.navigatorRestorationId, - required this.onPopPageWithRouteMatch, - required this.matchList, - required this.matches, - required this.configuration, - required this.errorBuilder, - required this.errorPageBuilder, - required this.requestFocus}); + const _CustomNavigator({ + super.key, + required this.navigatorKey, + required this.observers, + required this.navigatorRestorationId, + required this.onPopPageWithRouteMatch, + required this.matchList, + required this.matches, + required this.configuration, + required this.errorBuilder, + required this.errorPageBuilder, + required this.requestFocus, + }); final GlobalKey navigatorKey; final List observers; @@ -218,8 +216,10 @@ class _CustomNavigatorState extends State<_CustomNavigator> { } pages.add(page); pageToRouteMatchBase[page] = match; - registry[page] = - match.buildState(widget.configuration, widget.matchList); + registry[page] = match.buildState( + widget.configuration, + widget.matchList, + ); } } _pages = pages; @@ -243,8 +243,10 @@ class _CustomNavigatorState extends State<_CustomNavigator> { /// Builds a [Page] for a [RouteMatch] Page? _buildPageForGoRoute(BuildContext context, RouteMatch match) { final GoRouterPageBuilder? pageBuilder = match.route.pageBuilder; - final GoRouterState state = - match.buildState(widget.configuration, widget.matchList); + final GoRouterState state = match.buildState( + widget.configuration, + widget.matchList, + ); if (pageBuilder != null) { final Page page = pageBuilder(context, state); if (page is! NoOpPage) { @@ -257,10 +259,15 @@ class _CustomNavigatorState extends State<_CustomNavigator> { if (builder == null) { return null; } - return _buildPlatformAdapterPage(context, state, - Builder(builder: (BuildContext context) { - return builder(context, state); - })); + return _buildPlatformAdapterPage( + context, + state, + Builder( + builder: (BuildContext context) { + return builder(context, state); + }, + ), + ); } /// Builds a [Page] for a [ShellRouteMatch] @@ -268,8 +275,10 @@ class _CustomNavigatorState extends State<_CustomNavigator> { BuildContext context, ShellRouteMatch match, ) { - final GoRouterState state = - match.buildState(widget.configuration, widget.matchList); + final GoRouterState state = match.buildState( + widget.configuration, + widget.matchList, + ); final GlobalKey navigatorKey = match.navigatorKey; final ShellRouteContext shellRouteContext = ShellRouteContext( route: match.route, @@ -285,23 +294,27 @@ class _CustomNavigatorState extends State<_CustomNavigator> { String? restorationScopeId, ) { return _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); + // 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, state, shellRouteContext); + final Page? page = match.route.buildPage( + context, + state, + shellRouteContext, + ); if (page != null && page is! NoOpPage) { return page; } @@ -342,14 +355,14 @@ class _CustomNavigatorState extends State<_CustomNavigator> { (BuildContext c, GoRouterState s) => CupertinoErrorScreen(s.error); } else { log('Using WidgetsApp configuration'); - _pageBuilderForAppType = ({ - required LocalKey key, - required String? name, - required Object? arguments, - required String restorationId, - required Widget child, - }) => - NoTransitionPage( + _pageBuilderForAppType = + ({ + required LocalKey key, + required String? name, + required Object? arguments, + required String restorationId, + required Widget child, + }) => NoTransitionPage( name: name, arguments: arguments, key: key, @@ -378,7 +391,7 @@ class _CustomNavigatorState extends State<_CustomNavigator> { name: state.name ?? state.path, arguments: { ...state.pathParameters, - ...state.uri.queryParameters + ...state.uri.queryParameters, }, restorationId: state.pageKey.value, child: child, @@ -413,12 +426,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 a730500b6b0..c3e144a9b77 100644 --- a/packages/go_router/lib/src/configuration.dart +++ b/packages/go_router/lib/src/configuration.dart @@ -17,8 +17,8 @@ import 'router.dart'; import 'state.dart'; /// The signature of the redirect callback. -typedef GoRouterRedirect = FutureOr Function( - BuildContext context, GoRouterState state); +typedef GoRouterRedirect = + FutureOr Function(BuildContext context, GoRouterState state); typedef _NamedPath = ({String path, bool caseSensitive}); @@ -39,8 +39,10 @@ class RouteConfiguration { late bool subRouteIsTopLevel; if (route is GoRoute) { if (route.path != '/') { - assert(!route.path.endsWith('/'), - 'route path may not end with "/" except for the top "/" route. Found: $route'); + assert( + !route.path.endsWith('/'), + 'route path may not end with "/" except for the top "/" route. Found: $route', + ); } subRouteIsTopLevel = false; } else if (route is ShellRouteBase) { @@ -54,7 +56,9 @@ class RouteConfiguration { // Check that each parentNavigatorKey refers to either a ShellRoute's // navigatorKey or the root navigator key. static bool _debugCheckParentNavigatorKeys( - List routes, List> allowedKeys) { + List routes, + List> allowedKeys, + ) { for (final RouteBase route in routes) { if (route is GoRoute) { final GlobalKey? parentKey = route.parentNavigatorKey; @@ -62,10 +66,11 @@ class RouteConfiguration { // Verify that the root navigator or a ShellRoute ancestor has a // matching navigator key. assert( - allowedKeys.contains(parentKey), - 'parentNavigatorKey $parentKey must refer to' - " an ancestor ShellRoute's navigatorKey or GoRouter's" - ' navigatorKey'); + allowedKeys.contains(parentKey), + 'parentNavigatorKey $parentKey must refer to' + " an ancestor ShellRoute's navigatorKey or GoRouter's" + ' navigatorKey', + ); _debugCheckParentNavigatorKeys( route.routes, @@ -78,9 +83,7 @@ class RouteConfiguration { } else { _debugCheckParentNavigatorKeys( route.routes, - >[ - ...allowedKeys, - ], + >[...allowedKeys], ); } } else if (route is ShellRoute) { @@ -91,16 +94,14 @@ class RouteConfiguration { } else if (route is StatefulShellRoute) { for (final StatefulShellBranch branch in route.branches) { assert( - !allowedKeys.contains(branch.navigatorKey), - 'StatefulShellBranch must not reuse an ancestor navigatorKey ' - '(${branch.navigatorKey})'); + !allowedKeys.contains(branch.navigatorKey), + 'StatefulShellBranch must not reuse an ancestor navigatorKey ' + '(${branch.navigatorKey})', + ); _debugCheckParentNavigatorKeys( branch.routes, - >[ - ...allowedKeys, - branch.navigatorKey, - ], + >[...allowedKeys, branch.navigatorKey], ); } } @@ -109,7 +110,9 @@ class RouteConfiguration { } static bool _debugVerifyNoDuplicatePathParameter( - List routes, Map usedPathParams) { + List routes, + Map usedPathParams, + ) { for (final RouteBase route in routes) { if (route is! GoRoute) { continue; @@ -118,7 +121,8 @@ class RouteConfiguration { if (usedPathParams.containsKey(pathParam)) { final bool sameRoute = usedPathParams[pathParam] == route; throw GoError( - "duplicate path parameter, '$pathParam' found in ${sameRoute ? '$route' : '${usedPathParams[pathParam]}, and $route'}"); + "duplicate path parameter, '$pathParam' found in ${sameRoute ? '$route' : '${usedPathParams[pathParam]}, and $route'}", + ); } usedPathParams[pathParam] = route; } @@ -141,20 +145,24 @@ class RouteConfiguration { final String? initialLocation = route != null ? locationForRoute(route) : null; assert( - initialLocation != null, - 'The default location of a StatefulShellBranch must be ' - 'derivable from GoRoute descendant'); + initialLocation != null, + 'The default location of a StatefulShellBranch must be ' + 'derivable from GoRoute descendant', + ); assert( - route!.pathParameters.isEmpty, - 'The default location of a StatefulShellBranch cannot be ' - 'a parameterized route'); + route!.pathParameters.isEmpty, + 'The default location of a StatefulShellBranch cannot be ' + 'a parameterized route', + ); } else { - final RouteMatchList matchList = - findMatch(Uri.parse(branch.initialLocation!)); + final RouteMatchList matchList = findMatch( + Uri.parse(branch.initialLocation!), + ); assert( - !matchList.isError, - 'initialLocation (${matchList.uri}) of StatefulShellBranch must ' - 'be a valid location'); + !matchList.isError, + 'initialLocation (${matchList.uri}) of StatefulShellBranch must ' + 'be a valid location', + ); final List matchRoutes = matchList.routes; final int shellIndex = matchRoutes.indexOf(route); bool matchFound = false; @@ -163,10 +171,11 @@ class RouteConfiguration { matchFound = branch.routes.contains(branchRoot); } assert( - matchFound, - 'The initialLocation (${branch.initialLocation}) of ' - 'StatefulShellBranch must match a descendant route of the ' - 'branch'); + matchFound, + 'The initialLocation (${branch.initialLocation}) of ' + 'StatefulShellBranch must match a descendant route of the ' + 'branch', + ); } } } @@ -193,10 +202,18 @@ class RouteConfiguration { void _onRoutingTableChanged() { final RoutingConfig routingTable = _routingConfig.value; assert(_debugCheckPath(routingTable.routes, true)); - assert(_debugVerifyNoDuplicatePathParameter( - routingTable.routes, {})); - assert(_debugCheckParentNavigatorKeys( - routingTable.routes, >[navigatorKey])); + assert( + _debugVerifyNoDuplicatePathParameter( + routingTable.routes, + {}, + ), + ); + assert( + _debugCheckParentNavigatorKeys( + routingTable.routes, + >[navigatorKey], + ), + ); assert(_debugCheckStatefulShellBranchDefaultLocations(routingTable.routes)); _nameToPath.clear(); _cacheNameToPath('', routingTable.routes); @@ -258,11 +275,13 @@ class RouteConfiguration { String? fragment, }) { assert(() { - log('getting location for name: ' - '"$name"' - '${pathParameters.isEmpty ? '' : ', pathParameters: $pathParameters'}' - '${queryParameters.isEmpty ? '' : ', queryParameters: $queryParameters'}' - '${fragment != null ? ', fragment: $fragment' : ''}'); + log( + 'getting location for name: ' + '"$name"' + '${pathParameters.isEmpty ? '' : ', pathParameters: $pathParameters'}' + '${queryParameters.isEmpty ? '' : ', queryParameters: $queryParameters'}' + '${fragment != null ? ', fragment: $fragment' : ''}', + ); return true; }()); assert(_nameToPath.containsKey(name), 'unknown route name: $name'); @@ -272,8 +291,10 @@ class RouteConfiguration { final List paramNames = []; patternToRegExp(path.path, paramNames, caseSensitive: path.caseSensitive); for (final String paramName in paramNames) { - assert(pathParameters.containsKey(paramName), - 'missing param "$paramName" for $path'); + assert( + pathParameters.containsKey(paramName), + 'missing param "$paramName" for $path', + ); } // Check that there are no extra params @@ -284,24 +305,23 @@ class RouteConfiguration { }()); final Map encodedParams = { for (final MapEntry param in pathParameters.entries) - param.key: Uri.encodeComponent(param.value) + param.key: Uri.encodeComponent(param.value), }; - final String location = patternToPath( - path.path, - encodedParams, - ); + final String location = patternToPath(path.path, encodedParams); return Uri( - path: location, - queryParameters: queryParameters.isEmpty ? null : queryParameters, - fragment: fragment) - .toString(); + path: location, + queryParameters: queryParameters.isEmpty ? null : queryParameters, + fragment: fragment, + ).toString(); } /// Finds the routes that matched the given URL. RouteMatchList findMatch(Uri uri, {Object? extra}) { final Map pathParameters = {}; - final List matches = - _getLocRouteMatches(uri, pathParameters); + final List matches = _getLocRouteMatches( + uri, + pathParameters, + ); if (matches.isEmpty) { return _errorRouteMatchList( @@ -311,10 +331,11 @@ class RouteConfiguration { ); } return RouteMatchList( - matches: matches, - uri: uri, - pathParameters: pathParameters, - extra: extra); + matches: matches, + uri: uri, + pathParameters: pathParameters, + extra: extra, + ); } /// Reparse the input RouteMatchList @@ -324,17 +345,22 @@ class RouteConfiguration { for (final ImperativeRouteMatch imperativeMatch in matchList.matches.whereType()) { final ImperativeRouteMatch match = ImperativeRouteMatch( - pageKey: imperativeMatch.pageKey, - matches: findMatch(imperativeMatch.matches.uri, - extra: imperativeMatch.matches.extra), - completer: imperativeMatch.completer); + pageKey: imperativeMatch.pageKey, + matches: findMatch( + imperativeMatch.matches.uri, + extra: imperativeMatch.matches.extra, + ), + completer: imperativeMatch.completer, + ); result = result.push(match); } return result; } List _getLocRouteMatches( - Uri uri, Map pathParameters) { + Uri uri, + Map pathParameters, + ) { for (final RouteBase route in _routingConfig.value.routes) { final List result = RouteMatchBase.match( rootNavigatorKey: navigatorKey, @@ -352,12 +378,15 @@ class RouteConfiguration { /// Processes redirects by returning a new [RouteMatchList] representing the new /// location. FutureOr redirect( - BuildContext context, FutureOr prevMatchListFuture, - {required List redirectHistory}) { + BuildContext context, + FutureOr prevMatchListFuture, { + required List redirectHistory, + }) { FutureOr processRedirect(RouteMatchList prevMatchList) { final String prevLocation = prevMatchList.uri.toString(); FutureOr processTopLevelRedirect( - String? topRedirectLocation) { + String? topRedirectLocation, + ) { if (topRedirectLocation != null && topRedirectLocation != prevLocation) { final RouteMatchList newMatch = _getNewMatches( @@ -368,15 +397,12 @@ class RouteConfiguration { if (newMatch.isError) { return newMatch; } - return redirect( - context, - newMatch, - redirectHistory: redirectHistory, - ); + return redirect(context, newMatch, redirectHistory: redirectHistory); } FutureOr processRouteLevelRedirect( - String? routeRedirectLocation) { + String? routeRedirectLocation, + ) { if (routeRedirectLocation != null && routeRedirectLocation != prevLocation) { final RouteMatchList newMatch = _getNewMatches( @@ -410,8 +436,9 @@ class RouteConfiguration { if (routeLevelRedirectResult is String?) { return processRouteLevelRedirect(routeLevelRedirectResult); } - return routeLevelRedirectResult - .then(processRouteLevelRedirect); + return routeLevelRedirectResult.then( + processRouteLevelRedirect, + ); } redirectHistory.add(prevMatchList); @@ -446,7 +473,11 @@ class RouteConfiguration { FutureOr processRouteRedirect(String? newLocation) => newLocation ?? _getRouteLevelRedirect( - context, matchList, routeMatches, currentCheckIndex + 1); + context, + matchList, + routeMatches, + currentCheckIndex + 1, + ); final RouteBase route = match.route; final FutureOr routeRedirectResult = route.redirect!.call( context, @@ -483,17 +514,13 @@ class RouteConfiguration { ) { if (redirects.contains(newMatch)) { throw GoException( - 'redirect loop detected ${_formatRedirectionHistory([ - ...redirects, - newMatch - ])}'); + 'redirect loop detected ${_formatRedirectionHistory([...redirects, newMatch])}', + ); } if (redirects.length > _routingConfig.value.redirectLimit) { throw GoException( - 'too many redirects ${_formatRedirectionHistory([ - ...redirects, - newMatch - ])}'); + 'too many redirects ${_formatRedirectionHistory([...redirects, newMatch])}', + ); } redirects.add(newMatch); @@ -504,7 +531,8 @@ class RouteConfiguration { String _formatRedirectionHistory(List redirections) { return redirections .map( - (RouteMatchList routeMatches) => routeMatches.uri.toString()) + (RouteMatchList routeMatches) => routeMatches.uri.toString(), + ) .join(' => '); } @@ -529,24 +557,36 @@ class RouteConfiguration { final StringBuffer sb = StringBuffer(); sb.writeln('Full paths for routes:'); _debugFullPathsFor( - _routingConfig.value.routes, '', const <_DecorationType>[], sb); + _routingConfig.value.routes, + '', + const <_DecorationType>[], + sb, + ); if (_nameToPath.isNotEmpty) { sb.writeln('known full paths for route names:'); for (final MapEntry e in _nameToPath.entries) { sb.writeln( - ' ${e.key} => ${e.value.path}${e.value.caseSensitive ? '' : ' (case-insensitive)'}'); + ' ${e.key} => ${e.value.path}${e.value.caseSensitive ? '' : ' (case-insensitive)'}', + ); } } return sb.toString(); } - void _debugFullPathsFor(List routes, String parentFullpath, - List<_DecorationType> parentDecoration, StringBuffer sb) { + void _debugFullPathsFor( + List routes, + String parentFullpath, + List<_DecorationType> parentDecoration, + StringBuffer sb, + ) { for (final (int index, RouteBase route) in routes.indexed) { - final List<_DecorationType> decoration = - _getDecoration(parentDecoration, index, routes.length); + final List<_DecorationType> decoration = _getDecoration( + parentDecoration, + index, + routes.length, + ); final String decorationString = decoration.map((_DecorationType e) => e.toString()).join(); String path = parentFullpath; @@ -554,8 +594,10 @@ class RouteConfiguration { path = concatenatePaths(parentFullpath, route.path); final String? screenName = route.builder?.runtimeType.toString().split('=> ').last; - sb.writeln('$decorationString$path ' - '${screenName == null ? '' : '($screenName)'}'); + sb.writeln( + '$decorationString$path ' + '${screenName == null ? '' : '($screenName)'}', + ); } else if (route is ShellRouteBase) { sb.writeln('$decorationString (ShellRoute)'); } @@ -568,8 +610,9 @@ class RouteConfiguration { int index, int length, ) { - final Iterable<_DecorationType> newDecoration = - parentDecoration.map((_DecorationType e) { + final Iterable<_DecorationType> newDecoration = parentDecoration.map(( + _DecorationType e, + ) { switch (e) { // swap case _DecorationType.branch: @@ -598,11 +641,14 @@ class RouteConfiguration { if (route.name != null) { final String name = route.name!; assert( - !_nameToPath.containsKey(name), - 'duplication fullpaths for name ' - '"$name":${_nameToPath[name]!.path}, $fullPath'); - _nameToPath[name] = - (path: fullPath, caseSensitive: route.caseSensitive); + !_nameToPath.containsKey(name), + 'duplication fullpaths for name ' + '"$name":${_nameToPath[name]!.path}, $fullPath', + ); + _nameToPath[name] = ( + path: fullPath, + caseSensitive: route.caseSensitive, + ); } if (route.routes.isNotEmpty) { @@ -621,8 +667,7 @@ enum _DecorationType { parentBranch('│ '), branch('├─'), leaf('└─'), - none(' '), - ; + none(' '); const _DecorationType(this.value); diff --git a/packages/go_router/lib/src/delegate.dart b/packages/go_router/lib/src/delegate.dart index 3598a2237f2..02134a73197 100644 --- a/packages/go_router/lib/src/delegate.dart +++ b/packages/go_router/lib/src/delegate.dart @@ -68,8 +68,10 @@ class GoRouterDelegate extends RouterDelegate if (lastRoute.onExit != null && navigatorKey.currentContext != null) { return !(await lastRoute.onExit!( navigatorKey.currentContext!, - currentConfiguration.last - .buildState(_configuration, currentConfiguration), + currentConfiguration.last.buildState( + _configuration, + currentConfiguration, + ), )); } @@ -123,8 +125,9 @@ class GoRouterDelegate extends RouterDelegate final NavigatorState potentialCandidate = walker.navigatorKey.currentState!; - final ModalRoute? modalRoute = - ModalRoute.of(potentialCandidate.context); + final ModalRoute? modalRoute = ModalRoute.of( + potentialCandidate.context, + ); if (modalRoute == null || !modalRoute.isCurrent) { // Stop if there is a pageless route on top of the shell route. break; @@ -136,7 +139,10 @@ class GoRouterDelegate extends RouterDelegate } bool _handlePopPageWithRouteMatch( - Route route, Object? result, RouteMatchBase match) { + Route route, + Object? result, + RouteMatchBase match, + ) { if (route.willHandlePopInternally) { final bool popped = route.didPop(result); assert(!popped); @@ -192,8 +198,10 @@ class GoRouterDelegate extends RouterDelegate /// The top [GoRouterState], the state of the route that was /// last used in either [GoRouter.go] or [GoRouter.push]. - GoRouterState get state => currentConfiguration.last - .buildState(_configuration, currentConfiguration); + GoRouterState get state => currentConfiguration.last.buildState( + _configuration, + currentConfiguration, + ); /// For use by the Router architecture as part of the RouterDelegate. GlobalKey get navigatorKey => _configuration.navigatorKey; @@ -205,11 +213,7 @@ class GoRouterDelegate extends RouterDelegate /// For use by the Router architecture as part of the RouterDelegate. @override Widget build(BuildContext context) { - return builder.build( - context, - currentConfiguration, - routerNeglect, - ); + return builder.build(context, currentConfiguration, routerNeglect); } /// For use by the Router architecture as part of the RouterDelegate. @@ -287,11 +291,7 @@ class GoRouterDelegate extends RouterDelegate final RouteMatch match = matches[index]; final GoRoute goRoute = match.route; if (goRoute.onExit == null) { - return _callOnExitStartsAt( - index - 1, - context: context, - matches: matches, - ); + return _callOnExitStartsAt(index - 1, context: context, matches: matches); } Future handleOnExitResult(bool exit) { diff --git a/packages/go_router/lib/src/information_provider.dart b/packages/go_router/lib/src/information_provider.dart index 400ead006f7..79009888620 100644 --- a/packages/go_router/lib/src/information_provider.dart +++ b/packages/go_router/lib/src/information_provider.dart @@ -49,9 +49,11 @@ class RouteInformationState { this.completer, this.baseRouteMatchList, required this.type, - }) : assert((type == NavigatingType.go || type == NavigatingType.restore) == - (completer == null)), - assert((type != NavigatingType.go) == (baseRouteMatchList != null)); + }) : assert( + (type == NavigatingType.go || type == NavigatingType.restore) == + (completer == null), + ), + assert((type != NavigatingType.go) == (baseRouteMatchList != null)); /// The extra object used when navigating with [GoRouter]. final Object? extra; @@ -81,14 +83,16 @@ class GoRouteInformationProvider extends RouteInformationProvider required Object? initialExtra, Listenable? refreshListenable, bool routerNeglect = false, - }) : _refreshListenable = refreshListenable, - _value = RouteInformation( - uri: Uri.parse(initialLocation), - state: RouteInformationState( - extra: initialExtra, type: NavigatingType.go), - ), - _valueInEngine = _kEmptyRouteInformation, - _routerNeglect = routerNeglect { + }) : _refreshListenable = refreshListenable, + _value = RouteInformation( + uri: Uri.parse(initialLocation), + state: RouteInformationState( + extra: initialExtra, + type: NavigatingType.go, + ), + ), + _valueInEngine = _kEmptyRouteInformation, + _routerNeglect = routerNeglect { _refreshListenable?.addListener(notifyListeners); } @@ -97,13 +101,15 @@ class GoRouteInformationProvider extends RouteInformationProvider final bool _routerNeglect; static WidgetsBinding get _binding => WidgetsBinding.instance; - static final RouteInformation _kEmptyRouteInformation = - RouteInformation(uri: Uri.parse('')); + static final RouteInformation _kEmptyRouteInformation = RouteInformation( + uri: Uri.parse(''), + ); @override - void routerReportsNewRouteInformation(RouteInformation routeInformation, - {RouteInformationReportingType type = - RouteInformationReportingType.none}) { + void routerReportsNewRouteInformation( + RouteInformation routeInformation, { + RouteInformationReportingType type = RouteInformationReportingType.none, + }) { // GoRouteInformationParser should always report encoded route match list // in the state. assert(routeInformation.state != null); @@ -111,8 +117,9 @@ class GoRouteInformationProvider extends RouteInformationProvider switch (type) { case RouteInformationReportingType.none: if (!_valueHasChanged( - newLocationUri: routeInformation.uri, - newState: routeInformation.state)) { + newLocationUri: routeInformation.uri, + newState: routeInformation.state, + )) { return; } replace = _valueInEngine == _kEmptyRouteInformation; @@ -147,8 +154,10 @@ class GoRouteInformationProvider extends RouteInformationProvider uri = concatenateUris(_value.uri, uri); } - final bool shouldNotify = - _valueHasChanged(newLocationUri: uri, newState: state); + final bool shouldNotify = _valueHasChanged( + newLocationUri: uri, + newState: state, + ); _value = RouteInformation(uri: uri, state: state); if (shouldNotify) { notifyListeners(); @@ -156,8 +165,11 @@ class GoRouteInformationProvider extends RouteInformationProvider } /// Pushes the `location` as a new route on top of `base`. - Future push(String location, - {required RouteMatchList base, Object? extra}) { + Future push( + String location, { + required RouteMatchList base, + Object? extra, + }) { final Completer completer = Completer(); _setValue( location, @@ -175,10 +187,7 @@ class GoRouteInformationProvider extends RouteInformationProvider void go(String location, {Object? extra}) { _setValue( location, - RouteInformationState( - extra: extra, - type: NavigatingType.go, - ), + RouteInformationState(extra: extra, type: NavigatingType.go), ); } @@ -196,8 +205,11 @@ class GoRouteInformationProvider extends RouteInformationProvider /// Removes the top-most route match from `base` and pushes the `location` as a /// new route on top. - Future pushReplacement(String location, - {required RouteMatchList base, Object? extra}) { + Future pushReplacement( + String location, { + required RouteMatchList base, + Object? extra, + }) { final Completer completer = Completer(); _setValue( location, @@ -212,8 +224,11 @@ class GoRouteInformationProvider extends RouteInformationProvider } /// Replaces the top-most route match from `base` with the `location`. - Future replace(String location, - {required RouteMatchList base, Object? extra}) { + Future replace( + String location, { + required RouteMatchList base, + Object? extra, + }) { final Completer completer = Completer(); _setValue( location, @@ -245,16 +260,24 @@ class GoRouteInformationProvider extends RouteInformationProvider notifyListeners(); } - bool _valueHasChanged( - {required Uri newLocationUri, required Object? newState}) { + bool _valueHasChanged({ + required Uri newLocationUri, + required Object? newState, + }) { const DeepCollectionEquality deepCollectionEquality = DeepCollectionEquality(); return !deepCollectionEquality.equals( - _value.uri.path, newLocationUri.path) || + _value.uri.path, + newLocationUri.path, + ) || !deepCollectionEquality.equals( - _value.uri.queryParameters, newLocationUri.queryParameters) || + _value.uri.queryParameters, + newLocationUri.queryParameters, + ) || !deepCollectionEquality.equals( - _value.uri.fragment, newLocationUri.fragment) || + _value.uri.fragment, + newLocationUri.fragment, + ) || !deepCollectionEquality.equals(_value.state, newState); } diff --git a/packages/go_router/lib/src/match.dart b/packages/go_router/lib/src/match.dart index 8fbd083ce6e..556b5126c89 100644 --- a/packages/go_router/lib/src/match.dart +++ b/packages/go_router/lib/src/match.dart @@ -48,7 +48,9 @@ abstract class RouteMatchBase with Diagnosticable { /// Gets the state that represent this route match. GoRouterState buildState( - RouteConfiguration configuration, RouteMatchList matches); + RouteConfiguration configuration, + RouteMatchList matches, + ); /// Generates a list of [RouteMatchBase] objects by matching the `route` and /// its sub-routes with `uri`. @@ -88,7 +90,7 @@ abstract class RouteMatchBase with Diagnosticable { /// The scopedNavigatorKey must not be part of the returned map; otherwise, /// it is impossible to order the matches. static Map?, List> - _matchByNavigatorKey({ + _matchByNavigatorKey({ required RouteBase route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 @@ -136,7 +138,7 @@ abstract class RouteMatchBase with Diagnosticable { } static Map?, List> - _matchByNavigatorKeyForShellRoute({ + _matchByNavigatorKeyForShellRoute({ required ShellRouteBase route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 @@ -162,8 +164,9 @@ abstract class RouteMatchBase with Diagnosticable { uri: uri, scopedNavigatorKey: navigatorKeyUsed, ); - assert(!subRouteMatches - .containsKey(route.navigatorKeyForSubRoute(subRoute))); + assert( + !subRouteMatches.containsKey(route.navigatorKeyForSubRoute(subRoute)), + ); if (subRouteMatches.isNotEmpty) { break; } @@ -180,16 +183,15 @@ abstract class RouteMatchBase with Diagnosticable { pageKey: ValueKey(route.hashCode.toString()), navigatorKey: navigatorKeyUsed, ); - subRouteMatches.putIfAbsent(parentKey, () => []).insert( - 0, - result, - ); + subRouteMatches + .putIfAbsent(parentKey, () => []) + .insert(0, result); return subRouteMatches; } static Map?, List> - _matchByNavigatorKeyForGoRoute({ + _matchByNavigatorKeyForGoRoute({ required GoRoute route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 @@ -203,22 +205,28 @@ abstract class RouteMatchBase with Diagnosticable { ? null : route.parentNavigatorKey; - final RegExpMatch? regExpMatch = - route.matchPatternAsPrefix(remainingLocation); + final RegExpMatch? regExpMatch = route.matchPatternAsPrefix( + remainingLocation, + ); if (regExpMatch == null) { return _empty; } - final Map encodedParams = - route.extractPathParams(regExpMatch); + final Map encodedParams = route.extractPathParams( + regExpMatch, + ); // A temporary map to hold path parameters. This map is merged into // pathParameters only when this route is part of the returned result. - final Map currentPathParameter = - encodedParams.map((String key, String value) => - MapEntry(key, Uri.decodeComponent(value))); + final Map currentPathParameter = encodedParams + .map( + (String key, String value) => + MapEntry(key, Uri.decodeComponent(value)), + ); final String pathLoc = patternToPath(route.path, encodedParams); - final String newMatchedLocation = - concatenatePaths(matchedLocation, pathLoc); + final String newMatchedLocation = concatenatePaths( + matchedLocation, + pathLoc, + ); final String newMatchedPath = concatenatePaths(matchedPath, route.path); final String newMatchedLocationToCompare; @@ -248,7 +256,8 @@ abstract class RouteMatchBase with Diagnosticable { assert(remainingLocation.isNotEmpty); final String childRestLoc = uri.path.substring( - newMatchedLocation.length + (newMatchedLocation == '/' ? 0 : 1)); + newMatchedLocation.length + (newMatchedLocation == '/' ? 0 : 1), + ); Map?, List>? subRouteMatches; for (final RouteBase subRoute in route.routes) { @@ -272,13 +281,16 @@ abstract class RouteMatchBase with Diagnosticable { } pathParameters.addAll(currentPathParameter); - subRouteMatches!.putIfAbsent(parentKey, () => []).insert( - 0, - RouteMatch( - route: route, - matchedLocation: newMatchedLocation, - pageKey: ValueKey(newMatchedPath), - )); + subRouteMatches! + .putIfAbsent(parentKey, () => []) + .insert( + 0, + RouteMatch( + route: route, + matchedLocation: newMatchedLocation, + pageKey: ValueKey(newMatchedPath), + ), + ); return subRouteMatches; } @@ -327,7 +339,9 @@ class RouteMatch extends RouteMatchBase { @override GoRouterState buildState( - RouteConfiguration configuration, RouteMatchList matches) { + RouteConfiguration configuration, + RouteMatchList matches, + ) { return GoRouterState( configuration, uri: matches.uri, @@ -382,7 +396,9 @@ class ShellRouteMatch extends RouteMatchBase { @override GoRouterState buildState( - RouteConfiguration configuration, RouteMatchList matches) { + RouteConfiguration configuration, + RouteMatchList matches, + ) { // The route related data is stored in the leaf route match. final RouteMatch leafMatch = _lastLeaf; if (leafMatch is ImperativeRouteMatch) { @@ -407,9 +423,7 @@ class ShellRouteMatch extends RouteMatchBase { // TODO(loic-sharma): Remove meta library prefix. // https://github.com/flutter/flutter/issues/171410 @meta.internal - ShellRouteMatch copyWith({ - required List? matches, - }) { + ShellRouteMatch copyWith({required List? matches}) { return ShellRouteMatch( matches: matches ?? this.matches, route: route, @@ -436,17 +450,21 @@ class ShellRouteMatch extends RouteMatchBase { /// The route match that represent route pushed through [GoRouter.push]. class ImperativeRouteMatch extends RouteMatch { /// Constructor for [ImperativeRouteMatch]. - ImperativeRouteMatch( - {required super.pageKey, required this.matches, required this.completer}) - : super( - route: _getsLastRouteFromMatches(matches), - matchedLocation: _getsMatchedLocationFromMatches(matches), - ); + ImperativeRouteMatch({ + required super.pageKey, + required this.matches, + required this.completer, + }) : super( + route: _getsLastRouteFromMatches(matches), + matchedLocation: _getsMatchedLocationFromMatches(matches), + ); static GoRoute _getsLastRouteFromMatches(RouteMatchList matchList) { if (matchList.isError) { return GoRoute( - path: 'error', builder: (_, __) => throw UnimplementedError()); + path: 'error', + builder: (_, __) => throw UnimplementedError(), + ); } return matchList.last.route; } @@ -472,7 +490,9 @@ class ImperativeRouteMatch extends RouteMatch { @override GoRouterState buildState( - RouteConfiguration configuration, RouteMatchList matches) { + RouteConfiguration configuration, + RouteMatchList matches, + ) { return super.buildState(configuration, this.matches); } @@ -506,9 +526,10 @@ class RouteMatchList with Diagnosticable { /// Constructs an empty matches object. static RouteMatchList empty = RouteMatchList( - matches: const [], - uri: Uri(), - pathParameters: const {}); + matches: const [], + uri: Uri(), + pathParameters: const {}, + ); /// The route matches. final List matches; @@ -571,8 +592,9 @@ class RouteMatchList with Diagnosticable { /// ``` static String _generateFullPath(Iterable matches) { String fullPath = ''; - for (final RouteMatchBase match in matches - .where((RouteMatchBase match) => match is! ImperativeRouteMatch)) { + for (final RouteMatchBase match in matches.where( + (RouteMatchBase match) => match is! ImperativeRouteMatch, + )) { final String pathSegment; if (match is RouteMatch) { pathSegment = match.route.path; @@ -623,19 +645,25 @@ class RouteMatchList with Diagnosticable { newMatches.add( // Create a new copy of the `lastShellRouteMatch`. lastShellRouteMatch.copyWith( - matches: _createNewMatchUntilIncompatible(lastShellRouteMatch.matches, - (otherMatches.last as ShellRouteMatch).matches, match), + matches: _createNewMatchUntilIncompatible( + lastShellRouteMatch.matches, + (otherMatches.last as ShellRouteMatch).matches, + match, + ), ), ); return newMatches; } - newMatches - .add(_cloneBranchAndInsertImperativeMatch(otherMatches.last, match)); + newMatches.add( + _cloneBranchAndInsertImperativeMatch(otherMatches.last, match), + ); return newMatches; } static RouteMatchBase _cloneBranchAndInsertImperativeMatch( - RouteMatchBase branch, ImperativeRouteMatch match) { + RouteMatchBase branch, + ImperativeRouteMatch match, + ) { if (branch is ShellRouteMatch) { return branch.copyWith( matches: [ @@ -652,17 +680,17 @@ class RouteMatchList with Diagnosticable { /// Returns a new instance of RouteMatchList with the input `match` removed /// from the current instance. RouteMatchList remove(RouteMatchBase match) { - final List newMatches = - _removeRouteMatchFromList(matches, match); + final List newMatches = _removeRouteMatchFromList( + matches, + match, + ); if (newMatches == matches) { return this; } final String fullPath = _generateFullPath(newMatches); if (this.fullPath == fullPath) { - return copyWith( - matches: newMatches, - ); + return copyWith(matches: newMatches); } if (newMatches.isEmpty) { @@ -676,16 +704,22 @@ class RouteMatchList with Diagnosticable { newRoute as GoRoute; // Need to remove path parameters that are no longer in the fullPath. final List newParameters = []; - patternToRegExp(fullPath, newParameters, - caseSensitive: newRoute.caseSensitive); + patternToRegExp( + fullPath, + newParameters, + caseSensitive: newRoute.caseSensitive, + ); final Set validParameters = newParameters.toSet(); final Map newPathParameters = Map.fromEntries( - pathParameters.entries.where((MapEntry value) => - validParameters.contains(value.key)), + pathParameters.entries.where( + (MapEntry value) => + validParameters.contains(value.key), + ), + ); + final Uri newUri = uri.replace( + path: patternToPath(fullPath, newPathParameters), ); - final Uri newUri = - uri.replace(path: patternToPath(fullPath, newPathParameters)); return copyWith( matches: newMatches, uri: newUri, @@ -705,7 +739,9 @@ class RouteMatchList with Diagnosticable { /// If a target is found, the target and every node after the target in tree /// order is removed. static List _removeRouteMatchFromList( - List matches, RouteMatchBase target) { + List matches, + RouteMatchBase target, + ) { // Remove is caused by pop; therefore, start searching from the end. for (int index = matches.length - 1; index >= 0; index -= 1) { final RouteMatchBase match = matches[index]; @@ -721,8 +757,10 @@ class RouteMatchList with Diagnosticable { return matches.sublist(0, index); } if (match is ShellRouteMatch) { - final List newSubMatches = - _removeRouteMatchFromList(match.matches, target); + final List newSubMatches = _removeRouteMatchFromList( + match.matches, + target, + ); if (newSubMatches == match.matches) { // Didn't find target in the newSubMatches. continue; @@ -789,7 +827,9 @@ class RouteMatchList with Diagnosticable { } static bool _visitRouteMatches( - List matches, RouteMatchVisitor visitor) { + List matches, + RouteMatchVisitor visitor, + ) { for (final RouteMatchBase routeMatch in matches) { if (!visitor(routeMatch)) { return false; @@ -812,11 +852,12 @@ class RouteMatchList with Diagnosticable { Map? pathParameters, }) { return RouteMatchList( - matches: matches ?? this.matches, - uri: uri ?? this.uri, - extra: extra, - error: error, - pathParameters: pathParameters ?? this.pathParameters); + matches: matches ?? this.matches, + uri: uri ?? this.uri, + extra: extra, + error: error, + pathParameters: pathParameters ?? this.pathParameters, + ); } @override @@ -829,8 +870,10 @@ class RouteMatchList with Diagnosticable { extra == other.extra && error == other.error && const ListEquality().equals(matches, other.matches) && - const MapEquality() - .equals(pathParameters, other.pathParameters); + const MapEquality().equals( + pathParameters, + other.pathParameters, + ); } @override @@ -841,8 +884,10 @@ class RouteMatchList with Diagnosticable { extra, error, Object.hashAllUnordered( - pathParameters.entries.map((MapEntry entry) => - Object.hash(entry.key, entry.value)), + pathParameters.entries.map( + (MapEntry entry) => + Object.hash(entry.key, entry.value), + ), ), ); } @@ -851,8 +896,9 @@ class RouteMatchList with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('uri', uri)); - properties - .add(DiagnosticsProperty>('matches', matches)); + properties.add( + DiagnosticsProperty>('matches', matches), + ); } } @@ -866,8 +912,8 @@ class RouteMatchList with Diagnosticable { class RouteMatchListCodec extends Codec> { /// Creates a new [RouteMatchListCodec] object. RouteMatchListCodec(RouteConfiguration configuration) - : decoder = _RouteMatchListDecoder(configuration), - encoder = _RouteMatchListEncoder(configuration); + : decoder = _RouteMatchListDecoder(configuration), + encoder = _RouteMatchListEncoder(configuration); static const String _locationKey = 'location'; static const String _extraKey = 'state'; @@ -902,23 +948,35 @@ class _RouteMatchListEncoder }); final List> encodedImperativeMatches = imperativeMatches - .map((ImperativeRouteMatch e) => _toPrimitives( - e.matches.uri.toString(), e.matches.extra, - pageKey: e.pageKey.value)) + .map( + (ImperativeRouteMatch e) => _toPrimitives( + e.matches.uri.toString(), + e.matches.extra, + pageKey: e.pageKey.value, + ), + ) .toList(); - return _toPrimitives(input.uri.toString(), input.extra, - imperativeMatches: encodedImperativeMatches); + return _toPrimitives( + input.uri.toString(), + input.extra, + imperativeMatches: encodedImperativeMatches, + ); } - Map _toPrimitives(String location, Object? extra, - {List>? imperativeMatches, String? pageKey}) { + Map _toPrimitives( + String location, + Object? extra, { + List>? imperativeMatches, + String? pageKey, + }) { Map encodedExtra; if (configuration.extraCodec != null) { encodedExtra = { RouteMatchListCodec._codecKey: RouteMatchListCodec._customCodecName, - RouteMatchListCodec._encodedKey: - configuration.extraCodec?.encode(extra), + RouteMatchListCodec._encodedKey: configuration.extraCodec?.encode( + extra, + ), }; } else { String jsonEncodedExtra; @@ -927,10 +985,11 @@ class _RouteMatchListEncoder } on JsonUnsupportedObjectError { jsonEncodedExtra = json.encoder.convert(null); log( - 'An extra with complex data type ${extra.runtimeType} is provided ' - 'without a codec. Consider provide a codec to GoRouter to ' - 'prevent extra being dropped during serialization.', - level: Level.WARNING); + 'An extra with complex data type ${extra.runtimeType} is provided ' + 'without a codec. Consider provide a codec to GoRouter to ' + 'prevent extra being dropped during serialization.', + level: Level.WARNING, + ); } encodedExtra = { RouteMatchListCodec._codecKey: RouteMatchListCodec._jsonCodecName, @@ -964,24 +1023,30 @@ class _RouteMatchListDecoder if (encodedExtra[RouteMatchListCodec._codecKey] == RouteMatchListCodec._jsonCodecName) { - extra = json.decoder - .convert(encodedExtra[RouteMatchListCodec._encodedKey]! as String); + extra = json.decoder.convert( + encodedExtra[RouteMatchListCodec._encodedKey]! as String, + ); } else { - extra = configuration.extraCodec - ?.decode(encodedExtra[RouteMatchListCodec._encodedKey]); + extra = configuration.extraCodec?.decode( + encodedExtra[RouteMatchListCodec._encodedKey], + ); } - RouteMatchList matchList = - configuration.findMatch(Uri.parse(rootLocation), extra: extra); + RouteMatchList matchList = configuration.findMatch( + Uri.parse(rootLocation), + extra: extra, + ); final List? imperativeMatches = input[RouteMatchListCodec._imperativeMatchesKey] as List?; if (imperativeMatches != null) { for (final Map encodedImperativeMatch in imperativeMatches.whereType>()) { - final RouteMatchList imperativeMatchList = - convert(encodedImperativeMatch); + final RouteMatchList imperativeMatchList = convert( + encodedImperativeMatch, + ); final ValueKey pageKey = ValueKey( - encodedImperativeMatch[RouteMatchListCodec._pageKey]! as String); + encodedImperativeMatch[RouteMatchListCodec._pageKey]! as String, + ); final ImperativeRouteMatch imperativeMatch = ImperativeRouteMatch( pageKey: pageKey, // TODO(chunhtai): Figure out a way to preserve future. diff --git a/packages/go_router/lib/src/misc/custom_parameter.dart b/packages/go_router/lib/src/misc/custom_parameter.dart index 54fa0f06c96..cf4d3eea75b 100644 --- a/packages/go_router/lib/src/misc/custom_parameter.dart +++ b/packages/go_router/lib/src/misc/custom_parameter.dart @@ -29,10 +29,7 @@ import 'package:meta/meta_meta.dart' show Target, TargetKind; final class CustomParameterCodec { /// create a custom parameter codec /// - const CustomParameterCodec({ - required this.encode, - required this.decode, - }); + const CustomParameterCodec({required this.encode, required this.decode}); /// custom function to encode the field final String Function(String field) encode; diff --git a/packages/go_router/lib/src/misc/error_screen.dart b/packages/go_router/lib/src/misc/error_screen.dart index 1d0884ca5f4..412491414d3 100644 --- a/packages/go_router/lib/src/misc/error_screen.dart +++ b/packages/go_router/lib/src/misc/error_screen.dart @@ -18,35 +18,32 @@ class ErrorScreen extends StatelessWidget { @override Widget build(BuildContext context) => SafeArea( - child: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text( - 'Page Not Found', - style: TextStyle(fontWeight: FontWeight.bold), - ), - const SizedBox(height: 16), - Text(error?.toString() ?? 'page not found'), - const SizedBox(height: 16), - _Button( - onPressed: () => context.go('/'), - child: const Text( - 'Go to home page', - style: TextStyle(color: _kWhite), - ), - ), - ], + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text( + 'Page Not Found', + style: TextStyle(fontWeight: FontWeight.bold), ), - ), - ); + const SizedBox(height: 16), + Text(error?.toString() ?? 'page not found'), + const SizedBox(height: 16), + _Button( + onPressed: () => context.go('/'), + child: const Text( + 'Go to home page', + style: TextStyle(color: _kWhite), + ), + ), + ], + ), + ), + ); } class _Button extends StatefulWidget { - const _Button({ - required this.onPressed, - required this.child, - }); + const _Button({required this.onPressed, required this.child}); final VoidCallback onPressed; @@ -63,7 +60,8 @@ class _ButtonState extends State<_Button> { @override void didChangeDependencies() { super.didChangeDependencies(); - _color = (context as Element) + _color = + (context as Element) .findAncestorWidgetOfExactType() ?.color ?? const Color(0xFF2196F3); // blue @@ -71,11 +69,11 @@ class _ButtonState extends State<_Button> { @override Widget build(BuildContext context) => GestureDetector( - onTap: widget.onPressed, - child: Container( - padding: const EdgeInsets.all(8), - color: _color, - child: widget.child, - ), - ); + onTap: widget.onPressed, + child: Container( + padding: const EdgeInsets.all(8), + color: _color, + child: widget.child, + ), + ); } diff --git a/packages/go_router/lib/src/misc/extensions.dart b/packages/go_router/lib/src/misc/extensions.dart index 3c390c94598..222da22d0bc 100644 --- a/packages/go_router/lib/src/misc/extensions.dart +++ b/packages/go_router/lib/src/misc/extensions.dart @@ -17,11 +17,12 @@ extension GoRouterHelper on BuildContext { Map pathParameters = const {}, Map queryParameters = const {}, String? fragment, - }) => - GoRouter.of(this).namedLocation(name, - pathParameters: pathParameters, - queryParameters: queryParameters, - fragment: fragment); + }) => GoRouter.of(this).namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + fragment: fragment, + ); /// Navigate to a location. void go(String location, {Object? extra}) => @@ -34,12 +35,13 @@ extension GoRouterHelper on BuildContext { Map queryParameters = const {}, Object? extra, String? fragment, - }) => - GoRouter.of(this).goNamed(name, - pathParameters: pathParameters, - queryParameters: queryParameters, - extra: extra, - fragment: fragment); + }) => GoRouter.of(this).goNamed( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + extra: extra, + fragment: fragment, + ); /// Push a location onto the page stack. /// @@ -58,13 +60,12 @@ extension GoRouterHelper on BuildContext { Map pathParameters = const {}, Map queryParameters = const {}, Object? extra, - }) => - GoRouter.of(this).pushNamed( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - extra: extra, - ); + }) => GoRouter.of(this).pushNamed( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + extra: extra, + ); /// Returns `true` if there is more than 1 page on the stack. bool canPop() => GoRouter.of(this).canPop(); @@ -97,13 +98,12 @@ extension GoRouterHelper on BuildContext { Map pathParameters = const {}, Map queryParameters = const {}, Object? extra, - }) => - GoRouter.of(this).pushReplacementNamed( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - extra: extra, - ); + }) => GoRouter.of(this).pushReplacementNamed( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + extra: extra, + ); /// Replaces the top-most page of the page stack with the given one but treats /// it as the same page. @@ -134,9 +134,10 @@ extension GoRouterHelper on BuildContext { Map pathParameters = const {}, Map queryParameters = const {}, Object? extra, - }) => - GoRouter.of(this).replaceNamed(name, - pathParameters: pathParameters, - queryParameters: queryParameters, - extra: extra); + }) => GoRouter.of(this).replaceNamed( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + extra: extra, + ); } diff --git a/packages/go_router/lib/src/pages/cupertino.dart b/packages/go_router/lib/src/pages/cupertino.dart index cf64d812448..7d2121df0d3 100644 --- a/packages/go_router/lib/src/pages/cupertino.dart +++ b/packages/go_router/lib/src/pages/cupertino.dart @@ -22,14 +22,13 @@ CupertinoPage pageBuilderForCupertinoApp({ required Object? arguments, required String restorationId, required Widget child, -}) => - CupertinoPage( - name: name, - arguments: arguments, - key: key, - restorationId: restorationId, - child: child, - ); +}) => CupertinoPage( + name: name, + arguments: arguments, + key: key, + restorationId: restorationId, + child: child, +); /// Default error page implementation for Cupertino. class CupertinoErrorScreen extends StatelessWidget { @@ -41,19 +40,18 @@ class CupertinoErrorScreen extends StatelessWidget { @override Widget build(BuildContext context) => CupertinoPageScaffold( - navigationBar: - const CupertinoNavigationBar(middle: Text('Page Not Found')), - child: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text(error?.toString() ?? 'page not found'), - CupertinoButton( - onPressed: () => context.go('/'), - child: const Text('Home'), - ), - ], + navigationBar: const CupertinoNavigationBar(middle: Text('Page Not Found')), + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(error?.toString() ?? 'page not found'), + CupertinoButton( + onPressed: () => context.go('/'), + child: const Text('Home'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/lib/src/pages/custom_transition_page.dart b/packages/go_router/lib/src/pages/custom_transition_page.dart index 5e3752eaf78..f8e9c124202 100644 --- a/packages/go_router/lib/src/pages/custom_transition_page.dart +++ b/packages/go_router/lib/src/pages/custom_transition_page.dart @@ -99,8 +99,13 @@ class CustomTransitionPage extends Page { /// primary animation runs from 0.0 to 1.0. When the Navigator pops the /// topmost route, e.g. because the use pressed the back button, the primary /// animation runs from 1.0 to 0.0. - final Widget Function(BuildContext context, Animation animation, - Animation secondaryAnimation, Widget child) transitionsBuilder; + final Widget Function( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) + transitionsBuilder; @override Route createRoute(BuildContext context) => @@ -109,7 +114,7 @@ class CustomTransitionPage extends Page { class _CustomTransitionPageRoute extends PageRoute { _CustomTransitionPageRoute(CustomTransitionPage page) - : super(settings: page); + : super(settings: page); CustomTransitionPage get _page => settings as CustomTransitionPage; @@ -142,12 +147,11 @@ class _CustomTransitionPageRoute extends PageRoute { BuildContext context, Animation animation, Animation secondaryAnimation, - ) => - Semantics( - scopesRoute: true, - explicitChildNodes: true, - child: _page.child, - ); + ) => Semantics( + scopesRoute: true, + explicitChildNodes: true, + child: _page.child, + ); @override Widget buildTransitions( @@ -155,13 +159,7 @@ class _CustomTransitionPageRoute extends PageRoute { Animation animation, Animation secondaryAnimation, Widget child, - ) => - _page.transitionsBuilder( - context, - animation, - secondaryAnimation, - child, - ); + ) => _page.transitionsBuilder(context, animation, secondaryAnimation, child); } /// Custom transition page with no transition. @@ -174,15 +172,15 @@ class NoTransitionPage extends CustomTransitionPage { super.restorationId, super.key, }) : super( - transitionsBuilder: _transitionsBuilder, - transitionDuration: Duration.zero, - reverseTransitionDuration: Duration.zero, - ); + transitionsBuilder: _transitionsBuilder, + transitionDuration: Duration.zero, + reverseTransitionDuration: Duration.zero, + ); static Widget _transitionsBuilder( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child) => - child; + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => child; } diff --git a/packages/go_router/lib/src/pages/material.dart b/packages/go_router/lib/src/pages/material.dart index 06fb770a78e..27a700587ce 100644 --- a/packages/go_router/lib/src/pages/material.dart +++ b/packages/go_router/lib/src/pages/material.dart @@ -23,14 +23,13 @@ MaterialPage pageBuilderForMaterialApp({ required Object? arguments, required String restorationId, required Widget child, -}) => - MaterialPage( - name: name, - arguments: arguments, - key: key, - restorationId: restorationId, - child: child, - ); +}) => MaterialPage( + name: name, + arguments: arguments, + key: key, + restorationId: restorationId, + child: child, +); /// Default error page implementation for Material. class MaterialErrorScreen extends StatelessWidget { @@ -42,18 +41,18 @@ class MaterialErrorScreen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar(title: const Text('Page Not Found')), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SelectableText(error?.toString() ?? 'page not found'), - TextButton( - onPressed: () => context.go('/'), - child: const Text('Home'), - ), - ], + appBar: AppBar(title: const Text('Page Not Found')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SelectableText(error?.toString() ?? 'page not found'), + TextButton( + onPressed: () => context.go('/'), + child: const Text('Home'), ), - ), - ); + ], + ), + ), + ); } diff --git a/packages/go_router/lib/src/parser.dart b/packages/go_router/lib/src/parser.dart index d1981898a8b..0847767b41b 100644 --- a/packages/go_router/lib/src/parser.dart +++ b/packages/go_router/lib/src/parser.dart @@ -21,10 +21,11 @@ import 'router.dart'; /// /// The returned [RouteMatchList] is used as parsed result for the /// [GoRouterDelegate]. -typedef ParserExceptionHandler = RouteMatchList Function( - BuildContext context, - RouteMatchList routeMatchList, -); +typedef ParserExceptionHandler = + RouteMatchList Function( + BuildContext context, + RouteMatchList routeMatchList, + ); /// Converts between incoming URLs and a [RouteMatchList] using [RouteMatcher]. /// Also performs redirection using [RouteRedirector]. @@ -67,10 +68,13 @@ class GoRouteInformationParser extends RouteInformationParser { // This is a result of browser backward/forward button or state // restoration. In this case, the route match list is already stored in // the state. - final RouteMatchList matchList = - _routeMatchListCodec.decode(state as Map); - return debugParserFuture = _redirect(context, matchList) - .then((RouteMatchList value) { + final RouteMatchList matchList = _routeMatchListCodec.decode( + state as Map, + ); + return debugParserFuture = _redirect( + context, + matchList, + ).then((RouteMatchList value) { if (value.isError && onParserException != null) { // TODO(chunhtai): Figure out what to return if context is invalid. // ignore: use_build_context_synchronously @@ -107,8 +111,10 @@ class GoRouteInformationParser extends RouteInformationParser { 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}'); + 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; }()); @@ -123,9 +129,11 @@ class GoRouteInformationParser extends RouteInformationParser { @override Future parseRouteInformation( - RouteInformation routeInformation) { + RouteInformation routeInformation, + ) { throw UnimplementedError( - 'use parseRouteInformationWithDependencies instead'); + 'use parseRouteInformationWithDependencies instead', + ); } /// for use by the Router architecture as part of the RouteInformationParser @@ -159,9 +167,14 @@ class GoRouteInformationParser extends RouteInformationParser { } Future _redirect( - BuildContext context, RouteMatchList routeMatch) { - final FutureOr redirectedFuture = configuration - .redirect(context, routeMatch, redirectHistory: []); + BuildContext context, + RouteMatchList routeMatch, + ) { + final FutureOr redirectedFuture = configuration.redirect( + context, + routeMatch, + redirectHistory: [], + ); if (redirectedFuture is RouteMatchList) { return SynchronousFuture(redirectedFuture); } @@ -220,7 +233,10 @@ class GoRouteInformationParser extends RouteInformationParser { } ValueKey _getUniqueValueKey() { - return ValueKey(String.fromCharCodes( - List.generate(32, (_) => _random.nextInt(33) + 89))); + return ValueKey( + String.fromCharCodes( + List.generate(32, (_) => _random.nextInt(33) + 89), + ), + ); } } diff --git a/packages/go_router/lib/src/path_utils.dart b/packages/go_router/lib/src/path_utils.dart index 53c56b22fa9..d9192c6873f 100644 --- a/packages/go_router/lib/src/path_utils.dart +++ b/packages/go_router/lib/src/path_utils.dart @@ -23,8 +23,11 @@ final RegExp _parameterRegExp = RegExp(r':(\w+)(\((?:\\.|[^\\()])+\))?'); /// To extract the path parameter values from a [RegExpMatch], pass the /// [RegExpMatch] into [extractPathParameters] with the `parameters` that are /// used for generating the [RegExp]. -RegExp patternToRegExp(String pattern, List parameters, - {required bool caseSensitive}) { +RegExp patternToRegExp( + String pattern, + List parameters, { + required bool caseSensitive, +}) { final StringBuffer buffer = StringBuffer('^'); int start = 0; for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) { @@ -33,9 +36,10 @@ RegExp patternToRegExp(String pattern, List parameters, } 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; @@ -53,7 +57,9 @@ RegExp patternToRegExp(String pattern, List parameters, String _escapeGroup(String group, [String? name]) { final String escapedGroup = group.replaceFirstMapped( - RegExp(r'[:=!]'), (Match match) => '\\${match[0]}'); + RegExp(r'[:=!]'), + (Match match) => '\\${match[0]}', + ); if (name != null) { return '(?<$name>$escapedGroup)'; } @@ -95,10 +101,12 @@ String patternToPath(String pattern, Map pathParameters) { /// The [parameters] should originate from the call to [patternToRegExp] that /// creates the [RegExp]. Map extractPathParameters( - List parameters, RegExpMatch match) { + List parameters, + RegExpMatch match, +) { return { for (int i = 0; i < parameters.length; ++i) - parameters[i]: match.namedGroup(parameters[i])! + parameters[i]: match.namedGroup(parameters[i])!, }; } @@ -109,7 +117,7 @@ Map extractPathParameters( String concatenatePaths(String parentPath, String childPath) { final Iterable segments = [ ...parentPath.split('/'), - ...childPath.split('/') + ...childPath.split('/'), ].where((String segment) => segment.isNotEmpty); return '/${segments.join('/')}'; } @@ -140,19 +148,21 @@ String canonicalUri(String loc) { // /profile/ => /profile // / => / // /login?from=/ => /login?from=/ - canon = uri.path.endsWith('/') && - uri.path != '/' && - !uri.hasQuery && - !uri.hasFragment - ? canon.substring(0, canon.length - 1) - : canon; + canon = + uri.path.endsWith('/') && + 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 + 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) { @@ -164,17 +174,24 @@ String canonicalUri(String loc) { /// Builds an absolute path for the provided route. String? fullPathForRoute( - RouteBase targetRoute, String parentFullpath, List routes) { + RouteBase targetRoute, + String parentFullpath, + 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; } else { - final String? subRoutePath = - fullPathForRoute(targetRoute, fullPath, route.routes); + final String? subRoutePath = fullPathForRoute( + targetRoute, + fullPath, + route.routes, + ); if (subRoutePath != null) { return subRoutePath; } diff --git a/packages/go_router/lib/src/route.dart b/packages/go_router/lib/src/route.dart index 797e5fb44d0..fa08958be28 100644 --- a/packages/go_router/lib/src/route.dart +++ b/packages/go_router/lib/src/route.dart @@ -18,59 +18,57 @@ import 'router.dart'; import 'state.dart'; /// The page builder for [GoRoute]. -typedef GoRouterPageBuilder = Page Function( - BuildContext context, - GoRouterState state, -); +typedef GoRouterPageBuilder = + Page Function(BuildContext context, GoRouterState state); /// The widget builder for [GoRoute]. -typedef GoRouterWidgetBuilder = Widget Function( - BuildContext context, - GoRouterState state, -); +typedef GoRouterWidgetBuilder = + Widget Function(BuildContext context, GoRouterState state); /// The widget builder for [ShellRoute]. -typedef ShellRouteBuilder = Widget Function( - BuildContext context, - GoRouterState state, - Widget child, -); +typedef ShellRouteBuilder = + Widget Function(BuildContext context, GoRouterState state, Widget child); /// The page builder for [ShellRoute]. -typedef ShellRoutePageBuilder = Page Function( - BuildContext context, - GoRouterState state, - Widget child, -); +typedef ShellRoutePageBuilder = + Page Function( + BuildContext context, + GoRouterState state, + Widget child, + ); /// The widget builder for [StatefulShellRoute]. -typedef StatefulShellRouteBuilder = Widget Function( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, -); +typedef StatefulShellRouteBuilder = + Widget Function( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ); /// The page builder for [StatefulShellRoute]. -typedef StatefulShellRoutePageBuilder = Page Function( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, -); +typedef StatefulShellRoutePageBuilder = + Page Function( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ); /// Signature for functions used to build Navigators -typedef NavigatorBuilder = Widget Function( - GlobalKey navigatorKey, - ShellRouteMatch match, - RouteMatchList matchList, - List? observers, - String? restorationScopeId); +typedef NavigatorBuilder = + Widget Function( + GlobalKey navigatorKey, + ShellRouteMatch match, + RouteMatchList matchList, + List? observers, + String? restorationScopeId, + ); /// Signature for function used in [RouteBase.onExit]. /// /// If the return value is true or the future resolve to true, the route will /// exit as usual. Otherwise, the operation will abort. -typedef ExitCallback = FutureOr Function( - BuildContext context, GoRouterState state); +typedef ExitCallback = + FutureOr Function(BuildContext context, GoRouterState state); /// The base class for [GoRoute] and [ShellRoute]. /// @@ -236,15 +234,20 @@ abstract class RouteBase with Diagnosticable { /// descendant [routes]. static Iterable routesRecursively(Iterable routes) { return routes.expand( - (RouteBase e) => [e, ...routesRecursively(e.routes)]); + (RouteBase e) => [e, ...routesRecursively(e.routes)], + ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (parentNavigatorKey != null) { - properties.add(DiagnosticsProperty>( - 'parentNavKey', parentNavigatorKey)); + properties.add( + DiagnosticsProperty>( + 'parentNavKey', + parentNavigatorKey, + ), + ); } } } @@ -279,16 +282,23 @@ class GoRoute extends RouteBase { this.onExit, this.caseSensitive = true, super.routes = const [], - }) : assert(path.isNotEmpty, 'GoRoute path cannot be empty'), - assert(name == null || name.isNotEmpty, 'GoRoute name cannot be empty'), - assert(pageBuilder != null || builder != null || redirect != null, - 'builder, pageBuilder, or redirect must be provided'), - assert(onExit == null || pageBuilder != null || builder != null, - 'if onExit is provided, one of pageBuilder or builder must be provided'), - super._() { + }) : assert(path.isNotEmpty, 'GoRoute path cannot be empty'), + assert(name == null || name.isNotEmpty, 'GoRoute name cannot be empty'), + assert( + pageBuilder != null || builder != null || redirect != null, + 'builder, pageBuilder, or redirect must be provided', + ), + assert( + onExit == null || pageBuilder != null || builder != null, + 'if onExit is provided, one of pageBuilder or builder must be provided', + ), + super._() { // cache the path regexp and parameters - _pathRE = - patternToRegExp(path, pathParameters, caseSensitive: caseSensitive); + _pathRE = patternToRegExp( + path, + pathParameters, + caseSensitive: caseSensitive, + ); } /// Whether this [GoRoute] only redirects to another route. @@ -473,7 +483,8 @@ class GoRoute extends RouteBase { properties.add(StringProperty('name', name)); properties.add(StringProperty('path', path)); properties.add( - FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only')); + FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only'), + ); } late final RegExp _pathRE; @@ -490,12 +501,15 @@ abstract class ShellRouteBase extends RouteBase { }) : super._(); static void _debugCheckSubRouteParentNavigatorKeys( - List subRoutes, GlobalKey navigatorKey) { + List subRoutes, + GlobalKey navigatorKey, + ) { for (final RouteBase route in subRoutes) { assert( - route.parentNavigatorKey == null || - route.parentNavigatorKey == navigatorKey, - "sub-route's parent navigator key must either be null or has the same navigator key as parent's key"); + route.parentNavigatorKey == null || + route.parentNavigatorKey == navigatorKey, + "sub-route's parent navigator key must either be null or has the same navigator key as parent's key", + ); if (route is GoRoute && route.redirectOnly) { // This route does not produce a page, need to check its sub-routes // instead. @@ -508,15 +522,21 @@ abstract class ShellRouteBase extends RouteBase { /// /// Returns null if this shell route does not build a Widget, but instead uses /// a Page to represent itself (see [buildPage]). - Widget? buildWidget(BuildContext context, GoRouterState state, - ShellRouteContext shellRouteContext); + Widget? buildWidget( + BuildContext context, + GoRouterState state, + ShellRouteContext shellRouteContext, + ); /// Attempts to build the Page representing this shell route. /// /// Returns null if this shell route does not build a Page, but instead uses /// a Widget to represent itself (see [buildWidget]). - Page? buildPage(BuildContext context, GoRouterState state, - ShellRouteContext shellRouteContext); + Page? buildPage( + BuildContext context, + GoRouterState state, + ShellRouteContext shellRouteContext, + ); /// Returns the key for the [Navigator] that is to be used for the specified /// immediate sub-route of this shell route. @@ -557,9 +577,16 @@ class ShellRouteContext { final NavigatorBuilder navigatorBuilder; Widget _buildNavigatorForCurrentRoute( - List? observers, String? restorationScopeId) { + List? observers, + String? restorationScopeId, + ) { return navigatorBuilder( - navigatorKey, match, routeMatchList, observers, restorationScopeId); + navigatorKey, + match, + routeMatchList, + observers, + restorationScopeId, + ); } } @@ -669,12 +696,14 @@ class ShellRoute extends ShellRouteBase { super.parentNavigatorKey, GlobalKey? navigatorKey, this.restorationScopeId, - }) : assert(routes.isNotEmpty), - navigatorKey = navigatorKey ?? GlobalKey(), - super._() { + }) : assert(routes.isNotEmpty), + navigatorKey = navigatorKey ?? GlobalKey(), + super._() { assert(() { ShellRouteBase._debugCheckSubRouteParentNavigatorKeys( - routes, this.navigatorKey); + routes, + this.navigatorKey, + ); return true; }()); } @@ -696,22 +725,32 @@ class ShellRoute extends ShellRouteBase { final ShellRoutePageBuilder? pageBuilder; @override - Widget? buildWidget(BuildContext context, GoRouterState state, - ShellRouteContext shellRouteContext) { + Widget? buildWidget( + BuildContext context, + GoRouterState state, + ShellRouteContext shellRouteContext, + ) { if (builder != null) { final Widget navigator = shellRouteContext._buildNavigatorForCurrentRoute( - observers, restorationScopeId); + observers, + restorationScopeId, + ); return builder!(context, state, navigator); } return null; } @override - Page? buildPage(BuildContext context, GoRouterState state, - ShellRouteContext shellRouteContext) { + Page? buildPage( + BuildContext context, + GoRouterState state, + ShellRouteContext shellRouteContext, + ) { if (pageBuilder != null) { final Widget navigator = shellRouteContext._buildNavigatorForCurrentRoute( - observers, restorationScopeId); + observers, + restorationScopeId, + ); return pageBuilder!(context, state, navigator); } return null; @@ -741,8 +780,12 @@ class ShellRoute extends ShellRouteBase { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>( - 'navigatorKey', navigatorKey)); + properties.add( + DiagnosticsProperty>( + 'navigatorKey', + navigatorKey, + ), + ); } } @@ -831,15 +874,19 @@ class StatefulShellRoute extends ShellRouteBase { super.parentNavigatorKey, this.restorationScopeId, GlobalKey? key, - }) : assert(branches.isNotEmpty), - assert((pageBuilder != null) || (builder != null), - 'One of builder or pageBuilder must be provided'), - assert(_debugUniqueNavigatorKeys(branches).length == branches.length, - 'Navigator keys must be unique'), - assert(_debugValidateParentNavigatorKeys(branches)), - assert(_debugValidateRestorationScopeIds(restorationScopeId, branches)), - _shellStateKey = key ?? GlobalKey(), - super._(routes: _routes(branches)); + }) : assert(branches.isNotEmpty), + assert( + (pageBuilder != null) || (builder != null), + 'One of builder or pageBuilder must be provided', + ), + assert( + _debugUniqueNavigatorKeys(branches).length == branches.length, + 'Navigator keys must be unique', + ), + assert(_debugValidateParentNavigatorKeys(branches)), + assert(_debugValidateRestorationScopeIds(restorationScopeId, branches)), + _shellStateKey = key ?? GlobalKey(), + super._(routes: _routes(branches)); /// Constructs a StatefulShellRoute that uses an [IndexedStack] for its /// nested [Navigator]s. @@ -860,15 +907,15 @@ class StatefulShellRoute extends ShellRouteBase { String? restorationScopeId, GlobalKey? key, }) : this( - branches: branches, - redirect: redirect, - builder: builder, - pageBuilder: pageBuilder, - parentNavigatorKey: parentNavigatorKey, - restorationScopeId: restorationScopeId, - navigatorContainerBuilder: _indexedStackContainerBuilder, - key: key, - ); + branches: branches, + redirect: redirect, + builder: builder, + pageBuilder: pageBuilder, + parentNavigatorKey: parentNavigatorKey, + restorationScopeId: restorationScopeId, + navigatorContainerBuilder: _indexedStackContainerBuilder, + key: key, + ); /// Restoration ID to save and restore the state of the navigator, including /// its history. @@ -926,8 +973,11 @@ class StatefulShellRoute extends ShellRouteBase { final GlobalKey _shellStateKey; @override - Widget? buildWidget(BuildContext context, GoRouterState state, - ShellRouteContext shellRouteContext) { + Widget? buildWidget( + BuildContext context, + GoRouterState state, + ShellRouteContext shellRouteContext, + ) { if (builder != null) { return builder!(context, state, _createShell(context, shellRouteContext)); } @@ -935,11 +985,17 @@ class StatefulShellRoute extends ShellRouteBase { } @override - Page? buildPage(BuildContext context, GoRouterState state, - ShellRouteContext shellRouteContext) { + Page? buildPage( + BuildContext context, + GoRouterState state, + ShellRouteContext shellRouteContext, + ) { if (pageBuilder != null) { return pageBuilder!( - context, state, _createShell(context, shellRouteContext)); + context, + state, + _createShell(context, shellRouteContext), + ); } return null; } @@ -947,7 +1003,8 @@ class StatefulShellRoute extends ShellRouteBase { @override GlobalKey navigatorKeyForSubRoute(RouteBase subRoute) { final StatefulShellBranch? branch = branches.firstWhereOrNull( - (StatefulShellBranch e) => e.routes.contains(subRoute)); + (StatefulShellBranch e) => e.routes.contains(subRoute), + ); assert(branch != null); return branch!.navigatorKey; } @@ -956,33 +1013,44 @@ class StatefulShellRoute extends ShellRouteBase { branches.map((StatefulShellBranch b) => b.navigatorKey); StatefulNavigationShell _createShell( - BuildContext context, ShellRouteContext shellRouteContext) => - StatefulNavigationShell( - shellRouteContext: shellRouteContext, - router: GoRouter.of(context), - containerBuilder: navigatorContainerBuilder); - - static Widget _indexedStackContainerBuilder(BuildContext context, - StatefulNavigationShell navigationShell, List children) { + BuildContext context, + ShellRouteContext shellRouteContext, + ) => StatefulNavigationShell( + shellRouteContext: shellRouteContext, + router: GoRouter.of(context), + containerBuilder: navigatorContainerBuilder, + ); + + static Widget _indexedStackContainerBuilder( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ) { return _IndexedStackedRouteBranchContainer( - currentIndex: navigationShell.currentIndex, children: children); + currentIndex: navigationShell.currentIndex, + children: children, + ); } static List _routes(List branches) => branches.expand((StatefulShellBranch e) => e.routes).toList(); static Set> _debugUniqueNavigatorKeys( - List branches) => - Set>.from( - branches.map((StatefulShellBranch e) => e.navigatorKey)); + List branches, + ) => Set>.from( + branches.map((StatefulShellBranch e) => e.navigatorKey), + ); static bool _debugValidateParentNavigatorKeys( - List branches) { + List branches, + ) { for (final StatefulShellBranch branch in branches) { for (final RouteBase route in branch.routes) { if (route is GoRoute) { - assert(route.parentNavigatorKey == null || - route.parentNavigatorKey == branch.navigatorKey); + assert( + route.parentNavigatorKey == null || + route.parentNavigatorKey == branch.navigatorKey, + ); } } } @@ -990,16 +1058,19 @@ class StatefulShellRoute extends ShellRouteBase { } static bool _debugValidateRestorationScopeIds( - String? restorationScopeId, List branches) { + String? restorationScopeId, + List branches, + ) { if (branches .map((StatefulShellBranch e) => e.restorationScopeId) .nonNulls .isNotEmpty) { assert( - restorationScopeId != null, - 'A restorationScopeId must be set for ' - 'the StatefulShellRoute when using restorationScopeIds on one or more ' - 'of the branches'); + restorationScopeId != null, + 'A restorationScopeId must be set for ' + 'the StatefulShellRoute when using restorationScopeIds on one or more ' + 'of the branches', + ); } return true; } @@ -1007,8 +1078,12 @@ class StatefulShellRoute extends ShellRouteBase { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>>( - 'navigatorKeys', _navigatorKeys)); + properties.add( + DiagnosticsProperty>>( + 'navigatorKeys', + _navigatorKeys, + ), + ); } } @@ -1040,7 +1115,9 @@ class StatefulShellBranch { }) : navigatorKey = navigatorKey ?? GlobalKey() { assert(() { ShellRouteBase._debugCheckSubRouteParentNavigatorKeys( - routes, this.navigatorKey); + routes, + this.navigatorKey, + ); return true; }()); } @@ -1098,8 +1175,12 @@ class StatefulShellBranch { /// Builder for a custom container for the branch Navigators of a /// [StatefulShellRoute]. -typedef ShellNavigationContainerBuilder = Widget Function(BuildContext context, - StatefulNavigationShell navigationShell, List children); +typedef ShellNavigationContainerBuilder = + Widget Function( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ); /// Widget for managing the state of a [StatefulShellRoute]. /// @@ -1126,14 +1207,15 @@ class StatefulNavigationShell extends StatefulWidget { required this.shellRouteContext, required GoRouter router, required this.containerBuilder, - }) : assert(shellRouteContext.route is StatefulShellRoute), - _router = router, - currentIndex = _indexOfBranchNavigatorKey( - shellRouteContext.route as StatefulShellRoute, - shellRouteContext.navigatorKey), - super( - key: - (shellRouteContext.route as StatefulShellRoute)._shellStateKey); + }) : assert(shellRouteContext.route is StatefulShellRoute), + _router = router, + currentIndex = _indexOfBranchNavigatorKey( + shellRouteContext.route as StatefulShellRoute, + shellRouteContext.navigatorKey, + ), + super( + key: (shellRouteContext.route as StatefulShellRoute)._shellStateKey, + ); /// The ShellRouteContext responsible for building the Navigator for the /// current [StatefulShellBranch]. @@ -1198,12 +1280,17 @@ class StatefulNavigationShell extends StatefulWidget { /// find the first GoRoute, from which a full path will be derived. final GoRoute route = branch.defaultRoute!; final List parameters = []; - patternToRegExp(route.path, parameters, - caseSensitive: route.caseSensitive); + patternToRegExp( + route.path, + parameters, + caseSensitive: route.caseSensitive, + ); assert(parameters.isEmpty); final String fullPath = _router.configuration.locationForRoute(route)!; return patternToPath( - fullPath, shellRouteContext.routerState.pathParameters); + fullPath, + shellRouteContext.routerState.pathParameters, + ); } } @@ -1228,9 +1315,12 @@ class StatefulNavigationShell extends StatefulWidget { } static int _indexOfBranchNavigatorKey( - StatefulShellRoute route, GlobalKey navigatorKey) { + StatefulShellRoute route, + GlobalKey navigatorKey, + ) { final int index = route.branches.indexWhere( - (StatefulShellBranch branch) => branch.navigatorKey == navigatorKey); + (StatefulShellBranch branch) => branch.navigatorKey == navigatorKey, + ); assert(index >= 0); return index; } @@ -1264,14 +1354,19 @@ class StatefulNavigationShellState extends State : identityHashCode(branch).toString(); } - _StatefulShellBranchState _branchStateFor(StatefulShellBranch branch, - [bool register = true]) { + _StatefulShellBranchState _branchStateFor( + StatefulShellBranch branch, [ + bool register = true, + ]) { return _branchState.putIfAbsent(branch, () { final _StatefulShellBranchState branchState = _StatefulShellBranchState( - location: _RestorableRouteMatchList(_router.configuration)); + location: _RestorableRouteMatchList(_router.configuration), + ); if (register) { registerForRestoration( - branchState.location, _branchLocationRestorationScopeId(branch)); + branchState.location, + _branchLocationRestorationScopeId(branch), + ); } return branchState; }); @@ -1310,11 +1405,14 @@ class StatefulNavigationShellState extends State final StatefulShellBranch branch = route.branches[widget.currentIndex]; final ShellRouteContext shellRouteContext = widget.shellRouteContext; - final RouteMatchList currentBranchLocation = - _scopedMatchList(shellRouteContext.routeMatchList); + final RouteMatchList currentBranchLocation = _scopedMatchList( + shellRouteContext.routeMatchList, + ); - final _StatefulShellBranchState branchState = - _branchStateFor(branch, false); + final _StatefulShellBranchState branchState = _branchStateFor( + branch, + false, + ); final RouteMatchList previousBranchLocation = branchState.location.value; branchState.location.value = currentBranchLocation; final bool hasExistingNavigator = branchState.navigator != null; @@ -1324,7 +1422,9 @@ class StatefulNavigationShellState extends State previousBranchLocation != currentBranchLocation; if (locationChanged || !hasExistingNavigator) { branchState.navigator = shellRouteContext._buildNavigatorForCurrentRoute( - branch.observers, branch.restorationScopeId); + branch.observers, + branch.restorationScopeId, + ); } _cleanUpObsoleteBranches(); @@ -1337,8 +1437,9 @@ class StatefulNavigationShellState extends State // Find the match for the current StatefulShellRoute in matchList // returned by _effectiveInitialBranchLocation (the initial location // should already have been validated by RouteConfiguration). - final RouteMatchList matchList = _router.configuration - .findMatch(Uri.parse(widget._effectiveInitialBranchLocation(i))); + final RouteMatchList matchList = _router.configuration.findMatch( + Uri.parse(widget._effectiveInitialBranchLocation(i)), + ); ShellRouteMatch? match; matchList.visitRouteMatches((RouteMatchBase e) { match = e is ShellRouteMatch && e.route == route ? e : match; @@ -1354,8 +1455,10 @@ class StatefulNavigationShellState extends State branch.restorationScopeId, ); - final _StatefulShellBranchState branchState = - _branchStateFor(branch, false); + final _StatefulShellBranchState branchState = _branchStateFor( + branch, + false, + ); branchState.location.value = matchList; branchState.navigator = navigator; } @@ -1363,8 +1466,10 @@ class StatefulNavigationShellState extends State } void _cleanUpObsoleteBranches() { - _branchState.removeWhere( - (StatefulShellBranch branch, _StatefulShellBranchState branchState) { + _branchState.removeWhere(( + StatefulShellBranch branch, + _StatefulShellBranchState branchState, + ) { if (!route.branches.contains(branch)) { branchState.dispose(); return true; @@ -1423,22 +1528,25 @@ 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); } } class _StatefulShellBranchState { - _StatefulShellBranchState({ - required this.location, - }); + _StatefulShellBranchState({required this.location}); Widget? navigator; final _RestorableRouteMatchList location; @@ -1451,7 +1559,7 @@ class _StatefulShellBranchState { /// [RestorableProperty] for enabling state restoration of [RouteMatchList]s. class _RestorableRouteMatchList extends RestorableProperty { _RestorableRouteMatchList(RouteConfiguration configuration) - : _matchListCodec = RouteMatchListCodec(configuration); + : _matchListCodec = RouteMatchListCodec(configuration); final RouteMatchListCodec _matchListCodec; @@ -1530,8 +1638,10 @@ class _BranchNavigatorProxyState extends State<_BranchNavigatorProxy> /// Default implementation of a container widget for the [Navigator]s of the /// route branches. This implementation uses an [IndexedStack] as a container. class _IndexedStackedRouteBranchContainer extends StatelessWidget { - const _IndexedStackedRouteBranchContainer( - {required this.currentIndex, required this.children}); + const _IndexedStackedRouteBranchContainer({ + required this.currentIndex, + required this.children, + }); final int currentIndex; @@ -1539,22 +1649,28 @@ 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); } Widget _buildRouteBranchContainer( - BuildContext context, bool isActive, Widget child) { + BuildContext context, + bool isActive, + Widget child, + ) { return Offstage( offstage: !isActive, - child: TickerMode( - enabled: isActive, - child: child, - ), + child: TickerMode(enabled: isActive, child: child), ); } } diff --git a/packages/go_router/lib/src/route_data.dart b/packages/go_router/lib/src/route_data.dart index 24afed52740..c8e30bacd68 100644 --- a/packages/go_router/lib/src/route_data.dart +++ b/packages/go_router/lib/src/route_data.dart @@ -155,8 +155,8 @@ abstract class GoRouteData extends RouteData { void replace(BuildContext context) => throw _shouldBeGeneratedError; static UnimplementedError get _shouldBeGeneratedError => UnimplementedError( - 'Should be generated using [Type-safe routing](https://pub.dev/documentation/go_router/latest/topics/Type-safe%20routes-topic.html).', - ); + 'Should be generated using [Type-safe routing](https://pub.dev/documentation/go_router/latest/topics/Type-safe%20routes-topic.html).', + ); } /// A class to represent a [ShellRoute] in @@ -172,15 +172,10 @@ abstract class ShellRouteData extends RouteData { BuildContext context, GoRouterState state, Widget navigator, - ) => - const NoOpPage(); + ) => const NoOpPage(); /// [builder] is used to build the widget - Widget builder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => + Widget builder(BuildContext context, GoRouterState state, Widget navigator) => throw UnimplementedError( 'One of `builder` or `pageBuilder` must be implemented.', ); @@ -215,23 +210,13 @@ abstract class ShellRouteData extends RouteData { BuildContext context, GoRouterState state, Widget navigator, - ) => - factoryImpl(state).builder( - context, - state, - navigator, - ); + ) => factoryImpl(state).builder(context, state, navigator); Page pageBuilder( BuildContext context, GoRouterState state, Widget navigator, - ) => - factoryImpl(state).pageBuilder( - context, - state, - navigator, - ); + ) => factoryImpl(state).pageBuilder(context, state, navigator); return ShellRoute( builder: builder, @@ -248,9 +233,7 @@ abstract class ShellRouteData extends RouteData { /// Used to cache [ShellRouteData] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. static final Expando _stateObjectExpando = - Expando( - 'GoRouteState to ShellRouteData expando', - ); + Expando('GoRouteState to ShellRouteData expando'); } /// Base class for supporting @@ -272,8 +255,7 @@ abstract class StatefulShellRouteData extends RouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, - ) => - const NoOpPage(); + ) => const NoOpPage(); /// [builder] is used to build the widget Widget builder( @@ -303,23 +285,13 @@ abstract class StatefulShellRouteData extends RouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, - ) => - factoryImpl(state).builder( - context, - state, - navigationShell, - ); + ) => factoryImpl(state).builder(context, state, navigationShell); Page pageBuilder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, - ) => - factoryImpl(state).pageBuilder( - context, - state, - navigationShell, - ); + ) => factoryImpl(state).pageBuilder(context, state, navigationShell); FutureOr redirect(BuildContext context, GoRouterState state) => factoryImpl(state).redirect(context, state); @@ -349,8 +321,8 @@ abstract class StatefulShellRouteData extends RouteData { /// to minimize the number of times it has to be deserialized. static final Expando _stateObjectExpando = Expando( - 'GoRouteState to StatefulShellRouteData expando', - ); + 'GoRouteState to StatefulShellRouteData expando', + ); } /// Base class for supporting @@ -434,9 +406,7 @@ class TypedGoRoute extends TypedRoute { @Target({TargetKind.library, TargetKind.classType}) class TypedShellRoute extends TypedRoute { /// Default const constructor - const TypedShellRoute({ - this.routes = const >[], - }); + const TypedShellRoute({this.routes = const >[]}); /// Child route definitions. /// diff --git a/packages/go_router/lib/src/router.dart b/packages/go_router/lib/src/router.dart index 9962dd2d449..6ae32fc3437 100644 --- a/packages/go_router/lib/src/router.dart +++ b/packages/go_router/lib/src/router.dart @@ -21,11 +21,8 @@ import 'state.dart'; /// The function signature of [GoRouter.onException]. /// /// Use `state.error` to access the exception. -typedef GoExceptionHandler = void Function( - BuildContext context, - GoRouterState state, - GoRouter router, -); +typedef GoExceptionHandler = + void Function(BuildContext context, GoRouterState state, GoRouter router); /// A set of parameters that defines routing in GoRouter. /// @@ -46,8 +43,9 @@ class RoutingConfig { }); static FutureOr _defaultRedirect( - BuildContext context, GoRouterState state) => - null; + BuildContext context, + GoRouterState state, + ) => null; /// The supported routes. /// @@ -142,9 +140,10 @@ class GoRouter implements RouterConfig { return GoRouter.routingConfig( routingConfig: _ConstantRoutingConfig( RoutingConfig( - routes: routes, - redirect: redirect ?? RoutingConfig._defaultRedirect, - redirectLimit: redirectLimit), + routes: routes, + redirect: redirect ?? RoutingConfig._defaultRedirect, + redirectLimit: redirectLimit, + ), ), extraCodec: extraCodec, onException: onException, @@ -182,20 +181,23 @@ class GoRouter implements RouterConfig { GlobalKey? navigatorKey, String? restorationScopeId, bool requestFocus = true, - }) : _routingConfig = routingConfig, - backButtonDispatcher = RootBackButtonDispatcher(), - assert( - initialExtra == null || initialLocation != null, - 'initialLocation must be set in order to use initialExtra', - ), - assert(!overridePlatformDefaultLocation || initialLocation != null, - 'Initial location must be set to override platform default'), - assert( - (onException == null ? 0 : 1) + - (errorPageBuilder == null ? 0 : 1) + - (errorBuilder == null ? 0 : 1) < - 2, - 'Only one of onException, errorPageBuilder, or errorBuilder can be provided.') { + }) : _routingConfig = routingConfig, + backButtonDispatcher = RootBackButtonDispatcher(), + assert( + initialExtra == null || initialLocation != null, + 'initialLocation must be set in order to use initialExtra', + ), + assert( + !overridePlatformDefaultLocation || initialLocation != null, + 'Initial location must be set to override platform default', + ), + assert( + (onException == null ? 0 : 1) + + (errorPageBuilder == null ? 0 : 1) + + (errorBuilder == null ? 0 : 1) < + 2, + 'Only one of onException, errorPageBuilder, or errorBuilder can be provided.', + ) { setLogging(enabled: debugLogDiagnostics); WidgetsFlutterBinding.ensureInitialized(); @@ -210,10 +212,15 @@ class GoRouter implements RouterConfig { final ParserExceptionHandler? parserExceptionHandler; if (onException != null) { - parserExceptionHandler = - (BuildContext context, RouteMatchList routeMatchList) { - onException(context, - configuration.buildTopLevelGoRouterState(routeMatchList), this); + parserExceptionHandler = ( + BuildContext context, + RouteMatchList routeMatchList, + ) { + onException( + context, + configuration.buildTopLevelGoRouterState(routeMatchList), + this, + ); // Avoid updating GoRouterDelegate if onException is provided. return routerDelegate.currentConfiguration; }; @@ -238,15 +245,14 @@ class GoRouter implements RouterConfig { errorPageBuilder: errorPageBuilder, errorBuilder: errorBuilder, routerNeglect: routerNeglect, - observers: [ - ...observers ?? [], - ], + observers: [...observers ?? []], restorationScopeId: restorationScopeId, 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(() { @@ -331,16 +337,17 @@ class GoRouter implements RouterConfig { /// Get a location from route name and parameters. /// This is useful for redirecting to a named location. - String namedLocation(String name, - {Map pathParameters = const {}, - Map queryParameters = const {}, - String? fragment}) => - configuration.namedLocation( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - fragment: fragment, - ); + String namedLocation( + String name, { + Map pathParameters = const {}, + Map queryParameters = const {}, + String? fragment, + }) => configuration.namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + fragment: fragment, + ); /// Navigate to a URI location w/ optional query parameters, e.g. /// `/family/f2/person/p1?color=blue` @@ -368,15 +375,16 @@ class GoRouter implements RouterConfig { Object? extra, String? fragment, }) => - - /// Construct location with optional fragment, using null-safe navigation - go( - namedLocation(name, - pathParameters: pathParameters, - queryParameters: queryParameters, - fragment: fragment), - extra: extra, - ); + /// Construct location with optional fragment, using null-safe navigation + 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`. @@ -403,12 +411,14 @@ class GoRouter implements RouterConfig { Map pathParameters = const {}, Map queryParameters = const {}, Object? extra, - }) => - push( - namedLocation(name, - pathParameters: pathParameters, queryParameters: queryParameters), - extra: extra, - ); + }) => push( + namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + ), + extra: extra, + ); /// Replaces the top-most page of the page stack with the given URL location /// w/ optional query parameters, e.g. `/family/f2/person/p1?color=blue`. @@ -419,8 +429,10 @@ class GoRouter implements RouterConfig { /// * [replace] which replaces the top-most page of the page stack but treats /// it as the same page. The page key will be reused. This will preserve the /// state and not run any page animation. - Future pushReplacement(String location, - {Object? extra}) { + Future pushReplacement( + String location, { + Object? extra, + }) { log('pushReplacement $location'); return routeInformationProvider.pushReplacement( location, @@ -443,8 +455,11 @@ class GoRouter implements RouterConfig { Object? extra, }) { return pushReplacement( - namedLocation(name, - pathParameters: pathParameters, queryParameters: queryParameters), + namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + ), extra: extra, ); } @@ -486,8 +501,11 @@ class GoRouter implements RouterConfig { Object? extra, }) { return replace( - namedLocation(name, - pathParameters: pathParameters, queryParameters: queryParameters), + namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + ), extra: extra, ); } @@ -530,9 +548,11 @@ class GoRouter implements RouterConfig { /// /// This method returns null when it is called during redirects. static GoRouter? maybeOf(BuildContext context) { - final InheritedGoRouter? inherited = context - .getElementForInheritedWidgetOfExactType() - ?.widget as InheritedGoRouter?; + final InheritedGoRouter? inherited = + context + .getElementForInheritedWidgetOfExactType() + ?.widget + as InheritedGoRouter?; return inherited?.goRouter; } diff --git a/packages/go_router/lib/src/state.dart b/packages/go_router/lib/src/state.dart index 147d191140a..7808e62d547 100644 --- a/packages/go_router/lib/src/state.dart +++ b/packages/go_router/lib/src/state.dart @@ -125,14 +125,19 @@ class GoRouterState { } final RouteSettings settings = route.settings; if (settings is Page) { - scope = context - .dependOnInheritedWidgetOfExactType(); + scope = + context + .dependOnInheritedWidgetOfExactType< + GoRouterStateRegistryScope + >(); if (scope == null) { throw _noGoRouterStateError; } final GoRouterState? state = scope.notifier! ._createPageRouteAssociation( - route.settings as Page, route); + route.settings as Page, + route, + ); if (state != null) { return state; } @@ -146,10 +151,10 @@ class GoRouterState { } static GoError get _noGoRouterStateError => GoError( - 'There is no GoRouterState above the current context. ' - 'This method should only be called under the sub tree of a ' - 'RouteBase.builder.', - ); + 'There is no GoRouterState above the current context. ' + 'This method should only be called under the sub tree of a ' + 'RouteBase.builder.', + ); /// Get a location from route name and parameters. /// This is useful for redirecting to a named location. @@ -161,10 +166,12 @@ class GoRouterState { }) { // Generate base location using configuration, with optional path and query parameters // Then conditionally append fragment if it exists and is not empty - return _configuration.namedLocation(name, - pathParameters: pathParameters, - queryParameters: queryParameters, - fragment: fragment); + return _configuration.namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + fragment: fragment, + ); } @override @@ -183,16 +190,16 @@ class GoRouterState { @override int get hashCode => Object.hash( - uri, - matchedLocation, - name, - path, - fullPath, - pathParameters, - extra, - error, - pageKey, - ); + uri, + matchedLocation, + name, + path, + fullPath, + pathParameters, + extra, + error, + pageKey, + ); } /// An inherited widget to host a [GoRouterStateRegistry] for the subtree. @@ -228,7 +235,9 @@ class GoRouterStateRegistry extends ChangeNotifier { , Page>{}; GoRouterState? _createPageRouteAssociation( - Page page, ModalRoute route) { + Page page, + ModalRoute route, + ) { assert(route.settings == page); if (!registry.containsKey(page)) { return null; diff --git a/packages/go_router/pubspec.yaml b/packages/go_router/pubspec.yaml index d6526682829..24064f28914 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 d3fe5f05369..7648f42044e 100644 --- a/packages/go_router/test/builder_test.dart +++ b/packages/go_router/test/builder_test.dart @@ -28,21 +28,19 @@ void main() { ); final RouteMatchList matches = RouteMatchList( - matches: [ - RouteMatch( - route: config.routes.first as GoRoute, - matchedLocation: '/', - pageKey: const ValueKey('/'), - ), - ], - uri: Uri.parse('/'), - pathParameters: const {}); + matches: [ + RouteMatch( + route: config.routes.first as GoRoute, + matchedLocation: '/', + pageKey: const ValueKey('/'), + ), + ], + uri: Uri.parse('/'), + pathParameters: const {}, + ); await tester.pumpWidget( - _BuilderTestWidget( - routeConfiguration: config, - matches: matches, - ), + _BuilderTestWidget(routeConfiguration: config, matches: matches), ); expect(find.byType(_DetailsScreen), findsOneWidget); @@ -96,10 +94,7 @@ void main() { ); await tester.pumpWidget( - _BuilderTestWidget( - routeConfiguration: config, - matches: matches, - ), + _BuilderTestWidget(routeConfiguration: config, matches: matches), ); expect(find.byType(_DetailsScreen), findsOneWidget); @@ -125,28 +120,27 @@ void main() { ); final RouteMatchList matches = RouteMatchList( - matches: [ - RouteMatch( - route: config.routes.first as GoRoute, - matchedLocation: '/', - pageKey: const ValueKey('/'), - ), - ], - uri: Uri.parse('/'), - pathParameters: const {}); + matches: [ + RouteMatch( + route: config.routes.first as GoRoute, + matchedLocation: '/', + pageKey: const ValueKey('/'), + ), + ], + uri: Uri.parse('/'), + pathParameters: const {}, + ); await tester.pumpWidget( - _BuilderTestWidget( - routeConfiguration: config, - matches: matches, - ), + _BuilderTestWidget(routeConfiguration: config, matches: matches), ); expect(find.byKey(rootNavigatorKey), findsOneWidget); }); - testWidgets('Builds a Navigator for ShellRoute', - (WidgetTester tester) async { + testWidgets('Builds a Navigator for ShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(debugLabel: 'root'); final GlobalKey shellNavigatorKey = @@ -156,9 +150,7 @@ void main() { routes: [ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return _HomeScreen( - child: child, - ); + return _HomeScreen(child: child); }, navigatorKey: shellNavigatorKey, routes: [ @@ -178,28 +170,27 @@ void main() { ); final RouteMatchList matches = RouteMatchList( - matches: [ - ShellRouteMatch( - route: config.routes.first as ShellRouteBase, - matchedLocation: '', - pageKey: const ValueKey(''), - navigatorKey: shellNavigatorKey, - matches: [ - RouteMatch( - route: config.routes.first.routes.first as GoRoute, - matchedLocation: '/details', - pageKey: const ValueKey('/details'), - ), - ]), - ], - uri: Uri.parse('/details'), - pathParameters: const {}); + matches: [ + ShellRouteMatch( + route: config.routes.first as ShellRouteBase, + matchedLocation: '', + pageKey: const ValueKey(''), + navigatorKey: shellNavigatorKey, + matches: [ + RouteMatch( + route: config.routes.first.routes.first as GoRoute, + matchedLocation: '/details', + pageKey: const ValueKey('/details'), + ), + ], + ), + ], + uri: Uri.parse('/details'), + pathParameters: const {}, + ); await tester.pumpWidget( - _BuilderTestWidget( - routeConfiguration: config, - matches: matches, - ), + _BuilderTestWidget(routeConfiguration: config, matches: matches), ); expect(find.byType(_HomeScreen, skipOffstage: false), findsOneWidget); @@ -208,8 +199,9 @@ void main() { expect(find.byKey(shellNavigatorKey), findsOneWidget); }); - testWidgets('Builds a Navigator for ShellRoute with parentNavigatorKey', - (WidgetTester tester) async { + testWidgets('Builds a Navigator for ShellRoute with parentNavigatorKey', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(debugLabel: 'root'); final GlobalKey shellNavigatorKey = @@ -219,9 +211,7 @@ void main() { routes: [ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return _HomeScreen( - child: child, - ); + return _HomeScreen(child: child); }, navigatorKey: shellNavigatorKey, routes: [ @@ -251,21 +241,19 @@ void main() { ); final RouteMatchList matches = RouteMatchList( - matches: [ - RouteMatch( - route: config.routes.first.routes.first as GoRoute, - matchedLocation: '/a/details', - pageKey: const ValueKey('/a/details'), - ), - ], - uri: Uri.parse('/a/details'), - pathParameters: const {}); + matches: [ + RouteMatch( + route: config.routes.first.routes.first as GoRoute, + matchedLocation: '/a/details', + pageKey: const ValueKey('/a/details'), + ), + ], + uri: Uri.parse('/a/details'), + pathParameters: const {}, + ); await tester.pumpWidget( - _BuilderTestWidget( - routeConfiguration: config, - matches: matches, - ), + _BuilderTestWidget(routeConfiguration: config, matches: matches), ); // The Details screen should be visible, but the HomeScreen should be @@ -274,8 +262,9 @@ void main() { expect(find.byType(_DetailsScreen), findsOneWidget); }); - testWidgets('Uses the correct restorationScopeId for ShellRoute', - (WidgetTester tester) async { + testWidgets('Uses the correct restorationScopeId for ShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(debugLabel: 'root'); final GlobalKey shellNavigatorKey = @@ -326,21 +315,20 @@ void main() { ); await tester.pumpWidget( - _BuilderTestWidget( - routeConfiguration: config, - matches: matches, - ), + _BuilderTestWidget(routeConfiguration: config, matches: matches), ); expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); expect( - (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, - 'scope1'); + (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, + 'scope1', + ); }); - testWidgets('Uses the correct restorationScopeId for StatefulShellRoute', - (WidgetTester tester) async { + testWidgets('Uses the correct restorationScopeId for StatefulShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(debugLabel: 'root'); final GlobalKey shellNavigatorKey = @@ -351,9 +339,12 @@ void main() { routes: [ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) => - _HomeScreen(child: navigationShell), + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) => _HomeScreen(child: navigationShell), branches: [ StatefulShellBranch( navigatorKey: shellNavigatorKey, @@ -373,78 +364,69 @@ void main() { ); addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: goRouter, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); expect( - (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, - 'scope1'); + (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, + 'scope1', + ); }); - testWidgets('GoRouter requestFocus defaults to true', - (WidgetTester tester) async { + testWidgets('GoRouter requestFocus defaults to true', ( + WidgetTester tester, + ) async { final GoRouter router = GoRouter( 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'))), ), ], ); - await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - ), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); addTearDown(() => router.dispose()); - final Navigator navigator = - tester.widget(find.byType(Navigator)); + final Navigator navigator = tester.widget( + find.byType(Navigator), + ); expect(navigator.requestFocus, isTrue); }); - testWidgets('GoRouter requestFocus can be set to false', - (WidgetTester tester) async { + testWidgets('GoRouter requestFocus can be set to false', ( + WidgetTester tester, + ) async { final GoRouter router = GoRouter( 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, ); - await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - ), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); addTearDown(() => router.dispose()); - final Navigator navigator = - tester.widget(find.byType(Navigator)); + final Navigator navigator = tester.widget( + find.byType(Navigator), + ); expect(navigator.requestFocus, isFalse); }); }); } class _HomeScreen extends StatelessWidget { - const _HomeScreen({ - required this.child, - }); + const _HomeScreen({required this.child}); final Widget child; @@ -452,10 +434,7 @@ 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)], ), ); } @@ -464,17 +443,13 @@ class _HomeScreen extends StatelessWidget { class _DetailsScreen extends StatelessWidget { @override Widget build(BuildContext context) { - return const Scaffold( - body: Text('Details Screen'), - ); + return const Scaffold(body: Text('Details Screen')); } } class _BuilderTestWidget extends StatelessWidget { - _BuilderTestWidget({ - required this.routeConfiguration, - required this.matches, - }) : builder = _routeBuilder(routeConfiguration); + _BuilderTestWidget({required this.routeConfiguration, required this.matches}) + : builder = _routeBuilder(routeConfiguration); final RouteConfiguration routeConfiguration; final RouteBuilder builder; @@ -484,24 +459,13 @@ class _BuilderTestWidget extends StatelessWidget { static RouteBuilder _routeBuilder(RouteConfiguration configuration) { return RouteBuilder( configuration: configuration, - builderWithNav: ( - BuildContext context, - Widget child, - ) { + builderWithNav: (BuildContext context, Widget child) { return child; }, - errorPageBuilder: ( - BuildContext context, - GoRouterState state, - ) { - return MaterialPage( - child: Text('Error: ${state.error}'), - ); + errorPageBuilder: (BuildContext context, GoRouterState state) { + return MaterialPage(child: Text('Error: ${state.error}')); }, - errorBuilder: ( - BuildContext context, - GoRouterState state, - ) { + errorBuilder: (BuildContext context, GoRouterState state) { return Text('Error: ${state.error}'); }, restorationScopeId: null, @@ -512,8 +476,6 @@ class _BuilderTestWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - home: builder.build(context, matches, false), - ); + return MaterialApp(home: builder.build(context, matches, false)); } } diff --git a/packages/go_router/test/configuration_test.dart b/packages/go_router/test/configuration_test.dart index 0929756599f..bb19429ddc0 100644 --- a/packages/go_router/test/configuration_test.dart +++ b/packages/go_router/test/configuration_test.dart @@ -11,340 +11,355 @@ import 'test_helpers.dart'; void main() { group('RouteConfiguration', () { test('throws when parentNavigatorKey is not an ancestor', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey a = - GlobalKey(debugLabel: 'a'); - final GlobalKey b = - GlobalKey(debugLabel: 'b'); - - expect( - () { - createRouteConfiguration( - navigatorKey: root, - routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - routes: [ - ShellRoute( - navigatorKey: a, - builder: _mockShellBuilder, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - ) - ], - ), - ShellRoute( - navigatorKey: b, - builder: _mockShellBuilder, - routes: [ - GoRoute( - path: 'c', - parentNavigatorKey: a, - builder: _mockScreenBuilder, - ) - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - throwsAssertionError, + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey a = GlobalKey( + debugLabel: 'a', + ); + final GlobalKey b = GlobalKey( + debugLabel: 'b', ); + + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + GoRoute( + path: '/a', + builder: _mockScreenBuilder, + routes: [ + ShellRoute( + navigatorKey: a, + builder: _mockShellBuilder, + routes: [ + GoRoute(path: 'b', builder: _mockScreenBuilder), + ], + ), + ShellRoute( + navigatorKey: b, + builder: _mockShellBuilder, + routes: [ + GoRoute( + path: 'c', + parentNavigatorKey: a, + builder: _mockScreenBuilder, + ), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); }); test('throws when ShellRoute has no children', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final List shellRouteChildren = []; - expect( - () { - createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute(routes: shellRouteChildren), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - throwsAssertionError, + final GlobalKey root = GlobalKey( + debugLabel: 'root', ); + final List shellRouteChildren = []; + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ShellRoute(routes: shellRouteChildren)], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); }); test( - 'throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey keyA = - GlobalKey(debugLabel: 'A'); - final GlobalKey keyB = - GlobalKey(debugLabel: 'B'); + 'throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey', + () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey keyA = GlobalKey( + debugLabel: 'A', + ); + final GlobalKey keyB = GlobalKey( + debugLabel: 'B', + ); - expect( - () { + expect(() { createRouteConfiguration( navigatorKey: root, routes: [ - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch( - navigatorKey: keyA, - routes: [ - GoRoute( + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + navigatorKey: keyA, + routes: [ + GoRoute( path: '/a', builder: _mockScreenBuilder, routes: [ GoRoute( - path: 'details', - builder: _mockScreenBuilder, - parentNavigatorKey: keyB), - ]), - ], - ), - ], builder: mockStackedShellBuilder), + path: 'details', + builder: _mockScreenBuilder, + parentNavigatorKey: keyB, + ), + ], + ), + ], + ), + ], + builder: mockStackedShellBuilder, + ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, ); - }, - throwsA(isA()), - ); - }); + }, throwsA(isA())); + }, + ); test( - 'does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey keyA = - GlobalKey(debugLabel: 'A'); + 'does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys', + () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey keyA = GlobalKey( + debugLabel: 'A', + ); - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch( - navigatorKey: keyA, - routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - routes: [ - GoRoute( + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + navigatorKey: keyA, + routes: [ + GoRoute( + path: '/a', + builder: _mockScreenBuilder, + routes: [ + GoRoute( path: 'details', builder: _mockScreenBuilder, - parentNavigatorKey: keyA), - ]), + parentNavigatorKey: keyA, + ), + ], + ), + ], + ), ], + builder: mockStackedShellBuilder, ), - ], builder: mockStackedShellBuilder), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }); + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, + ); test( - 'throws when a sub-route of StatefulShellRoute has a parentNavigatorKey', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey someNavigatorKey = - GlobalKey(); - expect( - () { + 'throws when a sub-route of StatefulShellRoute has a parentNavigatorKey', + () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey someNavigatorKey = + GlobalKey(); + expect(() { createRouteConfiguration( navigatorKey: root, routes: [ - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch( - routes: [ - GoRoute( + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( path: '/a', builder: _mockScreenBuilder, routes: [ GoRoute( - path: 'details', - builder: _mockScreenBuilder, - parentNavigatorKey: someNavigatorKey), - ]), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( + path: 'details', + builder: _mockScreenBuilder, + parentNavigatorKey: someNavigatorKey, + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( path: '/b', builder: _mockScreenBuilder, - parentNavigatorKey: someNavigatorKey), - ], - ), - ], builder: mockStackedShellBuilder), + parentNavigatorKey: someNavigatorKey, + ), + ], + ), + ], + builder: mockStackedShellBuilder, + ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, ); - }, - throwsAssertionError, - ); - }); + }, throwsAssertionError); + }, + ); test('throws when StatefulShellRoute has duplicate navigator keys', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey keyA = - GlobalKey(debugLabel: 'A'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey keyA = GlobalKey( + debugLabel: 'A', + ); final List shellRouteChildren = [ GoRoute( - path: '/a', builder: _mockScreenBuilder, parentNavigatorKey: keyA), + path: '/a', + builder: _mockScreenBuilder, + parentNavigatorKey: keyA, + ), GoRoute( - path: '/b', builder: _mockScreenBuilder, parentNavigatorKey: keyA), + path: '/b', + builder: _mockScreenBuilder, + parentNavigatorKey: keyA, + ), ]; - expect( - () { - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch(routes: shellRouteChildren) - ], builder: mockStackedShellBuilder), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - throwsAssertionError, - ); + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch(routes: shellRouteChildren), + ], + builder: mockStackedShellBuilder, + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); }); - test( - 'throws when a child of StatefulShellRoute has an incorrect ' + test('throws when a child of StatefulShellRoute has an incorrect ' 'parentNavigatorKey', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); final GlobalKey sectionANavigatorKey = GlobalKey(); final GlobalKey sectionBNavigatorKey = GlobalKey(); final GoRoute routeA = GoRoute( - path: '/a', - builder: _mockScreenBuilder, - parentNavigatorKey: sectionBNavigatorKey); + path: '/a', + builder: _mockScreenBuilder, + parentNavigatorKey: sectionBNavigatorKey, + ); final GoRoute routeB = GoRoute( - path: '/b', - builder: _mockScreenBuilder, - parentNavigatorKey: sectionANavigatorKey); - expect( - () { - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack(branches: [ + path: '/b', + builder: _mockScreenBuilder, + parentNavigatorKey: sectionANavigatorKey, + ); + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ StatefulShellBranch( - routes: [routeA], - navigatorKey: sectionANavigatorKey), + routes: [routeA], + navigatorKey: sectionANavigatorKey, + ), StatefulShellBranch( - routes: [routeB], - navigatorKey: sectionBNavigatorKey), - ], builder: mockStackedShellBuilder), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - throwsAssertionError, - ); + routes: [routeB], + navigatorKey: sectionBNavigatorKey, + ), + ], + builder: mockStackedShellBuilder, + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); }); - test( - 'throws when a branch of a StatefulShellRoute has an incorrect ' + test('throws when a branch of a StatefulShellRoute has an incorrect ' 'initialLocation', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); final GlobalKey sectionANavigatorKey = GlobalKey(); final GlobalKey sectionBNavigatorKey = GlobalKey(); - expect( - () { - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack(branches: [ + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ StatefulShellBranch( initialLocation: '/x', navigatorKey: sectionANavigatorKey, routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - ), + GoRoute(path: '/a', builder: _mockScreenBuilder), ], ), StatefulShellBranch( navigatorKey: sectionBNavigatorKey, routes: [ - GoRoute( - path: '/b', - builder: _mockScreenBuilder, - ), + GoRoute(path: '/b', builder: _mockScreenBuilder), ], ), - ], builder: mockStackedShellBuilder), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - throwsA(isA()), - ); + ], + builder: mockStackedShellBuilder, + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsA(isA())); }); - test( - 'throws when a branch of a StatefulShellRoute has a initialLocation ' + test('throws when a branch of a StatefulShellRoute has a initialLocation ' 'that is not a descendant of the same branch', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); final GlobalKey sectionANavigatorKey = GlobalKey(); final GlobalKey sectionBNavigatorKey = GlobalKey(); - expect( - () { - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack(branches: [ + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ StatefulShellBranch( initialLocation: '/b', navigatorKey: sectionANavigatorKey, routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - ), + GoRoute(path: '/a', builder: _mockScreenBuilder), ], ), StatefulShellBranch( @@ -352,119 +367,120 @@ void main() { navigatorKey: sectionBNavigatorKey, routes: [ StatefulShellRoute.indexedStack( - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/b', - builder: _mockScreenBuilder, - ), - ], - ), - ], - builder: mockStackedShellBuilder), + branches: [ + StatefulShellBranch( + routes: [ + GoRoute(path: '/b', builder: _mockScreenBuilder), + ], + ), + ], + builder: mockStackedShellBuilder, + ), ], ), - ], builder: mockStackedShellBuilder), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - throwsA(isA()), - ); + ], + builder: mockStackedShellBuilder, + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsA(isA())); }); - test( - 'does not throw when a branch of a StatefulShellRoute has correctly ' + test('does not throw when a branch of a StatefulShellRoute has correctly ' 'configured initialLocations', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); createRouteConfiguration( navigatorKey: root, routes: [ - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch( - routes: [ - GoRoute( + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( path: '/a', builder: _mockScreenBuilder, routes: [ - GoRoute( - path: 'detail', - builder: _mockScreenBuilder, - ), - ]), - ], - ), - StatefulShellBranch( - initialLocation: '/b/detail', - routes: [ - GoRoute( + GoRoute(path: 'detail', builder: _mockScreenBuilder), + ], + ), + ], + ), + StatefulShellBranch( + initialLocation: '/b/detail', + routes: [ + GoRoute( path: '/b', builder: _mockScreenBuilder, routes: [ - GoRoute( - path: 'detail', - builder: _mockScreenBuilder, - ), - ]), - ], - ), - StatefulShellBranch( - initialLocation: '/c/detail', - routes: [ - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/c', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'detail', - builder: _mockScreenBuilder, - ), - ]), + GoRoute(path: 'detail', builder: _mockScreenBuilder), ], ), - StatefulShellBranch( - initialLocation: '/d/detail', - routes: [ - GoRoute( - path: '/d', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'detail', - builder: _mockScreenBuilder, - ), - ]), + ], + ), + StatefulShellBranch( + initialLocation: '/c/detail', + routes: [ + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/c', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'detail', + builder: _mockScreenBuilder, + ), + ], + ), + ], + ), + StatefulShellBranch( + initialLocation: '/d/detail', + routes: [ + GoRoute( + path: '/d', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'detail', + builder: _mockScreenBuilder, + ), + ], + ), + ], + ), ], + builder: mockStackedShellBuilder, ), - ], builder: mockStackedShellBuilder), - ], - ), - StatefulShellBranch(routes: [ - ShellRoute( - builder: _mockShellBuilder, + ], + ), + StatefulShellBranch( routes: [ ShellRoute( builder: _mockShellBuilder, routes: [ - GoRoute( - path: '/e', - builder: _mockScreenBuilder, + ShellRoute( + builder: _mockShellBuilder, + routes: [ + GoRoute(path: '/e', builder: _mockScreenBuilder), + ], ), ], - ) + ), ], ), - ]), - ], builder: mockStackedShellBuilder), + ], + builder: mockStackedShellBuilder, + ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { @@ -473,20 +489,19 @@ void main() { ); }); - test( - 'derives the correct initialLocation for a StatefulShellBranch', - () { - final StatefulShellBranch branchA; - final StatefulShellBranch branchY; - final StatefulShellBranch branchB; + test('derives the correct initialLocation for a StatefulShellBranch', () { + final StatefulShellBranch branchA; + final StatefulShellBranch branchY; + final StatefulShellBranch branchB; - final RouteConfiguration config = createRouteConfiguration( - navigatorKey: GlobalKey(debugLabel: 'root'), - routes: [ - StatefulShellRoute.indexedStack( - builder: mockStackedShellBuilder, - branches: [ - branchA = StatefulShellBranch(routes: [ + final RouteConfiguration config = createRouteConfiguration( + navigatorKey: GlobalKey(debugLabel: 'root'), + routes: [ + StatefulShellRoute.indexedStack( + builder: mockStackedShellBuilder, + branches: [ + branchA = StatefulShellBranch( + routes: [ GoRoute( path: '/a', builder: _mockScreenBuilder, @@ -496,78 +511,78 @@ void main() { builder: _mockScreenBuilder, routes: [ StatefulShellRoute.indexedStack( - builder: mockStackedShellBuilder, - branches: [ - branchY = - StatefulShellBranch(routes: [ + builder: mockStackedShellBuilder, + branches: [ + branchY = StatefulShellBranch( + routes: [ ShellRoute( - builder: _mockShellBuilder, - routes: [ - GoRoute( - path: 'y1', - builder: _mockScreenBuilder, - ), - GoRoute( - path: 'y2', - builder: _mockScreenBuilder, - ), - ]) - ]) - ]), + builder: _mockShellBuilder, + routes: [ + GoRoute( + path: 'y1', + builder: _mockScreenBuilder, + ), + GoRoute( + path: 'y2', + builder: _mockScreenBuilder, + ), + ], + ), + ], + ), + ], + ), ], ), ], ), - ]), - branchB = StatefulShellBranch(routes: [ + ], + ), + branchB = StatefulShellBranch( + routes: [ ShellRoute( builder: _mockShellBuilder, routes: [ ShellRoute( builder: _mockShellBuilder, routes: [ - GoRoute( - path: '/b1', - builder: _mockScreenBuilder, - ), - GoRoute( - path: '/b2', - builder: _mockScreenBuilder, - ), + GoRoute(path: '/b1', builder: _mockScreenBuilder), + GoRoute(path: '/b2', builder: _mockScreenBuilder), ], - ) + ), ], ), - ]), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); - String? initialLocation(StatefulShellBranch branch) { - final GoRoute? route = branch.defaultRoute; - return route != null ? config.locationForRoute(route) : null; - } + String? initialLocation(StatefulShellBranch branch) { + final GoRoute? route = branch.defaultRoute; + return route != null ? config.locationForRoute(route) : null; + } - expect('/a', initialLocation(branchA)); - expect('/a/x/y1', initialLocation(branchY)); - expect('/b1', initialLocation(branchB)); - }, - ); + expect('/a', initialLocation(branchA)); + expect('/a/x/y1', initialLocation(branchY)); + expect('/b1', initialLocation(branchB)); + }); test( - 'throws when there is a GoRoute ancestor with a different parentNavigatorKey', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); - expect( - () { + 'throws when there is a GoRoute ancestor with a different parentNavigatorKey', + () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); + expect(() { createRouteConfiguration( navigatorKey: root, routes: [ @@ -589,25 +604,79 @@ void main() { ], ), ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); + }, + ); + + test('Does not throw with valid parentNavigatorKey configuration', () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); + final GlobalKey shell2 = GlobalKey( + debugLabel: 'shell2', + ); + createRouteConfiguration( + navigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell, + routes: [ + GoRoute( + path: '/', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'a', + builder: _mockScreenBuilder, + parentNavigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell2, + routes: [ + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + parentNavigatorKey: shell2, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; }, - throwsAssertionError, ); }); test( - 'Does not throw with valid parentNavigatorKey configuration', + 'Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); - final GlobalKey shell2 = - GlobalKey(debugLabel: 'shell2'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); createRouteConfiguration( navigatorKey: root, routes: [ @@ -623,19 +692,15 @@ void main() { builder: _mockScreenBuilder, parentNavigatorKey: root, routes: [ - ShellRoute( - navigatorKey: shell2, + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + parentNavigatorKey: root, routes: [ GoRoute( - path: 'b', + path: 'c', builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - parentNavigatorKey: shell2, - ), - ], + parentNavigatorKey: root, ), ], ), @@ -654,14 +719,15 @@ void main() { }, ); - test( - 'Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); - createRouteConfiguration( + test('Throws when parentNavigatorKeys are overlapping', () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); + expect( + () => createRouteConfiguration( navigatorKey: root, routes: [ ShellRoute( @@ -679,12 +745,11 @@ void main() { GoRoute( path: 'b', builder: _mockScreenBuilder, - parentNavigatorKey: root, routes: [ GoRoute( - path: 'c', + path: 'b', builder: _mockScreenBuilder, - parentNavigatorKey: root, + parentNavigatorKey: shell, ), ], ), @@ -699,68 +764,20 @@ void main() { topRedirect: (BuildContext context, GoRouterState state) { return null; }, - ); - }, - ); - - test( - 'Throws when parentNavigatorKeys are overlapping', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); - expect( - () => createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute( - navigatorKey: shell, - routes: [ - GoRoute( - path: '/', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'a', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - parentNavigatorKey: shell, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ), - throwsA(isA()), - ); - }, - ); + ), + throwsA(isA()), + ); + }); test( 'Does not throw when parentNavigatorKeys are overlapping correctly', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); createRouteConfiguration( navigatorKey: root, routes: [ @@ -802,112 +819,20 @@ void main() { }, ); - test( - 'throws when a GoRoute with a different parentNavigatorKey ' - 'exists between a GoRoute with a parentNavigatorKey and ' - 'its ShellRoute ancestor', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); - final GlobalKey shell2 = - GlobalKey(debugLabel: 'shell2'); - expect( - () => createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute( - navigatorKey: shell, - routes: [ - GoRoute( - path: '/', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'a', - parentNavigatorKey: root, - builder: _mockScreenBuilder, - routes: [ - ShellRoute( - navigatorKey: shell2, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'c', - builder: _mockScreenBuilder, - parentNavigatorKey: shell, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ), - throwsA(isA()), - ); - }, - ); - test('does not throw when ShellRoute is the child of another ShellRoute', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - createRouteConfiguration( - routes: [ - ShellRoute( - builder: _mockShellBuilder, - routes: [ - ShellRoute( - builder: _mockShellBuilder, - routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - ), - ], - ), - GoRoute( - path: '/b', - builder: _mockScreenBuilder, - ), - ], - ), - GoRoute( - path: '/c', - builder: _mockScreenBuilder, - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - navigatorKey: root, + test('throws when a GoRoute with a different parentNavigatorKey ' + 'exists between a GoRoute with a parentNavigatorKey and ' + 'its ShellRoute ancestor', () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', ); - }); - - test( - 'Does not throw with valid parentNavigatorKey configuration', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); - final GlobalKey shell2 = - GlobalKey(debugLabel: 'shell2'); - createRouteConfiguration( + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); + final GlobalKey shell2 = GlobalKey( + debugLabel: 'shell2', + ); + expect( + () => createRouteConfiguration( navigatorKey: root, routes: [ ShellRoute( @@ -919,8 +844,8 @@ void main() { routes: [ GoRoute( path: 'a', - builder: _mockScreenBuilder, parentNavigatorKey: root, + builder: _mockScreenBuilder, routes: [ ShellRoute( navigatorKey: shell2, @@ -930,9 +855,9 @@ void main() { builder: _mockScreenBuilder, routes: [ GoRoute( - path: 'b', + path: 'c', builder: _mockScreenBuilder, - parentNavigatorKey: shell2, + parentNavigatorKey: shell, ), ], ), @@ -949,16 +874,103 @@ void main() { topRedirect: (BuildContext context, GoRouterState state) { return null; }, + ), + throwsA(isA()), + ); + }); + test( + 'does not throw when ShellRoute is the child of another ShellRoute', + () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + createRouteConfiguration( + routes: [ + ShellRoute( + builder: _mockShellBuilder, + routes: [ + ShellRoute( + builder: _mockShellBuilder, + routes: [ + GoRoute(path: '/a', builder: _mockScreenBuilder), + ], + ), + GoRoute(path: '/b', builder: _mockScreenBuilder), + ], + ), + GoRoute(path: '/c', builder: _mockScreenBuilder), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + navigatorKey: root, ); }, ); - test('throws when ShellRoute contains a GoRoute with a parentNavigatorKey', - () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - expect( - () { + test('Does not throw with valid parentNavigatorKey configuration', () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); + final GlobalKey shell2 = GlobalKey( + debugLabel: 'shell2', + ); + createRouteConfiguration( + navigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell, + routes: [ + GoRoute( + path: '/', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'a', + builder: _mockScreenBuilder, + parentNavigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell2, + routes: [ + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + parentNavigatorKey: shell2, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }); + + test( + 'throws when ShellRoute contains a GoRoute with a parentNavigatorKey', + () { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + expect(() { createRouteConfiguration( navigatorKey: root, routes: [ @@ -977,18 +989,19 @@ void main() { return null; }, ); - }, - throwsAssertionError, - ); - }); + }, throwsAssertionError); + }, + ); test( 'All known route strings returned by debugKnownRoutes are correct', () { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); expect( createRouteConfiguration( @@ -1045,18 +1058,12 @@ void main() { branches: [ StatefulShellBranch( routes: [ - GoRoute( - path: 'h', - builder: _mockScreenBuilder, - ), + GoRoute(path: 'h', builder: _mockScreenBuilder), ], ), StatefulShellBranch( routes: [ - GoRoute( - path: 'i', - builder: _mockScreenBuilder, - ), + GoRoute(path: 'i', builder: _mockScreenBuilder), ], ), ], @@ -1098,9 +1105,13 @@ Widget _mockScreenBuilder(BuildContext context, GoRouterState state) => _MockScreen(key: state.pageKey); Widget _mockShellBuilder( - BuildContext context, GoRouterState state, Widget child) => - child; + BuildContext context, + GoRouterState state, + Widget child, +) => child; -Widget _mockIndexedStackShellBuilder(BuildContext context, GoRouterState state, - StatefulNavigationShell shell) => - shell; +Widget _mockIndexedStackShellBuilder( + BuildContext context, + GoRouterState state, + StatefulNavigationShell shell, +) => shell; diff --git a/packages/go_router/test/cupertino_test.dart b/packages/go_router/test/cupertino_test.dart index 323aea3e02d..5c07b134869 100644 --- a/packages/go_router/test/cupertino_test.dart +++ b/packages/go_router/test/cupertino_test.dart @@ -11,28 +11,24 @@ import 'helpers/error_screen_helpers.dart'; void main() { group('isCupertinoApp', () { - testWidgets('returns [true] when CupertinoApp is present', - (WidgetTester tester) async { + testWidgets('returns [true] when CupertinoApp is present', ( + WidgetTester tester, + ) async { final GlobalKey<_DummyStatefulWidgetState> key = GlobalKey<_DummyStatefulWidgetState>(); await tester.pumpWidget( - CupertinoApp( - home: DummyStatefulWidget(key: key), - ), + CupertinoApp(home: DummyStatefulWidget(key: key)), ); final bool isCupertino = isCupertinoApp(key.currentContext! as Element); expect(isCupertino, true); }); - testWidgets('returns [false] when MaterialApp is present', - (WidgetTester tester) async { + testWidgets('returns [false] when MaterialApp is present', ( + WidgetTester tester, + ) async { final GlobalKey<_DummyStatefulWidgetState> key = GlobalKey<_DummyStatefulWidgetState>(); - await tester.pumpWidget( - MaterialApp( - home: DummyStatefulWidget(key: key), - ), - ); + await tester.pumpWidget(MaterialApp(home: DummyStatefulWidget(key: key))); final bool isCupertino = isCupertinoApp(key.currentContext! as Element); expect(isCupertino, false); }); @@ -62,9 +58,7 @@ void main() { testWidgets( 'shows "page not found" by default', testPageNotFound( - widget: const CupertinoApp( - home: CupertinoErrorScreen(null), - ), + widget: const CupertinoApp(home: CupertinoErrorScreen(null)), ), ); @@ -73,9 +67,7 @@ void main() { 'shows the exception message when provided', testPageShowsExceptionMessage( exception: exception, - widget: CupertinoApp( - home: CupertinoErrorScreen(exception), - ), + widget: CupertinoApp(home: CupertinoErrorScreen(exception)), ), ); @@ -84,9 +76,7 @@ void main() { testClickingTheButtonRedirectsToRoot( buttonFinder: find.byType(CupertinoButton), appRouterBuilder: cupertinoAppRouterBuilder, - widget: const CupertinoApp( - home: CupertinoErrorScreen(null), - ), + widget: const CupertinoApp(home: CupertinoErrorScreen(null)), ), ); }); diff --git a/packages/go_router/test/custom_transition_page_test.dart b/packages/go_router/test/custom_transition_page_test.dart index 710d9d19c67..431315028f5 100644 --- a/packages/go_router/test/custom_transition_page_test.dart +++ b/packages/go_router/test/custom_transition_page_test.dart @@ -7,35 +7,33 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; void main() { - testWidgets('CustomTransitionPage builds its child using transitionsBuilder', - (WidgetTester tester) async { - const HomeScreen child = HomeScreen(); - final CustomTransitionPage transition = CustomTransitionPage( - transitionsBuilder: expectAsync4((_, __, ___, Widget child) => child), - child: child, + testWidgets( + 'CustomTransitionPage builds its child using transitionsBuilder', + (WidgetTester tester) async { + const HomeScreen child = HomeScreen(); + final CustomTransitionPage transition = CustomTransitionPage( + transitionsBuilder: expectAsync4((_, __, ___, Widget child) => child), + child: child, + ); + final GoRouter router = GoRouter( + routes: [ + GoRoute(path: '/', pageBuilder: (_, __) => transition), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), + ); + expect(find.byWidget(child), findsOneWidget); + }, + ); + + testWidgets('NoTransitionPage does not apply any transition', ( + WidgetTester tester, + ) async { + final ValueNotifier showHomeValueNotifier = ValueNotifier( + false, ); - final GoRouter router = GoRouter( - routes: [ - GoRoute( - path: '/', - pageBuilder: (_, __) => transition, - ), - ], - ); - addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), - ); - expect(find.byWidget(child), findsOneWidget); - }); - - testWidgets('NoTransitionPage does not apply any transition', - (WidgetTester tester) async { - final ValueNotifier showHomeValueNotifier = - ValueNotifier(false); addTearDown(showHomeValueNotifier.dispose); await tester.pumpWidget( MaterialApp( @@ -44,13 +42,8 @@ void main() { builder: (_, bool showHome, __) { return Navigator( pages: >[ - const NoTransitionPage( - child: LoginScreen(), - ), - if (showHome) - const NoTransitionPage( - child: HomeScreen(), - ), + const NoTransitionPage(child: LoginScreen()), + if (showHome) const NoTransitionPage(child: HomeScreen()), ], onPopPage: (Route route, dynamic result) { return route.didPop(result); @@ -82,8 +75,9 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('NoTransitionPage does not apply any reverse transition', - (WidgetTester tester) async { + testWidgets('NoTransitionPage does not apply any reverse transition', ( + WidgetTester tester, + ) async { final ValueNotifier showHomeValueNotifier = ValueNotifier(true); addTearDown(showHomeValueNotifier.dispose); await tester.pumpWidget( @@ -93,13 +87,8 @@ void main() { builder: (_, bool showHome, __) { return Navigator( pages: >[ - const NoTransitionPage( - child: LoginScreen(), - ), - if (showHome) - const NoTransitionPage( - child: HomeScreen(), - ), + const NoTransitionPage(child: LoginScreen()), + if (showHome) const NoTransitionPage(child: HomeScreen()), ], onPopPage: (Route route, dynamic result) { return route.didPop(result); @@ -119,26 +108,26 @@ void main() { expect(homeScreenFinder, findsNothing); }); - testWidgets('Dismiss a screen by tapping a modal barrier', - (WidgetTester tester) async { + testWidgets('Dismiss a screen by tapping a modal barrier', ( + WidgetTester tester, + ) async { const ValueKey homeKey = ValueKey('home'); - const ValueKey dismissibleModalKey = - ValueKey('dismissibleModal'); + const ValueKey dismissibleModalKey = ValueKey( + 'dismissibleModal', + ); 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), + ), ), ], ); @@ -153,8 +142,9 @@ void main() { expect(find.byKey(homeKey), findsOneWidget); }); - testWidgets('transitionDuration and reverseTransitionDuration is different', - (WidgetTester tester) async { + testWidgets('transitionDuration and reverseTransitionDuration is different', ( + WidgetTester tester, + ) async { const ValueKey homeKey = ValueKey('home'); const ValueKey loginKey = ValueKey('login'); const Duration transitionDuration = Duration(milliseconds: 50); @@ -162,21 +152,19 @@ 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), + ), ), ], ); @@ -201,11 +189,7 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { - return const Scaffold( - body: Center( - child: Text('HomeScreen'), - ), - ); + return const Scaffold(body: Center(child: Text('HomeScreen'))); } } @@ -214,11 +198,7 @@ class LoginScreen extends StatelessWidget { @override Widget build(BuildContext context) { - return const Scaffold( - body: Center( - child: Text('LoginScreen'), - ), - ); + return const Scaffold(body: Center(child: Text('LoginScreen'))); } } diff --git a/packages/go_router/test/delegate_test.dart b/packages/go_router/test/delegate_test.dart index 945d7835034..fa9915bca2e 100644 --- a/packages/go_router/test/delegate_test.dart +++ b/packages/go_router/test/delegate_test.dart @@ -19,60 +19,66 @@ Future createGoRouter( routes: [ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), GoRoute(path: '/a', builder: (_, __) => const DummyStatefulWidget()), - GoRoute( - path: '/error', - builder: (_, __) => const ErrorScreen(null), - ), + GoRoute(path: '/error', builder: (_, __) => const ErrorScreen(null)), ], refreshListenable: refreshListenable, ); if (dispose) { addTearDown(router.dispose); } - await tester.pumpWidget(MaterialApp.router( - routerConfig: router, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router; } Future createGoRouterWithStatefulShellRoute( - WidgetTester tester) async { + WidgetTester tester, +) async { final GoRouter router = GoRouter( initialLocation: '/', routes: [ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), GoRoute(path: '/a', builder: (_, __) => const DummyStatefulWidget()), - StatefulShellRoute.indexedStack(branches: [ - StatefulShellBranch(routes: [ - GoRoute( - path: '/c', - builder: (_, __) => const DummyStatefulWidget(), - routes: [ - GoRoute( + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/c', + builder: (_, __) => const DummyStatefulWidget(), + routes: [ + GoRoute( path: 'c1', - builder: (_, __) => const DummyStatefulWidget()), - GoRoute( + builder: (_, __) => const DummyStatefulWidget(), + ), + GoRoute( path: 'c2', - builder: (_, __) => const DummyStatefulWidget()), - ]), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/d', - builder: (_, __) => const DummyStatefulWidget(), - routes: [ - GoRoute( + builder: (_, __) => const DummyStatefulWidget(), + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/d', + builder: (_, __) => const DummyStatefulWidget(), + routes: [ + GoRoute( path: 'd1', - builder: (_, __) => const DummyStatefulWidget()), - ]), - ]), - ], builder: mockStackedShellBuilder), + builder: (_, __) => const DummyStatefulWidget(), + ), + ], + ), + ], + ), + ], + builder: mockStackedShellBuilder, + ), ], ); addTearDown(router.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: router, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router; } @@ -90,50 +96,61 @@ Future createGoRouterWithStatefulShellRouteAndPopScopes( routes: [ StatefulShellRoute.indexedStack( branches: [ - StatefulShellBranch(routes: [ - GoRoute( + StatefulShellBranch( + 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'), + ), ), - ]), - ]), + ], + ), + ], + ), ], - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) => - PopScope( - onPopInvokedWithResult: onPopShellRouteBuilder, - canPop: canPopShellRouteBuilder, - child: navigationShell, - ), + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) => PopScope( + onPopInvokedWithResult: onPopShellRouteBuilder, + canPop: canPopShellRouteBuilder, + child: navigationShell, + ), ), ], ); addTearDown(router.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: router, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router; } void main() { group('pop', () { - testWidgets('restore() update currentConfiguration in pop()', - (WidgetTester tester) async { + testWidgets('restore() update currentConfiguration in pop()', ( + WidgetTester tester, + ) async { final ValueNotifier valueNotifier = ValueNotifier(0); - final GoRouter goRouter = await createGoRouter(tester, - refreshListenable: valueNotifier, dispose: false); + final GoRouter goRouter = await createGoRouter( + tester, + refreshListenable: valueNotifier, + dispose: false, + ); goRouter.push('/a'); await tester.pumpAndSettle(); @@ -143,7 +160,11 @@ void main() { await tester.pumpAndSettle(); expect( goRouter - .routerDelegate.currentConfiguration.matches.last.matchedLocation, + .routerDelegate + .currentConfiguration + .matches + .last + .matchedLocation, '/', ); @@ -161,12 +182,14 @@ void main() { await goRouter.routerDelegate.popRoute(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); expect( - goRouter.routerDelegate.currentConfiguration.matches.contains(last), - false); + goRouter.routerDelegate.currentConfiguration.matches.contains(last), + false, + ); }); - testWidgets('PopScope intercepts back button on root route', - (WidgetTester tester) async { + testWidgets('PopScope intercepts back button on root route', ( + WidgetTester tester, + ) async { bool didPop = false; final GoRouter goRouter = GoRouter( @@ -174,22 +197,21 @@ 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'), + ), ), ], ); addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: goRouter, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); expect(find.text('Home'), findsOneWidget); @@ -204,92 +226,96 @@ void main() { }); testWidgets( - 'PopScope intercepts back button on StatefulShellRoute builder route', - (WidgetTester tester) async { - bool didPopShellRouteBuilder = false; - bool didPopBranch = false; - bool didPopBranchSubRoute = false; - - await createGoRouterWithStatefulShellRouteAndPopScopes( - tester, - canPopShellRouteBuilder: false, - onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, - onPopBranch: (_, __) => didPopBranch = true, - onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, - ); + 'PopScope intercepts back button on StatefulShellRoute builder route', + (WidgetTester tester) async { + bool didPopShellRouteBuilder = false; + bool didPopBranch = false; + bool didPopBranchSubRoute = false; + + await createGoRouterWithStatefulShellRouteAndPopScopes( + tester, + canPopShellRouteBuilder: false, + onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, + onPopBranch: (_, __) => didPopBranch = true, + onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, + ); - expect(find.text('Home'), findsOneWidget); - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); - // Verify that PopScope intercepted the back button - expect(didPopShellRouteBuilder, isTrue); - expect(didPopBranch, isFalse); - expect(didPopBranchSubRoute, isFalse); + // Verify that PopScope intercepted the back button + expect(didPopShellRouteBuilder, isTrue); + expect(didPopBranch, isFalse); + expect(didPopBranchSubRoute, isFalse); - expect(find.text('Home'), findsOneWidget); - }); + expect(find.text('Home'), findsOneWidget); + }, + ); testWidgets( - 'PopScope intercepts back button on StatefulShellRoute branch route', - (WidgetTester tester) async { - bool didPopShellRouteBuilder = false; - bool didPopBranch = false; - bool didPopBranchSubRoute = false; - - await createGoRouterWithStatefulShellRouteAndPopScopes( - tester, - canPopBranch: false, - onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, - onPopBranch: (_, __) => didPopBranch = true, - onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, - ); + 'PopScope intercepts back button on StatefulShellRoute branch route', + (WidgetTester tester) async { + bool didPopShellRouteBuilder = false; + bool didPopBranch = false; + bool didPopBranchSubRoute = false; + + await createGoRouterWithStatefulShellRouteAndPopScopes( + tester, + canPopBranch: false, + onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, + onPopBranch: (_, __) => didPopBranch = true, + onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, + ); - expect(find.text('Home'), findsOneWidget); - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); - // Verify that PopScope intercepted the back button - expect(didPopShellRouteBuilder, isFalse); - expect(didPopBranch, isTrue); - expect(didPopBranchSubRoute, isFalse); + // Verify that PopScope intercepted the back button + expect(didPopShellRouteBuilder, isFalse); + expect(didPopBranch, isTrue); + expect(didPopBranchSubRoute, isFalse); - expect(find.text('Home'), findsOneWidget); - }); + expect(find.text('Home'), findsOneWidget); + }, + ); testWidgets( - 'PopScope intercepts back button on StatefulShellRoute branch sub route', - (WidgetTester tester) async { - bool didPopShellRouteBuilder = false; - bool didPopBranch = false; - bool didPopBranchSubRoute = false; - - final GoRouter goRouter = - await createGoRouterWithStatefulShellRouteAndPopScopes( - tester, - canPopBranchSubRoute: false, - onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, - onPopBranch: (_, __) => didPopBranch = true, - onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, - ); + 'PopScope intercepts back button on StatefulShellRoute branch sub route', + (WidgetTester tester) async { + bool didPopShellRouteBuilder = false; + bool didPopBranch = false; + bool didPopBranchSubRoute = false; - goRouter.push('/c/c1'); - await tester.pumpAndSettle(); + final GoRouter goRouter = + await createGoRouterWithStatefulShellRouteAndPopScopes( + tester, + canPopBranchSubRoute: false, + onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, + onPopBranch: (_, __) => didPopBranch = true, + onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, + ); - expect(find.text('SubRoute'), findsOneWidget); - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); + goRouter.push('/c/c1'); + await tester.pumpAndSettle(); - // Verify that PopScope intercepted the back button - expect(didPopShellRouteBuilder, isFalse); - expect(didPopBranch, isFalse); - expect(didPopBranchSubRoute, isTrue); + expect(find.text('SubRoute'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); - expect(find.text('SubRoute'), findsOneWidget); - }); + // Verify that PopScope intercepted the back button + expect(didPopShellRouteBuilder, isFalse); + expect(didPopBranch, isFalse); + expect(didPopBranchSubRoute, isTrue); - testWidgets('pops more than matches count should return false', - (WidgetTester tester) async { + expect(find.text('SubRoute'), findsOneWidget); + }, + ); + + testWidgets('pops more than matches count should return false', ( + WidgetTester tester, + ) async { final GoRouter goRouter = await createGoRouter(tester) ..push('/error'); await tester.pumpAndSettle(); @@ -300,29 +326,26 @@ void main() { testWidgets('throw if nothing to pop', (WidgetTester tester) async { final GlobalKey rootKey = GlobalKey(); final GlobalKey navKey = GlobalKey(); - final GoRouter goRouter = await createRouter( - [ - ShellRoute( - navigatorKey: rootKey, - builder: (_, __, Widget child) => child, - routes: [ - ShellRoute( - parentNavigatorKey: rootKey, - navigatorKey: navKey, - builder: (_, __, Widget child) => child, - routes: [ - GoRoute( - path: '/', - parentNavigatorKey: navKey, - builder: (_, __) => const Text('Home'), - ), - ], - ), - ], - ), - ], - tester, - ); + final GoRouter goRouter = await createRouter([ + ShellRoute( + navigatorKey: rootKey, + builder: (_, __, Widget child) => child, + routes: [ + ShellRoute( + parentNavigatorKey: rootKey, + navigatorKey: navKey, + builder: (_, __, Widget child) => child, + routes: [ + GoRoute( + path: '/', + parentNavigatorKey: navKey, + builder: (_, __) => const Text('Home'), + ), + ], + ), + ], + ), + ], tester); await tester.pumpAndSettle(); expect(find.text('Home'), findsOneWidget); String? message; @@ -334,65 +357,66 @@ void main() { expect(message, 'There is nothing to pop'); }); - testWidgets('poproute return false if nothing to pop', - (WidgetTester tester) async { + testWidgets('poproute return false if nothing to pop', ( + WidgetTester tester, + ) async { final GlobalKey rootKey = GlobalKey(); final GlobalKey navKey = GlobalKey(); - final GoRouter goRouter = await createRouter( - [ - ShellRoute( - navigatorKey: rootKey, - builder: (_, __, Widget child) => child, - routes: [ - ShellRoute( - parentNavigatorKey: rootKey, - navigatorKey: navKey, - builder: (_, __, Widget child) => child, - routes: [ - GoRoute( - path: '/', - parentNavigatorKey: navKey, - builder: (_, __) => const Text('Home'), - ), - ], - ), - ], - ), - ], - tester, - ); + final GoRouter goRouter = await createRouter([ + ShellRoute( + navigatorKey: rootKey, + builder: (_, __, Widget child) => child, + routes: [ + ShellRoute( + parentNavigatorKey: rootKey, + navigatorKey: navKey, + builder: (_, __, Widget child) => child, + routes: [ + GoRoute( + path: '/', + parentNavigatorKey: navKey, + builder: (_, __) => const Text('Home'), + ), + ], + ), + ], + ), + ], tester); expect(await goRouter.routerDelegate.popRoute(), isFalse); }); }); group('push', () { - testWidgets( - 'It should return different pageKey when push is called', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + testWidgets('It should return different pageKey when push is called', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - goRouter.push('/a'); - await tester.pumpAndSettle(); + goRouter.push('/a'); + await tester.pumpAndSettle(); - goRouter.push('/a'); - await tester.pumpAndSettle(); + goRouter.push('/a'); + await tester.pumpAndSettle(); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); - expect( - goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, - isNot(equals( - goRouter.routerDelegate.currentConfiguration.matches[2].pageKey)), - ); - }, - ); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); + expect( + goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, + isNot( + equals( + goRouter.routerDelegate.currentConfiguration.matches[2].pageKey, + ), + ), + ); + }); testWidgets( 'It should successfully push a route from outside the the current ' 'StatefulShellRoute', (WidgetTester tester) async { - final GoRouter goRouter = - await createGoRouterWithStatefulShellRoute(tester); + final GoRouter goRouter = await createGoRouterWithStatefulShellRoute( + tester, + ); goRouter.push('/c/c1'); await tester.pumpAndSettle(); goRouter.push('/a'); @@ -400,8 +424,11 @@ void main() { expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); expect( goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, - isNot(equals( - goRouter.routerDelegate.currentConfiguration.matches[2].pageKey)), + isNot( + equals( + goRouter.routerDelegate.currentConfiguration.matches[2].pageKey, + ), + ), ); }, ); @@ -410,8 +437,9 @@ void main() { 'It should successfully push a route that is a descendant of the current ' 'StatefulShellRoute branch', (WidgetTester tester) async { - final GoRouter goRouter = - await createGoRouterWithStatefulShellRoute(tester); + final GoRouter goRouter = await createGoRouterWithStatefulShellRoute( + tester, + ); goRouter.push('/c/c1'); await tester.pumpAndSettle(); @@ -419,8 +447,9 @@ void main() { await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ShellRouteMatch shellRouteMatch = goRouter.routerDelegate - .currentConfiguration.matches.last as ShellRouteMatch; + final ShellRouteMatch shellRouteMatch = + goRouter.routerDelegate.currentConfiguration.matches.last + as ShellRouteMatch; expect(shellRouteMatch.matches.length, 2); expect( shellRouteMatch.matches[0].pageKey, @@ -433,8 +462,9 @@ void main() { 'It should successfully push the root of the current StatefulShellRoute ' 'branch upon itself', (WidgetTester tester) async { - final GoRouter goRouter = - await createGoRouterWithStatefulShellRoute(tester); + final GoRouter goRouter = await createGoRouterWithStatefulShellRoute( + tester, + ); goRouter.push('/c'); await tester.pumpAndSettle(); @@ -442,8 +472,9 @@ void main() { await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ShellRouteMatch shellRouteMatch = goRouter.routerDelegate - .currentConfiguration.matches.last as ShellRouteMatch; + final ShellRouteMatch shellRouteMatch = + goRouter.routerDelegate.currentConfiguration.matches.last + as ShellRouteMatch; expect(shellRouteMatch.matches.length, 2); expect( shellRouteMatch.matches[0].pageKey, @@ -475,25 +506,25 @@ void main() { expect(goRouter.routerDelegate.canPop(), true); }, ); - testWidgets( - 'It should return false if there are no matches in the stack', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/', - routes: [], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - await tester.pumpAndSettle(); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 0); - expect(goRouter.routerDelegate.canPop(), false); - }, - ); + testWidgets('It should return false if there are no matches in the stack', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/', + routes: [], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + await tester.pumpAndSettle(); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 0); + expect(goRouter.routerDelegate.canPop(), false); + }); }); group('pushReplacement', () { - testWidgets('It should replace the last match with the given one', - (WidgetTester tester) async { + testWidgets('It should replace the last match with the given one', ( + WidgetTester tester, + ) async { final GoRouter goRouter = GoRouter( initialLocation: '/', routes: [ @@ -503,11 +534,7 @@ void main() { ], ); addTearDown(goRouter.dispose); - await tester.pumpWidget( - MaterialApp.router( - routerConfig: goRouter, - ), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); goRouter.push('/page-0'); @@ -568,65 +595,62 @@ void main() { }); group('pushReplacementNamed', () { - testWidgets( - 'It should replace the last match with the given one', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/', - routes: [ - GoRoute(path: '/', builder: (_, __) => const SizedBox()), - GoRoute( - path: '/page-0', - name: 'page0', - builder: (_, __) => const SizedBox()), - GoRoute( - path: '/page-1', - name: 'page1', - builder: (_, __) => const SizedBox()), - ], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget( - MaterialApp.router( - routerConfig: goRouter, + testWidgets('It should replace the last match with the given one', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/', + routes: [ + GoRoute(path: '/', builder: (_, __) => const SizedBox()), + GoRoute( + path: '/page-0', + name: 'page0', + builder: (_, __) => const SizedBox(), ), - ); + GoRoute( + path: '/page-1', + name: 'page1', + builder: (_, __) => const SizedBox(), + ), + ], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - goRouter.pushNamed('page0'); + goRouter.pushNamed('page0'); - goRouter.routerDelegate.addListener(expectAsync0(() {})); - final RouteMatchBase first = - goRouter.routerDelegate.currentConfiguration.matches.first; - final RouteMatch last = - goRouter.routerDelegate.currentConfiguration.last; - goRouter.pushReplacementNamed('page1'); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect( - goRouter.routerDelegate.currentConfiguration.matches.first, - first, - reason: 'The first match should still be in the list of matches', - ); - expect( - goRouter.routerDelegate.currentConfiguration.last, - isNot(last), - reason: 'The last match should have been removed', - ); - expect( - goRouter.routerDelegate.currentConfiguration.last, - isA().having( - (RouteMatch match) => match.route.name, - 'match.route.name', - 'page1', - ), - reason: 'The new location should have been pushed', - ); - }, - ); + goRouter.routerDelegate.addListener(expectAsync0(() {})); + final RouteMatchBase first = + goRouter.routerDelegate.currentConfiguration.matches.first; + final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; + goRouter.pushReplacementNamed('page1'); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect( + goRouter.routerDelegate.currentConfiguration.matches.first, + first, + reason: 'The first match should still be in the list of matches', + ); + expect( + goRouter.routerDelegate.currentConfiguration.last, + isNot(last), + reason: 'The last match should have been removed', + ); + expect( + goRouter.routerDelegate.currentConfiguration.last, + isA().having( + (RouteMatch match) => match.route.name, + 'match.route.name', + 'page1', + ), + reason: 'The new location should have been pushed', + ); + }); }); group('replace', () { - testWidgets('It should replace the last match with the given one', - (WidgetTester tester) async { + testWidgets('It should replace the last match with the given one', ( + WidgetTester tester, + ) async { final GoRouter goRouter = GoRouter( initialLocation: '/', routes: [ @@ -636,11 +660,7 @@ void main() { ], ); addTearDown(goRouter.dispose); - await tester.pumpWidget( - MaterialApp.router( - routerConfig: goRouter, - ), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); goRouter.push('/page-0'); @@ -754,14 +774,13 @@ void main() { ], ); addTearDown(router.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: router, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router; } - testWidgets('It should replace the last match with the given one', - (WidgetTester tester) async { + testWidgets('It should replace the last match with the given one', ( + WidgetTester tester, + ) async { final GoRouter goRouter = await createGoRouter(tester); goRouter.pushNamed('page0'); @@ -850,8 +869,9 @@ void main() { ); }); - testWidgets('dispose unsubscribes from refreshListenable', - (WidgetTester tester) async { + testWidgets('dispose unsubscribes from refreshListenable', ( + WidgetTester tester, + ) async { final FakeRefreshListenable refreshListenable = FakeRefreshListenable(); addTearDown(refreshListenable.dispose); diff --git a/packages/go_router/test/error_page_test.dart b/packages/go_router/test/error_page_test.dart index f2d1e573725..10bb3199bff 100644 --- a/packages/go_router/test/error_page_test.dart +++ b/packages/go_router/test/error_page_test.dart @@ -11,11 +11,7 @@ import 'helpers/error_screen_helpers.dart'; void main() { testWidgets( 'shows "page not found" by default', - testPageNotFound( - widget: widgetsAppBuilder( - home: const ErrorScreen(null), - ), - ), + testPageNotFound(widget: widgetsAppBuilder(home: const ErrorScreen(null))), ); final Exception exception = Exception('Something went wrong!'); @@ -23,20 +19,17 @@ void main() { 'shows the exception message when provided', testPageShowsExceptionMessage( exception: exception, - widget: widgetsAppBuilder( - home: ErrorScreen(exception), - ), + widget: widgetsAppBuilder(home: ErrorScreen(exception)), ), ); testWidgets( 'clicking the button should redirect to /', testClickingTheButtonRedirectsToRoot( - buttonFinder: - find.byWidgetPredicate((Widget widget) => widget is GestureDetector), - widget: widgetsAppBuilder( - home: const ErrorScreen(null), + buttonFinder: find.byWidgetPredicate( + (Widget widget) => widget is GestureDetector, ), + widget: widgetsAppBuilder(home: const ErrorScreen(null)), ), ); } @@ -44,9 +37,7 @@ void main() { Widget widgetsAppBuilder({required Widget home}) { return WidgetsApp( onGenerateRoute: (_) { - return MaterialPageRoute( - builder: (BuildContext _) => home, - ); + return MaterialPageRoute(builder: (BuildContext _) => home); }, color: Colors.white, ); diff --git a/packages/go_router/test/exception_handling_test.dart b/packages/go_router/test/exception_handling_test.dart index d8ad3c3f565..44e387e8cff 100644 --- a/packages/go_router/test/exception_handling_test.dart +++ b/packages/go_router/test/exception_handling_test.dart @@ -9,15 +9,17 @@ import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { - testWidgets('throws if more than one exception handlers are provided.', - (WidgetTester tester) async { + testWidgets('throws if more than one exception handlers are provided.', ( + WidgetTester tester, + ) async { bool thrown = false; try { GoRouter( routes: [ GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home')), + path: '/', + builder: (_, GoRouterState state) => const Text('home'), + ), ], errorBuilder: (_, __) => const Text(''), onException: (_, __, ___) {}, @@ -32,8 +34,9 @@ void main() { GoRouter( routes: [ GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home')), + path: '/', + builder: (_, GoRouterState state) => const Text('home'), + ), ], errorBuilder: (_, __) => const Text(''), errorPageBuilder: (_, __) => const MaterialPage(child: Text('')), @@ -48,8 +51,9 @@ void main() { GoRouter( routes: [ GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home')), + path: '/', + builder: (_, GoRouterState state) => const Text('home'), + ), ], onException: (_, __, ___) {}, errorPageBuilder: (_, __) => const MaterialPage(child: Text('')), @@ -62,14 +66,19 @@ void main() { group('onException', () { testWidgets('can redirect.', (WidgetTester tester) async { - final GoRouter router = await createRouter([ - GoRoute( + final GoRouter router = await createRouter( + [ + GoRoute( path: '/error', - builder: (_, GoRouterState state) => - Text('redirected ${state.extra}')), - ], tester, - onException: (_, GoRouterState state, GoRouter router) => - router.go('/error', extra: state.uri.toString())); + builder: + (_, GoRouterState state) => Text('redirected ${state.extra}'), + ), + ], + tester, + onException: + (_, GoRouterState state, GoRouter router) => + router.go('/error', extra: state.uri.toString()), + ); expect(find.text('redirected /'), findsOneWidget); router.go('/some-other-location'); @@ -78,13 +87,18 @@ void main() { }); testWidgets('can redirect with extra', (WidgetTester tester) async { - final GoRouter router = await createRouter([ - GoRoute( + final GoRouter router = await createRouter( + [ + GoRoute( path: '/error', - builder: (_, GoRouterState state) => Text('extra: ${state.extra}')), - ], tester, - onException: (_, GoRouterState state, GoRouter router) => - router.go('/error', extra: state.extra)); + builder: (_, GoRouterState state) => Text('extra: ${state.extra}'), + ), + ], + tester, + onException: + (_, GoRouterState state, GoRouter router) => + router.go('/error', extra: state.extra), + ); expect(find.text('extra: null'), findsOneWidget); router.go('/some-other-location', extra: 'X'); @@ -96,8 +110,9 @@ void main() { final GoRouter router = await createRouter( [ GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home')), + path: '/', + builder: (_, GoRouterState state) => const Text('home'), + ), ], tester, onException: (_, __, ___) {}, diff --git a/packages/go_router/test/extension_test.dart b/packages/go_router/test/extension_test.dart index c13a47de002..d3540476ced 100644 --- a/packages/go_router/test/extension_test.dart +++ b/packages/go_router/test/extension_test.dart @@ -21,25 +21,27 @@ void main() { builder: (_, __) => const _MyWidget(), ), GoRoute( - path: '/page-0/:tab', - name: 'page-0', - builder: (_, __) => const SizedBox()) + path: '/page-0/:tab', + name: 'page-0', + builder: (_, __) => const SizedBox(), + ), ], ); addTearDown(router.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: router, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router; } - testWidgets('Passes GoRouter parameters through context call.', - (WidgetTester tester) async { + testWidgets('Passes GoRouter parameters through context call.', ( + WidgetTester tester, + ) async { final GoRouter router = await createGoRouter(tester); await tester.tap(find.text('Settings')); await tester.pumpAndSettle(); - expect(router.routerDelegate.currentConfiguration.uri.toString(), - '/page-0/settings?search=notification'); + expect( + router.routerDelegate.currentConfiguration.uri.toString(), + '/page-0/settings?search=notification', + ); }); }); } @@ -50,9 +52,13 @@ class _MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ElevatedButton( - onPressed: () => context.replaceNamed('page-0', + onPressed: + () => context.replaceNamed( + 'page-0', pathParameters: {'tab': 'settings'}, - queryParameters: {'search': 'notification'}), - child: const Text('Settings')); + queryParameters: {'search': 'notification'}, + ), + child: const Text('Settings'), + ); } } diff --git a/packages/go_router/test/extra_codec_test.dart b/packages/go_router/test/extra_codec_test.dart index 0005d1d535f..3c8065d9d1d 100644 --- a/packages/go_router/test/extra_codec_test.dart +++ b/packages/go_router/test/extra_codec_test.dart @@ -11,8 +11,9 @@ import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { - testWidgets('router rebuild with extra codec works', - (WidgetTester tester) async { + testWidgets('router rebuild with extra codec works', ( + WidgetTester tester, + ) async { const String initialString = 'some string'; const String empty = 'empty'; final GoRouter router = GoRouter( @@ -21,10 +22,11 @@ void main() { initialExtra: ComplexData(initialString), routes: [ GoRoute( - path: '/', - builder: (_, GoRouterState state) { - return Text((state.extra as ComplexData?)?.data ?? empty); - }), + path: '/', + builder: (_, GoRouterState state) { + return Text((state.extra as ComplexData?)?.data ?? empty); + }, + ), ], redirect: (BuildContext context, _) { // Set up dependency. @@ -40,9 +42,7 @@ void main() { await tester.pumpWidget( SimpleDependencyProvider( dependency: dependency, - child: MaterialApp.router( - routerConfig: router, - ), + child: MaterialApp.router(routerConfig: router), ), ); expect(find.text(initialString), findsOneWidget); diff --git a/packages/go_router/test/go_route_test.dart b/packages/go_router/test/go_route_test.dart index 752a1a16580..588ad685161 100644 --- a/packages/go_router/test/go_route_test.dart +++ b/packages/go_router/test/go_route_test.dart @@ -21,8 +21,9 @@ void main() { GoRoute(path: '/', redirect: (_, __) => '/a'); }); - testWidgets('ShellRoute can use parent navigator key', - (WidgetTester tester) async { + testWidgets('ShellRoute can use parent navigator key', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey shellNavigatorKey = @@ -45,15 +46,16 @@ void main() { GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, routes: [ ShellRoute( parentNavigatorKey: rootNavigatorKey, - builder: - (BuildContext context, GoRouterState state, Widget child) { + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { return Scaffold( body: Column( children: [ @@ -67,9 +69,7 @@ void main() { GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen C'), - ); + return const Scaffold(body: Text('Screen C')); }, ), ], @@ -80,16 +80,21 @@ void main() { ), ]; - await createRouter(routes, tester, - initialLocation: '/b/c', navigatorKey: rootNavigatorKey); + await createRouter( + routes, + tester, + initialLocation: '/b/c', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen D'), findsOneWidget); expect(find.text('Screen C'), findsOneWidget); }); - testWidgets('StatefulShellRoute can use parent navigator key', - (WidgetTester tester) async { + testWidgets('StatefulShellRoute can use parent navigator key', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey shellNavigatorKey = @@ -112,9 +117,7 @@ void main() { GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, routes: [ StatefulShellRoute.indexedStack( @@ -133,9 +136,7 @@ void main() { GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen C'), - ); + return const Scaffold(body: Text('Screen C')); }, ), ], @@ -148,8 +149,12 @@ void main() { ), ]; - await createRouter(routes, tester, - initialLocation: '/b/c', navigatorKey: rootNavigatorKey); + await createRouter( + routes, + tester, + initialLocation: '/b/c', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen D'), findsOneWidget); @@ -169,10 +174,7 @@ void main() { parentNavigatorKey: key2, builder: (_, __, Widget child) => child, routes: [ - GoRoute( - path: '1', - builder: (_, __) => const Text('/route/1'), - ), + GoRoute(path: '1', builder: (_, __) => const Text('/route/1')), ], ), ], @@ -185,27 +187,21 @@ void main() { group('Redirect only GoRoute', () { testWidgets('can redirect to subroute', (WidgetTester tester) async { - final GoRouter router = await createRouter( - [ - GoRoute( - path: '/', - builder: (_, __) => const Text('home'), - routes: [ - GoRoute( - path: 'route', - redirect: (_, __) => '/route/1', - routes: [ - GoRoute( - path: '1', - builder: (_, __) => const Text('/route/1'), - ), - ], - ), - ], - ), - ], - tester, - ); + final GoRouter router = await createRouter([ + GoRoute( + path: '/', + builder: (_, __) => const Text('home'), + routes: [ + GoRoute( + path: 'route', + redirect: (_, __) => '/route/1', + routes: [ + GoRoute(path: '1', builder: (_, __) => const Text('/route/1')), + ], + ), + ], + ), + ], tester); expect(find.text('home'), findsOneWidget); router.go('/route'); @@ -220,27 +216,21 @@ void main() { }); testWidgets('throw if redirect to itself.', (WidgetTester tester) async { - final GoRouter router = await createRouter( - [ - GoRoute( - path: '/', - builder: (_, __) => const Text('home'), - routes: [ - GoRoute( - path: 'route', - redirect: (_, __) => '/route', - routes: [ - GoRoute( - path: '1', - builder: (_, __) => const Text('/route/1'), - ), - ], - ), - ], - ), - ], - tester, - ); + final GoRouter router = await createRouter([ + GoRoute( + path: '/', + builder: (_, __) => const Text('home'), + routes: [ + GoRoute( + path: 'route', + redirect: (_, __) => '/route', + routes: [ + GoRoute(path: '1', builder: (_, __) => const Text('/route/1')), + ], + ), + ], + ), + ], tester); expect(find.text('home'), findsOneWidget); router.go('/route'); @@ -249,46 +239,49 @@ void main() { expect(tester.takeException(), isAssertionError); }); - testWidgets('redirects to a valid route based on fragment.', - (WidgetTester tester) async { - final GoRouter router = await createRouter( - [ - GoRoute( - path: '/', - builder: (_, __) => const Text('home'), - routes: [ - GoRoute( - path: 'route', - name: 'route', - redirect: (BuildContext context, GoRouterState state) { - // Redirection logic based on the fragment in the URI - if (state.uri.fragment == '1') { - // If fragment is "1", redirect to "/route/1" - return '/route/1'; - } - return null; // No redirection for other cases - }, - routes: [ - GoRoute( - path: '1', - builder: (_, __) => - const Text('/route/1'), // Renders "/route/1" text - ), - ], - ), - ], - ), - ], - tester, - ); + testWidgets('redirects to a valid route based on fragment.', ( + WidgetTester tester, + ) async { + final GoRouter router = await createRouter([ + GoRoute( + path: '/', + builder: (_, __) => const Text('home'), + routes: [ + GoRoute( + path: 'route', + name: 'route', + redirect: (BuildContext context, GoRouterState state) { + // Redirection logic based on the fragment in the URI + if (state.uri.fragment == '1') { + // If fragment is "1", redirect to "/route/1" + return '/route/1'; + } + return null; // No redirection for other cases + }, + routes: [ + GoRoute( + path: '1', + builder: + (_, __) => + const Text('/route/1'), // Renders "/route/1" text + ), + ], + ), + ], + ), + ], tester); // Verify that the root route ("/") initially displays the "home" text expect(find.text('home'), findsOneWidget); // Generate a location string for the named route "route" with fragment "2" - final String locationWithFragment = - router.namedLocation('route', fragment: '2'); - expect(locationWithFragment, - '/route#2'); // Expect the generated location to be "/route#2" + final String locationWithFragment = router.namedLocation( + 'route', + fragment: '2', + ); + expect( + locationWithFragment, + '/route#2', + ); // Expect the generated location to be "/route#2" // Navigate to the named route "route" with fragment "1" router.goNamed('route', fragment: '1'); @@ -301,33 +294,35 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('throw if sub route does not conform with parent navigator key', - (WidgetTester tester) async { - final GlobalKey key1 = GlobalKey(); - final GlobalKey key2 = GlobalKey(); - bool hasError = false; - try { - ShellRoute( - navigatorKey: key1, - builder: (_, __, Widget child) => child, - routes: [ - GoRoute( - path: '/', - redirect: (_, __) => '/route', - routes: [ - GoRoute( - parentNavigatorKey: key2, - path: 'route', - builder: (_, __) => const Text('/route/1'), - ), - ], - ), - ], - ); - } on AssertionError catch (_) { - hasError = true; - } - expect(hasError, isTrue); - }); + testWidgets( + 'throw if sub route does not conform with parent navigator key', + (WidgetTester tester) async { + final GlobalKey key1 = GlobalKey(); + final GlobalKey key2 = GlobalKey(); + bool hasError = false; + try { + ShellRoute( + navigatorKey: key1, + builder: (_, __, Widget child) => child, + routes: [ + GoRoute( + path: '/', + redirect: (_, __) => '/route', + routes: [ + GoRoute( + parentNavigatorKey: key2, + path: 'route', + builder: (_, __) => const Text('/route/1'), + ), + ], + ), + ], + ); + } on AssertionError catch (_) { + hasError = true; + } + expect(hasError, isTrue); + }, + ); }); } diff --git a/packages/go_router/test/go_router_state_test.dart b/packages/go_router/test/go_router_state_test.dart index 4c588177eb2..c7478d12f91 100644 --- a/packages/go_router/test/go_router_state_test.dart +++ b/packages/go_router/test/go_router_state_test.dart @@ -14,17 +14,19 @@ void main() { testWidgets('works in builder', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (BuildContext context, _) { - final GoRouterState state = GoRouterState.of(context); - return Text('/ ${state.uri.queryParameters['p']}'); - }), + path: '/', + builder: (BuildContext context, _) { + final GoRouterState state = GoRouterState.of(context); + return Text('/ ${state.uri.queryParameters['p']}'); + }, + ), GoRoute( - path: '/a', - builder: (BuildContext context, _) { - final GoRouterState state = GoRouterState.of(context); - return Text('/a ${state.uri.queryParameters['p']}'); - }), + path: '/a', + builder: (BuildContext context, _) { + final GoRouterState state = GoRouterState.of(context); + return Text('/a ${state.uri.queryParameters['p']}'); + }, + ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/?p=123'); @@ -39,21 +41,27 @@ void main() { testWidgets('works in subtree', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (_, __) { - return Builder(builder: (BuildContext context) { + path: '/', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { return Text('1 ${GoRouterState.of(context).uri.path}'); - }); - }, - routes: [ - GoRoute( - path: 'a', - builder: (_, __) { - return Builder(builder: (BuildContext context) { - return Text('2 ${GoRouterState.of(context).uri.path}'); - }); - }), - ]), + }, + ); + }, + routes: [ + GoRoute( + path: 'a', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { + return Text('2 ${GoRouterState.of(context).uri.path}'); + }, + ); + }, + ), + ], + ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/'); @@ -67,26 +75,34 @@ void main() { expect(find.text('1 /a', skipOffstage: false), findsOneWidget); }); - testWidgets('path parameter persists after page is popped', - (WidgetTester tester) async { + testWidgets('path parameter persists after page is popped', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/', - builder: (_, __) { - return Builder(builder: (BuildContext context) { + path: '/', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { return Text('1 ${GoRouterState.of(context).uri.path}'); - }); - }, - routes: [ - GoRoute( - path: ':id', - builder: (_, __) { - return Builder(builder: (BuildContext context) { - return Text( - '2 ${GoRouterState.of(context).pathParameters['id']}'); - }); - }), - ]), + }, + ); + }, + routes: [ + GoRoute( + path: ':id', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { + return Text( + '2 ${GoRouterState.of(context).pathParameters['id']}', + ); + }, + ); + }, + ), + ], + ), ]; final GoRouter router = await createRouter(routes, tester); await tester.pumpAndSettle(); @@ -102,34 +118,46 @@ void main() { expect(find.text('2 123'), findsOneWidget); }); - testWidgets('registry retains GoRouterState for exiting route', - (WidgetTester tester) async { + testWidgets('registry retains GoRouterState for exiting route', ( + WidgetTester tester, + ) async { final UniqueKey key = UniqueKey(); final List routes = [ GoRoute( - path: '/', - builder: (_, __) { - return Builder(builder: (BuildContext context) { + path: '/', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { return Text(GoRouterState.of(context).uri.path); - }); - }, - routes: [ - GoRoute( - path: 'a', - builder: (_, __) { - return Builder(builder: (BuildContext context) { - return Text(key: key, GoRouterState.of(context).uri.path); - }); - }), - ]), + }, + ); + }, + routes: [ + GoRoute( + path: 'a', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { + return Text(key: key, GoRouterState.of(context).uri.path); + }, + ); + }, + ), + ], + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + 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(); @@ -143,35 +171,48 @@ void main() { expect(find.byKey(key), findsNothing); }); - testWidgets('imperative pop clears out registry', - (WidgetTester tester) async { + testWidgets('imperative pop clears out registry', ( + WidgetTester tester, + ) async { final UniqueKey key = UniqueKey(); final GlobalKey nav = GlobalKey(); final List routes = [ GoRoute( - path: '/', - builder: (_, __) { - return Builder(builder: (BuildContext context) { + path: '/', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { return Text(GoRouterState.of(context).uri.path); - }); - }, - routes: [ - GoRoute( - path: 'a', - builder: (_, __) { - return Builder(builder: (BuildContext context) { - return Text(key: key, GoRouterState.of(context).uri.path); - }); - }), - ]), + }, + ); + }, + routes: [ + GoRoute( + path: 'a', + builder: (_, __) { + return Builder( + builder: (BuildContext context) { + return Text(key: key, GoRouterState.of(context).uri.path); + }, + ); + }, + ), + ], + ), ]; - await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: nav); + await createRouter( + routes, + tester, + initialLocation: '/a', + 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(); @@ -186,40 +227,44 @@ void main() { }); testWidgets( - 'GoRouterState look up should be resilient when there is a nested navigator.', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) { - return Scaffold( - appBar: AppBar(), - body: Navigator( - pages: >[ - MaterialPage( - child: Builder( - builder: (BuildContext context) { - return Center( - child: Text(GoRouterState.of(context).uri.toString()), - ); - }, + 'GoRouterState look up should be resilient when there is a nested navigator.', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) { + return Scaffold( + appBar: AppBar(), + body: Navigator( + pages: >[ + MaterialPage( + child: Builder( + builder: (BuildContext context) { + return Center( + child: Text( + GoRouterState.of(context).uri.toString(), + ), + ); + }, + ), ), - ), - ], - onPopPage: (Route route, Object? result) { - throw UnimplementedError(); - }, - ), - ); - }, - ) - ]; - await createRouter(routes, tester); - expect(find.text('/'), findsOneWidget); - }); + ], + onPopPage: (Route route, Object? result) { + throw UnimplementedError(); + }, + ), + ); + }, + ), + ]; + await createRouter(routes, tester); + expect(find.text('/'), findsOneWidget); + }, + ); - testWidgets('GoRouterState topRoute accessible from StatefulShellRoute', - (WidgetTester tester) async { + testWidgets('GoRouterState topRoute accessible from StatefulShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey shellNavigatorKey = @@ -242,9 +287,7 @@ void main() { name: 'root', path: '/', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen 1'), - ); + return const Scaffold(body: Text('Screen 1')); }, routes: [ StatefulShellRoute.indexedStack( @@ -275,9 +318,7 @@ void main() { name: 'a', path: 'a', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen 2'), - ); + return const Scaffold(body: Text('Screen 2')); }, ), ], @@ -288,22 +329,24 @@ void main() { name: 'b', path: 'b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen 2'), - ); + return const Scaffold(body: Text('Screen 2')); }, ), ], - ) + ), ], ), ], - ) + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); expect(find.text('A'), findsOneWidget); router.go('/b'); diff --git a/packages/go_router/test/go_router_test.dart b/packages/go_router/test/go_router_test.dart index 5d6b142c313..b3e6b984ed0 100644 --- a/packages/go_router/test/go_router_test.dart +++ b/packages/go_router/test/go_router_test.dart @@ -28,8 +28,11 @@ Future sendPlatformUrl(String url, WidgetTester tester) async { final ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); } void main() { @@ -41,9 +44,10 @@ void main() { testWidgets('match home route', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen()), + path: '/', + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -53,24 +57,27 @@ void main() { expect(find.byType(HomeScreen), findsOneWidget); }); - testWidgets('If there is more than one route to match, use the first match', - (WidgetTester tester) async { - final List routes = [ - GoRoute(name: '1', path: '/', builder: dummy), - GoRoute(name: '2', path: '/', builder: dummy), - ]; + testWidgets( + 'If there is more than one route to match, use the first match', + (WidgetTester tester) async { + final List routes = [ + GoRoute(name: '1', path: '/', builder: dummy), + GoRoute(name: '2', path: '/', builder: dummy), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('/'); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect((matches.first.route as GoRoute).name, '1'); - expect(find.byType(DummyScreen), findsOneWidget); - }); + final GoRouter router = await createRouter(routes, tester); + router.go('/'); + final List matches = + router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect((matches.first.route as GoRoute).name, '1'); + expect(find.byType(DummyScreen), findsOneWidget); + }, + ); - testWidgets('pushReplacement and replace when only one matches', - (WidgetTester tester) async { + testWidgets('pushReplacement and replace when only one matches', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute(name: '1', path: '/', builder: dummy), GoRoute(name: '2', path: '/a', builder: dummy), @@ -104,12 +111,7 @@ void main() { GoRoute( path: '/', builder: dummy, - routes: [ - GoRoute( - path: 'foo/', - builder: dummy, - ), - ], + routes: [GoRoute(path: 'foo/', builder: dummy)], ), ], ); @@ -124,8 +126,9 @@ 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(); @@ -138,13 +141,16 @@ void main() { testWidgets('match 2nd top level route', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen()), + path: '/', + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), + ), GoRoute( - path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen()), + path: '/login', + builder: + (BuildContext context, GoRouterState state) => + const LoginScreen(), + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -157,24 +163,29 @@ void main() { expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('match 2nd top level route with subroutes', - (WidgetTester tester) async { + testWidgets('match 2nd top level route with subroutes', ( + WidgetTester tester, + ) async { 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()) + path: 'page1', + builder: + (BuildContext context, GoRouterState state) => + const Page1Screen(), + ), ], ), GoRoute( - path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen()), + path: '/login', + builder: + (BuildContext context, GoRouterState state) => + const LoginScreen(), + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -187,18 +198,20 @@ void main() { expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('match top level route when location has trailing /', - (WidgetTester tester) async { + testWidgets('match top level route when location has trailing /', ( + WidgetTester tester, + ) async { 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(), ), ]; @@ -212,13 +225,15 @@ void main() { expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('match top level route when location has trailing / (2)', - (WidgetTester tester) async { + testWidgets('match top level route when location has trailing / (2)', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/profile', - builder: dummy, - redirect: (_, __) => '/profile/foo'), + path: '/profile', + builder: dummy, + redirect: (_, __) => '/profile/foo', + ), GoRoute(path: '/profile/:kind', builder: dummy), ]; @@ -232,13 +247,15 @@ void main() { expect(find.byType(DummyScreen), findsOneWidget); }); - testWidgets('match top level route when location has trailing / (3)', - (WidgetTester tester) async { + testWidgets('match top level route when location has trailing / (3)', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/profile', - builder: dummy, - redirect: (_, __) => '/profile/foo'), + path: '/profile', + builder: dummy, + redirect: (_, __) => '/profile/foo', + ), GoRoute(path: '/profile/:kind', builder: dummy), ]; @@ -253,113 +270,123 @@ void main() { }); testWidgets( - 'match top level route when location has scheme/host and has trailing /', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - ]; + 'match top level route when location has scheme/host and has trailing /', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/', + builder: + (BuildContext context, GoRouterState state) => + const HomeScreen(), + ), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/?bar=baz'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/'); - expect(find.byType(HomeScreen), findsOneWidget); - }); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/?bar=baz'); + await tester.pumpAndSettle(); + final List matches = + router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/'); + expect(find.byType(HomeScreen), findsOneWidget); + }, + ); testWidgets( - 'match top level route when location has scheme/host and has trailing / (2)', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - GoRoute( - path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), - ), - ]; + 'match top level route when location has scheme/host and has trailing / (2)', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/', + builder: + (BuildContext context, GoRouterState state) => + const HomeScreen(), + ), + GoRoute( + path: '/login', + builder: + (BuildContext context, GoRouterState state) => + const LoginScreen(), + ), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/login/'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/login'); - expect(find.byType(LoginScreen), findsOneWidget); - }); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/login/'); + await tester.pumpAndSettle(); + final List matches = + router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/login'); + expect(find.byType(LoginScreen), findsOneWidget); + }, + ); testWidgets( - 'match top level route when location has scheme/host and has trailing / (3)', - (WidgetTester tester) async { - final List routes = [ - GoRoute( + 'match top level route when location has scheme/host and has trailing / (3)', + (WidgetTester tester) async { + final List routes = [ + GoRoute( path: '/profile', builder: dummy, - redirect: (_, __) => '/profile/foo'), - GoRoute(path: '/profile/:kind', builder: dummy), - ]; + redirect: (_, __) => '/profile/foo', + ), + GoRoute(path: '/profile/:kind', builder: dummy), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/profile/'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/profile/foo'); - expect(find.byType(DummyScreen), findsOneWidget); - }); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/profile/'); + await tester.pumpAndSettle(); + final List matches = + router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/profile/foo'); + expect(find.byType(DummyScreen), findsOneWidget); + }, + ); testWidgets( - 'match top level route when location has scheme/host and has trailing / (4)', - (WidgetTester tester) async { - final List routes = [ - GoRoute( + 'match top level route when location has scheme/host and has trailing / (4)', + (WidgetTester tester) async { + final List routes = [ + GoRoute( path: '/profile', builder: dummy, - redirect: (_, __) => '/profile/foo'), - GoRoute(path: '/profile/:kind', builder: dummy), - ]; + redirect: (_, __) => '/profile/foo', + ), + GoRoute(path: '/profile/:kind', builder: dummy), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/profile/?bar=baz'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/profile/foo'); - expect(find.byType(DummyScreen), findsOneWidget); - }); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/profile/?bar=baz'); + await tester.pumpAndSettle(); + final List matches = + router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/profile/foo'); + expect(find.byType(DummyScreen), findsOneWidget); + }, + ); - testWidgets('repeatedly pops imperative route does not crash', - (WidgetTester tester) async { + testWidgets('repeatedly pops imperative route does not crash', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/123369. final UniqueKey home = UniqueKey(); final UniqueKey settings = UniqueKey(); 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), ), ]; - final GoRouter router = - await createRouter(routes, tester, navigatorKey: navKey); + final GoRouter router = await createRouter( + routes, + tester, + navigatorKey: navKey, + ); expect(find.byKey(home), findsOneWidget); router.push('/settings'); @@ -392,50 +419,51 @@ void main() { expect(find.byKey(settings), findsOneWidget); }); - testWidgets('android back button pop in correct order', - (WidgetTester tester) async { + testWidgets('android back button pop in correct order', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/141906. final List routes = [ GoRoute( - path: '/', - builder: (_, __) => const Text('home'), - routes: [ - ShellRoute( - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Column( - children: [ - const Text('shell'), - child, - ], - ); - }, - routes: [ - GoRoute( - path: 'page', - builder: (BuildContext context, __) { - return TextButton( - onPressed: () { - Navigator.of(context, rootNavigator: true).push( - MaterialPageRoute( - builder: (BuildContext context) { + path: '/', + builder: (_, __) => const Text('home'), + routes: [ + ShellRoute( + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { + return Column(children: [const Text('shell'), child]); + }, + routes: [ + GoRoute( + path: 'page', + builder: (BuildContext context, __) { + return TextButton( + onPressed: () { + Navigator.of(context, rootNavigator: true).push( + MaterialPageRoute( + builder: (BuildContext context) { return const Text('pageless'); - }), - ); - }, - child: const Text('page'), - ); - }, - ), - ], - ), - ]), + }, + ), + ); + }, + child: const Text('page'), + ); + }, + ), + ], + ), + ], + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/page'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/page', + ); expect(find.text('shell'), findsOneWidget); expect(find.text('page'), findsOneWidget); @@ -453,30 +481,34 @@ void main() { expect(find.text('pageless'), findsNothing); }); - testWidgets('can correctly pop stacks of repeated pages', - (WidgetTester tester) async { + testWidgets('can correctly pop stacks of repeated pages', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/#132229. final GlobalKey navKey = GlobalKey(); 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(routes, tester, navigatorKey: navKey); + final GoRouter router = await createRouter( + routes, + tester, + navigatorKey: navKey, + ); expect(find.byType(HomeScreen), findsOneWidget); router.push('/page1'); @@ -504,13 +536,14 @@ 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(), ), ], ), @@ -532,25 +565,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: '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(), ), ], ), @@ -604,33 +640,38 @@ void main() { } }); - testWidgets('return first matching route if too many subroutes', - (WidgetTester tester) async { + testWidgets('return first matching route if too many subroutes', ( + WidgetTester tester, + ) async { 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(), ), ], ), @@ -720,14 +761,16 @@ void main() { expect(state.name, 'person'); expect(state.path, 'person/:pid'); expect(state.fullPath, '/family/:fid/person/:pid'); - expect( - state.pathParameters, - {'fid': 'f2', 'pid': 'p1'}, - ); + expect(state.pathParameters, { + 'fid': 'f2', + 'pid': 'p1', + }); expect(state.error, null); expect(state.extra! as int, 4); - return PersonScreen(state.pathParameters['fid']!, - state.pathParameters['pid']!); + return PersonScreen( + state.pathParameters['fid']!, + state.pathParameters['pid']!, + ); }, ), ], @@ -751,14 +794,15 @@ 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']!), ), ]; @@ -773,10 +817,9 @@ void main() { // path case whereas the location can be any case; so long as the path // produces a match regardless of the location case, we win! expect( - router.routerDelegate.currentConfiguration.uri - .toString() - .toLowerCase(), - loc.toLowerCase()); + router.routerDelegate.currentConfiguration.uri.toString().toLowerCase(), + loc.toLowerCase(), + ); expect(matches, hasLength(1)); expect(find.byType(FamilyScreen), findsOneWidget); @@ -786,13 +829,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', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -811,32 +855,32 @@ void main() { final List matches = router.routerDelegate.currentConfiguration.matches; - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - loc, - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); expect(matches, hasLength(1)); expect(find.byType(FamilyScreen), findsOne); }); - testWidgets('supports routes with a different case', - (WidgetTester tester) async { + testWidgets('supports routes with a different case', ( + WidgetTester tester, + ) async { 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')), ), ]; @@ -856,41 +900,39 @@ void main() { }); testWidgets( - 'If there is more than one route to match, use the first match.', - (WidgetTester tester) async { - final List routes = [ - GoRoute(path: '/', builder: dummy), - GoRoute(path: '/page1', builder: dummy), - GoRoute(path: '/page1', builder: dummy), - GoRoute(path: '/:ok', builder: dummy), - ]; + 'If there is more than one route to match, use the first match.', + (WidgetTester tester) async { + final List routes = [ + GoRoute(path: '/', builder: dummy), + GoRoute(path: '/page1', builder: dummy), + GoRoute(path: '/page1', builder: dummy), + GoRoute(path: '/:ok', builder: dummy), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('/user'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(find.byType(DummyScreen), findsOneWidget); - }); + final GoRouter router = await createRouter(routes, tester); + router.go('/user'); + await tester.pumpAndSettle(); + final List matches = + router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(find.byType(DummyScreen), findsOneWidget); + }, + ); - testWidgets('Handles the Android back button correctly', - (WidgetTester tester) async { + testWidgets('Handles the Android back button correctly', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, routes: [ GoRoute( path: 'b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, ), ], @@ -907,8 +949,9 @@ void main() { expect(find.text('Screen B'), findsNothing); }); - testWidgets('Handles the Android back button correctly with ShellRoute', - (WidgetTester tester) async { + testWidgets('Handles the Android back button correctly with ShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); @@ -924,34 +967,26 @@ void main() { GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, routes: [ GoRoute( path: 'b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, routes: [ GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen C'), - ); + return const Scaffold(body: Text('Screen C')); }, routes: [ GoRoute( path: 'd', parentNavigatorKey: rootNavigatorKey, builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen D'), - ); + return const Scaffold(body: Text('Screen D')); }, ), ], @@ -964,8 +999,12 @@ void main() { ), ]; - await createRouter(routes, tester, - initialLocation: '/a/b/c/d', navigatorKey: rootNavigatorKey); + await createRouter( + routes, + tester, + initialLocation: '/a/b/c/d', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Shell'), findsNothing); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); @@ -989,57 +1028,66 @@ void main() { }); testWidgets( - 'Handles the Android back button when parentNavigatorKey is set to the root navigator', - (WidgetTester tester) async { - final List log = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, - (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); - - Future verify(AsyncCallback test, List expectations) async { - log.clear(); - await test(); - expect(log, expectations); - } - - final GlobalKey rootNavigatorKey = - GlobalKey(); + 'Handles the Android back button when parentNavigatorKey is set to the root navigator', + (WidgetTester tester) async { + final List log = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); + + Future verify( + AsyncCallback test, + List expectations, + ) async { + log.clear(); + await test(); + expect(log, expectations); + } + + final GlobalKey rootNavigatorKey = + GlobalKey(); - final List routes = [ - GoRoute( - parentNavigatorKey: rootNavigatorKey, - path: '/a', - builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); - }, - ), - ]; + final List routes = [ + GoRoute( + parentNavigatorKey: rootNavigatorKey, + path: '/a', + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen A')); + }, + ), + ]; - await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); - expect(find.text('Screen A'), findsOneWidget); + await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); + expect(find.text('Screen A'), findsOneWidget); - await tester.runAsync(() async { - await verify(() => simulateAndroidBackButton(tester), [ - isMethodCall('SystemNavigator.pop', arguments: null), - ]); - }); - }); + await tester.runAsync(() async { + await verify(() => simulateAndroidBackButton(tester), [ + isMethodCall('SystemNavigator.pop', arguments: null), + ]); + }); + }, + ); - testWidgets("Handles the Android back button when ShellRoute can't pop", - (WidgetTester tester) async { + testWidgets("Handles the Android back button when ShellRoute can't pop", ( + WidgetTester tester, + ) async { final List log = []; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, - (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + .setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); Future verify(AsyncCallback test, List expectations) async { log.clear(); @@ -1055,17 +1103,13 @@ void main() { parentNavigatorKey: rootNavigatorKey, path: '/a', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, ), ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( - appBar: AppBar( - title: const Text('Shell'), - ), + appBar: AppBar(title: const Text('Shell')), body: child, ); }, @@ -1073,17 +1117,19 @@ void main() { GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, ), ], ), ]; - await createRouter(routes, tester, - initialLocation: '/b', navigatorKey: rootNavigatorKey); + await createRouter( + routes, + tester, + initialLocation: '/b', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen B'), findsOneWidget); await tester.runAsync(() async { @@ -1094,28 +1140,26 @@ void main() { }); }); - testWidgets('does not crash when inherited widget changes', - (WidgetTester tester) async { + testWidgets('does not crash when inherited widget changes', ( + WidgetTester tester, + ) async { final ValueNotifier notifier = ValueNotifier('initial'); addTearDown(notifier.dispose); final List routes = [ GoRoute( - path: '/', - pageBuilder: (BuildContext context, GoRouterState state) { - final String value = context - .dependOnInheritedWidgetOfExactType()! - .notifier! - .value; - return MaterialPage( - key: state.pageKey, - child: Text(value), - ); - }), + path: '/', + pageBuilder: (BuildContext context, GoRouterState state) { + final String value = + context + .dependOnInheritedWidgetOfExactType()! + .notifier! + .value; + return MaterialPage(key: state.pageKey, child: Text(value)); + }, + ), ]; - final GoRouter router = GoRouter( - routes: routes, - ); + final GoRouter router = GoRouter(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( @@ -1133,105 +1177,107 @@ void main() { }); testWidgets( - 'Handles the Android back button when a second Shell has a GoRoute with parentNavigator key', - (WidgetTester tester) async { - final List log = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, - (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + 'Handles the Android back button when a second Shell has a GoRoute with parentNavigator key', + (WidgetTester tester) async { + final List log = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); - Future verify(AsyncCallback test, List expectations) async { - log.clear(); - await test(); - expect(log, expectations); - } + Future verify(AsyncCallback test, List expectations) async { + log.clear(); + await test(); + expect(log, expectations); + } - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GlobalKey shellNavigatorKeyA = - GlobalKey(); - final GlobalKey shellNavigatorKeyB = - GlobalKey(); - - final List routes = [ - ShellRoute( - navigatorKey: shellNavigatorKeyA, - builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar( - title: const Text('Shell'), - ), - body: child, - ); - }, - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); - }, - routes: [ - ShellRoute( - navigatorKey: shellNavigatorKeyB, - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar( - title: const Text('Shell'), + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GlobalKey shellNavigatorKeyA = + GlobalKey(); + final GlobalKey shellNavigatorKeyB = + GlobalKey(); + + final List routes = [ + ShellRoute( + navigatorKey: shellNavigatorKeyA, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + appBar: AppBar(title: const Text('Shell')), + body: child, + ); + }, + routes: [ + GoRoute( + path: '/a', + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen A')); + }, + routes: [ + ShellRoute( + navigatorKey: shellNavigatorKeyB, + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { + return Scaffold( + appBar: AppBar(title: const Text('Shell')), + body: child, + ); + }, + routes: [ + GoRoute( + path: 'b', + parentNavigatorKey: shellNavigatorKeyB, + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen B')); + }, ), - body: child, - ); - }, - routes: [ - GoRoute( - path: 'b', - parentNavigatorKey: shellNavigatorKeyB, - builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); - }, - ), - ], - ), - ], - ), - ], - ), - ]; + ], + ), + ], + ), + ], + ), + ]; - await createRouter(routes, tester, - initialLocation: '/a/b', navigatorKey: rootNavigatorKey); - expect(find.text('Screen B'), findsOneWidget); + await createRouter( + routes, + tester, + initialLocation: '/a/b', + navigatorKey: rootNavigatorKey, + ); + expect(find.text('Screen B'), findsOneWidget); - // The first pop should not exit the app. - await tester.runAsync(() async { - await verify(() => simulateAndroidBackButton(tester), []); - }); + // The first pop should not exit the app. + await tester.runAsync(() async { + await verify(() => simulateAndroidBackButton(tester), []); + }); - // The second pop should exit the app. - await tester.runAsync(() async { - await verify(() => simulateAndroidBackButton(tester), [ - isMethodCall('SystemNavigator.pop', arguments: null), - ]); - }); - }); + // The second pop should exit the app. + await tester.runAsync(() async { + await verify(() => simulateAndroidBackButton(tester), [ + isMethodCall('SystemNavigator.pop', arguments: null), + ]); + }); + }, + ); group('report correct url', () { final List log = []; setUp(() { GoRouter.optionURLReflectsImperativeAPIs = false; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.navigation, - (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + .setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); }); tearDown(() { GoRouter.optionURLReflectsImperativeAPIs = false; @@ -1241,218 +1287,251 @@ void main() { }); testWidgets( - 'on push shell route with optionURLReflectImperativeAPIs = true', - (WidgetTester tester) async { - GoRouter.optionURLReflectsImperativeAPIs = true; - final List routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - routes: [ - ShellRoute( - builder: - (BuildContext context, GoRouterState state, Widget child) => - child, - routes: [ - GoRoute( - path: 'c', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - ) - ], - ), - ], - ), - ]; + 'on push shell route with optionURLReflectImperativeAPIs = true', + (WidgetTester tester) async { + GoRouter.optionURLReflectsImperativeAPIs = true; + final List routes = [ + GoRoute( + path: '/', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + routes: [ + ShellRoute( + builder: + (BuildContext context, GoRouterState state, Widget child) => + child, + routes: [ + GoRoute( + path: 'c', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), + ], + ), + ], + ), + ]; - final GoRouter router = await createRouter(routes, tester); + final GoRouter router = await createRouter(routes, tester); - log.clear(); - router.push('/c?foo=bar'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); - await tester.pumpAndSettle(); - expect(log, [ - isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/c?foo=bar', false, - codec.encode(router.routerDelegate.currentConfiguration)), - ]); - GoRouter.optionURLReflectsImperativeAPIs = false; - }); + log.clear(); + router.push('/c?foo=bar'); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); + await tester.pumpAndSettle(); + expect(log, [ + isMethodCall('selectMultiEntryHistory', arguments: null), + IsRouteUpdateCall( + '/c?foo=bar', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), + ]); + GoRouter.optionURLReflectsImperativeAPIs = false; + }, + ); - testWidgets('on push with optionURLReflectImperativeAPIs = true', - (WidgetTester tester) async { + testWidgets('on push with optionURLReflectImperativeAPIs = true', ( + WidgetTester tester, + ) async { GoRouter.optionURLReflectsImperativeAPIs = true; final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - ), - GoRoute( - path: '/settings', - builder: (_, __) => const DummyScreen(), - ), + GoRoute(path: '/', builder: (_, __) => const DummyScreen()), + GoRoute(path: '/settings', builder: (_, __) => const DummyScreen()), ]; final GoRouter router = await createRouter(routes, tester); log.clear(); router.push('/settings'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/settings', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/settings', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); GoRouter.optionURLReflectsImperativeAPIs = false; }); testWidgets('on push', (WidgetTester tester) async { final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - ), - GoRoute( - path: '/settings', - builder: (_, __) => const DummyScreen(), - ), + GoRoute(path: '/', builder: (_, __) => const DummyScreen()), + GoRoute(path: '/settings', builder: (_, __) => const DummyScreen()), ]; final GoRouter router = await createRouter(routes, tester); log.clear(); router.push('/settings'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); testWidgets('on pop', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute( - path: 'settings', - builder: (_, __) => const DummyScreen(), - ), - ]), + path: '/', + builder: (_, __) => const DummyScreen(), + routes: [ + GoRoute(path: 'settings', builder: (_, __) => const DummyScreen()), + ], + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/settings'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/settings', + ); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); testWidgets('on pop twice', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute( - path: 'settings', - builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute( - path: 'profile', - builder: (_, __) => const DummyScreen(), - ), - ]), - ]), + path: '/', + builder: (_, __) => const DummyScreen(), + routes: [ + GoRoute( + path: 'settings', + builder: (_, __) => const DummyScreen(), + routes: [ + GoRoute( + path: 'profile', + builder: (_, __) => const DummyScreen(), + ), + ], + ), + ], + ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/settings/profile'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/settings/profile', + ); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); log.clear(); router.pop(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); testWidgets('on pop with path parameters', (WidgetTester tester) async { final List routes = [ GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute( - path: 'settings/:id', - builder: (_, __) => const DummyScreen(), - ), - ]), + path: '/', + builder: (_, __) => const DummyScreen(), + routes: [ + GoRoute( + path: 'settings/:id', + builder: (_, __) => const DummyScreen(), + ), + ], + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/settings/123'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/settings/123', + ); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); - testWidgets('on pop with path parameters case 2', - (WidgetTester tester) async { + testWidgets('on pop with path parameters case 2', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute( - path: ':id', - builder: (_, __) => const DummyScreen(), - ), - ]), + path: '/', + builder: (_, __) => const DummyScreen(), + routes: [ + GoRoute(path: ':id', builder: (_, __) => const DummyScreen()), + ], + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/123/'); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/123/', + ); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); - testWidgets('Can manually pop root navigator and display correct url', - (WidgetTester tester) async { + testWidgets('Can manually pop root navigator and display correct url', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); @@ -1460,34 +1539,28 @@ void main() { GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Home'), - ); + return const Scaffold(body: Text('Home')); }, 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', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, routes: [ GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen C'), - ); + return const Scaffold(body: Text('Screen C')); }, ), ], @@ -1498,15 +1571,23 @@ void main() { ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/b/c', navigatorKey: rootNavigatorKey); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/b/c', + navigatorKey: rootNavigatorKey, + ); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); expect(find.text('Screen C'), findsOneWidget); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/b/c', true, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/b/c', + true, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); log.clear(); @@ -1516,13 +1597,17 @@ void main() { expect(find.text('Home'), findsOneWidget); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/', false, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); - testWidgets('can handle route information update from browser', - (WidgetTester tester) async { + testWidgets('can handle route information update from browser', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', @@ -1530,8 +1615,10 @@ void main() { routes: [ GoRoute( path: 'settings', - builder: (_, GoRouterState state) => - DummyScreen(key: ValueKey('settings-${state.extra}')), + builder: + (_, GoRouterState state) => DummyScreen( + key: ValueKey('settings-${state.extra}'), + ), ), ], ), @@ -1563,7 +1650,8 @@ void main() { expect(find.byKey(const ValueKey('home')), findsOneWidget); router.routeInformationProvider.didPushRouteInformation( - RouteInformation(uri: Uri.parse(location), state: state)); + RouteInformation(uri: Uri.parse(location), state: state), + ); await tester.pumpAndSettle(); // Make sure it has all the imperative routes. expect(find.byKey(const ValueKey('settings-1')), findsOneWidget); @@ -1577,27 +1665,26 @@ void main() { expect(find.byKey(const ValueKey('home')), findsOneWidget); }); - testWidgets('works correctly with async redirect', - (WidgetTester tester) async { + testWidgets('works correctly with async redirect', ( + WidgetTester tester, + ) async { final UniqueKey login = UniqueKey(); final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const DummyScreen(), - ), - GoRoute( - path: '/login', - builder: (_, __) => DummyScreen(key: login), - ), + GoRoute(path: '/', builder: (_, __) => const DummyScreen()), + GoRoute(path: '/login', builder: (_, __) => DummyScreen(key: login)), ]; final Completer completer = Completer(); - final GoRouter router = - await createRouter(routes, tester, redirect: (_, __) async { - await completer.future; - return '/login'; - }); - final RouteMatchListCodec codec = - RouteMatchListCodec(router.configuration); + final GoRouter router = await createRouter( + routes, + tester, + redirect: (_, __) async { + await completer.future; + return '/login'; + }, + ); + final RouteMatchListCodec codec = RouteMatchListCodec( + router.configuration, + ); await tester.pumpAndSettle(); expect(find.byKey(login), findsNothing); expect(tester.takeException(), isNull); @@ -1610,8 +1697,11 @@ void main() { expect(tester.takeException(), isNull); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall('/login', true, - codec.encode(router.routerDelegate.currentConfiguration)), + IsRouteUpdateCall( + '/login', + true, + codec.encode(router.routerDelegate.currentConfiguration), + ), ]); }); }); @@ -1620,10 +1710,11 @@ void main() { testWidgets('match home route', (WidgetTester tester) async { final List routes = [ GoRoute( - name: 'home', - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen()), + name: 'home', + path: '/', + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -1662,14 +1753,15 @@ 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(), ), ]; @@ -1682,14 +1774,15 @@ 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(), ), ], ), @@ -1704,21 +1797,24 @@ 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) { - expect(state.pathParameters, - {'fid': 'f2', 'pid': 'p1'}); + expect(state.pathParameters, { + 'fid': 'f2', + 'pid': 'p1', + }); return const PersonScreen('dummy', 'dummy'); }, ), @@ -1729,8 +1825,10 @@ void main() { ]; final GoRouter router = await createRouter(routes, tester); - router.goNamed('person', - pathParameters: {'fid': 'f2', 'pid': 'p1'}); + router.goNamed( + 'person', + pathParameters: {'fid': 'f2', 'pid': 'p1'}, + ); }); testWidgets('too few params', (WidgetTester tester) async { @@ -1738,20 +1836,22 @@ 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'), ), ], ), @@ -1770,21 +1870,24 @@ 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) { - expect(state.pathParameters, - {'fid': 'f2', 'pid': 'p1'}); + expect(state.pathParameters, { + 'fid': 'f2', + 'pid': 'p1', + }); return const PersonScreen('dummy', 'dummy'); }, ), @@ -1795,15 +1898,12 @@ void main() { ]; final GoRouter router = await createRouter(routes, tester); - expect( - () { - router.goNamed( - 'person', - pathParameters: {'fid': 'f2', 'pid': 'p1'}, - ); - }, - throwsAssertionError, - ); + expect(() { + router.goNamed( + 'person', + pathParameters: {'fid': 'f2', 'pid': 'p1'}, + ); + }, throwsAssertionError); }); testWidgets('too few params', (WidgetTester tester) async { @@ -1811,8 +1911,9 @@ 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 { @@ -1826,52 +1927,54 @@ 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 { final GoRouter router = await createRouter(routes, tester); - router.goNamed('family', - pathParameters: {'fid': 'f2', 'pid': 'p1'}); + router.goNamed( + 'family', + pathParameters: {'fid': 'f2', 'pid': 'p1'}, + ); }, throwsA(isAssertionError)); }); testWidgets('sparsely named routes', (WidgetTester tester) async { final List routes = [ - GoRoute( - path: '/', - builder: dummy, - redirect: (_, __) => '/family/f2', - ), + 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( - state.pathParameters['fid']!, - state.pathParameters['pid']!, - ), + builder: + (BuildContext context, GoRouterState state) => PersonScreen( + state.pathParameters['fid']!, + state.pathParameters['pid']!, + ), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); - router.goNamed('person', - pathParameters: {'fid': 'f2', 'pid': 'p1'}); + router.goNamed( + 'person', + pathParameters: {'fid': 'f2', 'pid': 'p1'}, + ); await tester.pumpAndSettle(); expect(find.byType(PersonScreen), findsOneWidget); }); - testWidgets('preserve path param spaces and slashes', - (WidgetTester tester) async { + testWidgets('preserve path param spaces and slashes', ( + WidgetTester tester, + ) async { const String param1 = 'param w/ spaces and slashes'; final List routes = [ GoRoute( @@ -1885,8 +1988,10 @@ void main() { ]; final GoRouter router = await createRouter(routes, tester); - final String loc = router.namedLocation('page1', - pathParameters: {'param1': param1}); + final String loc = router.namedLocation( + 'page1', + pathParameters: {'param1': param1}, + ); router.go(loc); await tester.pumpAndSettle(); @@ -1895,8 +2000,9 @@ void main() { expect(matches.pathParameters['param1'], param1); }); - testWidgets('preserve query param spaces and slashes', - (WidgetTester tester) async { + testWidgets('preserve query param spaces and slashes', ( + WidgetTester tester, + ) async { const String param1 = 'param w/ spaces and slashes'; final List routes = [ GoRoute( @@ -1910,8 +2016,10 @@ void main() { ]; final GoRouter router = await createRouter(routes, tester); - final String loc = router.namedLocation('page1', - queryParameters: {'param1': param1}); + final String loc = router.namedLocation( + 'page1', + queryParameters: {'param1': param1}, + ); router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; @@ -1925,13 +2033,14 @@ 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(), ), ], ), @@ -1947,13 +2056,14 @@ 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(), ), ], ), @@ -1973,20 +2083,23 @@ 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', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { - expect(state.pathParameters, - {'fid': fid, 'pid': pid}); + expect(state.pathParameters, { + 'fid': fid, + 'pid': pid, + }); return const PersonScreen('dummy', 'dummy'); }, ), @@ -1996,8 +2109,11 @@ void main() { ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/home'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/home', + ); router.go('./family/$fid'); await tester.pumpAndSettle(); @@ -2015,19 +2131,21 @@ 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) { - expect(state.uri.queryParameters, - {'pid': pid}); + expect(state.uri.queryParameters, { + 'pid': pid, + }); return const PersonScreen('dummy', 'dummy'); }, ), @@ -2037,8 +2155,11 @@ void main() { ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/home'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/home', + ); router.go('./family?fid=$fid'); await tester.pumpAndSettle(); @@ -2055,18 +2176,20 @@ 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'), ), ], ), @@ -2078,8 +2201,9 @@ 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(); @@ -2094,18 +2218,20 @@ 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'), ), ], ), @@ -2117,8 +2243,9 @@ 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'); @@ -2130,8 +2257,9 @@ void main() { expect(matches, hasLength(0)); }); - testWidgets('preserve path param spaces and slashes', - (WidgetTester tester) async { + testWidgets('preserve path param spaces and slashes', ( + WidgetTester tester, + ) async { const String param1 = 'param w/ spaces and slashes'; final List routes = [ GoRoute( @@ -2146,11 +2274,14 @@ void main() { }, ), ], - ) + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/home'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/home', + ); final String loc = 'page1/${Uri.encodeComponent(param1)}'; router.go('./$loc'); @@ -2161,8 +2292,9 @@ void main() { expect(matches.pathParameters['param1'], param1); }); - testWidgets('preserve query param spaces and slashes', - (WidgetTester tester) async { + testWidgets('preserve query param spaces and slashes', ( + WidgetTester tester, + ) async { const String param1 = 'param w/ spaces and slashes'; final List routes = [ GoRoute( @@ -2177,16 +2309,20 @@ void main() { }, ), ], - ) + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/home'); + final GoRouter router = await createRouter( + routes, + tester, + 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(); @@ -2202,30 +2338,39 @@ 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()), + path: 'dummy', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), GoRoute( - path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen()), + path: 'login', + builder: + (BuildContext context, GoRouterState state) => + const LoginScreen(), + ), ], ), ]; bool redirected = false; - final GoRouter router = await createRouter(routes, tester, - redirect: (BuildContext context, GoRouterState state) { - redirected = true; - return state.matchedLocation == '/login' ? null : '/login'; - }); + final GoRouter router = await createRouter( + routes, + tester, + redirect: (BuildContext context, GoRouterState state) { + redirected = true; + return state.matchedLocation == '/login' ? null : '/login'; + }, + ); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/login'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/login', + ); expect(redirected, isTrue); redirected = false; @@ -2234,62 +2379,75 @@ void main() { await tester.pumpAndSettle(); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/login'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/login', + ); expect(redirected, isTrue); }); - testWidgets('redirect can redirect to same path', - (WidgetTester tester) async { + testWidgets('redirect can redirect to same path', ( + WidgetTester tester, + ) async { 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()), + path: 'dummy', + // Return same location. + redirect: (_, GoRouterState state) => state.uri.toString(), + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - redirect: (BuildContext context, GoRouterState state) { - // Return same location. - return state.uri.toString(); - }); + final GoRouter router = await createRouter( + routes, + tester, + redirect: (BuildContext context, GoRouterState state) { + // Return same location. + return state.uri.toString(); + }, + ); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); // Directly set the url through platform message. await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/dummy', + ); }); - testWidgets('top-level redirect w/ named routes', - (WidgetTester tester) async { + testWidgets('top-level redirect w/ named routes', ( + WidgetTester tester, + ) async { final List routes = [ 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(), ), ], ), @@ -2298,32 +2456,37 @@ 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(), '/login'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/login', + ); }); testWidgets('route-level redirect', (WidgetTester tester) async { 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(), ), ], ), @@ -2333,75 +2496,93 @@ void main() { router.go('/dummy'); await tester.pump(); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/login'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/login', + ); }); - testWidgets('top-level redirect take priority over route level', - (WidgetTester tester) async { + testWidgets('top-level redirect take priority over route level', ( + WidgetTester tester, + ) async { 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(), - redirect: (BuildContext context, GoRouterState state) { - // should never be reached. - assert(false); - return '/dummy2'; - }), + path: 'dummy', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + redirect: (BuildContext context, GoRouterState state) { + // should never be reached. + assert(false); + return '/dummy2'; + }, + ), GoRoute( - path: 'dummy2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen()), + path: 'dummy2', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), GoRoute( - path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen()), + path: 'login', + builder: + (BuildContext context, GoRouterState state) => + const LoginScreen(), + ), ], ), ]; bool redirected = false; - final GoRouter router = await createRouter(routes, tester, - redirect: (BuildContext context, GoRouterState state) { - redirected = true; - return state.matchedLocation == '/login' ? null : '/login'; - }); + final GoRouter router = await createRouter( + routes, + tester, + redirect: (BuildContext context, GoRouterState state) { + redirected = true; + return state.matchedLocation == '/login' ? null : '/login'; + }, + ); redirected = false; // Directly set the url through platform message. await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/login'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/login', + ); expect(redirected, isTrue); }); - testWidgets('route-level redirect w/ named routes', - (WidgetTester tester) async { + testWidgets('route-level redirect w/ named routes', ( + WidgetTester tester, + ) async { final List routes = [ 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(), ), ], ), @@ -2411,34 +2592,42 @@ void main() { router.go('/dummy'); await tester.pump(); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/login'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/login', + ); }); testWidgets('multiple mixed redirect', (WidgetTester tester) async { 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) => '/', ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/dummy1' ? '/dummy2' : null); + final GoRouter router = await createRouter( + routes, + tester, + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/dummy1' ? '/dummy2' : null, + ); router.go('/dummy1'); await tester.pump(); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); @@ -2448,21 +2637,24 @@ void main() { final GoRouter router = await createRouter( [], tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' - ? '/login' - : state.matchedLocation == '/login' + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' + ? '/login' + : state.matchedLocation == '/login' ? '/' : null, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: + (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = - tester.widget(find.byType(TestErrorScreen)); + final TestErrorScreen screen = tester.widget( + find.byType(TestErrorScreen), + ); expect(screen.ex, isNotNull); }); @@ -2481,16 +2673,18 @@ void main() { ), ], tester, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: + (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = - tester.widget(find.byType(TestErrorScreen)); + final TestErrorScreen screen = tester.widget( + find.byType(TestErrorScreen), + ); expect(screen.ex, isNotNull); }); @@ -2504,52 +2698,60 @@ 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 = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = - tester.widget(find.byType(TestErrorScreen)); + final TestErrorScreen screen = tester.widget( + find.byType(TestErrorScreen), + ); expect(screen.ex, isNotNull); }); - testWidgets('top-level redirect loop w/ query params', - (WidgetTester tester) async { + testWidgets('top-level redirect loop w/ query params', ( + WidgetTester tester, + ) async { final GoRouter router = await createRouter( [], tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' - ? '/login?from=${state.uri}' - : state.matchedLocation == '/login' + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' + ? '/login?from=${state.uri}' + : state.matchedLocation == '/login' ? '/' : null, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: + (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = - tester.widget(find.byType(TestErrorScreen)); + final TestErrorScreen screen = tester.widget( + find.byType(TestErrorScreen), + ); expect(screen.ex, isNotNull); }); - testWidgets('expect null path/fullPath on top-level redirect', - (WidgetTester tester) async { + testWidgets('expect null path/fullPath on top-level redirect', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/dummy', @@ -2570,13 +2772,14 @@ 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(), ), ]; @@ -2602,20 +2805,24 @@ void main() { expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('top-level redirect state contains path parameters', - (WidgetTester tester) async { + testWidgets('top-level redirect state contains path parameters', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - routes: [ - GoRoute( - path: ':id', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - ), - ]), + path: '/', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + routes: [ + GoRoute( + path: ':id', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), + ], + ), ]; final GoRouter router = await createRouter( @@ -2666,8 +2873,9 @@ void main() { expect(find.byType(HomeScreen), findsOneWidget); }); - testWidgets('sub-sub-route-level redirect params', - (WidgetTester tester) async { + testWidgets('sub-sub-route-level redirect params', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', @@ -2675,8 +2883,9 @@ 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', @@ -2685,10 +2894,11 @@ 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']!, + ), ), ], ), @@ -2707,8 +2917,9 @@ void main() { expect(matches.length, 3); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(find.byType(FamilyScreen, skipOffstage: false), findsOneWidget); - final PersonScreen page = - tester.widget(find.byType(PersonScreen)); + final PersonScreen page = tester.widget( + find.byType(PersonScreen), + ); expect(page.fid, 'f2'); expect(page.pid, 'p1'); }); @@ -2717,10 +2928,11 @@ 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, ); @@ -2728,16 +2940,15 @@ void main() { router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = - tester.widget(find.byType(TestErrorScreen)); + final TestErrorScreen screen = tester.widget( + find.byType(TestErrorScreen), + ); expect(screen.ex, isNotNull); }); testWidgets('can push error page', (WidgetTester tester) async { final GoRouter router = await createRouter( - [ - GoRoute(path: '/', builder: (_, __) => const Text('/')), - ], + [GoRoute(path: '/', builder: (_, __) => const Text('/'))], tester, errorBuilder: (_, GoRouterState state) { return Text(state.uri.toString()); @@ -2782,8 +2993,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', @@ -2822,39 +3033,46 @@ void main() { expect(isCallRouteRedirect, true); }); - testWidgets('parent route level redirect take priority over child', - (WidgetTester tester) async { + testWidgets('parent route level redirect take priority over child', ( + WidgetTester tester, + ) async { 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(), - redirect: (BuildContext context, GoRouterState state) => - '/other', - routes: [ - GoRoute( - path: 'dummy2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - redirect: (BuildContext context, GoRouterState state) { - assert(false); - return '/other2'; - }, - ), - ]), + path: 'dummy', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + redirect: (BuildContext context, GoRouterState state) => '/other', + routes: [ + GoRoute( + path: 'dummy2', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + redirect: (BuildContext context, GoRouterState state) { + assert(false); + return '/other2'; + }, + ), + ], + ), GoRoute( - path: 'other', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen()), + path: 'other', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), GoRoute( - path: 'other2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen()), + path: 'other2', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), ], ), ]; @@ -2866,33 +3084,40 @@ void main() { await tester.pumpAndSettle(); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/other'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/other', + ); }); - testWidgets('redirect when go to a shell route', - (WidgetTester tester) async { + testWidgets('redirect when go to a shell route', ( + WidgetTester tester, + ) async { 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(), ), ]; @@ -2908,13 +3133,17 @@ void main() { } }); - testWidgets('redirect when go to a stateful shell route', - (WidgetTester tester) async { + testWidgets('redirect when go to a stateful shell route', ( + WidgetTester tester, + ) async { final List routes = [ StatefulShellRoute.indexedStack( redirect: (BuildContext context, GoRouterState state) => '/dummy', - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { return navigationShell; }, branches: [ @@ -2922,8 +3151,9 @@ void main() { routes: [ GoRoute( path: '/other', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -2931,8 +3161,9 @@ void main() { routes: [ GoRoute( path: '/other2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -2940,8 +3171,9 @@ void main() { ), GoRoute( path: '/dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ]; @@ -2963,13 +3195,14 @@ 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(), ), ], ), @@ -2981,15 +3214,17 @@ void main() { initialLocation: '/dummy', ); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/dummy', + ); }); testWidgets('initial location with extra', (WidgetTester tester) async { final List routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', @@ -3008,7 +3243,9 @@ void main() { initialExtra: 'extra', ); expect( - router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); + router.routerDelegate.currentConfiguration.uri.toString(), + '/dummy', + ); expect(find.byKey(const ValueKey('extra')), findsOneWidget); }); @@ -3016,8 +3253,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', @@ -3035,41 +3272,40 @@ void main() { }); testWidgets( - 'does not take precedence over platformDispatcher.defaultRouteName', - (WidgetTester tester) async { - TestWidgetsFlutterBinding - .instance.platformDispatcher.defaultRouteNameTestValue = '/dummy'; + 'does not take precedence over platformDispatcher.defaultRouteName', + (WidgetTester tester) async { + TestWidgetsFlutterBinding + .instance + .platformDispatcher + .defaultRouteNameTestValue = '/dummy'; - final List routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - routes: [ - GoRoute( - path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - ), - ], - ), - ]; + final List routes = [ + GoRoute( + path: '/', + builder: + (BuildContext context, GoRouterState state) => + const HomeScreen(), + routes: [ + GoRoute( + path: 'dummy', + builder: + (BuildContext context, GoRouterState state) => + const DummyScreen(), + ), + ], + ), + ]; - final GoRouter router = await createRouter( - routes, - tester, - ); - expect(router.routeInformationProvider.value.uri.path, '/dummy'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }); + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.path, '/dummy'); + TestWidgetsFlutterBinding.instance.platformDispatcher + .clearDefaultRouteNameTestValue(); + }, + ); test('throws assertion if initialExtra is set w/o initialLocation', () { expect( - () => GoRouter( - routes: const [], - initialExtra: 1, - ), + () => GoRouter(routes: const [], initialExtra: 1), throwsA( isA().having( (AssertionError e) => e.message, @@ -3085,54 +3321,58 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), ), ]; testWidgets( - 'When platformDispatcher.defaultRouteName is deep-link Uri with ' - 'scheme, authority, no path', (WidgetTester tester) async { - TestWidgetsFlutterBinding.instance.platformDispatcher - .defaultRouteNameTestValue = 'https://domain.com'; - final GoRouter router = await createRouter( - routes, - tester, - ); - expect(router.routeInformationProvider.value.uri.path, '/'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }); + 'When platformDispatcher.defaultRouteName is deep-link Uri with ' + 'scheme, authority, no path', + (WidgetTester tester) async { + TestWidgetsFlutterBinding + .instance + .platformDispatcher + .defaultRouteNameTestValue = 'https://domain.com'; + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.path, '/'); + TestWidgetsFlutterBinding.instance.platformDispatcher + .clearDefaultRouteNameTestValue(); + }, + ); testWidgets( - 'When platformDispatcher.defaultRouteName is deep-link Uri with ' - 'scheme, authority, no path, but trailing slash', - (WidgetTester tester) async { - TestWidgetsFlutterBinding.instance.platformDispatcher - .defaultRouteNameTestValue = 'https://domain.com/'; - final GoRouter router = await createRouter( - routes, - tester, - ); - expect(router.routeInformationProvider.value.uri.path, '/'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }); + 'When platformDispatcher.defaultRouteName is deep-link Uri with ' + 'scheme, authority, no path, but trailing slash', + (WidgetTester tester) async { + TestWidgetsFlutterBinding + .instance + .platformDispatcher + .defaultRouteNameTestValue = 'https://domain.com/'; + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.path, '/'); + TestWidgetsFlutterBinding.instance.platformDispatcher + .clearDefaultRouteNameTestValue(); + }, + ); testWidgets( - 'When platformDispatcher.defaultRouteName is deep-link Uri with ' - 'scheme, authority, no path, and query parameters', - (WidgetTester tester) async { - TestWidgetsFlutterBinding.instance.platformDispatcher - .defaultRouteNameTestValue = 'https://domain.com?param=1'; - final GoRouter router = await createRouter( - routes, - tester, - ); - expect(router.routeInformationProvider.value.uri.toString(), '/?param=1'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }); + 'When platformDispatcher.defaultRouteName is deep-link Uri with ' + 'scheme, authority, no path, and query parameters', + (WidgetTester tester) async { + TestWidgetsFlutterBinding + .instance + .platformDispatcher + .defaultRouteNameTestValue = 'https://domain.com?param=1'; + final GoRouter router = await createRouter(routes, tester); + expect( + router.routeInformationProvider.value.uri.toString(), + '/?param=1', + ); + TestWidgetsFlutterBinding.instance.platformDispatcher + .clearDefaultRouteNameTestValue(); + }, + ); }); group('params', () { @@ -3140,13 +3380,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', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -3169,14 +3410,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', - builder: (BuildContext context, GoRouterState state) => FamilyScreen( - state.uri.queryParameters['fid']!, - ), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.uri.queryParameters['fid']!), ), ]; @@ -3195,8 +3436,9 @@ void main() { } }); - testWidgets('preserve path param spaces and slashes', - (WidgetTester tester) async { + testWidgets('preserve path param spaces and slashes', ( + WidgetTester tester, + ) async { const String param1 = 'param w/ spaces and slashes'; final List routes = [ GoRoute( @@ -3218,8 +3460,9 @@ void main() { expect(matches.pathParameters['param1'], param1); }); - testWidgets('preserve query param spaces and slashes', - (WidgetTester tester) async { + testWidgets('preserve query param spaces and slashes', ( + WidgetTester tester, + ) async { const String param1 = 'param w/ spaces and slashes'; final List routes = [ GoRoute( @@ -3253,13 +3496,11 @@ void main() { try { GoRouter( routes: [ - GoRoute( - path: '/:id/:blah/:bam/:id/:blah', - builder: dummy, - ), + 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); @@ -3292,19 +3533,16 @@ void main() { }); testWidgets('duplicate path + query param', (WidgetTester tester) async { - final GoRouter router = await createRouter( - [ - GoRoute( - path: '/:id', - builder: (BuildContext context, GoRouterState state) { - expect(state.pathParameters, {'id': '0'}); - expect(state.uri.queryParameters, {'id': '1'}); - return const HomeScreen(); - }, - ), - ], - tester, - ); + final GoRouter router = await createRouter([ + GoRoute( + path: '/:id', + builder: (BuildContext context, GoRouterState state) { + expect(state.pathParameters, {'id': '0'}); + expect(state.uri.queryParameters, {'id': '1'}); + return const HomeScreen(); + }, + ), + ], tester); router.go('/0?id=1'); await tester.pumpAndSettle(); @@ -3315,75 +3553,71 @@ void main() { }); testWidgets('push + query param', (WidgetTester tester) async { - final GoRouter router = await createRouter( - [ - GoRoute(path: '/', builder: dummy), - GoRoute( - path: '/family', - 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']!, - ), - ), - ], - tester, - ); + final GoRouter router = await createRouter([ + GoRoute(path: '/', builder: dummy), + GoRoute( + path: '/family', + 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']!, + ), + ), + ], tester); router.go('/family?fid=f2'); await tester.pumpAndSettle(); router.push('/person?fid=f2&pid=p1'); await tester.pumpAndSettle(); - final FamilyScreen page1 = tester - .widget(find.byType(FamilyScreen, skipOffstage: false)); + final FamilyScreen page1 = tester.widget( + find.byType(FamilyScreen, skipOffstage: false), + ); expect(page1.fid, 'f2'); - final PersonScreen page2 = - tester.widget(find.byType(PersonScreen)); + final PersonScreen page2 = tester.widget( + find.byType(PersonScreen), + ); expect(page2.fid, 'f2'); expect(page2.pid, 'p1'); }); testWidgets('push + extra param', (WidgetTester tester) async { - final GoRouter router = await createRouter( - [ - GoRoute(path: '/', builder: dummy), - GoRoute( - path: '/family', - 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']!, - ), - ), - ], - tester, - ); + final GoRouter router = await createRouter([ + GoRoute(path: '/', builder: dummy), + GoRoute( + path: '/family', + 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']!, + ), + ), + ], tester); router.go('/family', extra: {'fid': 'f2'}); await tester.pumpAndSettle(); router.push('/person', extra: {'fid': 'f2', 'pid': 'p1'}); await tester.pumpAndSettle(); - final FamilyScreen page1 = tester - .widget(find.byType(FamilyScreen, skipOffstage: false)); + final FamilyScreen page1 = tester.widget( + find.byType(FamilyScreen, skipOffstage: false), + ); expect(page1.fid, 'f2'); - final PersonScreen page2 = - tester.widget(find.byType(PersonScreen)); + final PersonScreen page2 = tester.widget( + find.byType(PersonScreen), + ); expect(page2.fid, 'f2'); expect(page2.pid, 'p1'); }); @@ -3392,13 +3626,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', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -3431,13 +3666,17 @@ void main() { expect(imperativeRouteMatch.matches.pathParameters['pid'], pid); }); - testWidgets('StatefulShellRoute supports nested routes with params', - (WidgetTester tester) async { + testWidgets('StatefulShellRoute supports nested routes with params', ( + WidgetTester tester, + ) async { StatefulNavigationShell? routeState; final List routes = [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { routeState = navigationShell; return navigationShell; }, @@ -3446,44 +3685,50 @@ void main() { routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), StatefulShellBranch( routes: [ GoRoute( - path: '/family', - builder: (BuildContext context, GoRouterState state) => - const Text('Families'), - routes: [ - GoRoute( - path: ':fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), - routes: [ - GoRoute( - path: 'person/:pid', - builder: - (BuildContext context, GoRouterState state) { - final String fid = state.pathParameters['fid']!; - final String pid = state.pathParameters['pid']!; + path: '/family', + builder: + (BuildContext context, GoRouterState state) => + const Text('Families'), + routes: [ + GoRoute( + path: ':fid', + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), + routes: [ + GoRoute( + path: 'person/:pid', + builder: (BuildContext context, GoRouterState state) { + final String fid = state.pathParameters['fid']!; + final String pid = state.pathParameters['pid']!; - return PersonScreen(fid, pid); - }, - ), - ], - ) - ]), + return PersonScreen(fid, pid); + }, + ), + ], + ), + ], + ), ], ), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); const String fid = 'f1'; const String pid = 'p2'; const String loc = '/family/$fid/person/$pid'; @@ -3515,14 +3760,18 @@ void main() { expect(matches.pathParameters['pid'], pid); }); - testWidgets('StatefulShellRoute preserve extra when switching branch', - (WidgetTester tester) async { + testWidgets('StatefulShellRoute preserve extra when switching branch', ( + WidgetTester tester, + ) async { StatefulNavigationShell? routeState; Object? latestExtra; final List routes = [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { routeState = navigationShell; return navigationShell; }, @@ -3531,19 +3780,21 @@ void main() { routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), StatefulShellBranch( routes: [ GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) { - latestExtra = state.extra; - return const DummyScreen(); - }), + path: '/b', + builder: (BuildContext context, GoRouterState state) { + latestExtra = state.extra; + return const DummyScreen(); + }, + ), ], ), ], @@ -3551,8 +3802,12 @@ void main() { ]; final Object expectedExtra = Object(); - await createRouter(routes, tester, - initialLocation: '/b', initialExtra: expectedExtra); + await createRouter( + routes, + tester, + initialLocation: '/b', + initialExtra: expectedExtra, + ); expect(latestExtra, expectedExtra); routeState!.goBranch(0); await tester.pumpAndSettle(); @@ -3561,8 +3816,9 @@ void main() { expect(latestExtra, expectedExtra); }); - testWidgets('goNames should allow dynamics values for queryParams', - (WidgetTester tester) async { + testWidgets('goNames should allow dynamics values for queryParams', ( + WidgetTester tester, + ) async { const Map queryParametersAll = >{ 'q1': ['v1'], 'q2': ['v2', 'v3'], @@ -3576,8 +3832,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', @@ -3594,17 +3850,21 @@ void main() { final GoRouter router = await createRouter(routes, tester); - router.goNamed('page', queryParameters: const { - 'q1': 'v1', - 'q2': ['v2', 'v3'], - }); - await tester.pumpAndSettle(); + router.goNamed( + 'page', + queryParameters: const { + 'q1': 'v1', + 'q2': ['v2', 'v3'], + }, + ); + await tester.pumpAndSettle(); final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expectLocationWithQueryParams( - router.routerDelegate.currentConfiguration.uri.toString()); + router.routerDelegate.currentConfiguration.uri.toString(), + ); expect( tester.widget(find.byType(DummyScreen)), isA().having( @@ -3616,8 +3876,9 @@ void main() { }); }); - testWidgets('go should preserve the query parameters when navigating', - (WidgetTester tester) async { + testWidgets('go should preserve the query parameters when navigating', ( + WidgetTester tester, + ) async { const Map queryParametersAll = >{ 'q1': ['v1'], 'q2': ['v2', 'v3'], @@ -3631,8 +3892,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', @@ -3640,9 +3901,7 @@ void main() { builder: (BuildContext context, GoRouterState state) { expect(state.uri.queryParametersAll, queryParametersAll); expectLocationWithQueryParams(state.uri.toString()); - return DummyScreen( - queryParametersAll: state.uri.queryParametersAll, - ); + return DummyScreen(queryParametersAll: state.uri.queryParametersAll); }, ), ]; @@ -3656,7 +3915,8 @@ void main() { expect(matches, hasLength(1)); expectLocationWithQueryParams( - router.routerDelegate.currentConfiguration.uri.toString()); + router.routerDelegate.currentConfiguration.uri.toString(), + ); expect( tester.widget(find.byType(DummyScreen)), isA().having( @@ -3667,8 +3927,9 @@ void main() { ); }); - testWidgets('goRouter should rebuild widget if ', - (WidgetTester tester) async { + testWidgets('goRouter should rebuild widget if ', ( + WidgetTester tester, + ) async { const Map queryParametersAll = >{ 'q1': ['v1'], 'q2': ['v2', 'v3'], @@ -3682,8 +3943,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', @@ -3691,9 +3952,7 @@ void main() { builder: (BuildContext context, GoRouterState state) { expect(state.uri.queryParametersAll, queryParametersAll); expectLocationWithQueryParams(state.uri.toString()); - return DummyScreen( - queryParametersAll: state.uri.queryParametersAll, - ); + return DummyScreen(queryParametersAll: state.uri.queryParametersAll); }, ), ]; @@ -3707,7 +3966,8 @@ void main() { expect(matches, hasLength(1)); expectLocationWithQueryParams( - router.routerDelegate.currentConfiguration.uri.toString()); + router.routerDelegate.currentConfiguration.uri.toString(), + ); expect( tester.widget(find.byType(DummyScreen)), isA().having( @@ -3725,14 +3985,15 @@ 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(), ), ]; @@ -3746,16 +4007,15 @@ void main() { const String location = '/page1'; const String extra = 'Hello'; - testWidgets('calls [namedLocation] on closest GoRouter', - (WidgetTester tester) async { - final GoRouterNamedLocationSpy router = - GoRouterNamedLocationSpy(routes: routes); + testWidgets('calls [namedLocation] on closest GoRouter', ( + WidgetTester tester, + ) async { + final GoRouterNamedLocationSpy router = GoRouterNamedLocationSpy( + routes: routes, + ); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); key.currentContext!.namedLocation( name, @@ -3771,28 +4031,20 @@ void main() { final GoRouterGoSpy router = GoRouterGoSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), - ); - key.currentContext!.go( - location, - extra: extra, + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); + key.currentContext!.go(location, extra: extra); expect(router.myLocation, location); expect(router.extra, extra); }); - testWidgets('calls [goNamed] on closest GoRouter', - (WidgetTester tester) async { + testWidgets('calls [goNamed] on closest GoRouter', ( + WidgetTester tester, + ) async { final GoRouterGoNamedSpy router = GoRouterGoNamedSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); key.currentContext!.goNamed( name, @@ -3806,26 +4058,22 @@ void main() { expect(router.extra, extra); }); - testWidgets('calls [push] on closest GoRouter', - (WidgetTester tester) async { + testWidgets('calls [push] on closest GoRouter', ( + WidgetTester tester, + ) async { final GoRouterPushSpy router = GoRouterPushSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), - ); - key.currentContext!.push( - location, - extra: extra, + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); + key.currentContext!.push(location, extra: extra); expect(router.myLocation, location); expect(router.extra, extra); }); - testWidgets('calls [push] on closest GoRouter and waits for result', - (WidgetTester tester) async { + testWidgets('calls [push] on closest GoRouter and waits for result', ( + WidgetTester tester, + ) async { final GoRouterPushSpy router = GoRouterPushSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( @@ -3836,24 +4084,19 @@ void main() { title: 'GoRouter Example', ), ); - final String? result = await router.push( - location, - extra: extra, - ); + final String? result = await router.push(location, extra: extra); expect(result, extra); expect(router.myLocation, location); expect(router.extra, extra); }); - testWidgets('calls [pushNamed] on closest GoRouter', - (WidgetTester tester) async { + testWidgets('calls [pushNamed] on closest GoRouter', ( + WidgetTester tester, + ) async { final GoRouterPushNamedSpy router = GoRouterPushNamedSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); key.currentContext!.pushNamed( name, @@ -3867,8 +4110,9 @@ void main() { expect(router.extra, extra); }); - testWidgets('calls [pushNamed] on closest GoRouter and waits for result', - (WidgetTester tester) async { + testWidgets('calls [pushNamed] on closest GoRouter and waits for result', ( + WidgetTester tester, + ) async { final GoRouterPushNamedSpy router = GoRouterPushNamedSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( @@ -3896,25 +4140,20 @@ void main() { final GoRouterPopSpy router = GoRouterPopSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); key.currentContext!.pop(); expect(router.popped, true); expect(router.poppedResult, null); }); - testWidgets('calls [pop] on closest GoRouter with result', - (WidgetTester tester) async { + testWidgets('calls [pop] on closest GoRouter with result', ( + WidgetTester tester, + ) async { final GoRouterPopSpy router = GoRouterPopSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ), + MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), ); key.currentContext!.pop('result'); expect(router.popped, true); @@ -3927,25 +4166,19 @@ void main() { final List routes = [ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: child, - ); + return Scaffold(body: child); }, routes: [ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, ), GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, ), ], @@ -3974,17 +4207,13 @@ void main() { ), ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: child, - ); + return Scaffold(body: child); }, routes: [ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, ), ], @@ -4004,58 +4233,54 @@ void main() { }); testWidgets( - 'Pops from the correct Navigator when the Android back button is pressed', - (WidgetTester tester) async { - final List routes = [ - ShellRoute( - builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: Column( - children: [ - const Text('Screen A'), - Expanded(child: child), + 'Pops from the correct Navigator when the Android back button is pressed', + (WidgetTester tester) async { + final List routes = [ + ShellRoute( + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Column( + children: [ + const Text('Screen A'), + Expanded(child: child), + ], + ), + ); + }, + routes: [ + GoRoute( + path: '/b', + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen B')); + }, + routes: [ + GoRoute( + path: 'c', + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen C')); + }, + ), ], ), - ); - }, - routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); - }, - routes: [ - GoRoute( - path: 'c', - builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen C'), - ); - }, - ), - ], - ), - ], - ), - ]; + ], + ), + ]; - await createRouter(routes, tester, initialLocation: '/b/c'); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsOneWidget); + await createRouter(routes, tester, initialLocation: '/b/c'); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsOneWidget); - await simulateAndroidBackButton(tester); - await tester.pumpAndSettle(); + await simulateAndroidBackButton(tester); + await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B'), findsOneWidget); - expect(find.text('Screen C'), findsNothing); - }); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B'), findsOneWidget); + expect(find.text('Screen C'), findsNothing); + }, + ); - testWidgets( - 'Pops from the correct navigator when a sub-route is placed on ' + testWidgets('Pops from the correct navigator when a sub-route is placed on ' 'the root Navigator', (WidgetTester tester) async { final GlobalKey rootNavigatorKey = GlobalKey(); @@ -4079,18 +4304,14 @@ void main() { GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, routes: [ GoRoute( path: 'c', parentNavigatorKey: rootNavigatorKey, builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen C'), - ); + return const Scaffold(body: Text('Screen C')); }, ), ], @@ -4099,8 +4320,12 @@ void main() { ), ]; - await createRouter(routes, tester, - initialLocation: '/b/c', navigatorKey: rootNavigatorKey); + await createRouter( + routes, + tester, + initialLocation: '/b/c', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsOneWidget); @@ -4119,30 +4344,43 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) => - navigationShell, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) => navigationShell, branches: [ - StatefulShellBranch(routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + ), + ], + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); @@ -4152,103 +4390,45 @@ void main() { expect(find.text('Screen B'), findsOneWidget); }); - testWidgets('Builds StatefulShellRoute as a sub-route', - (WidgetTester tester) async { + testWidgets('Builds StatefulShellRoute as a sub-route', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); 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: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) => - navigationShell, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) => navigationShell, branches: [ - StatefulShellBranch(routes: [ - GoRoute( - path: 'a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: 'b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ]), - ], - ), - ], - ), - ]; - - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/root/a', navigatorKey: rootNavigatorKey); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - - router.go('/root/b'); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B'), findsOneWidget); - }); - - testWidgets( - 'Navigation with goBranch is correctly handled in StatefulShellRoute', - (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GlobalKey statefulWidgetKey = - GlobalKey(); - StatefulNavigationShell? routeState; - - final List routes = [ - StatefulShellRoute.indexedStack( - 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'), - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/c', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C'), + StatefulShellBranch( + routes: [ + GoRoute( + path: 'a', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), + ), + ], ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/d', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen D'), + StatefulShellBranch( + routes: [ + GoRoute( + path: 'b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + ), + ], ), ], ), @@ -4256,158 +4436,273 @@ void main() { ), ]; - await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); - statefulWidgetKey.currentState?.increment(); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/root/a', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsNothing); - expect(find.text('Screen D'), findsNothing); - routeState!.goBranch(1); + router.go('/root/b'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); - expect(find.text('Screen C'), findsNothing); - expect(find.text('Screen D'), findsNothing); - - routeState!.goBranch(2); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsOneWidget); - expect(find.text('Screen D'), findsNothing); - - routeState!.goBranch(3); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsNothing); - expect(find.text('Screen D'), findsOneWidget); - - expect(() { - // Verify that navigation to unknown index fails - routeState!.goBranch(4); - }, throwsA(isA())); }); testWidgets( - 'Navigates to correct nested navigation tree in StatefulShellRoute ' - 'and maintains state', (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GlobalKey statefulWidgetKey = - GlobalKey(); - StatefulNavigationShell? routeState; + 'Navigation with goBranch is correctly handled in StatefulShellRoute', + (WidgetTester tester) async { + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GlobalKey statefulWidgetKey = + GlobalKey(); + StatefulNavigationShell? routeState; - final List routes = [ - StatefulShellRoute.indexedStack( - 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'), + final List routes = [ + StatefulShellRoute.indexedStack( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + StatefulShellBranch( routes: [ GoRoute( - path: 'detailA', - builder: (BuildContext context, GoRouterState state) => - Column(children: [ - const Text('Screen A Detail'), - DummyStatefulWidget(key: statefulWidgetKey), - ]), + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + ), + ], ), - ]), - ], - ), - ]; + StatefulShellBranch( + routes: [ + GoRoute( + path: '/c', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen C'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/d', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen D'), + ), + ], + ), + ], + ), + ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey); - statefulWidgetKey.currentState?.increment(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); + await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); + statefulWidgetKey.currentState?.increment(); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsNothing); + expect(find.text('Screen D'), findsNothing); - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsOneWidget); + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B'), findsOneWidget); + expect(find.text('Screen C'), findsNothing); + expect(find.text('Screen D'), findsNothing); - routeState!.goBranch(0); - await tester.pumpAndSettle(); - expect(statefulWidgetKey.currentState?.counter, equals(1)); + routeState!.goBranch(2); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsOneWidget); + expect(find.text('Screen D'), findsNothing); - router.go('/a'); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen A Detail'), findsNothing); - router.go('/a/detailA'); - await tester.pumpAndSettle(); - expect(statefulWidgetKey.currentState?.counter, equals(0)); - }); + routeState!.goBranch(3); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsNothing); + expect(find.text('Screen D'), findsOneWidget); + + expect(() { + // Verify that navigation to unknown index fails + routeState!.goBranch(4); + }, throwsA(isA())); + }, + ); testWidgets( - 'Navigates to correct nested navigation tree in StatefulShellRoute ' - 'and maintains path parameters', (WidgetTester tester) async { - StatefulNavigationShell? routeState; + 'Navigates to correct nested navigation tree in StatefulShellRoute ' + 'and maintains state', + (WidgetTester tester) async { + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GlobalKey statefulWidgetKey = + GlobalKey(); + StatefulNavigationShell? routeState; - final List routes = [ - GoRoute( + final List routes = [ + StatefulShellRoute.indexedStack( + 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'), + routes: [ + GoRoute( + path: 'detailA', + builder: + (BuildContext context, GoRouterState state) => + Column( + children: [ + const Text('Screen A Detail'), + DummyStatefulWidget(key: statefulWidgetKey), + ], + ), + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + ), + ], + ), + ], + ), + ]; + + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + ); + statefulWidgetKey.currentState?.increment(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsOneWidget); + + routeState!.goBranch(0); + await tester.pumpAndSettle(); + expect(statefulWidgetKey.currentState?.counter, equals(1)); + + router.go('/a'); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen A Detail'), findsNothing); + router.go('/a/detailA'); + await tester.pumpAndSettle(); + expect(statefulWidgetKey.currentState?.counter, equals(0)); + }, + ); + + testWidgets( + 'Navigates to correct nested navigation tree in StatefulShellRoute ' + 'and maintains path parameters', + (WidgetTester tester) async { + StatefulNavigationShell? routeState; + + final List routes = [ + GoRoute( path: '/:id', builder: (_, __) => const Placeholder(), routes: [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell 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']}'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: 'b', - builder: (BuildContext context, GoRouterState state) => - Text('b id is ${state.pathParameters['id']}'), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: 'a', + builder: + (BuildContext context, GoRouterState state) => + Text('a id is ${state.pathParameters['id']}'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: 'b', + builder: + (BuildContext context, GoRouterState state) => + Text('b id is ${state.pathParameters['id']}'), + ), + ], + ), ], ), - ]) - ]; + ], + ), + ]; - await createRouter(routes, tester, initialLocation: '/123/a'); - expect(find.text('a id is 123'), findsOneWidget); + await createRouter(routes, tester, initialLocation: '/123/a'); + expect(find.text('a id is 123'), findsOneWidget); - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('b id is 123'), findsOneWidget); - }); + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('b id is 123'), findsOneWidget); + }, + ); - testWidgets('Maintains state for nested StatefulShellRoute', - (WidgetTester tester) async { + testWidgets('Maintains state for nested StatefulShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey statefulWidgetKey = @@ -4417,67 +4712,96 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { routeState1 = navigationShell; return navigationShell; }, branches: [ - StatefulShellBranch(routes: [ - StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + StatefulShellBranch( + routes: [ + StatefulShellRoute.indexedStack( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { routeState2 = navigationShell; return navigationShell; }, branches: [ - StatefulShellBranch(routes: [ - GoRoute( - path: '/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), - ]), - ), - ], - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/c', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C'), - ), - ]), - ]), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/d', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen D'), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/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, + ), + ], + ), + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/c', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen C'), + ), + ], + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/d', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen D'), + ), + ], + ), ], ), ]; - await createRouter(routes, tester, - initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey); + await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + ); statefulWidgetKey.currentState?.increment(); expect(find.text('Screen A Detail'), findsOneWidget); routeState2!.goBranch(1); @@ -4503,96 +4827,110 @@ void main() { }); testWidgets( - 'Pops from the correct Navigator in a StatefulShellRoute when the ' - 'Android back button is pressed', (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GlobalKey sectionANavigatorKey = - GlobalKey(); - final GlobalKey sectionBNavigatorKey = - GlobalKey(); - StatefulNavigationShell? routeState; + 'Pops from the correct Navigator in a StatefulShellRoute when the ' + 'Android back button is pressed', + (WidgetTester tester) async { + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GlobalKey sectionANavigatorKey = + GlobalKey(); + final GlobalKey sectionBNavigatorKey = + GlobalKey(); + StatefulNavigationShell? routeState; - final List routes = [ - StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( + final List routes = [ + StatefulShellRoute.indexedStack( + 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'), ), ], ), - ]), - StatefulShellBranch( + ], + ), + StatefulShellBranch( navigatorKey: sectionBNavigatorKey, 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'), ), ], ), - ]), - ], - ), - ]; + ], + ), + ], + ), + ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Detail'), findsNothing); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + ); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Detail'), findsNothing); - router.go('/b/detailB'); - await tester.pumpAndSettle(); + router.go('/b/detailB'); + await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Detail'), findsOneWidget); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Detail'), findsOneWidget); - await simulateAndroidBackButton(tester); - await tester.pumpAndSettle(); + await simulateAndroidBackButton(tester); + await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsOneWidget); - expect(find.text('Screen B Detail'), findsNothing); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsOneWidget); + expect(find.text('Screen B Detail'), findsNothing); - routeState!.goBranch(0); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsOneWidget); + routeState!.goBranch(0); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsOneWidget); - await simulateAndroidBackButton(tester); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen A Detail'), findsNothing); - }); + await simulateAndroidBackButton(tester); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen A Detail'), findsNothing); + }, + ); - testWidgets( - 'Maintains extra navigation information when navigating ' + testWidgets('Maintains extra navigation information when navigating ' 'between branches in StatefulShellRoute', (WidgetTester tester) async { final GlobalKey rootNavigatorKey = GlobalKey(); @@ -4600,32 +4938,45 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell 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'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - Text('Screen B - ${state.extra}'), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + Text('Screen B - ${state.extra}'), + ), + ], + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsOneWidget); router.go('/b', extra: 'X'); @@ -4644,10 +4995,10 @@ void main() { expect(find.text('Screen B - X'), findsOneWidget); }); - testWidgets( - 'Pushed non-descendant routes are correctly restored when ' - 'navigating between branches in StatefulShellRoute', - (WidgetTester tester) async { + testWidgets('Pushed non-descendant routes are correctly restored when ' + 'navigating between branches in StatefulShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); StatefulNavigationShell? routeState; @@ -4655,36 +5006,50 @@ 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) { + 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'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + ), + ], + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); expect(find.text('Screen A'), findsOneWidget); router.go('/b'); @@ -4709,8 +5074,9 @@ void main() { expect(find.text('Screen B'), findsOneWidget); }); - testWidgets('Preloads routes correctly in a StatefulShellRoute', - (WidgetTester tester) async { + testWidgets('Preloads routes correctly in a StatefulShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey statefulWidgetKeyA = @@ -4728,20 +5094,26 @@ void main() { StatefulShellRoute.indexedStack( builder: mockStackedShellBuilder, branches: [ - StatefulShellBranch(routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyA), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyB), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyA), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyB), + ), + ], + ), ], ), StatefulShellRoute.indexedStack( @@ -4752,8 +5124,9 @@ void main() { routes: [ GoRoute( path: '/c', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyC), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyC), ), ], ), @@ -4762,8 +5135,9 @@ void main() { routes: [ GoRoute( path: '/d', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyD), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyD), ), ], ), @@ -4772,16 +5146,19 @@ void main() { initialLocation: '/e/details', routes: [ GoRoute( - path: '/e', - builder: (BuildContext context, GoRouterState state) => - const Text('E'), - routes: [ - GoRoute( - path: 'details', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyE), - ), - ]), + path: '/e', + builder: + (BuildContext context, GoRouterState state) => + const Text('E'), + routes: [ + GoRoute( + path: 'details', + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyE), + ), + ], + ), ], ), ], @@ -4806,8 +5183,9 @@ void main() { expect(statefulWidgetKeyE.currentState?.counter, equals(0)); }); - testWidgets('Preloads nested routes correctly in a StatefulShellRoute', - (WidgetTester tester) async { + testWidgets('Preloads nested routes correctly in a StatefulShellRoute', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey statefulWidgetKeyA = @@ -4829,20 +5207,28 @@ void main() { StatefulShellRoute.indexedStack( builder: mockStackedShellBuilder, branches: [ - StatefulShellBranch(preload: true, routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyA), - ), - ]), - StatefulShellBranch(preload: true, routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyB), - ), - ]), + StatefulShellBranch( + preload: true, + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyA), + ), + ], + ), + StatefulShellBranch( + preload: true, + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyB), + ), + ], + ), ], ), ], @@ -4852,8 +5238,9 @@ void main() { routes: [ GoRoute( path: '/c', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyC), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyC), ), ], ), @@ -4861,8 +5248,9 @@ void main() { routes: [ GoRoute( path: '/d', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyD), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyD), ), ], ), @@ -4882,8 +5270,7 @@ void main() { expect(statefulWidgetKeyD.currentState?.counter, null); }); - testWidgets( - 'Redirects are correctly handled when switching branch in a ' + testWidgets('Redirects are correctly handled when switching branch in a ' 'StatefulShellRoute', (WidgetTester tester) async { final GlobalKey rootNavigatorKey = GlobalKey(); @@ -4891,54 +5278,66 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell 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'), - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - routes: [ - GoRoute( - path: 'details1', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B Detail1'), - ), - GoRoute( - path: 'details2', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B Detail2'), - ), - ], - ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/c', - redirect: (_, __) => '/c/main2', - ), - GoRoute( - path: '/c/main1', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C1'), - ), - GoRoute( - path: '/c/main2', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C2'), - ), - ]), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B'), + routes: [ + GoRoute( + path: 'details1', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B Detail1'), + ), + GoRoute( + path: 'details2', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B Detail2'), + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute(path: '/c', redirect: (_, __) => '/c/main2'), + GoRoute( + path: '/c/main1', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen C1'), + ), + GoRoute( + path: '/c/main2', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen C2'), + ), + ], + ), ], ), ]; @@ -4979,184 +5378,212 @@ void main() { }); testWidgets( - 'Pushed top-level route is correctly handled by StatefulShellRoute', - (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GlobalKey nestedNavigatorKey = - GlobalKey(); - StatefulNavigationShell? routeState; + 'Pushed top-level route is correctly handled by StatefulShellRoute', + (WidgetTester tester) async { + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GlobalKey nestedNavigatorKey = + GlobalKey(); + StatefulNavigationShell? routeState; - final List routes = [ - // First level shell - StatefulShellRoute.indexedStack( - 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'), + final List routes = [ + // First level shell + StatefulShellRoute.indexedStack( + 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'), + ), + ], ), - ]), - StatefulShellBranch(routes: [ - // Second level / nested shell - StatefulShellRoute.indexedStack( - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) => - navigationShell, - branches: [ - StatefulShellBranch(routes: [ - GoRoute( - path: '/b1', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B1'), - ), - ]), - StatefulShellBranch( - navigatorKey: nestedNavigatorKey, - routes: [ - GoRoute( - path: '/b2', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B2'), - ), - GoRoute( - path: '/b2-modal', - // We pass an explicit parentNavigatorKey here, to - // properly test the logic in RouteBuilder, i.e. - // routes with parentNavigatorKeys under the shell - // should not be stripped. - parentNavigatorKey: nestedNavigatorKey, - builder: - (BuildContext context, GoRouterState state) => - const Text('Nested Modal'), - ), - ]), + StatefulShellBranch( + routes: [ + // Second level / nested shell + StatefulShellRoute.indexedStack( + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) => navigationShell, + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b1', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B1'), + ), + ], + ), + StatefulShellBranch( + navigatorKey: nestedNavigatorKey, + routes: [ + GoRoute( + path: '/b2', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B2'), + ), + GoRoute( + path: '/b2-modal', + // We pass an explicit parentNavigatorKey here, to + // properly test the logic in RouteBuilder, i.e. + // routes with parentNavigatorKeys under the shell + // should not be stripped. + parentNavigatorKey: nestedNavigatorKey, + builder: + (BuildContext context, GoRouterState state) => + const Text('Nested Modal'), + ), + ], + ), + ], + ), ], ), - ]), - ], - ), - GoRoute( - path: '/top-modal', - parentNavigatorKey: rootNavigatorKey, - builder: (BuildContext context, GoRouterState state) => - const Text('Top Modal'), - ), - ]; + ], + ), + GoRoute( + path: '/top-modal', + parentNavigatorKey: rootNavigatorKey, + builder: + (BuildContext context, GoRouterState state) => + const Text('Top Modal'), + ), + ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a', navigatorKey: rootNavigatorKey); - expect(find.text('Screen A'), findsOneWidget); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, + ); + expect(find.text('Screen A'), findsOneWidget); - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen B1'), findsOneWidget); + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen B1'), findsOneWidget); - // Navigate nested (second level) shell to second branch - router.go('/b2'); - await tester.pumpAndSettle(); - expect(find.text('Screen B2'), findsOneWidget); + // Navigate nested (second level) shell to second branch + router.go('/b2'); + await tester.pumpAndSettle(); + expect(find.text('Screen B2'), findsOneWidget); - // Push route over second branch of nested (second level) shell - router.push('/b2-modal'); - await tester.pumpAndSettle(); - expect(find.text('Nested Modal'), findsOneWidget); + // Push route over second branch of nested (second level) shell + router.push('/b2-modal'); + await tester.pumpAndSettle(); + expect(find.text('Nested Modal'), findsOneWidget); - // Push top-level route while on second branch - router.push('/top-modal'); - await tester.pumpAndSettle(); - expect(find.text('Top Modal'), findsOneWidget); + // Push top-level route while on second branch + router.push('/top-modal'); + await tester.pumpAndSettle(); + expect(find.text('Top Modal'), findsOneWidget); - // Return to shell and first branch - router.go('/a'); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); + // Return to shell and first branch + router.go('/a'); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsOneWidget); - // Switch to second branch, which should only contain 'Nested Modal' - // (in the nested shell) - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B1'), findsNothing); - expect(find.text('Screen B2'), findsNothing); - expect(find.text('Top Modal'), findsNothing); - expect(find.text('Nested Modal'), findsOneWidget); - }); + // Switch to second branch, which should only contain 'Nested Modal' + // (in the nested shell) + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B1'), findsNothing); + expect(find.text('Screen B2'), findsNothing); + expect(find.text('Top Modal'), findsNothing); + expect(find.text('Nested Modal'), findsOneWidget); + }, + ); testWidgets( - 'Obsolete branches in StatefulShellRoute are cleaned up after route ' - 'configuration change', - // TODO(tolo): Temporarily skipped due to a bug that causes test to faiL - skip: true, (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(debugLabel: 'root'); - final GlobalKey statefulShellKey = - GlobalKey(debugLabel: 'shell'); - StatefulNavigationShell? routeState; - StatefulShellBranch makeBranch(String name) => StatefulShellBranch( - navigatorKey: - GlobalKey(debugLabel: 'branch-$name'), - preload: true, - initialLocation: '/$name', - routes: [ - GoRoute( - path: '/$name', - builder: (BuildContext context, GoRouterState state) => + 'Obsolete branches in StatefulShellRoute are cleaned up after route ' + 'configuration change', + // TODO(tolo): Temporarily skipped due to a bug that causes test to faiL + skip: true, + (WidgetTester tester) async { + final GlobalKey rootNavigatorKey = + GlobalKey(debugLabel: 'root'); + final GlobalKey statefulShellKey = + GlobalKey(debugLabel: 'shell'); + StatefulNavigationShell? routeState; + StatefulShellBranch makeBranch(String name) => StatefulShellBranch( + navigatorKey: GlobalKey(debugLabel: 'branch-$name'), + preload: true, + initialLocation: '/$name', + routes: [ + GoRoute( + path: '/$name', + builder: + (BuildContext context, GoRouterState state) => Text('Screen $name'), - ), - ]); - - List createRoutes(bool includeCRoute) => [ - StatefulShellRoute.indexedStack( - key: statefulShellKey, - builder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - makeBranch('a'), - makeBranch('b'), - if (includeCRoute) makeBranch('c'), - ], ), - ]; + ], + ); - final ValueNotifier config = ValueNotifier( - RoutingConfig(routes: createRoutes(true)), - ); - addTearDown(config.dispose); - await createRouterWithRoutingConfig( - navigatorKey: rootNavigatorKey, - config, - tester, - initialLocation: '/a', - errorBuilder: (_, __) => const Text('error'), - ); - await tester.pumpAndSettle(); + List createRoutes(bool includeCRoute) => [ + StatefulShellRoute.indexedStack( + key: statefulShellKey, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + makeBranch('a'), + makeBranch('b'), + if (includeCRoute) makeBranch('c'), + ], + ), + ]; + + final ValueNotifier config = + ValueNotifier( + RoutingConfig(routes: createRoutes(true)), + ); + addTearDown(config.dispose); + await createRouterWithRoutingConfig( + navigatorKey: rootNavigatorKey, + config, + tester, + initialLocation: '/a', + errorBuilder: (_, __) => const Text('error'), + ); + await tester.pumpAndSettle(); - bool hasLoadedBranch(String name) => routeState!.debugLoadedBranches - .any((StatefulShellBranch e) => e.initialLocation == '/$name'); + bool hasLoadedBranch(String name) => routeState!.debugLoadedBranches + .any((StatefulShellBranch e) => e.initialLocation == '/$name'); - expect(hasLoadedBranch('a'), isTrue); - expect(hasLoadedBranch('b'), isTrue); - expect(hasLoadedBranch('c'), isTrue); + expect(hasLoadedBranch('a'), isTrue); + expect(hasLoadedBranch('b'), isTrue); + expect(hasLoadedBranch('c'), isTrue); - // Unload branch 'c' by changing the route configuration - config.value = RoutingConfig(routes: createRoutes(false)); - await tester.pumpAndSettle(); + // Unload branch 'c' by changing the route configuration + config.value = RoutingConfig(routes: createRoutes(false)); + await tester.pumpAndSettle(); - expect(hasLoadedBranch('a'), isTrue); - expect(hasLoadedBranch('b'), isTrue); - expect(hasLoadedBranch('c'), isFalse); - }); + expect(hasLoadedBranch('a'), isTrue); + expect(hasLoadedBranch('b'), isTrue); + expect(hasLoadedBranch('c'), isFalse); + }, + ); }); group('Imperative navigation', () { @@ -5198,9 +5625,10 @@ void main() { await tester.pumpWidget( MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate), + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), ); expect(router.canPop(), false); @@ -5209,104 +5637,110 @@ void main() { await tester.pumpAndSettle(); expect( - find.text('pageless route', skipOffstage: false), findsOneWidget); + find.text('pageless route', skipOffstage: false), + findsOneWidget, + ); expect(router.canPop(), true); }, ); - testWidgets( - 'It checks if ShellRoute navigators can pop', - (WidgetTester tester) async { - final GlobalKey shellNavigatorKey = - GlobalKey(); - final GoRouter router = GoRouter( - initialLocation: '/a', - routes: [ - ShellRoute( - navigatorKey: shellNavigatorKey, - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); - }, - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, _) { - return Scaffold( - body: TextButton( - onPressed: () async { - shellNavigatorKey.currentState!.push( - MaterialPageRoute( - builder: (BuildContext context) { - return const Scaffold( - body: Text('pageless route'), - ); - }, - ), - ); - }, - child: const Text('Push'), - ), - ); - }, - ), - ], - ), - ], - ); - addTearDown(router.dispose); + testWidgets('It checks if ShellRoute navigators can pop', ( + WidgetTester tester, + ) async { + final GlobalKey shellNavigatorKey = + GlobalKey(); + final GoRouter router = GoRouter( + initialLocation: '/a', + routes: [ + ShellRoute( + navigatorKey: shellNavigatorKey, + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { + return Scaffold( + appBar: AppBar(title: const Text('Shell')), + body: child, + ); + }, + routes: [ + GoRoute( + path: '/a', + builder: (BuildContext context, _) { + return Scaffold( + body: TextButton( + onPressed: () async { + shellNavigatorKey.currentState!.push( + MaterialPageRoute( + builder: (BuildContext context) { + return const Scaffold( + body: Text('pageless route'), + ); + }, + ), + ); + }, + child: const Text('Push'), + ), + ); + }, + ), + ], + ), + ], + ); + addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate), - ); + await tester.pumpWidget( + MaterialApp.router( + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), + ); - expect(router.canPop(), false); - expect(find.text('Push'), findsOneWidget); + expect(router.canPop(), false); + expect(find.text('Push'), findsOneWidget); - await tester.tap(find.text('Push')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Push')); + await tester.pumpAndSettle(); - expect( - find.text('pageless route', skipOffstage: false), findsOneWidget); - expect(router.canPop(), true); - }, - ); + expect( + find.text('pageless route', skipOffstage: false), + findsOneWidget, + ); + expect(router.canPop(), true); + }); - testWidgets( - 'It checks if StatefulShellRoute navigators can pop', - (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GoRouter router = GoRouter( - navigatorKey: rootNavigatorKey, - initialLocation: '/a', - routes: [ - StatefulShellRoute.indexedStack( - builder: mockStackedShellBuilder, - branches: [ - StatefulShellBranch(routes: [ + testWidgets('It checks if StatefulShellRoute navigators can pop', ( + WidgetTester tester, + ) async { + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GoRouter router = GoRouter( + navigatorKey: rootNavigatorKey, + initialLocation: '/a', + routes: [ + StatefulShellRoute.indexedStack( + builder: mockStackedShellBuilder, + branches: [ + StatefulShellBranch( + routes: [ GoRoute( path: '/a', builder: (BuildContext context, _) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, ), - ]), - StatefulShellBranch(routes: [ + ], + ), + StatefulShellBranch( + routes: [ GoRoute( path: '/b', builder: (BuildContext context, _) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, routes: [ GoRoute( @@ -5319,48 +5753,57 @@ void main() { ), ], ), - ]), - ], - ), - ], - ); - addTearDown(router.dispose); + ], + ), + ], + ), + ], + ); + addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate), - ); + await tester.pumpWidget( + MaterialApp.router( + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), + ); - expect(router.canPop(), false); + expect(router.canPop(), false); - router.go('/b/detail'); - await tester.pumpAndSettle(); + router.go('/b/detail'); + await tester.pumpAndSettle(); - expect(find.text('Screen B detail', skipOffstage: false), - findsOneWidget); - expect(router.canPop(), true); - // Verify that it is actually the StatefulShellRoute that reports - // canPop = true - expect(rootNavigatorKey.currentState?.canPop(), false); - }, - ); + expect( + find.text('Screen B detail', skipOffstage: false), + findsOneWidget, + ); + expect(router.canPop(), true); + // Verify that it is actually the StatefulShellRoute that reports + // canPop = true + expect(rootNavigatorKey.currentState?.canPop(), false); + }); - testWidgets('Pageless route should include in can pop', - (WidgetTester tester) async { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); + testWidgets('Pageless route should include in can pop', ( + WidgetTester tester, + ) async { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); final GoRouter router = GoRouter( navigatorKey: root, routes: [ ShellRoute( navigatorKey: shell, - builder: - (BuildContext context, GoRouterState state, Widget child) { + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { return Scaffold( body: Center( child: Column( @@ -5373,10 +5816,7 @@ void main() { ); }, routes: [ - GoRoute( - path: '/', - builder: (_, __) => const Text('A Screen'), - ), + GoRoute(path: '/', builder: (_, __) => const Text('A Screen')), ], ), ], @@ -5389,8 +5829,9 @@ void main() { expect(find.text('A Screen'), findsOneWidget); expect(find.text('Shell'), findsOneWidget); showDialog( - context: root.currentContext!, - builder: (_) => const Text('A dialog')); + context: root.currentContext!, + builder: (_) => const Text('A dialog'), + ); await tester.pumpAndSettle(); expect(find.text('A dialog'), findsOneWidget); expect(router.canPop(), isTrue); @@ -5401,10 +5842,12 @@ void main() { testWidgets( 'Should pop from the correct navigator when parentNavigatorKey is set', (WidgetTester tester) async { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); final GoRouter router = GoRouter( initialLocation: '/a/b', @@ -5413,15 +5856,16 @@ void main() { GoRoute( path: '/', builder: (BuildContext context, _) { - return const Scaffold( - body: Text('Home'), - ); + return const Scaffold(body: Text('Home')); }, routes: [ ShellRoute( navigatorKey: shell, - builder: (BuildContext context, GoRouterState state, - Widget child) { + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { return Scaffold( body: Center( child: Column( @@ -5455,9 +5899,10 @@ void main() { await tester.pumpWidget( MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate), + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), ); expect(router.canPop(), isTrue); @@ -5477,12 +5922,15 @@ void main() { }, ); - testWidgets('Should pop dialog if it is present', - (WidgetTester tester) async { - final GlobalKey root = - GlobalKey(debugLabel: 'root'); - final GlobalKey shell = - GlobalKey(debugLabel: 'shell'); + testWidgets('Should pop dialog if it is present', ( + WidgetTester tester, + ) async { + final GlobalKey root = GlobalKey( + debugLabel: 'root', + ); + final GlobalKey shell = GlobalKey( + debugLabel: 'shell', + ); final GoRouter router = GoRouter( initialLocation: '/a', @@ -5491,15 +5939,16 @@ void main() { GoRoute( path: '/', builder: (BuildContext context, _) { - return const Scaffold( - body: Text('Home'), - ); + return const Scaffold(body: Text('Home')); }, routes: [ ShellRoute( navigatorKey: shell, - builder: (BuildContext context, GoRouterState state, - Widget child) { + builder: ( + BuildContext context, + GoRouterState state, + Widget child, + ) { return Scaffold( body: Center( child: Column( @@ -5531,8 +5980,9 @@ void main() { expect(find.text('Shell'), findsOneWidget); expect(find.text('Home'), findsNothing); final Future resultFuture = showDialog( - context: root.currentContext!, - builder: (_) => const Text('A dialog')); + context: root.currentContext!, + builder: (_) => const Text('A dialog'), + ); await tester.pumpAndSettle(); expect(find.text('A dialog'), findsOneWidget); expect(router.canPop(), isTrue); @@ -5546,8 +5996,9 @@ void main() { expect(result, isTrue); }); - testWidgets('Triggers a Hero inside a ShellRoute', - (WidgetTester tester) async { + testWidgets('Triggers a Hero inside a ShellRoute', ( + WidgetTester tester, + ) async { final UniqueKey heroKey = UniqueKey(); const String kHeroTag = 'hero'; @@ -5558,29 +6009,31 @@ void main() { }, routes: [ GoRoute( - path: '/a', - builder: (BuildContext context, _) { - return Hero( - tag: kHeroTag, - child: Container(), - flightShuttleBuilder: (_, __, ___, ____, _____) { - return Container(key: heroKey); - }, - ); - }), + path: '/a', + builder: (BuildContext context, _) { + return Hero( + tag: kHeroTag, + child: Container(), + flightShuttleBuilder: (_, __, ___, ____, _____) { + return Container(key: heroKey); + }, + ); + }, + ), GoRoute( - path: '/b', - builder: (BuildContext context, _) { - return Hero( - tag: kHeroTag, - child: Container(), - ); - }), + path: '/b', + builder: (BuildContext context, _) { + return Hero(tag: kHeroTag, child: Container()); + }, + ), ], - ) + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); // check that flightShuttleBuilder widget is not yet present expect(find.byKey(heroKey), findsNothing); @@ -5599,54 +6052,45 @@ void main() { }); group('of', () { - testWidgets( - 'It should return the go router instance of the widget tree', - (WidgetTester tester) async { - const Key key = Key('key'); - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const SizedBox(key: key), - ), - ]; + testWidgets('It should return the go router instance of the widget tree', ( + WidgetTester tester, + ) async { + const Key key = Key('key'); + final List routes = [ + GoRoute(path: '/', builder: (_, __) => const SizedBox(key: key)), + ]; - final GoRouter router = await createRouter(routes, tester); - final Element context = tester.element(find.byKey(key)); - final GoRouter foundRouter = GoRouter.of(context); - expect(foundRouter, router); - }, - ); + final GoRouter router = await createRouter(routes, tester); + final Element context = tester.element(find.byKey(key)); + final GoRouter foundRouter = GoRouter.of(context); + expect(foundRouter, router); + }); - testWidgets( - 'It should throw if there is no go router in the widget tree', - (WidgetTester tester) async { - const Key key = Key('key'); - await tester.pumpWidget(const SizedBox(key: key)); + testWidgets('It should throw if there is no go router in the widget tree', ( + WidgetTester tester, + ) async { + const Key key = Key('key'); + await tester.pumpWidget(const SizedBox(key: key)); - final Element context = tester.element(find.byKey(key)); - expect(() => GoRouter.of(context), throwsA(anything)); - }, - ); + final Element context = tester.element(find.byKey(key)); + expect(() => GoRouter.of(context), throwsA(anything)); + }); }); group('maybeOf', () { - testWidgets( - 'It should return the go router instance of the widget tree', - (WidgetTester tester) async { - const Key key = Key('key'); - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const SizedBox(key: key), - ), - ]; + testWidgets('It should return the go router instance of the widget tree', ( + WidgetTester tester, + ) async { + const Key key = Key('key'); + final List routes = [ + GoRoute(path: '/', builder: (_, __) => const SizedBox(key: key)), + ]; - final GoRouter router = await createRouter(routes, tester); - final Element context = tester.element(find.byKey(key)); - final GoRouter? foundRouter = GoRouter.maybeOf(context); - expect(foundRouter, router); - }, - ); + final GoRouter router = await createRouter(routes, tester); + final Element context = tester.element(find.byKey(key)); + final GoRouter? foundRouter = GoRouter.maybeOf(context); + expect(foundRouter, router); + }); testWidgets( 'It should return null if there is no go router in the widget tree', @@ -5669,24 +6113,35 @@ void main() { GoRoute( path: '/a', pageBuilder: createPageBuilder( - restorationId: 'screenA', child: const Text('Screen A')), + restorationId: 'screenA', + child: const Text('Screen A'), + ), routes: [ GoRoute( path: 'detail', pageBuilder: createPageBuilder( - restorationId: 'screenADetail', - child: Column(children: [ + restorationId: 'screenADetail', + child: Column( + children: [ const Text('Screen A Detail'), DummyRestorableStatefulWidget( - key: statefulWidgetKeyA, restorationId: 'counterA'), - ])), + key: statefulWidgetKeyA, + restorationId: 'counterA', + ), + ], + ), + ), ), ], ), ]; - await createRouter(routes, tester, - initialLocation: '/a/detail', restorationScopeId: 'test'); + await createRouter( + routes, + tester, + initialLocation: '/a/detail', + restorationScopeId: 'test', + ); await tester.pumpAndSettle(); statefulWidgetKeyA.currentState?.increment(); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); @@ -5699,8 +6154,9 @@ void main() { expect(statefulWidgetKeyA.currentState?.counter, equals(1)); }); - testWidgets('Restores state of branches in StatefulShellRoute correctly', - (WidgetTester tester) async { + testWidgets('Restores state of branches in StatefulShellRoute correctly', ( + WidgetTester tester, + ) async { final GlobalKey rootNavigatorKey = GlobalKey(); final GlobalKey statefulWidgetKeyA = @@ -5714,87 +6170,115 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', - pageBuilder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { routeState = navigationShell; return MaterialPage( - restorationId: 'shellWidget', child: navigationShell); + restorationId: 'shellWidget', + child: navigationShell, + ); }, branches: [ StatefulShellBranch( - restorationScopeId: 'branchA', - routes: [ - GoRoute( - path: '/a', - pageBuilder: createPageBuilder( - restorationId: 'screenA', - child: const Text('Screen A')), - routes: [ - GoRoute( - path: 'detailA', - pageBuilder: createPageBuilder( - restorationId: 'screenADetail', - child: Column(children: [ - const Text('Screen A Detail'), - DummyRestorableStatefulWidget( - key: statefulWidgetKeyA, - restorationId: 'counterA'), - ])), + restorationScopeId: 'branchA', + routes: [ + GoRoute( + path: '/a', + pageBuilder: createPageBuilder( + restorationId: 'screenA', + child: const Text('Screen A'), + ), + routes: [ + GoRoute( + path: 'detailA', + pageBuilder: createPageBuilder( + restorationId: 'screenADetail', + child: Column( + children: [ + const Text('Screen A Detail'), + DummyRestorableStatefulWidget( + key: statefulWidgetKeyA, + restorationId: 'counterA', + ), + ], + ), + ), + ), + ], + ), + ], + ), + StatefulShellBranch( + restorationScopeId: 'branchB', + routes: [ + GoRoute( + path: '/b', + pageBuilder: createPageBuilder( + restorationId: 'screenB', + child: const Text('Screen B'), + ), + routes: [ + GoRoute( + path: 'detailB', + pageBuilder: createPageBuilder( + restorationId: 'screenBDetail', + child: Column( + children: [ + const Text('Screen B Detail'), + DummyRestorableStatefulWidget( + key: statefulWidgetKeyB, + restorationId: 'counterB', + ), + ], + ), ), - ], - ), - ]), + ), + ], + ), + ], + ), StatefulShellBranch( - restorationScopeId: 'branchB', - routes: [ - GoRoute( - path: '/b', - pageBuilder: createPageBuilder( - restorationId: 'screenB', - child: const Text('Screen B')), - routes: [ - GoRoute( - path: 'detailB', - pageBuilder: createPageBuilder( - restorationId: 'screenBDetail', - child: Column(children: [ - const Text('Screen B Detail'), - DummyRestorableStatefulWidget( - key: statefulWidgetKeyB, - restorationId: 'counterB'), - ])), - ), - ], + routes: [ + GoRoute( + path: '/c', + pageBuilder: createPageBuilder( + restorationId: 'screenC', + child: const Text('Screen C'), ), - ]), - StatefulShellBranch(routes: [ - GoRoute( - path: '/c', - pageBuilder: createPageBuilder( - restorationId: 'screenC', child: const Text('Screen C')), - routes: [ - GoRoute( - path: 'detailC', - pageBuilder: createPageBuilder( + routes: [ + GoRoute( + path: 'detailC', + pageBuilder: createPageBuilder( restorationId: 'screenCDetail', - child: Column(children: [ - const Text('Screen C Detail'), - DummyRestorableStatefulWidget( + child: Column( + children: [ + const Text('Screen C Detail'), + DummyRestorableStatefulWidget( key: statefulWidgetKeyC, - restorationId: 'counterC'), - ])), - ), - ], - ), - ]), + restorationId: 'counterC', + ), + ], + ), + ), + ), + ], + ), + ], + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/a/detailA', - navigatorKey: rootNavigatorKey, - restorationScopeId: 'test'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + restorationScopeId: 'test', + ); await tester.pumpAndSettle(); statefulWidgetKeyA.currentState?.increment(); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); @@ -5832,172 +6316,205 @@ void main() { }); testWidgets( - 'Restores state of imperative routes in StatefulShellRoute correctly', - (WidgetTester tester) async { - final GlobalKey rootNavigatorKey = - GlobalKey(); - final GlobalKey statefulWidgetKeyA = - GlobalKey(); - final GlobalKey statefulWidgetKeyB = - GlobalKey(); - StatefulNavigationShell? routeStateRoot; - StatefulNavigationShell? routeStateNested; + 'Restores state of imperative routes in StatefulShellRoute correctly', + (WidgetTester tester) async { + final GlobalKey rootNavigatorKey = + GlobalKey(); + final GlobalKey statefulWidgetKeyA = + GlobalKey(); + final GlobalKey statefulWidgetKeyB = + GlobalKey(); + StatefulNavigationShell? routeStateRoot; + StatefulNavigationShell? routeStateNested; - final List routes = [ - StatefulShellRoute.indexedStack( - restorationScopeId: 'shell', - pageBuilder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { - routeStateRoot = navigationShell; - return MaterialPage( - restorationId: 'shellWidget', child: navigationShell); - }, - branches: [ - StatefulShellBranch( + final List routes = [ + StatefulShellRoute.indexedStack( + restorationScopeId: 'shell', + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeStateRoot = navigationShell; + return MaterialPage( + restorationId: 'shellWidget', + child: navigationShell, + ); + }, + branches: [ + StatefulShellBranch( restorationScopeId: 'branchA', routes: [ GoRoute( path: '/a', pageBuilder: createPageBuilder( - restorationId: 'screenA', - child: const Text('Screen A')), + restorationId: 'screenA', + child: const Text('Screen A'), + ), routes: [ GoRoute( path: 'detailA', pageBuilder: createPageBuilder( - restorationId: 'screenADetail', - child: Column(children: [ + restorationId: 'screenADetail', + child: Column( + children: [ const Text('Screen A Detail'), DummyRestorableStatefulWidget( - key: statefulWidgetKeyA, - restorationId: 'counterA'), - ])), + key: statefulWidgetKeyA, + restorationId: 'counterA', + ), + ], + ), + ), ), ], ), - ]), - StatefulShellBranch( + ], + ), + StatefulShellBranch( restorationScopeId: 'branchB', routes: [ StatefulShellRoute.indexedStack( - restorationScopeId: 'branchB-nested-shell', - pageBuilder: (BuildContext context, GoRouterState state, - StatefulNavigationShell navigationShell) { - routeStateNested = navigationShell; - return MaterialPage( - restorationId: 'shellWidget-nested', - child: navigationShell); - }, - branches: [ - StatefulShellBranch( - restorationScopeId: 'branchB-nested', - routes: [ + restorationScopeId: 'branchB-nested-shell', + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeStateNested = navigationShell; + return MaterialPage( + restorationId: 'shellWidget-nested', + child: navigationShell, + ); + }, + branches: [ + StatefulShellBranch( + restorationScopeId: 'branchB-nested', + routes: [ + GoRoute( + path: '/b', + pageBuilder: createPageBuilder( + restorationId: 'screenB', + child: const Text('Screen B'), + ), + routes: [ GoRoute( - path: '/b', + path: 'detailB', pageBuilder: createPageBuilder( - restorationId: 'screenB', - child: const Text('Screen B')), - routes: [ - GoRoute( - path: 'detailB', - pageBuilder: createPageBuilder( - restorationId: 'screenBDetail', - child: Column(children: [ - const Text('Screen B Detail'), - DummyRestorableStatefulWidget( - key: statefulWidgetKeyB, - restorationId: 'counterB'), - ])), + restorationId: 'screenBDetail', + child: Column( + children: [ + const Text('Screen B Detail'), + DummyRestorableStatefulWidget( + key: statefulWidgetKeyB, + restorationId: 'counterB', + ), + ], ), - ], - ), - ]), - StatefulShellBranch( - restorationScopeId: 'branchC-nested', - routes: [ - GoRoute( - path: '/c', - pageBuilder: createPageBuilder( - restorationId: 'screenC', - child: const Text('Screen C')), + ), ), - ]), - ]) - ]), - ], - ), - ]; + ], + ), + ], + ), + StatefulShellBranch( + restorationScopeId: 'branchC-nested', + routes: [ + GoRoute( + path: '/c', + pageBuilder: createPageBuilder( + restorationId: 'screenC', + child: const Text('Screen C'), + ), + ), + ], + ), + ], + ), + ], + ), + ], + ), + ]; - final GoRouter router = await createRouter(routes, tester, + final GoRouter router = await createRouter( + routes, + tester, initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey, - restorationScopeId: 'test'); - await tester.pumpAndSettle(); - statefulWidgetKeyA.currentState?.increment(); - expect(statefulWidgetKeyA.currentState?.counter, equals(1)); + restorationScopeId: 'test', + ); + await tester.pumpAndSettle(); + statefulWidgetKeyA.currentState?.increment(); + expect(statefulWidgetKeyA.currentState?.counter, equals(1)); - routeStateRoot!.goBranch(1); - await tester.pumpAndSettle(); + routeStateRoot!.goBranch(1); + await tester.pumpAndSettle(); - router.go('/b/detailB'); - await tester.pumpAndSettle(); - statefulWidgetKeyB.currentState?.increment(); - expect(statefulWidgetKeyB.currentState?.counter, equals(1)); + router.go('/b/detailB'); + await tester.pumpAndSettle(); + statefulWidgetKeyB.currentState?.increment(); + expect(statefulWidgetKeyB.currentState?.counter, equals(1)); - routeStateRoot!.goBranch(0); - await tester.pumpAndSettle(); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Pushed Detail'), findsNothing); + routeStateRoot!.goBranch(0); + await tester.pumpAndSettle(); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Pushed Detail'), findsNothing); - await tester.restartAndRestore(); + await tester.restartAndRestore(); - await tester.pumpAndSettle(); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Pushed Detail'), findsNothing); - expect(statefulWidgetKeyA.currentState?.counter, equals(1)); + await tester.pumpAndSettle(); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Pushed Detail'), findsNothing); + expect(statefulWidgetKeyA.currentState?.counter, equals(1)); - routeStateRoot!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Detail'), findsOneWidget); - expect(statefulWidgetKeyB.currentState?.counter, equals(1)); + routeStateRoot!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Detail'), findsOneWidget); + expect(statefulWidgetKeyB.currentState?.counter, equals(1)); - routeStateNested!.goBranch(1); - await tester.pumpAndSettle(); - routeStateNested!.goBranch(0); - await tester.pumpAndSettle(); + routeStateNested!.goBranch(1); + await tester.pumpAndSettle(); + routeStateNested!.goBranch(0); + await tester.pumpAndSettle(); - expect(find.text('Screen B Detail'), findsOneWidget); - expect(statefulWidgetKeyB.currentState?.counter, equals(1)); - }); + expect(find.text('Screen B Detail'), findsOneWidget); + expect(statefulWidgetKeyB.currentState?.counter, equals(1)); + }, + ); }); ///Regression tests for https://github.com/flutter/flutter/issues/132557 group('overridePlatformDefaultLocation', () { test('No initial location provided', () { expect( - () => GoRouter( - overridePlatformDefaultLocation: true, - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), - ), - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), - ), - ], - ), - throwsA(const TypeMatcher())); + () => GoRouter( + overridePlatformDefaultLocation: true, + routes: [ + GoRoute( + path: '/a', + builder: + (BuildContext context, GoRouterState state) => + const Placeholder(), + ), + GoRoute( + path: '/b', + builder: + (BuildContext context, GoRouterState state) => + const Placeholder(), + ), + ], + ), + throwsA(const TypeMatcher()), + ); }); - testWidgets('Test override using routeInformationProvider', - (WidgetTester tester) async { + testWidgets('Test override using routeInformationProvider', ( + WidgetTester tester, + ) async { tester.binding.platformDispatcher.defaultRouteNameTestValue = '/some-route'; final String platformRoute = @@ -6008,13 +6525,15 @@ 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(), ), ]; @@ -6024,153 +6543,165 @@ void main() { overridePlatformDefaultLocation: true, initialLocation: expectedInitialRoute, ); - expect(router.routeInformationProvider.value.uri.toString(), - expectedInitialRoute); + expect( + router.routeInformationProvider.value.uri.toString(), + expectedInitialRoute, + ); }); }); testWidgets( - 'test the pathParameters in redirect when the Router is recreated', - (WidgetTester tester) async { - final GoRouter router = GoRouter( - initialLocation: '/foo', - routes: [ - GoRoute( - path: '/foo', - builder: dummy, - routes: [ - GoRoute( - path: ':id', - redirect: (_, GoRouterState state) { - expect(state.pathParameters['id'], isNotNull); - return null; - }, - builder: dummy, - ), - ], - ), - ], - ); - addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router( - key: UniqueKey(), - routerConfig: router, - ), - ); - router.push('/foo/123'); - await tester.pump(); // wait reportRouteInformation - await tester.pumpWidget( - MaterialApp.router( - key: UniqueKey(), - routerConfig: router, - ), - ); - }); + 'test the pathParameters in redirect when the Router is recreated', + (WidgetTester tester) async { + final GoRouter router = GoRouter( + initialLocation: '/foo', + routes: [ + GoRoute( + path: '/foo', + builder: dummy, + routes: [ + GoRoute( + path: ':id', + redirect: (_, GoRouterState state) { + expect(state.pathParameters['id'], isNotNull); + return null; + }, + builder: dummy, + ), + ], + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + MaterialApp.router(key: UniqueKey(), routerConfig: router), + ); + router.push('/foo/123'); + await tester.pump(); // wait reportRouteInformation + await tester.pumpWidget( + MaterialApp.router(key: UniqueKey(), routerConfig: router), + ); + }, + ); testWidgets( - 'should return the current GoRouterState when router.currentState is called', - (WidgetTester tester) async { - final List routes = [ - GoRoute( + 'should return the current GoRouterState when router.currentState is called', + (WidgetTester tester) async { + final List routes = [ + GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen()), - GoRoute( + builder: + (BuildContext context, GoRouterState state) => const HomeScreen(), + ), + GoRoute( name: 'books', path: '/books', - builder: (BuildContext context, GoRouterState state) => - const Text('books')), - GoRoute( + builder: + (BuildContext context, GoRouterState state) => + const Text('books'), + ), + GoRoute( name: 'boats', path: '/boats', - builder: (BuildContext context, GoRouterState state) => - const Text('boats')), - ShellRoute( - 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('boats'), + ), + ShellRoute( + builder: + (BuildContext context, GoRouterState state, Widget child) => + child, + routes: [ + GoRoute( + name: 'tulips', + path: '/tulips', + builder: + (BuildContext context, GoRouterState state) => + const Text('tulips'), + ), + ], + ), + ]; - final GoRouter router = await createRouter(routes, tester); - await tester.pumpAndSettle(); + final GoRouter router = await createRouter(routes, tester); + await tester.pumpAndSettle(); - GoRouterState? state = router.state; - expect(state.name, 'home'); - expect(state.fullPath, '/'); + GoRouterState? state = router.state; + expect(state.name, 'home'); + expect(state.fullPath, '/'); - router.go('/books'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'books'); - expect(state.fullPath, '/books'); + router.go('/books'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'books'); + expect(state.fullPath, '/books'); - router.push('/boats'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'boats'); - expect(state.fullPath, '/boats'); + router.push('/boats'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'boats'); + expect(state.fullPath, '/boats'); - router.pop(); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'books'); - expect(state.fullPath, '/books'); + router.pop(); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'books'); + expect(state.fullPath, '/books'); - router.go('/tulips'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'tulips'); - expect(state.fullPath, '/tulips'); + router.go('/tulips'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'tulips'); + expect(state.fullPath, '/tulips'); - router.go('/books'); - router.push('/tulips'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'tulips'); - expect(state.fullPath, '/tulips'); - }); + router.go('/books'); + router.push('/tulips'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'tulips'); + expect(state.fullPath, '/tulips'); + }, + ); - testWidgets('should allow route paths without leading /', - (WidgetTester tester) async { + testWidgets('should allow route paths without leading /', ( + WidgetTester tester, + ) async { 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', ), ], - ) + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/child-route/grand-child-route'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/child-route/grand-child-route', + ); RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(3)); expect(matches.uri.toString(), '/child-route/grand-child-route'); @@ -6184,37 +6715,44 @@ void main() { expect(find.text('/child-route'), findsOneWidget); }); - testWidgets('should allow route paths with leading /', - (WidgetTester tester) async { + testWidgets('should allow route paths with leading /', ( + WidgetTester tester, + ) async { 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', ), ], - ) + ), ], ), ]; - final GoRouter router = await createRouter(routes, tester, - initialLocation: '/child-route/grand-child-route'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/child-route/grand-child-route', + ); RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(3)); expect(matches.uri.toString(), '/child-route/grand-child-route'); diff --git a/packages/go_router/test/helpers/error_screen_helpers.dart b/packages/go_router/test/helpers/error_screen_helpers.dart index 56f03e9fd38..e781f551c9b 100644 --- a/packages/go_router/test/helpers/error_screen_helpers.dart +++ b/packages/go_router/test/helpers/error_screen_helpers.dart @@ -36,10 +36,7 @@ WidgetTesterCallback testClickingTheButtonRedirectsToRoot({ initialLocation: '/error', routes: [ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), - GoRoute( - path: '/error', - builder: (_, __) => widget, - ), + GoRoute(path: '/error', builder: (_, __) => widget), ], ); addTearDown(router.dispose); @@ -51,15 +48,9 @@ WidgetTesterCallback testClickingTheButtonRedirectsToRoot({ } Widget materialAppRouterBuilder(GoRouter router) { - return MaterialApp.router( - routerConfig: router, - title: 'GoRouter Example', - ); + return MaterialApp.router(routerConfig: router, title: 'GoRouter Example'); } Widget cupertinoAppRouterBuilder(GoRouter router) { - return CupertinoApp.router( - routerConfig: router, - title: 'GoRouter Example', - ); + return CupertinoApp.router(routerConfig: router, title: 'GoRouter Example'); } diff --git a/packages/go_router/test/imperative_api_test.dart b/packages/go_router/test/imperative_api_test.dart index 0598acf00bb..b7cb22712bc 100644 --- a/packages/go_router/test/imperative_api_test.dart +++ b/packages/go_router/test/imperative_api_test.dart @@ -22,19 +22,16 @@ 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)), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); @@ -51,10 +48,7 @@ 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( @@ -63,15 +57,15 @@ void main() { ); }, routes: [ - GoRoute( - path: '/b', - builder: (_, __) => DummyScreen(key: b), - ), + GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); expect(find.text('shell'), findsNothing); expect(find.byKey(a), findsOneWidget); @@ -83,8 +77,9 @@ void main() { expect(find.byKey(b), findsOneWidget); }); - testWidgets('shell route reflect imperative push', - (WidgetTester tester) async { + testWidgets('shell route reflect imperative push', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/125752. final UniqueKey home = UniqueKey(); final UniqueKey a = UniqueKey(); @@ -98,19 +93,20 @@ void main() { }, routes: [ GoRoute( - path: '/', - builder: (_, __) => DummyScreen(key: home), - routes: [ - GoRoute( - path: 'a', - builder: (_, __) => DummyScreen(key: a), - ), - ]), + path: '/', + builder: (_, __) => DummyScreen(key: home), + routes: [ + GoRoute(path: 'a', builder: (_, __) => DummyScreen(key: a)), + ], + ), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); expect(find.text('location: /a'), findsOneWidget); expect(find.byKey(a), findsOneWidget); @@ -128,8 +124,9 @@ void main() { expect(find.byKey(home), findsNothing); }); - testWidgets('push shell route in another shell route', - (WidgetTester tester) async { + testWidgets('push shell route in another shell route', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/120791. final UniqueKey b = UniqueKey(); final UniqueKey a = UniqueKey(); @@ -142,10 +139,7 @@ void main() { ); }, routes: [ - GoRoute( - path: '/a', - builder: (_, __) => DummyScreen(key: a), - ), + GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), ], ), ShellRoute( @@ -156,15 +150,15 @@ void main() { ); }, routes: [ - GoRoute( - path: '/b', - builder: (_, __) => DummyScreen(key: b), - ), + GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); expect(find.text('shell1'), findsOneWidget); expect(find.byKey(a), findsOneWidget); @@ -177,8 +171,9 @@ void main() { expect(find.byKey(b), findsOneWidget); }); - testWidgets('push inside or outside shell route', - (WidgetTester tester) async { + testWidgets('push inside or outside shell route', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/120665. final UniqueKey inside = UniqueKey(); final UniqueKey outside = UniqueKey(); @@ -191,19 +186,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, tester, initialLocation: '/out'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/out', + ); expect(find.text('shell'), findsNothing); expect(find.byKey(outside), findsOneWidget); @@ -237,33 +229,24 @@ 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, tester, initialLocation: '/a'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + ); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); diff --git a/packages/go_router/test/information_provider_test.dart b/packages/go_router/test/information_provider_test.dart index 2bdb0e6178f..24d6ed2da38 100644 --- a/packages/go_router/test/information_provider_test.dart +++ b/packages/go_router/test/information_provider_test.dart @@ -12,29 +12,37 @@ const String newRoute = '/new'; void main() { group('GoRouteInformationProvider', () { - testWidgets('notifies its listeners when set by the app', - (WidgetTester tester) async { + testWidgets('notifies its listeners when set by the app', ( + WidgetTester tester, + ) async { late final GoRouteInformationProvider provider = GoRouteInformationProvider( - initialLocation: initialRoute, initialExtra: null); + initialLocation: initialRoute, + initialExtra: null, + ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); provider.go(newRoute); }); - testWidgets('notifies its listeners when set by the platform', - (WidgetTester tester) async { + testWidgets('notifies its listeners when set by the platform', ( + WidgetTester tester, + ) async { late final GoRouteInformationProvider provider = GoRouteInformationProvider( - initialLocation: initialRoute, initialExtra: null); + initialLocation: initialRoute, + initialExtra: null, + ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); - provider - .didPushRouteInformation(RouteInformation(uri: Uri.parse(newRoute))); + provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse(newRoute)), + ); }); - testWidgets('didPushRouteInformation maintains uri scheme and host', - (WidgetTester tester) async { + testWidgets('didPushRouteInformation maintains uri scheme and host', ( + WidgetTester tester, + ) async { const String expectedScheme = 'https'; const String expectedHost = 'www.example.com'; const String expectedPath = '/some/path'; @@ -42,19 +50,23 @@ void main() { '$expectedScheme://$expectedHost$expectedPath'; late final GoRouteInformationProvider provider = GoRouteInformationProvider( - initialLocation: initialRoute, initialExtra: null); + initialLocation: initialRoute, + initialExtra: null, + ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); provider.didPushRouteInformation( - RouteInformation(uri: Uri.parse(expectedUriString))); + RouteInformation(uri: Uri.parse(expectedUriString)), + ); expect(provider.value.uri.scheme, 'https'); expect(provider.value.uri.host, 'www.example.com'); expect(provider.value.uri.path, '/some/path'); expect(provider.value.uri.toString(), expectedUriString); }); - testWidgets('didPushRoute maintains uri scheme and host', - (WidgetTester tester) async { + testWidgets('didPushRoute maintains uri scheme and host', ( + WidgetTester tester, + ) async { const String expectedScheme = 'https'; const String expectedHost = 'www.example.com'; const String expectedPath = '/some/path'; @@ -62,50 +74,58 @@ void main() { '$expectedScheme://$expectedHost$expectedPath'; late final GoRouteInformationProvider provider = GoRouteInformationProvider( - initialLocation: initialRoute, initialExtra: null); + initialLocation: initialRoute, + initialExtra: null, + ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); provider.didPushRouteInformation( - RouteInformation(uri: Uri.parse(expectedUriString))); + RouteInformation(uri: Uri.parse(expectedUriString)), + ); expect(provider.value.uri.scheme, 'https'); expect(provider.value.uri.host, 'www.example.com'); expect(provider.value.uri.path, '/some/path'); expect(provider.value.uri.toString(), expectedUriString); }); - testWidgets('Route is correctly neglected when routerNeglect is true', - (WidgetTester tester) async { + testWidgets('Route is correctly neglected when routerNeglect is true', ( + WidgetTester tester, + ) async { final _SystemChannelsNavigationMock systemChannelsMock = _SystemChannelsNavigationMock(); late final GoRouteInformationProvider provider = GoRouteInformationProvider( - initialLocation: initialRoute, - initialExtra: null, - routerNeglect: true); + initialLocation: initialRoute, + initialExtra: null, + routerNeglect: true, + ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); provider.go(newRoute); provider.routerReportsNewRouteInformation( - RouteInformation( - uri: Uri.parse(newRoute), state: {}), - type: RouteInformationReportingType.navigate); + RouteInformation(uri: Uri.parse(newRoute), state: {}), + type: RouteInformationReportingType.navigate, + ); expect(systemChannelsMock.uriIsNeglected[newRoute], true); }); - testWidgets('Route is NOT neglected when routerNeglect is false', - (WidgetTester tester) async { + testWidgets('Route is NOT neglected when routerNeglect is false', ( + WidgetTester tester, + ) async { final _SystemChannelsNavigationMock systemChannelsMock = _SystemChannelsNavigationMock(); late final GoRouteInformationProvider provider = GoRouteInformationProvider( - initialLocation: initialRoute, initialExtra: null); + initialLocation: initialRoute, + initialExtra: null, + ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); provider.go(newRoute); provider.routerReportsNewRouteInformation( - RouteInformation( - uri: Uri.parse(newRoute), state: {}), - type: RouteInformationReportingType.navigate); + RouteInformation(uri: Uri.parse(newRoute), state: {}), + type: RouteInformationReportingType.navigate, + ); expect(systemChannelsMock.uriIsNeglected[newRoute], false); }); }); @@ -114,18 +134,19 @@ void main() { class _SystemChannelsNavigationMock { _SystemChannelsNavigationMock() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.navigation, - (MethodCall methodCall) async { - if (methodCall.method == 'routeInformationUpdated' && - methodCall.arguments is Map) { - final Map args = - methodCall.arguments as Map; - final String? uri = - args['location'] as String? ?? args['uri'] as String?; - uriIsNeglected[uri ?? ''] = args['replace'] as bool; - } - return null; - }); + .setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { + if (methodCall.method == 'routeInformationUpdated' && + methodCall.arguments is Map) { + final Map args = + methodCall.arguments as Map; + final String? uri = + args['location'] as String? ?? args['uri'] as String?; + uriIsNeglected[uri ?? ''] = args['replace'] as bool; + } + return null; + }); } Map uriIsNeglected = {}; diff --git a/packages/go_router/test/inherited_test.dart b/packages/go_router/test/inherited_test.dart index a5902d47dfe..a8dfa62e970 100644 --- a/packages/go_router/test/inherited_test.dart +++ b/packages/go_router/test/inherited_test.dart @@ -14,10 +14,7 @@ void main() { test('does not update when goRouter does not change', () { final GoRouter goRouter = GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, __) => const Page1(), - ), + GoRoute(path: '/', builder: (_, __) => const Page1()), ], ); final bool shouldNotify = setupInheritedGoRouterChange( @@ -30,18 +27,12 @@ void main() { test('does not update even when goRouter changes', () { final GoRouter oldGoRouter = GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, __) => const Page1(), - ), + GoRoute(path: '/', builder: (_, __) => const Page1()), ], ); final GoRouter newGoRouter = GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, __) => const Page2(), - ), + GoRoute(path: '/', builder: (_, __) => const Page2()), ], ); final bool shouldNotify = setupInheritedGoRouterChange( @@ -54,12 +45,7 @@ void main() { test('adds [goRouter] as a diagnostics property', () { final GoRouter goRouter = GoRouter( - routes: [ - GoRoute( - path: '/', - builder: (_, __) => const Page1(), - ), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Page1())], ); final InheritedGoRouter inheritedGoRouter = InheritedGoRouter( goRouter: goRouter, @@ -73,11 +59,15 @@ void main() { expect(properties.properties.first.value, goRouter); }); - testWidgets("mediates Widget's access to GoRouter.", - (WidgetTester tester) async { + testWidgets("mediates Widget's access to GoRouter.", ( + WidgetTester tester, + ) async { final MockGoRouter router = MockGoRouter(); - await tester.pumpWidget(MaterialApp( - home: InheritedGoRouter(goRouter: router, child: const _MyWidget()))); + await tester.pumpWidget( + MaterialApp( + home: InheritedGoRouter(goRouter: router, child: const _MyWidget()), + ), + ); await tester.tap(find.text('My Page')); expect(router.latestPushedName, 'my_page'); }); @@ -94,16 +84,17 @@ void main() { buildContextRouter = GoRouter.of(context); return const DummyScreen(); }, - ) + ), ], ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate), + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), ); expect(buildContextRouter, isNotNull); @@ -123,9 +114,7 @@ bool setupInheritedGoRouterChange({ goRouter: newGoRouter, child: Container(), ); - return newInheritedGoRouter.updateShouldNotify( - oldInheritedGoRouter, - ); + return newInheritedGoRouter.updateShouldNotify(oldInheritedGoRouter); } class Page1 extends StatelessWidget { @@ -148,24 +137,29 @@ class _MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ElevatedButton( - onPressed: () => context.pushNamed('my_page'), - child: const Text('My Page')); + onPressed: () => context.pushNamed('my_page'), + child: const Text('My Page'), + ); } } class MockGoRouter extends GoRouter { MockGoRouter() - : super.routingConfig( - routingConfig: const ConstantRoutingConfig( - RoutingConfig(routes: []))); + : super.routingConfig( + routingConfig: const ConstantRoutingConfig( + RoutingConfig(routes: []), + ), + ); late String latestPushedName; @override - Future pushNamed(String name, - {Map pathParameters = const {}, - Map queryParameters = const {}, - Object? extra}) { + Future pushNamed( + String name, { + Map pathParameters = const {}, + Map queryParameters = const {}, + Object? extra, + }) { latestPushedName = name; return Future.value(); } diff --git a/packages/go_router/test/logging_test.dart b/packages/go_router/test/logging_test.dart index d3251ee1b14..d72347d2b28 100644 --- a/packages/go_router/test/logging_test.dart +++ b/packages/go_router/test/logging_test.dart @@ -34,10 +34,8 @@ void main() { 'It should not log anything the if debugLogDiagnostics is false', (WidgetTester tester) async { testDeveloperLog = expectAsync1((LogRecord data) {}, count: 0); - final StreamSubscription subscription = - Logger.root.onRecord.listen( - expectAsync1((LogRecord data) {}, count: 0), - ); + final StreamSubscription subscription = Logger.root.onRecord + .listen(expectAsync1((LogRecord data) {}, count: 0)); addTearDown(subscription.cancel); GoRouter( routes: [ @@ -59,9 +57,7 @@ void main() { reason: 'Go router should log the 2 events', ); final List logs = []; - Logger.root.onRecord.listen( - (LogRecord event) => logs.add(event.message), - ); + Logger.root.onRecord.listen((LogRecord event) => logs.add(event.message)); GoRouter( debugLogDiagnostics: true, routes: [ @@ -72,14 +68,10 @@ void main() { ], ); - expect( - logs, - const [ - 'Full paths for routes:\n└─/ (Text)\n', - 'setting initial location null' - ], - reason: 'Go router should have sent the 2 events to the logger', - ); + expect(logs, const [ + 'Full paths for routes:\n└─/ (Text)\n', + 'setting initial location null', + ], reason: 'Go router should have sent the 2 events to the logger'); }, ); @@ -94,9 +86,7 @@ void main() { hierarchicalLoggingEnabled = true; final List logs = []; - Logger.root.onRecord.listen( - (LogRecord event) => logs.add(event.message), - ); + Logger.root.onRecord.listen((LogRecord event) => logs.add(event.message)); GoRouter( debugLogDiagnostics: true, routes: [ @@ -107,14 +97,10 @@ void main() { ], ); - expect( - logs, - const [ - 'Full paths for routes:\n└─/ (Text)\n', - 'setting initial location null' - ], - reason: 'Go router should have sent the 2 events to the logger', - ); + expect(logs, const [ + 'Full paths for routes:\n└─/ (Text)\n', + 'setting initial location null', + ], reason: 'Go router should have sent the 2 events to the logger'); }, ); } diff --git a/packages/go_router/test/match_test.dart b/packages/go_router/test/match_test.dart index 57951b2ae23..f0af7290e15 100644 --- a/packages/go_router/test/match_test.dart +++ b/packages/go_router/test/match_test.dart @@ -11,10 +11,7 @@ import 'package:go_router/go_router.dart'; void main() { group('RouteMatch', () { test('simple', () { - final GoRoute route = GoRoute( - path: '/users/:userId', - builder: _builder, - ); + final GoRoute route = GoRoute(path: '/users/:userId', builder: _builder); final Map pathParameters = {}; final List matches = RouteMatchBase.match( route: route, @@ -33,12 +30,7 @@ void main() { test('ShellRoute has a unique pageKey', () { final ShellRoute route = ShellRoute( builder: _shellBuilder, - routes: [ - GoRoute( - path: '/users/:userId', - builder: _builder, - ), - ], + routes: [GoRoute(path: '/users/:userId', builder: _builder)], ); final Map pathParameters = {}; final List matches = RouteMatchBase.match( @@ -54,12 +46,7 @@ void main() { test('ShellRoute Match has stable unique key', () { final ShellRoute route = ShellRoute( builder: _shellBuilder, - routes: [ - GoRoute( - path: '/users/:userId', - builder: _builder, - ), - ], + routes: [GoRoute(path: '/users/:userId', builder: _builder)], ); final Map pathParameters = {}; final List matches1 = RouteMatchBase.match( @@ -80,10 +67,7 @@ void main() { }); test('GoRoute Match has stable unique key', () { - final GoRoute route = GoRoute( - path: '/users/:userId', - builder: _builder, - ); + final GoRoute route = GoRoute(path: '/users/:userId', builder: _builder); final Map pathParameters = {}; final List matches1 = RouteMatchBase.match( route: route, @@ -160,11 +144,7 @@ void main() { expect(matches.length, 4); expect( matches[0].route, - isA().having( - (GoRoute route) => route.path, - 'path', - '/', - ), + isA().having((GoRoute route) => route.path, 'path', '/'), ); expect( matches[1].route, @@ -176,44 +156,38 @@ void main() { ); expect( matches[2].route, - isA().having( - (GoRoute route) => route.path, - 'path', - 'b', - ), + isA().having((GoRoute route) => route.path, 'path', 'b'), ); expect( matches[3].route, - isA().having( - (GoRoute route) => route.path, - 'path', - 'd', - ), + isA().having((GoRoute route) => route.path, 'path', 'd'), ); }); group('ImperativeRouteMatch', () { final RouteMatchList matchList1 = RouteMatchList( - matches: [ - RouteMatch( - route: GoRoute(path: '/', builder: (_, __) => const Text('hi')), - matchedLocation: '/', - pageKey: const ValueKey('dummy'), - ), - ], - uri: Uri.parse('/'), - pathParameters: const {}); + matches: [ + RouteMatch( + route: GoRoute(path: '/', builder: (_, __) => const Text('hi')), + matchedLocation: '/', + pageKey: const ValueKey('dummy'), + ), + ], + uri: Uri.parse('/'), + pathParameters: const {}, + ); final RouteMatchList matchList2 = RouteMatchList( - matches: [ - RouteMatch( - route: GoRoute(path: '/a', builder: (_, __) => const Text('a')), - matchedLocation: '/a', - pageKey: const ValueKey('dummy'), - ), - ], - uri: Uri.parse('/a'), - pathParameters: const {}); + matches: [ + RouteMatch( + route: GoRoute(path: '/a', builder: (_, __) => const Text('a')), + matchedLocation: '/a', + pageKey: const ValueKey('dummy'), + ), + ], + uri: Uri.parse('/a'), + pathParameters: const {}, + ); const ValueKey key1 = ValueKey('key1'); const ValueKey key2 = ValueKey('key2'); @@ -223,30 +197,54 @@ void main() { test('can equal and has', () async { ImperativeRouteMatch match1 = ImperativeRouteMatch( - pageKey: key1, matches: matchList1, completer: completer1); + pageKey: key1, + matches: matchList1, + completer: completer1, + ); ImperativeRouteMatch match2 = ImperativeRouteMatch( - pageKey: key1, matches: matchList1, completer: completer1); + pageKey: key1, + matches: matchList1, + completer: completer1, + ); expect(match1 == match2, isTrue); expect(match1.hashCode == match2.hashCode, isTrue); match1 = ImperativeRouteMatch( - pageKey: key1, matches: matchList1, completer: completer1); + pageKey: key1, + matches: matchList1, + completer: completer1, + ); match2 = ImperativeRouteMatch( - pageKey: key2, matches: matchList1, completer: completer1); + pageKey: key2, + matches: matchList1, + completer: completer1, + ); expect(match1 == match2, isFalse); expect(match1.hashCode == match2.hashCode, isFalse); match1 = ImperativeRouteMatch( - pageKey: key1, matches: matchList1, completer: completer1); + pageKey: key1, + matches: matchList1, + completer: completer1, + ); match2 = ImperativeRouteMatch( - pageKey: key1, matches: matchList2, completer: completer1); + pageKey: key1, + matches: matchList2, + completer: completer1, + ); expect(match1 == match2, isFalse); expect(match1.hashCode == match2.hashCode, isFalse); match1 = ImperativeRouteMatch( - pageKey: key1, matches: matchList1, completer: completer1); + pageKey: key1, + matches: matchList1, + completer: completer1, + ); match2 = ImperativeRouteMatch( - pageKey: key1, matches: matchList1, completer: completer2); + pageKey: key1, + matches: matchList1, + completer: completer2, + ); expect(match1 == match2, isFalse); expect(match1.hashCode == match2.hashCode, isFalse); }); diff --git a/packages/go_router/test/matching_test.dart b/packages/go_router/test/matching_test.dart index f2dffbd3de1..df49cdad4bc 100644 --- a/packages/go_router/test/matching_test.dart +++ b/packages/go_router/test/matching_test.dart @@ -12,17 +12,22 @@ import 'package:go_router/src/match.dart'; import 'test_helpers.dart'; void main() { - testWidgets('RouteMatchList toString prints the fullPath', - (WidgetTester tester) async { + testWidgets('RouteMatchList toString prints the fullPath', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/page-0', - builder: (BuildContext context, GoRouterState state) => - const Placeholder()), + path: '/page-0', + builder: + (BuildContext context, GoRouterState state) => const Placeholder(), + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/page-0'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/page-0', + ); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.toString(), contains('/page-0')); @@ -31,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( @@ -77,13 +82,15 @@ 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, @@ -94,10 +101,13 @@ void main() { final RouteMatchList list1 = configuration.findMatch(Uri.parse('/a')); final RouteMatchList list2 = configuration.findMatch(Uri.parse('/b')); - list1.push(ImperativeRouteMatch( + list1.push( + ImperativeRouteMatch( pageKey: const ValueKey('/b-p0'), matches: list2, - completer: Completer())); + completer: Completer(), + ), + ); final Map encoded = codec.encode(list1); final RouteMatchList decoded = codec.decode(encoded); diff --git a/packages/go_router/test/material_test.dart b/packages/go_router/test/material_test.dart index 4da273ea7b0..01a95d59780 100644 --- a/packages/go_router/test/material_test.dart +++ b/packages/go_router/test/material_test.dart @@ -11,27 +11,23 @@ import 'helpers/error_screen_helpers.dart'; void main() { group('isMaterialApp', () { - testWidgets('returns [true] when MaterialApp is present', - (WidgetTester tester) async { + testWidgets('returns [true] when MaterialApp is present', ( + WidgetTester tester, + ) async { final GlobalKey<_DummyStatefulWidgetState> key = GlobalKey<_DummyStatefulWidgetState>(); - await tester.pumpWidget( - MaterialApp( - home: DummyStatefulWidget(key: key), - ), - ); + await tester.pumpWidget(MaterialApp(home: DummyStatefulWidget(key: key))); final bool isMaterial = isMaterialApp(key.currentContext! as Element); expect(isMaterial, true); }); - testWidgets('returns [false] when CupertinoApp is present', - (WidgetTester tester) async { + testWidgets('returns [false] when CupertinoApp is present', ( + WidgetTester tester, + ) async { final GlobalKey<_DummyStatefulWidgetState> key = GlobalKey<_DummyStatefulWidgetState>(); await tester.pumpWidget( - CupertinoApp( - home: DummyStatefulWidget(key: key), - ), + CupertinoApp(home: DummyStatefulWidget(key: key)), ); final bool isMaterial = isMaterialApp(key.currentContext! as Element); expect(isMaterial, false); @@ -62,9 +58,7 @@ void main() { testWidgets( 'shows "page not found" by default', testPageNotFound( - widget: const MaterialApp( - home: MaterialErrorScreen(null), - ), + widget: const MaterialApp(home: MaterialErrorScreen(null)), ), ); @@ -73,9 +67,7 @@ void main() { 'shows the exception message when provided', testPageShowsExceptionMessage( exception: exception, - widget: MaterialApp( - home: MaterialErrorScreen(exception), - ), + widget: MaterialApp(home: MaterialErrorScreen(exception)), ), ); @@ -83,9 +75,7 @@ void main() { 'clicking the TextButton should redirect to /', testClickingTheButtonRedirectsToRoot( buttonFinder: find.byType(TextButton), - widget: const MaterialApp( - home: MaterialErrorScreen(null), - ), + widget: const MaterialApp(home: MaterialErrorScreen(null)), ), ); }); diff --git a/packages/go_router/test/name_case_test.dart b/packages/go_router/test/name_case_test.dart index d2323c34653..29d25b840b8 100644 --- a/packages/go_router/test/name_case_test.dart +++ b/packages/go_router/test/name_case_test.dart @@ -7,45 +7,35 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; void main() { - testWidgets( - 'Route names are case sensitive', - (WidgetTester tester) async { - // config router with 2 routes with the same name but different case (Name, name) - final GoRouter router = GoRouter( - routes: [ - GoRoute( - path: '/', - name: 'Name', - builder: (_, __) => const ScreenA(), - ), - GoRoute( - path: '/path', - name: 'name', - builder: (_, __) => const ScreenB(), - ), - ], - ); - addTearDown(router.dispose); - - // run MaterialApp, initial screen path is '/' -> ScreenA - await tester.pumpWidget( - MaterialApp.router( - routerConfig: router, - title: 'GoRouter Testcase', + testWidgets('Route names are case sensitive', (WidgetTester tester) async { + // config router with 2 routes with the same name but different case (Name, name) + final GoRouter router = GoRouter( + routes: [ + GoRoute(path: '/', name: 'Name', builder: (_, __) => const ScreenA()), + GoRoute( + path: '/path', + name: 'name', + builder: (_, __) => const ScreenB(), ), - ); - - // go to ScreenB - router.goNamed('name'); - await tester.pumpAndSettle(); - expect(find.byType(ScreenB), findsOneWidget); - - // go to ScreenA - router.goNamed('Name'); - await tester.pumpAndSettle(); - expect(find.byType(ScreenA), findsOneWidget); - }, - ); + ], + ); + addTearDown(router.dispose); + + // run MaterialApp, initial screen path is '/' -> ScreenA + await tester.pumpWidget( + MaterialApp.router(routerConfig: router, title: 'GoRouter Testcase'), + ); + + // go to ScreenB + router.goNamed('name'); + await tester.pumpAndSettle(); + expect(find.byType(ScreenB), findsOneWidget); + + // go to ScreenA + router.goNamed('Name'); + await tester.pumpAndSettle(); + expect(find.byType(ScreenA), findsOneWidget); + }); } class ScreenA extends StatelessWidget { diff --git a/packages/go_router/test/on_exit_test.dart b/packages/go_router/test/on_exit_test.dart index 8a7bd83ab64..e9afa81ae46 100644 --- a/packages/go_router/test/on_exit_test.dart +++ b/packages/go_router/test/on_exit_test.dart @@ -18,23 +18,28 @@ 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; }, - ) + ), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/1'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/1', + ); expect(find.byKey(page1), findsOneWidget); router.pop(); @@ -54,21 +59,26 @@ 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; }, - ) + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/1'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/1', + ); expect(find.byKey(page1), findsOneWidget); router.go('/'); @@ -88,23 +98,28 @@ 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; }, - ) + ), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/1'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/1', + ); expect(find.byKey(page1), findsOneWidget); router.pop(); @@ -132,21 +147,26 @@ 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; }, - ) + ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/1'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/1', + ); expect(find.byKey(page1), findsOneWidget); router.go('/'); @@ -167,15 +187,17 @@ void main() { expect(find.byKey(home), findsOneWidget); }); - testWidgets('android back button respects the last route.', - (WidgetTester tester) async { + testWidgets('android back button respects the last route.', ( + WidgetTester tester, + ) async { bool allow = false; final UniqueKey home = UniqueKey(); 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; }, @@ -192,15 +214,17 @@ void main() { expect(await router.routerDelegate.popRoute(), false); }); - testWidgets('android back button respects the last route. async', - (WidgetTester tester) async { + testWidgets('android back button respects the last route. async', ( + WidgetTester tester, + ) async { bool allow = false; final UniqueKey home = UniqueKey(); 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; }, @@ -217,21 +241,26 @@ void main() { expect(await router.routerDelegate.popRoute(), false); }); - testWidgets('android back button respects the last route with shell route.', - (WidgetTester tester) async { + testWidgets('android back button respects the last route with shell route.', ( + WidgetTester tester, + ) async { bool allow = false; final UniqueKey home = UniqueKey(); final List routes = [ - ShellRoute(builder: (_, __, Widget child) => child, routes: [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), - onExit: (BuildContext context, GoRouterState state) { - return allow; - }, - ), - ]) + ShellRoute( + builder: (_, __, Widget child) => child, + routes: [ + GoRoute( + path: '/', + builder: + (BuildContext context, GoRouterState state) => + DummyScreen(key: home), + onExit: (BuildContext context, GoRouterState state) { + return allow; + }, + ), + ], + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -244,8 +273,9 @@ void main() { expect(await router.routerDelegate.popRoute(), false); }); - testWidgets('It should provide the correct uri to the onExit callback', - (WidgetTester tester) async { + testWidgets('It should provide the correct uri to the onExit callback', ( + WidgetTester tester, + ) async { final UniqueKey home = UniqueKey(); final UniqueKey page1 = UniqueKey(); final UniqueKey page2 = UniqueKey(); @@ -256,13 +286,15 @@ 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; @@ -270,8 +302,9 @@ 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; @@ -279,23 +312,27 @@ 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; }, - ) + ), ], - ) + ), ], - ) + ), ], ), ]; - final GoRouter router = - await createRouter(routes, tester, initialLocation: '/1/2/3'); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/1/2/3', + ); expect(find.byKey(page3), findsOneWidget); router.pop(); @@ -328,13 +365,15 @@ 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; @@ -342,8 +381,9 @@ 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; @@ -409,8 +449,9 @@ 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; @@ -418,8 +459,9 @@ 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; @@ -427,8 +469,9 @@ 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 9cb4aa2a071..0d087c54556 100644 --- a/packages/go_router/test/parser_test.dart +++ b/packages/go_router/test/parser_test.dart @@ -10,9 +10,9 @@ import 'test_helpers.dart'; RouteInformation createRouteInformation(String location, [Object? extra]) { return RouteInformation( - uri: Uri.parse(location), - state: - RouteInformationState(type: NavigatingType.go, extra: extra)); + uri: Uri.parse(location), + state: RouteInformationState(type: NavigatingType.go, extra: extra), + ); } void main() { @@ -28,23 +28,19 @@ void main() { redirect: redirect, ); addTearDown(router.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: router, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router.routeInformationParser; } - testWidgets('GoRouteInformationParser can parse route', - (WidgetTester tester) async { + testWidgets('GoRouteInformationParser can parse route', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', builder: (_, __) => const Placeholder(), routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), ], ), ]; @@ -57,9 +53,11 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/'), context); + RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/'), + context, + ); List matches = matchesObj.matches; expect(matches.length, 1); expect(matchesObj.uri.toString(), '/'); @@ -69,7 +67,9 @@ void main() { final Object extra = Object(); matchesObj = await parser.parseRouteInformationWithDependencies( - createRouteInformation('/abc?def=ghi', extra), context); + createRouteInformation('/abc?def=ghi', extra), + context, + ); matches = matchesObj.matches; expect(matches.length, 2); expect(matchesObj.uri.toString(), '/abc?def=ghi'); @@ -81,48 +81,47 @@ void main() { expect(matches[1].route, routes[0].routes[0]); }); - testWidgets('GoRouteInformationParser can handle empty path for non http uri', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); - - final BuildContext context = tester.element(find.byType(Router)); - - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('elbaapp://domain'), context); - final List matches = matchesObj.matches; - expect(matches.length, 1); - expect(matchesObj.uri.toString(), 'elbaapp://domain/'); - }); - - testWidgets('GoRouteInformationParser cleans up uri', - (WidgetTester tester) async { + testWidgets( + 'GoRouteInformationParser can handle empty path for non http uri', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); + + final BuildContext context = tester.element(find.byType(Router)); + + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('elbaapp://domain'), + context, + ); + final List matches = matchesObj.matches; + expect(matches.length, 1); + expect(matchesObj.uri.toString(), 'elbaapp://domain/'); + }, + ); + + testWidgets('GoRouteInformationParser cleans up uri', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', builder: (_, __) => const Placeholder(), routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), ], ), ]; @@ -135,145 +134,152 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('http://domain/abc/?query=bde'), context); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('http://domain/abc/?query=bde'), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 2); expect(matchesObj.uri.toString(), 'http://domain/abc?query=bde'); }); testWidgets( - "GoRouteInformationParser can parse deeplink root route and maintain uri's scheme, host, query and fragment", - (WidgetTester tester) async { - const String expectedScheme = 'https'; - const String expectedHost = 'www.example.com'; - const String expectedQuery = 'abc=def'; - const String expectedFragment = 'abc'; - const String expectedUriString = - '$expectedScheme://$expectedHost/?$expectedQuery#$expectedFragment'; - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); - - final BuildContext context = tester.element(find.byType(Router)); - - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation(expectedUriString), context); - final List matches = matchesObj.matches; - expect(matches.length, 1); - expect(matchesObj.uri.toString(), expectedUriString); - expect(matchesObj.uri.scheme, expectedScheme); - expect(matchesObj.uri.host, expectedHost); - expect(matchesObj.uri.query, expectedQuery); - expect(matchesObj.uri.fragment, expectedFragment); - - expect(matches[0].matchedLocation, '/'); - expect(matches[0].route, routes[0]); - }); + "GoRouteInformationParser can parse deeplink root route and maintain uri's scheme, host, query and fragment", + (WidgetTester tester) async { + const String expectedScheme = 'https'; + const String expectedHost = 'www.example.com'; + const String expectedQuery = 'abc=def'; + const String expectedFragment = 'abc'; + const String expectedUriString = + '$expectedScheme://$expectedHost/?$expectedQuery#$expectedFragment'; + final List routes = [ + GoRoute(path: '/', builder: (_, __) => const Placeholder()), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); + + final BuildContext context = tester.element(find.byType(Router)); + + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation(expectedUriString), + context, + ); + final List matches = matchesObj.matches; + expect(matches.length, 1); + expect(matchesObj.uri.toString(), expectedUriString); + expect(matchesObj.uri.scheme, expectedScheme); + expect(matchesObj.uri.host, expectedHost); + expect(matchesObj.uri.query, expectedQuery); + expect(matchesObj.uri.fragment, expectedFragment); + + expect(matches[0].matchedLocation, '/'); + expect(matches[0].route, routes[0]); + }, + ); testWidgets( - "GoRouteInformationParser can parse deeplink route with a path and maintain uri's scheme, host, query and fragment", - (WidgetTester tester) async { - const String expectedScheme = 'https'; - const String expectedHost = 'www.example.com'; - const String expectedPath = '/abc'; - const String expectedQuery = 'abc=def'; - const String expectedFragment = 'abc'; - const String expectedUriString = - '$expectedScheme://$expectedHost$expectedPath?$expectedQuery#$expectedFragment'; - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); - - final BuildContext context = tester.element(find.byType(Router)); - - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation(expectedUriString), context); - final List matches = matchesObj.matches; - expect(matches.length, 2); - expect(matchesObj.uri.toString(), expectedUriString); - expect(matchesObj.uri.scheme, expectedScheme); - expect(matchesObj.uri.host, expectedHost); - expect(matchesObj.uri.path, expectedPath); - expect(matchesObj.uri.query, expectedQuery); - expect(matchesObj.uri.fragment, expectedFragment); - - expect(matches[0].matchedLocation, '/'); - expect(matches[0].route, routes[0]); - - expect(matches[1].matchedLocation, '/abc'); - expect(matches[1].route, routes[0].routes[0]); - }); + "GoRouteInformationParser can parse deeplink route with a path and maintain uri's scheme, host, query and fragment", + (WidgetTester tester) async { + const String expectedScheme = 'https'; + const String expectedHost = 'www.example.com'; + const String expectedPath = '/abc'; + const String expectedQuery = 'abc=def'; + const String expectedFragment = 'abc'; + const String expectedUriString = + '$expectedScheme://$expectedHost$expectedPath?$expectedQuery#$expectedFragment'; + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); + + final BuildContext context = tester.element(find.byType(Router)); + + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation(expectedUriString), + context, + ); + final List matches = matchesObj.matches; + expect(matches.length, 2); + expect(matchesObj.uri.toString(), expectedUriString); + expect(matchesObj.uri.scheme, expectedScheme); + expect(matchesObj.uri.host, expectedHost); + expect(matchesObj.uri.path, expectedPath); + expect(matchesObj.uri.query, expectedQuery); + expect(matchesObj.uri.fragment, expectedFragment); + + expect(matches[0].matchedLocation, '/'); + expect(matches[0].route, routes[0]); + + expect(matches[1].matchedLocation, '/abc'); + expect(matches[1].route, routes[0].routes[0]); + }, + ); testWidgets( - 'GoRouteInformationParser can restore full route matches if optionURLReflectsImperativeAPIs is true', - (WidgetTester tester) async { - final GlobalKey navKey = GlobalKey(); - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; - GoRouter.optionURLReflectsImperativeAPIs = true; - final GoRouter router = - await createRouter(routes, tester, navigatorKey: navKey); - - // Generate RouteMatchList with imperative route match - router.go('/abc'); - await tester.pumpAndSettle(); - router.push('/'); - await tester.pumpAndSettle(); - final RouteMatchList matchList = router.routerDelegate.currentConfiguration; - expect(matchList.uri.toString(), '/abc'); - expect(matchList.matches.length, 3); - - final RouteInformation restoredRouteInformation = - router.routeInformationParser.restoreRouteInformation(matchList)!; - expect(restoredRouteInformation.uri.path, '/'); - - // Can restore back to original RouteMatchList. - final RouteMatchList parsedRouteMatch = await router.routeInformationParser - .parseRouteInformationWithDependencies( - restoredRouteInformation, navKey.currentContext!); - expect(parsedRouteMatch.uri.toString(), '/abc'); - expect(parsedRouteMatch.matches.length, 3); + 'GoRouteInformationParser can restore full route matches if optionURLReflectsImperativeAPIs is true', + (WidgetTester tester) async { + final GlobalKey navKey = GlobalKey(); + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), + ], + ), + ]; + GoRouter.optionURLReflectsImperativeAPIs = true; + final GoRouter router = await createRouter( + routes, + tester, + navigatorKey: navKey, + ); + + // Generate RouteMatchList with imperative route match + router.go('/abc'); + await tester.pumpAndSettle(); + router.push('/'); + await tester.pumpAndSettle(); + final RouteMatchList matchList = + router.routerDelegate.currentConfiguration; + expect(matchList.uri.toString(), '/abc'); + expect(matchList.matches.length, 3); + + final RouteInformation restoredRouteInformation = + router.routeInformationParser.restoreRouteInformation(matchList)!; + expect(restoredRouteInformation.uri.path, '/'); + + // Can restore back to original RouteMatchList. + final RouteMatchList parsedRouteMatch = await router + .routeInformationParser + .parseRouteInformationWithDependencies( + restoredRouteInformation, + navKey.currentContext!, + ); + expect(parsedRouteMatch.uri.toString(), '/abc'); + expect(parsedRouteMatch.matches.length, 3); - GoRouter.optionURLReflectsImperativeAPIs = false; - }); + GoRouter.optionURLReflectsImperativeAPIs = false; + }, + ); test('GoRouteInformationParser can retrieve route by name', () async { final List routes = [ @@ -314,60 +320,67 @@ void main() { // With query parameters expect(configuration.namedLocation('lowercase'), '/abc'); expect( - configuration.namedLocation('lowercase', - queryParameters: const {'q': '1'}), - '/abc?q=1'); - expect( - configuration.namedLocation('lowercase', - queryParameters: const {'q': '1', 'g': '2'}), - '/abc?q=1&g=2'); - }); - - test( - 'GoRouteInformationParser can retrieve route by name with query parameters', - () async { - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: 'abc', - name: 'routeName', - builder: (_, __) => const Placeholder(), - ), - ], + configuration.namedLocation( + 'lowercase', + queryParameters: const {'q': '1'}, ), - ]; - - final RouteConfiguration configuration = createRouteConfiguration( - routes: routes, - redirectLimit: 100, - topRedirect: (_, __) => null, - navigatorKey: GlobalKey(), + '/abc?q=1', ); - expect( - configuration - .namedLocation('routeName', queryParameters: const { - 'q1': 'v1', - 'q2': ['v2', 'v3'], - }), - '/abc?q1=v1&q2=v2&q2=v3', + configuration.namedLocation( + 'lowercase', + queryParameters: const {'q': '1', 'g': '2'}, + ), + '/abc?q=1&g=2', ); }); - testWidgets('GoRouteInformationParser returns error when unknown route', - (WidgetTester tester) async { + test( + 'GoRouteInformationParser can retrieve route by name with query parameters', + () async { + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute( + path: 'abc', + name: 'routeName', + builder: (_, __) => const Placeholder(), + ), + ], + ), + ]; + + final RouteConfiguration configuration = createRouteConfiguration( + routes: routes, + redirectLimit: 100, + topRedirect: (_, __) => null, + navigatorKey: GlobalKey(), + ); + + expect( + configuration.namedLocation( + 'routeName', + queryParameters: const { + 'q1': 'v1', + 'q2': ['v2', 'v3'], + }, + ), + '/abc?q1=v1&q2=v2&q2=v3', + ); + }, + ); + + testWidgets('GoRouteInformationParser returns error when unknown route', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', builder: (_, __) => const Placeholder(), routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), ], ), ]; @@ -380,51 +393,56 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/def'), context); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/def'), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 0); expect(matchesObj.uri.toString(), '/def'); expect(matchesObj.extra, isNull); - expect(matchesObj.error!.toString(), - 'GoException: no routes for location: /def'); + expect( + matchesObj.error!.toString(), + 'GoException: no routes for location: /def', + ); }); testWidgets( - 'GoRouteInformationParser calls redirector with correct uri when unknown route', - (WidgetTester tester) async { - String? lastRedirectLocation; - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: 'abc', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, GoRouterState state) { - lastRedirectLocation = state.uri.toString(); - return null; - }, - ); - - final BuildContext context = tester.element(find.byType(Router)); - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/def'), context); - expect(lastRedirectLocation, '/def'); - }); + 'GoRouteInformationParser calls redirector with correct uri when unknown route', + (WidgetTester tester) async { + String? lastRedirectLocation; + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, GoRouterState state) { + lastRedirectLocation = state.uri.toString(); + return null; + }, + ); - testWidgets('GoRouteInformationParser can work with route parameters', - (WidgetTester tester) async { + final BuildContext context = tester.element(find.byType(Router)); + await parser.parseRouteInformationWithDependencies( + createRouteInformation('/def'), + context, + ); + expect(lastRedirectLocation, '/def'); + }, + ); + + testWidgets('GoRouteInformationParser can work with route parameters', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( path: '/', @@ -445,9 +463,11 @@ void main() { ); final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/123/family/456'), context); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/123/family/456'), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 2); @@ -462,158 +482,162 @@ void main() { }); testWidgets( - 'GoRouteInformationParser processes top level redirect when there is no match', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: ':uid/family/:fid', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (BuildContext context, GoRouterState state) { - if (state.uri.toString() != '/123/family/345') { - return '/123/family/345'; - } - return null; - }, - ); + 'GoRouteInformationParser processes top level redirect when there is no match', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute( + path: ':uid/family/:fid', + builder: (_, __) => const Placeholder(), + ), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (BuildContext context, GoRouterState state) { + if (state.uri.toString() != '/123/family/345') { + return '/123/family/345'; + } + return null; + }, + ); - final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/random/uri'), context); - final List matches = matchesObj.matches; + final BuildContext context = tester.element(find.byType(Router)); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/random/uri'), + context, + ); + final List matches = matchesObj.matches; - expect(matches.length, 2); - expect(matchesObj.uri.toString(), '/123/family/345'); - expect(matches[0].matchedLocation, '/'); + expect(matches.length, 2); + expect(matchesObj.uri.toString(), '/123/family/345'); + expect(matches[0].matchedLocation, '/'); - expect(matches[1].matchedLocation, '/123/family/345'); - }); + expect(matches[1].matchedLocation, '/123/family/345'); + }, + ); testWidgets( - 'GoRouteInformationParser can do route level redirect when there is a match', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: ':uid/family/:fid', - builder: (_, __) => const Placeholder(), - ), - GoRoute( - path: 'redirect', - redirect: (_, __) => '/123/family/345', - builder: (_, __) => throw UnimplementedError(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); - - final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/redirect'), context); - final List matches = matchesObj.matches; + 'GoRouteInformationParser can do route level redirect when there is a match', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute( + path: ':uid/family/:fid', + builder: (_, __) => const Placeholder(), + ), + GoRoute( + path: 'redirect', + redirect: (_, __) => '/123/family/345', + builder: (_, __) => throw UnimplementedError(), + ), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); + + final BuildContext context = tester.element(find.byType(Router)); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/redirect'), + context, + ); + final List matches = matchesObj.matches; - expect(matches.length, 2); - expect(matchesObj.uri.toString(), '/123/family/345'); - expect(matches[0].matchedLocation, '/'); + expect(matches.length, 2); + expect(matchesObj.uri.toString(), '/123/family/345'); + expect(matches[0].matchedLocation, '/'); - expect(matches[1].matchedLocation, '/123/family/345'); - }); + expect(matches[1].matchedLocation, '/123/family/345'); + }, + ); testWidgets( - 'GoRouteInformationParser throws an exception when route is malformed', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/abc', - builder: (_, __) => const Placeholder(), - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); - - final BuildContext context = tester.element(find.byType(Router)); - expect(() async { - await parser.parseRouteInformationWithDependencies( - createRouteInformation('::Not valid URI::'), context); - }, throwsA(isA())); - }); + 'GoRouteInformationParser throws an exception when route is malformed', + (WidgetTester tester) async { + final List routes = [ + GoRoute(path: '/abc', builder: (_, __) => const Placeholder()), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); + + final BuildContext context = tester.element(find.byType(Router)); + expect(() async { + await parser.parseRouteInformationWithDependencies( + createRouteInformation('::Not valid URI::'), + context, + ); + }, throwsA(isA())); + }, + ); testWidgets( - 'GoRouteInformationParser returns an error if a redirect is detected.', - (WidgetTester tester) async { - final List routes = [ - GoRoute( - path: '/abc', - builder: (_, __) => const Placeholder(), - redirect: (BuildContext context, GoRouterState state) => - state.uri.toString(), - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirect: (_, __) => null, - ); - - final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/abd'), context); - final List matches = matchesObj.matches; + 'GoRouteInformationParser returns an error if a redirect is detected.', + (WidgetTester tester) async { + final List routes = [ + GoRoute( + path: '/abc', + builder: (_, __) => const Placeholder(), + redirect: + (BuildContext context, GoRouterState state) => + state.uri.toString(), + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirect: (_, __) => null, + ); + + final BuildContext context = tester.element(find.byType(Router)); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/abd'), + context, + ); + final List matches = matchesObj.matches; - expect(matches, hasLength(0)); - expect(matchesObj.error, isNotNull); - }); + expect(matches, hasLength(0)); + expect(matchesObj.error, isNotNull); + }, + ); testWidgets('Creates a match for ShellRoute', (WidgetTester tester) async { final List routes = [ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: child, - ); + return Scaffold(body: child); }, routes: [ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen A'), - ); + return const Scaffold(body: Text('Screen A')); }, ), GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { - return const Scaffold( - body: Text('Screen B'), - ); + return const Scaffold(body: Text('Screen B')); }, ), ], @@ -626,9 +650,11 @@ void main() { ); final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/a'), context); + final RouteMatchList matchesObj = await parser + .parseRouteInformationWithDependencies( + createRouteInformation('/a'), + context, + ); final List matches = matchesObj.matches; expect(matches, hasLength(1)); diff --git a/packages/go_router/test/path_utils_test.dart b/packages/go_router/test/path_utils_test.dart index e2d79a73571..d5193212548 100644 --- a/packages/go_router/test/path_utils_test.dart +++ b/packages/go_router/test/path_utils_test.dart @@ -9,8 +9,11 @@ void main() { test('patternToRegExp without path parameter', () async { const String pattern = '/settings/detail'; final List pathParameter = []; - final RegExp regex = - patternToRegExp(pattern, pathParameter, caseSensitive: true); + final RegExp regex = patternToRegExp( + pattern, + pathParameter, + caseSensitive: true, + ); expect(pathParameter.isEmpty, isTrue); expect(regex.hasMatch('/settings/detail'), isTrue); expect(regex.hasMatch('/settings/'), isFalse); @@ -23,16 +26,21 @@ void main() { test('patternToRegExp with path parameter', () async { const String pattern = '/user/:id/book/:bookId'; final List pathParameter = []; - final RegExp regex = - patternToRegExp(pattern, pathParameter, caseSensitive: true); + final RegExp regex = patternToRegExp( + pattern, + pathParameter, + caseSensitive: true, + ); expect(pathParameter.length, 2); expect(pathParameter[0], 'id'); expect(pathParameter[1], 'bookId'); final RegExpMatch? match = regex.firstMatch('/user/123/book/456/'); expect(match, isNotNull); - final Map parameterValues = - extractPathParameters(pathParameter, match!); + final Map parameterValues = extractPathParameters( + pathParameter, + match!, + ); expect(parameterValues.length, 2); expect(parameterValues[pathParameter[0]], '123'); expect(parameterValues[pathParameter[1]], '456'); @@ -46,15 +54,20 @@ void main() { test('patternToPath without path parameter', () async { const String pattern = '/settings/detail'; final List pathParameter = []; - final RegExp regex = - patternToRegExp(pattern, pathParameter, caseSensitive: true); + final RegExp regex = patternToRegExp( + pattern, + pathParameter, + caseSensitive: true, + ); const String url = '/settings/detail'; final RegExpMatch? match = regex.firstMatch(url); expect(match, isNotNull); - final Map parameterValues = - extractPathParameters(pathParameter, match!); + final Map parameterValues = extractPathParameters( + pathParameter, + match!, + ); final String restoredUrl = patternToPath(pattern, parameterValues); expect(url, restoredUrl); @@ -63,15 +76,20 @@ void main() { test('patternToPath with path parameter', () async { const String pattern = '/user/:id/book/:bookId'; final List pathParameter = []; - final RegExp regex = - patternToRegExp(pattern, pathParameter, caseSensitive: true); + final RegExp regex = patternToRegExp( + pattern, + pathParameter, + caseSensitive: true, + ); const String url = '/user/123/book/456'; final RegExpMatch? match = regex.firstMatch(url); expect(match, isNotNull); - final Map parameterValues = - extractPathParameters(pathParameter, match!); + final Map parameterValues = extractPathParameters( + pathParameter, + match!, + ); final String restoredUrl = patternToPath(pattern, parameterValues); expect(url, restoredUrl); diff --git a/packages/go_router/test/rebuild_test.dart b/packages/go_router/test/rebuild_test.dart index 4617ef01312..cfc2df8876e 100644 --- a/packages/go_router/test/rebuild_test.dart +++ b/packages/go_router/test/rebuild_test.dart @@ -9,21 +9,25 @@ import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { - testWidgets('GoRouter.push does not trigger unnecessary rebuilds', - (WidgetTester tester) async { + testWidgets('GoRouter.push does not trigger unnecessary rebuilds', ( + WidgetTester tester, + ) async { final List routes = [ GoRoute( - path: '/', builder: (BuildContext context, __) => const HomePage()), + path: '/', + builder: (BuildContext context, __) => const HomePage(), + ), GoRoute( - path: '/1', - builder: (BuildContext context, __) { - return ElevatedButton( - onPressed: () { - context.push('/1'); - }, - child: const Text('/1'), - ); - }), + path: '/1', + builder: (BuildContext context, __) { + return ElevatedButton( + onPressed: () { + context.push('/1'); + }, + child: const Text('/1'), + ); + }, + ), ]; await createRouter(routes, tester); diff --git a/packages/go_router/test/request_focus.dart b/packages/go_router/test/request_focus.dart index f9ccc9681f3..0f586e05c4f 100644 --- a/packages/go_router/test/request_focus.dart +++ b/packages/go_router/test/request_focus.dart @@ -7,18 +7,15 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; void main() { - testWidgets('GoRouter does not request focus if requestFocus is false', - (WidgetTester tester) async { + testWidgets('GoRouter does not request focus if requestFocus is false', ( + WidgetTester tester, + ) async { final GlobalKey innerKey = GlobalKey(); final FocusScopeNode focusNode = FocusScopeNode(); final GoRouter router = GoRouter( initialLocation: '/', routes: [ - GoRoute( - path: '/', - name: 'home', - builder: (_, __) => const Text('A'), - ), + GoRoute(path: '/', name: 'home', builder: (_, __) => const Text('A')), GoRoute( path: '/second', name: 'second', @@ -28,16 +25,14 @@ void main() { requestFocus: false, ); - await tester.pumpWidget(Column( - children: [ - FocusScope(node: focusNode, child: Container()), - Expanded( - child: MaterialApp.router( - routerConfig: router, - ), - ), - ], - )); + await tester.pumpWidget( + Column( + children: [ + FocusScope(node: focusNode, child: Container()), + Expanded(child: MaterialApp.router(routerConfig: router)), + ], + ), + ); expect(find.text('A'), findsOneWidget); expect(find.text('B', skipOffstage: false), findsNothing); diff --git a/packages/go_router/test/route_data_test.dart b/packages/go_router/test/route_data_test.dart index a3b7485748d..61b31e7cb8c 100644 --- a/packages/go_router/test/route_data_test.dart +++ b/packages/go_router/test/route_data_test.dart @@ -29,15 +29,8 @@ class _ShellRouteDataBuilder extends ShellRouteData { const _ShellRouteDataBuilder(); @override - Widget builder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => - SizedBox( - key: const Key('builder'), - child: navigator, - ); + Widget builder(BuildContext context, GoRouterState state, Widget navigator) => + SizedBox(key: const Key('builder'), child: navigator); } class _ShellRouteDataWithKey extends ShellRouteData { @@ -46,15 +39,8 @@ class _ShellRouteDataWithKey extends ShellRouteData { final Key key; @override - Widget builder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => - KeyedSubtree( - key: key, - child: navigator, - ); + Widget builder(BuildContext context, GoRouterState state, Widget navigator) => + KeyedSubtree(key: key, child: navigator); } class _GoRouteDataBuildWithKey extends GoRouteData { @@ -86,9 +72,7 @@ class _GoRouteDataBuildPage extends GoRouteData { @override Page buildPage(BuildContext context, GoRouterState state) => - const MaterialPage( - child: SizedBox(key: Key('buildPage')), - ); + const MaterialPage(child: SizedBox(key: Key('buildPage'))); } class _ShellRouteDataPageBuilder extends ShellRouteData { @@ -99,13 +83,9 @@ class _ShellRouteDataPageBuilder extends ShellRouteData { BuildContext context, GoRouterState state, Widget navigator, - ) => - MaterialPage( - child: SizedBox( - key: const Key('page-builder'), - child: navigator, - ), - ); + ) => MaterialPage( + child: SizedBox(key: const Key('page-builder'), child: navigator), + ); } class _StatefulShellRouteDataRedirectPage extends StatefulShellRouteData { @@ -154,27 +134,23 @@ class _StatefulShellRouteDataBuilder extends StatefulShellRouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigator, - ) => - SizedBox( - key: const Key('builder'), - child: navigator, - ); + ) => SizedBox(key: const Key('builder'), child: navigator); } final StatefulShellRoute _statefulShellRouteDataBuilder = StatefulShellRouteData.$route( - factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(), - branches: [ - StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), + factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(), + branches: [ + StatefulShellBranchData.$branch( + routes: [ + GoRouteData.$route( + path: '/child', + factory: (GoRouterState state) => const _GoRouteDataBuild(), + ), + ], ), ], - ), - ], -); + ); class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData { const _StatefulShellRouteDataPageBuilder(); @@ -184,29 +160,26 @@ class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigator, - ) => - MaterialPage( - child: SizedBox( - key: const Key('page-builder'), - child: navigator, - ), - ); + ) => MaterialPage( + child: SizedBox(key: const Key('page-builder'), child: navigator), + ); } final StatefulShellRoute _statefulShellRouteDataPageBuilder = StatefulShellRouteData.$route( - factory: (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(), - branches: [ - StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), + factory: + (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(), + branches: [ + StatefulShellBranchData.$branch( + routes: [ + GoRouteData.$route( + path: '/child', + factory: (GoRouterState state) => const _GoRouteDataBuild(), + ), + ], ), ], - ), - ], -); + ); class _GoRouteDataRedirectPage extends GoRouteData { const _GoRouteDataRedirectPage(); @@ -237,19 +210,18 @@ String toBase64(String value) { void main() { group('GoRouteData', () { - testWidgets( - 'It should build the page from the overridden build method', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/build', - routes: _routes, - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsOneWidget); - expect(find.byKey(const Key('buildPage')), findsNothing); - }, - ); + testWidgets('It should build the page from the overridden build method', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/build', + routes: _routes, + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsOneWidget); + expect(find.byKey(const Key('buildPage')), findsNothing); + }); testWidgets( 'It should build the page from the overridden buildPage method', @@ -290,160 +262,156 @@ void main() { }, ); - testWidgets( - 'It should throw beacuase there is no code generated', - (WidgetTester tester) async { - final List errors = []; + testWidgets('It should throw beacuase there is no code generated', ( + WidgetTester tester, + ) async { + final List errors = []; - FlutterError.onError = - (FlutterErrorDetails details) => errors.add(details); + FlutterError.onError = + (FlutterErrorDetails details) => errors.add(details); - const String errorText = 'Should be generated'; + const String errorText = 'Should be generated'; - Widget buildWidget(void Function(BuildContext) onTap) { - return MaterialApp( - home: Builder( - builder: (BuildContext context) => GestureDetector( - child: const Text('Tap'), - onTap: () => onTap(context), - ), - ), - ); - } + Widget buildWidget(void Function(BuildContext) onTap) { + return MaterialApp( + home: Builder( + builder: + (BuildContext context) => GestureDetector( + child: const Text('Tap'), + onTap: () => onTap(context), + ), + ), + ); + } - final Widget pushThrower = buildWidget((BuildContext context) { - const _GoRouteDataBuild().push(context); - }); - await tester.pumpWidget(pushThrower); - await tester.tap(find.text('Tap')); + final Widget pushThrower = buildWidget((BuildContext context) { + const _GoRouteDataBuild().push(context); + }); + await tester.pumpWidget(pushThrower); + await tester.tap(find.text('Tap')); - expect(errors.first.exception, isA()); - expect(errors.first.exception.toString(), contains(errorText)); + expect(errors.first.exception, isA()); + expect(errors.first.exception.toString(), contains(errorText)); - errors.clear(); + errors.clear(); - final Widget goThrower = buildWidget((BuildContext context) { - const _GoRouteDataBuild().go(context); - }); - await tester.pumpWidget(goThrower); - await tester.tap(find.text('Tap')); + final Widget goThrower = buildWidget((BuildContext context) { + const _GoRouteDataBuild().go(context); + }); + await tester.pumpWidget(goThrower); + await tester.tap(find.text('Tap')); - expect(errors.first.exception, isA()); - expect(errors.first.exception.toString(), contains(errorText)); + expect(errors.first.exception, isA()); + expect(errors.first.exception.toString(), contains(errorText)); - errors.clear(); + errors.clear(); - final Widget pushReplacementThrower = - buildWidget((BuildContext context) { - const _GoRouteDataBuild().pushReplacement(context); - }); - await tester.pumpWidget(pushReplacementThrower); - await tester.tap(find.text('Tap')); + final Widget pushReplacementThrower = buildWidget((BuildContext context) { + const _GoRouteDataBuild().pushReplacement(context); + }); + await tester.pumpWidget(pushReplacementThrower); + await tester.tap(find.text('Tap')); - expect(errors.first.exception, isA()); - expect(errors.first.exception.toString(), contains(errorText)); + expect(errors.first.exception, isA()); + expect(errors.first.exception.toString(), contains(errorText)); - errors.clear(); + errors.clear(); - final Widget replaceThrower = buildWidget((BuildContext context) { - const _GoRouteDataBuild().pushReplacement(context); - }); - await tester.pumpWidget(replaceThrower); - await tester.tap(find.text('Tap')); + final Widget replaceThrower = buildWidget((BuildContext context) { + const _GoRouteDataBuild().pushReplacement(context); + }); + await tester.pumpWidget(replaceThrower); + await tester.tap(find.text('Tap')); - expect(errors.first.exception, isA()); - expect(errors.first.exception.toString(), contains(errorText)); + expect(errors.first.exception, isA()); + expect(errors.first.exception.toString(), contains(errorText)); - errors.clear(); + errors.clear(); - FlutterError.onError = FlutterError.dumpErrorToConsole; - }, - ); + FlutterError.onError = FlutterError.dumpErrorToConsole; + }); }); group('ShellRouteData', () { - testWidgets( - 'It should build the page from the overridden build method', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/child', - routes: [ - _shellRouteDataBuilder, - ], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('builder')), findsOneWidget); - expect(find.byKey(const Key('page-builder')), findsNothing); - }, - ); + testWidgets('It should build the page from the overridden build method', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/child', + routes: [_shellRouteDataBuilder], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('builder')), findsOneWidget); + expect(find.byKey(const Key('page-builder')), findsNothing); + }); - testWidgets( - 'It should build the page from the overridden build method', - (WidgetTester tester) async { - final GlobalKey root = GlobalKey(); - final GlobalKey inner = GlobalKey(); - final GoRouter goRouter = GoRouter( - navigatorKey: root, - initialLocation: '/child/test', - routes: [ - ShellRouteData.$route( - factory: (GoRouterState state) => - const _ShellRouteDataWithKey(Key('under-shell')), - routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => + testWidgets('It should build the page from the overridden build method', ( + WidgetTester tester, + ) async { + final GlobalKey root = GlobalKey(); + final GlobalKey inner = GlobalKey(); + final GoRouter goRouter = GoRouter( + navigatorKey: root, + initialLocation: '/child/test', + routes: [ + ShellRouteData.$route( + factory: + (GoRouterState state) => + const _ShellRouteDataWithKey(Key('under-shell')), + routes: [ + GoRouteData.$route( + path: '/child', + factory: + (GoRouterState state) => const _GoRouteDataBuildWithKey(Key('under')), - routes: [ - ShellRouteData.$route( - factory: (GoRouterState state) => + routes: [ + ShellRouteData.$route( + factory: + (GoRouterState state) => const _ShellRouteDataWithKey(Key('above-shell')), - navigatorKey: inner, - parentNavigatorKey: root, - routes: [ - GoRouteData.$route( - parentNavigatorKey: inner, - path: 'test', - factory: (GoRouterState state) => + navigatorKey: inner, + parentNavigatorKey: root, + routes: [ + GoRouteData.$route( + parentNavigatorKey: inner, + path: 'test', + factory: + (GoRouterState state) => const _GoRouteDataBuildWithKey(Key('above')), - ), - ], ), - ]), - ], - ), - ], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router( - routerConfig: goRouter, - )); - expect(find.byKey(const Key('under-shell')), findsNothing); - expect(find.byKey(const Key('under')), findsNothing); + ], + ), + ], + ), + ], + ), + ], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('under-shell')), findsNothing); + expect(find.byKey(const Key('under')), findsNothing); - expect(find.byKey(const Key('above-shell')), findsOneWidget); - expect(find.byKey(const Key('above')), findsOneWidget); + expect(find.byKey(const Key('above-shell')), findsOneWidget); + expect(find.byKey(const Key('above')), findsOneWidget); - goRouter.pop(); - await tester.pumpAndSettle(); + goRouter.pop(); + await tester.pumpAndSettle(); - expect(find.byKey(const Key('under-shell')), findsOneWidget); - expect(find.byKey(const Key('under')), findsOneWidget); + expect(find.byKey(const Key('under-shell')), findsOneWidget); + expect(find.byKey(const Key('under')), findsOneWidget); - expect(find.byKey(const Key('above-shell')), findsNothing); - expect(find.byKey(const Key('above')), findsNothing); - }, - ); + expect(find.byKey(const Key('above-shell')), findsNothing); + expect(find.byKey(const Key('above')), findsNothing); + }); testWidgets( 'It should build the page from the overridden buildPage method', (WidgetTester tester) async { final GoRouter goRouter = GoRouter( initialLocation: '/child', - routes: [ - _shellRouteDataPageBuilder, - ], + routes: [_shellRouteDataPageBuilder], ); addTearDown(goRouter.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); @@ -452,49 +420,40 @@ void main() { }, ); - testWidgets( - 'It should redirect using the overridden redirect method', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/child', - routes: [ - _goRouteDataBuildPage, - _shellRouteDataRedirect, - ], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsNothing); - expect(find.byKey(const Key('buildPage')), findsOneWidget); - }, - ); + testWidgets('It should redirect using the overridden redirect method', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/child', + routes: [_goRouteDataBuildPage, _shellRouteDataRedirect], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsNothing); + expect(find.byKey(const Key('buildPage')), findsOneWidget); + }); }); group('StatefulShellRouteData', () { - testWidgets( - 'It should build the page from the overridden build method', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/child', - routes: [ - _statefulShellRouteDataBuilder, - ], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('builder')), findsOneWidget); - expect(find.byKey(const Key('page-builder')), findsNothing); - }, - ); + testWidgets('It should build the page from the overridden build method', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/child', + routes: [_statefulShellRouteDataBuilder], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('builder')), findsOneWidget); + expect(find.byKey(const Key('page-builder')), findsNothing); + }); testWidgets( 'It should build the page from the overridden buildPage method', (WidgetTester tester) async { final GoRouter goRouter = GoRouter( initialLocation: '/child', - routes: [ - _statefulShellRouteDataPageBuilder, - ], + routes: [_statefulShellRouteDataPageBuilder], ); addTearDown(goRouter.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); @@ -507,8 +466,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: [ @@ -539,19 +498,18 @@ void main() { }); }); - testWidgets( - 'It should redirect using the overridden redirect method', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/redirect', - routes: _routes, - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsNothing); - expect(find.byKey(const Key('buildPage')), findsOneWidget); - }, - ); + testWidgets('It should redirect using the overridden redirect method', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/redirect', + routes: _routes, + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsNothing); + expect(find.byKey(const Key('buildPage')), findsOneWidget); + }); testWidgets( 'It should redirect using the overridden StatefulShellRoute redirect method', @@ -561,8 +519,9 @@ void main() { routes: [ _goRouteDataBuildPage, StatefulShellRouteData.$route( - factory: (GoRouterState state) => - const _StatefulShellRouteDataRedirectPage(), + factory: + (GoRouterState state) => + const _StatefulShellRouteDataRedirectPage(), branches: [ StatefulShellBranchData.$branch( routes: [ @@ -571,9 +530,9 @@ void main() { factory: (GoRouterState state) => const _GoRouteDataBuild(), ), ], - ) + ), ], - ) + ), ], ); addTearDown(goRouter.dispose); @@ -583,19 +542,18 @@ void main() { }, ); - testWidgets( - 'It should redirect using the overridden redirect method', - (WidgetTester tester) async { - final GoRouter goRouter = GoRouter( - initialLocation: '/redirect-with-state', - routes: _routes, - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsNothing); - expect(find.byKey(const Key('buildPage')), findsNothing); - }, - ); + testWidgets('It should redirect using the overridden redirect method', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = GoRouter( + initialLocation: '/redirect-with-state', + routes: _routes, + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsNothing); + expect(find.byKey(const Key('buildPage')), findsNothing); + }); test('TypedGoRoute with default parameters', () { const TypedGoRoute typedGoRoute = TypedGoRoute( path: '/path', @@ -628,8 +586,11 @@ void main() { expect( typedGoRoute.routes.single, isA>() - .having((TypedGoRoute route) => route.path, 'path', - 'sub-path') + .having( + (TypedGoRoute route) => route.path, + 'path', + 'sub-path', + ) .having( (TypedGoRoute route) => route.name, 'name', diff --git a/packages/go_router/test/routing_config_test.dart b/packages/go_router/test/routing_config_test.dart index b1b02a98fbb..904991a134e 100644 --- a/packages/go_router/test/routing_config_test.dart +++ b/packages/go_router/test/routing_config_test.dart @@ -28,8 +28,9 @@ void main() { expect(find.text('home'), findsOneWidget); }); - testWidgets('routing config works after builder changes', - (WidgetTester tester) async { + testWidgets('routing config works after builder changes', ( + WidgetTester tester, + ) async { final ValueNotifier config = ValueNotifier( RoutingConfig( routes: [ @@ -50,8 +51,9 @@ void main() { expect(find.text('home1'), findsOneWidget); }); - testWidgets('routing config works after routing changes', - (WidgetTester tester) async { + testWidgets('routing config works after routing changes', ( + WidgetTester tester, + ) async { final ValueNotifier config = ValueNotifier( RoutingConfig( routes: [ @@ -81,8 +83,9 @@ void main() { expect(find.text('/abc'), findsOneWidget); }); - testWidgets('routing config works after routing changes case 2', - (WidgetTester tester) async { + testWidgets('routing config works after routing changes case 2', ( + WidgetTester tester, + ) async { final ValueNotifier config = ValueNotifier( RoutingConfig( routes: [ @@ -112,10 +115,12 @@ void main() { expect(find.text('error'), findsOneWidget); }); - testWidgets('routing config works after routing changes case 3', - (WidgetTester tester) async { - final GlobalKey<_StatefulTestState> key = - GlobalKey<_StatefulTestState>(debugLabel: 'testState'); + testWidgets('routing config works after routing changes case 3', ( + WidgetTester tester, + ) async { + final GlobalKey<_StatefulTestState> key = GlobalKey<_StatefulTestState>( + debugLabel: 'testState', + ); final GlobalKey rootNavigatorKey = GlobalKey(debugLabel: 'root'); @@ -123,9 +128,10 @@ void main() { RoutingConfig( routes: [ GoRoute( - path: '/', - builder: (_, __) => - StatefulTest(key: key, child: const Text('home'))), + path: '/', + builder: + (_, __) => StatefulTest(key: key, child: const Text('home')), + ), ], ), ); @@ -142,9 +148,9 @@ void main() { config.value = RoutingConfig( routes: [ GoRoute( - path: '/', - builder: (_, __) => - StatefulTest(key: key, child: const Text('home'))), + path: '/', + builder: (_, __) => StatefulTest(key: key, child: const Text('home')), + ), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], ); @@ -152,66 +158,75 @@ void main() { expect(key.currentState!.value == 1, isTrue); }); - testWidgets('routing config works with shell route', - // TODO(tolo): Temporarily skipped due to a bug that causes test to faiL - skip: true, (WidgetTester tester) async { - final GlobalKey<_StatefulTestState> key = - GlobalKey<_StatefulTestState>(debugLabel: 'testState'); - final GlobalKey rootNavigatorKey = - GlobalKey(debugLabel: 'root'); - final GlobalKey shellNavigatorKey = - GlobalKey(debugLabel: 'shell'); + testWidgets( + 'routing config works with shell route', + // TODO(tolo): Temporarily skipped due to a bug that causes test to faiL + skip: true, + (WidgetTester tester) async { + final GlobalKey<_StatefulTestState> key = GlobalKey<_StatefulTestState>( + debugLabel: 'testState', + ); + final GlobalKey rootNavigatorKey = + GlobalKey(debugLabel: 'root'); + final GlobalKey shellNavigatorKey = + GlobalKey(debugLabel: 'shell'); - final ValueNotifier config = ValueNotifier( - RoutingConfig( - routes: [ - ShellRoute( + final ValueNotifier config = ValueNotifier( + RoutingConfig( + routes: [ + ShellRoute( navigatorKey: shellNavigatorKey, routes: [ GoRoute(path: '/', builder: (_, __) => const Text('home')), ], - builder: (_, __, Widget widget) => - StatefulTest(key: key, child: widget)), - ], - ), - ); - addTearDown(config.dispose); - await createRouterWithRoutingConfig( - navigatorKey: rootNavigatorKey, - config, - tester, - errorBuilder: (_, __) => const Text('error'), - ); - expect(find.text('home'), findsOneWidget); - key.currentState!.value = 1; + builder: + (_, __, Widget widget) => + StatefulTest(key: key, child: widget), + ), + ], + ), + ); + addTearDown(config.dispose); + await createRouterWithRoutingConfig( + navigatorKey: rootNavigatorKey, + config, + tester, + errorBuilder: (_, __) => const Text('error'), + ); + expect(find.text('home'), findsOneWidget); + key.currentState!.value = 1; - config.value = RoutingConfig( - routes: [ - ShellRoute( + config.value = RoutingConfig( + routes: [ + ShellRoute( navigatorKey: shellNavigatorKey, routes: [ GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], - builder: (_, __, Widget widget) => - StatefulTest(key: key, child: widget)), - ], - ); - await tester.pumpAndSettle(); + builder: + (_, __, Widget widget) => StatefulTest(key: key, child: widget), + ), + ], + ); + await tester.pumpAndSettle(); - expect(key.currentState!.value == 1, isTrue); - }); + expect(key.currentState!.value == 1, isTrue); + }, + ); - testWidgets('routing config works with named route', - (WidgetTester tester) async { + testWidgets('routing config works with named route', ( + WidgetTester tester, + ) async { final ValueNotifier config = ValueNotifier( RoutingConfig( routes: [ GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute( - path: '/abc', - name: 'abc', - builder: (_, __) => const Text('/abc')), + path: '/abc', + name: 'abc', + builder: (_, __) => const Text('/abc'), + ), ], ), ); @@ -231,9 +246,15 @@ void main() { config.value = RoutingConfig( routes: [ GoRoute( - path: '/', name: 'home', builder: (_, __) => const Text('home')), + path: '/', + name: 'home', + builder: (_, __) => const Text('home'), + ), GoRoute( - path: '/abc', name: 'def', builder: (_, __) => const Text('def')), + path: '/abc', + name: 'def', + builder: (_, __) => const Text('def'), + ), ], ); await tester.pumpAndSettle(); @@ -263,11 +284,6 @@ class _StatefulTestState extends State { @override Widget build(BuildContext context) { - return Column( - children: [ - widget.child, - Text('State: $value'), - ], - ); + return Column(children: [widget.child, Text('State: $value')]); } } diff --git a/packages/go_router/test/test_helpers.dart b/packages/go_router/test/test_helpers.dart index cb1c2acdb96..d1d11673c9c 100644 --- a/packages/go_router/test/test_helpers.dart +++ b/packages/go_router/test/test_helpers.dart @@ -23,9 +23,7 @@ Future createGoRouter(WidgetTester tester) async { ), ], ); - await tester.pumpWidget(MaterialApp.router( - routerConfig: goRouter, - )); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); return goRouter; } @@ -33,14 +31,13 @@ Widget fakeNavigationBuilder( BuildContext context, GoRouterState state, Widget child, -) => - child; +) => child; class GoRouterNamedLocationSpy extends GoRouter { GoRouterNamedLocationSpy({required List routes}) - : super.routingConfig( - routingConfig: - ConstantRoutingConfig(RoutingConfig(routes: routes))); + : super.routingConfig( + routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), + ); String? name; Map? pathParameters; @@ -48,10 +45,12 @@ class GoRouterNamedLocationSpy extends GoRouter { String? fragment; @override - String namedLocation(String name, - {Map pathParameters = const {}, - Map queryParameters = const {}, - String? fragment}) { + String namedLocation( + String name, { + Map pathParameters = const {}, + Map queryParameters = const {}, + String? fragment, + }) { this.name = name; this.pathParameters = pathParameters; this.queryParameters = queryParameters; @@ -62,9 +61,9 @@ class GoRouterNamedLocationSpy extends GoRouter { class GoRouterGoSpy extends GoRouter { GoRouterGoSpy({required List routes}) - : super.routingConfig( - routingConfig: - ConstantRoutingConfig(RoutingConfig(routes: routes))); + : super.routingConfig( + routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), + ); String? myLocation; Object? extra; @@ -78,9 +77,9 @@ class GoRouterGoSpy extends GoRouter { class GoRouterGoNamedSpy extends GoRouter { GoRouterGoNamedSpy({required List routes}) - : super.routingConfig( - routingConfig: - ConstantRoutingConfig(RoutingConfig(routes: routes))); + : super.routingConfig( + routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), + ); String? name; Map? pathParameters; @@ -106,9 +105,9 @@ class GoRouterGoNamedSpy extends GoRouter { class GoRouterPushSpy extends GoRouter { GoRouterPushSpy({required List routes}) - : super.routingConfig( - routingConfig: - ConstantRoutingConfig(RoutingConfig(routes: routes))); + : super.routingConfig( + routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), + ); String? myLocation; Object? extra; @@ -123,9 +122,9 @@ class GoRouterPushSpy extends GoRouter { class GoRouterPushNamedSpy extends GoRouter { GoRouterPushNamedSpy({required List routes}) - : super.routingConfig( - routingConfig: - ConstantRoutingConfig(RoutingConfig(routes: routes))); + : super.routingConfig( + routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), + ); String? name; Map? pathParameters; @@ -149,9 +148,9 @@ class GoRouterPushNamedSpy extends GoRouter { class GoRouterPopSpy extends GoRouter { GoRouterPopSpy({required List routes}) - : super.routingConfig( - routingConfig: - ConstantRoutingConfig(RoutingConfig(routes: routes))); + : super.routingConfig( + routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), + ); bool popped = false; Object? poppedResult; @@ -305,8 +304,8 @@ class DummyStatefulWidgetState extends State { int counter = 0; void increment() => setState(() { - counter++; - }); + counter++; + }); @override Widget build(BuildContext context) => Container(); @@ -322,7 +321,8 @@ class DummyRestorableStatefulWidget extends StatefulWidget { } class DummyRestorableStatefulWidgetState - extends State with RestorationMixin { + extends State + with RestorationMixin { final RestorableInt _counter = RestorableInt(0); @override @@ -331,8 +331,8 @@ class DummyRestorableStatefulWidgetState int get counter => _counter.value; void increment([int count = 1]) => setState(() { - _counter.value += count; - }); + _counter.value += count; + }); @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { @@ -352,19 +352,28 @@ class DummyRestorableStatefulWidgetState } Future simulateAndroidBackButton(WidgetTester tester) async { - final ByteData message = - const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + final ByteData message = const JSONMethodCodec().encodeMethodCall( + const MethodCall('popRoute'), + ); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); } -GoRouterPageBuilder createPageBuilder( - {String? restorationId, required Widget child}) => +GoRouterPageBuilder createPageBuilder({ + String? restorationId, + required Widget child, +}) => (BuildContext context, GoRouterState state) => MaterialPage(restorationId: restorationId, child: child); -StatefulShellRouteBuilder mockStackedShellBuilder = (BuildContext context, - GoRouterState state, StatefulNavigationShell navigationShell) { +StatefulShellRouteBuilder mockStackedShellBuilder = ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, +) { return navigationShell; }; @@ -392,18 +401,23 @@ RouteConfiguration createRouteConfiguration({ required int redirectLimit, }) { return RouteConfiguration( - ConstantRoutingConfig(RoutingConfig( + ConstantRoutingConfig( + RoutingConfig( routes: routes, redirect: topRedirect, redirectLimit: redirectLimit, - )), - navigatorKey: navigatorKey); + ), + ), + navigatorKey: navigatorKey, + ); } class SimpleDependencyProvider extends InheritedNotifier { - const SimpleDependencyProvider( - {super.key, required SimpleDependency dependency, required super.child}) - : super(notifier: dependency); + const SimpleDependencyProvider({ + super.key, + required SimpleDependency dependency, + required super.child, + }) : super(notifier: dependency); static SimpleDependency of(BuildContext context) { final SimpleDependencyProvider result = diff --git a/packages/go_router/tool/run_tests.dart b/packages/go_router/tool/run_tests.dart index d3fb6b315bd..1fc22bd6eb8 100644 --- a/packages/go_router/tool/run_tests.dart +++ b/packages/go_router/tool/run_tests.dart @@ -39,28 +39,20 @@ Future main(List args) async { ); // Run dart pub get in the temp directory to set it up. - final int pubGetStatusCode = await _runProcess( - 'dart', - [ - 'pub', - 'get', - ], - workingDirectory: testTempDir.path, - ); + final int pubGetStatusCode = await _runProcess('dart', [ + 'pub', + 'get', + ], workingDirectory: testTempDir.path); if (pubGetStatusCode != 0) { await cleanUpAndExit(pubGetStatusCode); } // Run dart fix --compare-to-golden in the temp directory. - final int dartFixStatusCode = await _runProcess( - 'dart', - [ - 'fix', - '--compare-to-golden', - ], - workingDirectory: testTempDir.path, - ); + final int dartFixStatusCode = await _runProcess('dart', [ + 'fix', + '--compare-to-golden', + ], workingDirectory: testTempDir.path); await cleanUpAndExit(dartFixStatusCode); } @@ -70,8 +62,9 @@ Future _prepareTemplate({ required Directory testTempDir, }) async { // The src test_fixes directory. - final Directory testFixesSrcDir = - Directory(p.join(packageRoot.path, 'test_fixes')); + final Directory testFixesSrcDir = Directory( + p.join(packageRoot.path, 'test_fixes'), + ); // Copy from src `test_fixes/` to the temp directory. await io.copyPath(testFixesSrcDir.path, testTempDir.path); @@ -110,10 +103,8 @@ Future _runProcess( List arguments, { String? workingDirectory, }) async { - final Process process = await _streamOutput(Process.start( - command, - arguments, - workingDirectory: workingDirectory, - )); + final Process process = await _streamOutput( + Process.start(command, arguments, workingDirectory: workingDirectory), + ); return process.exitCode; } diff --git a/packages/google_adsense/CHANGELOG.md b/packages/google_adsense/CHANGELOG.md index 381c2567a56..b524ece4e9e 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.1.2 diff --git a/packages/google_adsense/doc/ad_unit_widget.md b/packages/google_adsense/doc/ad_unit_widget.md index bec5aa1a5c4..f8b7535aece 100644 --- a/packages/google_adsense/doc/ad_unit_widget.md +++ b/packages/google_adsense/doc/ad_unit_widget.md @@ -67,7 +67,7 @@ translates into: ```dart - AdUnitWidget( +AdUnitWidget( configuration: AdUnitConfiguration.displayAdUnit( // TODO: Replace with your Ad Unit ID adSlot: '1234567890', @@ -102,8 +102,10 @@ Note some [policies and restrictions](https://support.google.com/adsense/answer/ ```dart Container( - constraints: - const BoxConstraints(maxHeight: 100, maxWidth: 1200), + constraints: const BoxConstraints( + maxHeight: 100, + maxWidth: 1200, + ), padding: const EdgeInsets.only(bottom: 10), child: AdUnitWidget( configuration: AdUnitConfiguration.displayAdUnit( diff --git a/packages/google_adsense/example/integration_test/core_test.dart b/packages/google_adsense/example/integration_test/core_test.dart index 4193e414c1b..98e0503c0da 100644 --- a/packages/google_adsense/example/integration_test/core_test.dart +++ b/packages/google_adsense/example/integration_test/core_test.dart @@ -45,44 +45,55 @@ void main() async { expect(injected.async, true); }); - testWidgets('sets AdSenseCodeParameters in script tag.', - (WidgetTester _) async { + testWidgets('sets AdSenseCodeParameters in script tag.', ( + WidgetTester _, + ) async { final web.HTMLElement target = web.HTMLDivElement(); - await adSense.initialize(testClient, - jsLoaderTarget: target, - adSenseCodeParameters: AdSenseCodeParameters( - adHost: 'test-adHost', - admobInterstitialSlot: 'test-admobInterstitialSlot', - admobRewardedSlot: 'test-admobRewardedSlot', - adChannel: 'test-adChannel', - adbreakTest: 'test-adbreakTest', - tagForChildDirectedTreatment: 'test-tagForChildDirectedTreatment', - tagForUnderAgeOfConsent: 'test-tagForUnderAgeOfConsent', - adFrequencyHint: 'test-adFrequencyHint', - )); + await adSense.initialize( + testClient, + jsLoaderTarget: target, + adSenseCodeParameters: AdSenseCodeParameters( + adHost: 'test-adHost', + admobInterstitialSlot: 'test-admobInterstitialSlot', + admobRewardedSlot: 'test-admobRewardedSlot', + adChannel: 'test-adChannel', + adbreakTest: 'test-adbreakTest', + tagForChildDirectedTreatment: 'test-tagForChildDirectedTreatment', + tagForUnderAgeOfConsent: 'test-tagForUnderAgeOfConsent', + adFrequencyHint: 'test-adFrequencyHint', + ), + ); final web.HTMLScriptElement injected = target.lastElementChild! as web.HTMLScriptElement; expect(injected.dataset['adHost'], 'test-adHost'); - expect(injected.dataset['admobInterstitialSlot'], - 'test-admobInterstitialSlot'); + expect( + injected.dataset['admobInterstitialSlot'], + 'test-admobInterstitialSlot', + ); expect(injected.dataset['admobRewardedSlot'], 'test-admobRewardedSlot'); expect(injected.dataset['adChannel'], 'test-adChannel'); expect(injected.dataset['adbreakTest'], 'test-adbreakTest'); - expect(injected.dataset['tagForChildDirectedTreatment'], - 'test-tagForChildDirectedTreatment'); - expect(injected.dataset['tagForUnderAgeOfConsent'], - 'test-tagForUnderAgeOfConsent'); + expect( + injected.dataset['tagForChildDirectedTreatment'], + 'test-tagForChildDirectedTreatment', + ); + expect( + injected.dataset['tagForUnderAgeOfConsent'], + 'test-tagForUnderAgeOfConsent', + ); expect(injected.dataset['adFrequencyHint'], 'test-adFrequencyHint'); }); - testWidgets('Skips initialization if script is already present.', - (WidgetTester _) async { - final web.HTMLScriptElement script = web.HTMLScriptElement() - ..id = 'previously-injected' - ..src = testScriptUrl; + testWidgets('Skips initialization if script is already present.', ( + WidgetTester _, + ) async { + 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); @@ -91,8 +102,9 @@ void main() async { expect(target.firstElementChild?.id, 'previously-injected'); }); - testWidgets('Skips initialization if adsense object is already present.', - (WidgetTester _) async { + testWidgets('Skips initialization if adsense object is already present.', ( + WidgetTester _, + ) async { final web.HTMLElement target = web.HTMLDivElement(); // Write an empty noop object 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 54fa26e0a7f..0434217e424 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 @@ -44,17 +44,14 @@ void main() async { }); group('adSense.adUnit', () { - testWidgets('Responsive (with adFormat) ad units reflow flutter', - (WidgetTester tester) async { + testWidgets('Responsive (with adFormat) ad units reflow flutter', ( + WidgetTester tester, + ) async { // The size of the ad that we're going to "inject" const double expectedHeight = 137; // When - mockAdsByGoogle( - mockAd( - size: const Size(320, expectedHeight), - ), - ); + mockAdsByGoogle(mockAd(size: const Size(320, expectedHeight))); await adSense.initialize(testClient); @@ -80,47 +77,43 @@ void main() async { }); testWidgets( - 'Fixed size (without adFormat) ad units respect flutter constraints', - (WidgetTester tester) async { - const double maxHeight = 100; - const BoxConstraints constraints = BoxConstraints(maxHeight: maxHeight); - - // When - mockAdsByGoogle( - mockAd( - size: const Size(320, 157), - ), - ); - - await adSense.initialize(testClient); - - final CallbackTracker tracker = CallbackTracker(); - final Widget adUnitWidget = AdUnitWidget( - configuration: AdUnitConfiguration.displayAdUnit( - adSlot: testSlot, - ), - adClient: adSense.adClient, - onInjected: tracker.createCallback(), - ); - - final Widget constrainedAd = Container( - constraints: constraints, - child: adUnitWidget, - ); - - await pumpAdWidget(constrainedAd, tester, tracker); - - // Then - // Widget level - final Finder adUnit = find.byWidget(adUnitWidget); - expect(adUnit, findsOneWidget); - - final Size size = tester.getSize(adUnit); - expect(size.height, maxHeight); - }); - - testWidgets('Unfilled ad units collapse widget height', - (WidgetTester tester) async { + 'Fixed size (without adFormat) ad units respect flutter constraints', + (WidgetTester tester) async { + const double maxHeight = 100; + const BoxConstraints constraints = BoxConstraints(maxHeight: maxHeight); + + // When + mockAdsByGoogle(mockAd(size: const Size(320, 157))); + + await adSense.initialize(testClient); + + final CallbackTracker tracker = CallbackTracker(); + final Widget adUnitWidget = AdUnitWidget( + configuration: AdUnitConfiguration.displayAdUnit(adSlot: testSlot), + adClient: adSense.adClient, + onInjected: tracker.createCallback(), + ); + + final Widget constrainedAd = Container( + constraints: constraints, + child: adUnitWidget, + ); + + await pumpAdWidget(constrainedAd, tester, tracker); + + // Then + // Widget level + final Finder adUnit = find.byWidget(adUnitWidget); + expect(adUnit, findsOneWidget); + + final Size size = tester.getSize(adUnit); + expect(size.height, maxHeight); + }, + ); + + testWidgets('Unfilled ad units collapse widget height', ( + WidgetTester tester, + ) async { // When mockAdsByGoogle(mockAd(adStatus: AdStatus.UNFILLED)); @@ -128,9 +121,7 @@ void main() async { final CallbackTracker tracker = CallbackTracker(); final Widget adUnitWidget = AdUnitWidget( - configuration: AdUnitConfiguration.displayAdUnit( - adSlot: testSlot, - ), + configuration: AdUnitConfiguration.displayAdUnit(adSlot: testSlot), adClient: adSense.adClient, onInjected: tracker.createCallback(), ); @@ -138,8 +129,11 @@ void main() async { await pumpAdWidget(adUnitWidget, tester, tracker); // Then - expect(find.byType(HtmlElementView), findsNothing, - reason: 'Unfilled ads should remove their platform view'); + expect( + find.byType(HtmlElementView), + findsNothing, + reason: 'Unfilled ads should remove their platform view', + ); final Finder adUnit = find.byWidget(adUnitWidget); expect(adUnit, findsOneWidget); @@ -197,33 +191,42 @@ void main() async { // Then // Widget level final Finder platformViews = find.byType(HtmlElementView); - expect(platformViews, findsExactly(2), - reason: 'The platform view of unfilled ads should be removed.'); + expect( + platformViews, + findsExactly(2), + reason: 'The platform view of unfilled ads should be removed.', + ); final Finder adUnits = find.byType(AdUnitWidget); expect(adUnits, findsExactly(3)); - expect(tester.getSize(adUnits.at(0)).height, 200, - reason: 'Responsive ad widget should resize to match its `ins`'); - expect(tester.getSize(adUnits.at(1)).height, 0, - reason: 'Unfulfilled ad should be 0x0'); - expect(tester.getSize(adUnits.at(2)).height, 100, - reason: 'The constrained ad should use the height of container'); + expect( + tester.getSize(adUnits.at(0)).height, + 200, + reason: 'Responsive ad widget should resize to match its `ins`', + ); + expect( + tester.getSize(adUnits.at(1)).height, + 0, + reason: 'Unfulfilled ad should be 0x0', + ); + expect( + tester.getSize(adUnits.at(2)).height, + 100, + reason: 'The constrained ad should use the height of container', + ); }); }); } // Pumps an AdUnit Widget into a given tester, with some parameters Future pumpAdWidget( - Widget adUnit, WidgetTester tester, CallbackTracker tracker) async { + Widget adUnit, + WidgetTester tester, + 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/h5_test.dart b/packages/google_adsense/example/integration_test/h5_test.dart index 28ab89b460f..28cecff8502 100644 --- a/packages/google_adsense/example/integration_test/h5_test.dart +++ b/packages/google_adsense/example/integration_test/h5_test.dart @@ -25,9 +25,7 @@ void main() { group('h5GamesAds.adBreak', () { testWidgets('can do ad breaks', (WidgetTester tester) async { - mockAdsByGoogle( - mockAdBreak(), - ); + mockAdsByGoogle(mockAdBreak()); await adSense.initialize('_'); final AdBreakPlacement adBreakPlacement = AdBreakPlacement( @@ -45,8 +43,9 @@ void main() { expect(lastAdBreakPlacement!.type?.toDart, 'reward'); }); - testWidgets('can call the adBreakDone callback', - (WidgetTester tester) async { + testWidgets('can call the adBreakDone callback', ( + WidgetTester tester, + ) async { AdBreakDonePlacementInfo? lastPlacementInfo; void adBreakDoneCallback(AdBreakDonePlacementInfo placementInfo) { @@ -79,9 +78,7 @@ void main() { }); testWidgets('prefixes adBreak name', (WidgetTester tester) async { - mockAdsByGoogle( - mockAdBreak(), - ); + mockAdsByGoogle(mockAdBreak()); await adSense.initialize('_'); final AdBreakPlacement adBreakPlacement = AdBreakPlacement( @@ -107,9 +104,7 @@ void main() { called = true; } - mockAdsByGoogle( - mockAdConfig(), - ); + mockAdsByGoogle(mockAdConfig()); await adSense.initialize('_'); h5GamesAds.adConfig( 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 a48c22ecc84..9a9f140077c 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,13 +19,15 @@ 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 811f7eca910..31db6f21932 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 @@ -17,13 +17,8 @@ export 'adsbygoogle_js_interop.dart'; typedef MockAdConfig = ({Size size, String adStatus}); /// Returns a function that generates a "push" function for [mockAdsByGoogle]. -PushFn mockAd({ - Size size = Size.zero, - String adStatus = AdStatus.FILLED, -}) { - return mockAds( - [(size: size, adStatus: adStatus)], - ); +PushFn mockAd({Size size = Size.zero, String adStatus = AdStatus.FILLED}) { + return mockAds([(size: size, adStatus: adStatus)]); } /// Returns a function that handles a bunch of ad units at once. Can be used with [mockAdsByGoogle]. @@ -40,10 +35,11 @@ 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/integration_test/js_interop_mocks/h5_test_js_interop.dart b/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart index f28498fa68a..db4ea425154 100644 --- a/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart +++ b/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart @@ -14,9 +14,7 @@ export 'adsbygoogle_js_interop.dart'; /// Returns a push implementation that handles calls to `adBreak`. AdBreakPlacement? lastAdBreakPlacement; -PushFn mockAdBreak({ - AdBreakDonePlacementInfo? adBreakDonePlacementInfo, -}) { +PushFn mockAdBreak({AdBreakDonePlacementInfo? adBreakDonePlacementInfo}) { lastAdBreakPlacement = null; return (JSAny? adBreakPlacement) { adBreakPlacement as AdBreakPlacement?; @@ -25,8 +23,10 @@ PushFn mockAdBreak({ // Call `adBreakDone` if set, with `adBreakDonePlacementInfo`. if (adBreakPlacement?.adBreakDone != null) { assert(adBreakDonePlacementInfo != null); - adBreakPlacement!.adBreakDone! - .callAsFunction(null, adBreakDonePlacementInfo); + adBreakPlacement!.adBreakDone!.callAsFunction( + null, + adBreakDonePlacementInfo, + ); } }; } diff --git a/packages/google_adsense/example/lib/ad_unit_widget.dart b/packages/google_adsense/example/lib/ad_unit_widget.dart index 7ab1f380182..8d665ddd68a 100644 --- a/packages/google_adsense/example/lib/ad_unit_widget.dart +++ b/packages/google_adsense/example/lib/ad_unit_widget.dart @@ -56,15 +56,13 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text( - 'Responsive Ad Constrained by width of 150px:', - ), + const Text('Responsive Ad Constrained by width of 150px:'), Container( constraints: const BoxConstraints(maxWidth: 150), padding: const EdgeInsets.only(bottom: 10), child: - // #docregion adUnit - AdUnitWidget( + // #docregion adUnit + AdUnitWidget( configuration: AdUnitConfiguration.displayAdUnit( // TODO: Replace with your Ad Unit ID adSlot: '1234567890', @@ -79,8 +77,10 @@ class _MyHomePageState extends State { ), // #docregion constraints Container( - constraints: - const BoxConstraints(maxHeight: 100, maxWidth: 1200), + constraints: const BoxConstraints( + maxHeight: 100, + maxWidth: 1200, + ), padding: const EdgeInsets.only(bottom: 10), child: AdUnitWidget( configuration: AdUnitConfiguration.displayAdUnit( @@ -92,9 +92,7 @@ class _MyHomePageState extends State { ), ), // #enddocregion constraints - const Text( - 'Fixed 125x125 size Ad:', - ), + const Text('Fixed 125x125 size Ad:'), Container( height: 125, width: 125, diff --git a/packages/google_adsense/example/lib/h5.dart b/packages/google_adsense/example/lib/h5.dart index f40cfef2f99..fa4e192d374 100644 --- a/packages/google_adsense/example/lib/h5.dart +++ b/packages/google_adsense/example/lib/h5.dart @@ -169,17 +169,15 @@ class _MyHomePageState extends State { ), Text( 'Interstitial Ad Status:', - style: Theme.of(context).textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.bold, - ), + style: Theme.of( + context, + ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), ), Text('Last Status: ${_lastInterstitialInfo?.breakStatus}'), const Divider(), PaddedCard( children: [ - const Text( - '🪙 Available coins:', - ), + const Text('🪙 Available coins:'), Text( '$_coins', style: Theme.of(context).textTheme.displayLarge, @@ -199,9 +197,9 @@ class _MyHomePageState extends State { ), Text( 'Rewarded Ad Status:', - style: Theme.of(context).textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.bold, - ), + style: Theme.of( + context, + ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), ), Text('Requested? $_adBreakRequested'), Text('Available? $adBreakAvailable'), @@ -227,9 +225,7 @@ class PaddedCard extends StatelessWidget { margin: const EdgeInsets.only(bottom: 16), child: Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Column( - children: children, - ), + child: Column(children: children), ), ); } diff --git a/packages/google_adsense/example/pubspec.yaml b/packages/google_adsense/example/pubspec.yaml index 98b46062fd7..6585ef0768e 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 740ce728a4a..5f4f962c7d1 100644 --- a/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart +++ b/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart @@ -70,22 +70,21 @@ class AdUnitConfiguration { bool? isFullWidthResponsive = true, bool? isAdTest, }) : _adUnitParams = { - AdUnitParams.AD_SLOT: adSlot, - if (adFormat != null) AdUnitParams.AD_FORMAT: adFormat.toString(), - if (adLayout != null) AdUnitParams.AD_LAYOUT: adLayout.toString(), - if (adLayoutKey != null) AdUnitParams.AD_LAYOUT_KEY: adLayoutKey, - if (isFullWidthResponsive != null) - AdUnitParams.FULL_WIDTH_RESPONSIVE: - isFullWidthResponsive.toString(), - if (matchedContentUiType != null) - AdUnitParams.MATCHED_CONTENT_UI_TYPE: - matchedContentUiType.toString(), - if (columnsNum != null) - AdUnitParams.MATCHED_CONTENT_COLUMNS_NUM: columnsNum.toString(), - if (rowsNum != null) - AdUnitParams.MATCHED_CONTENT_ROWS_NUM: rowsNum.toString(), - if (isAdTest != null && isAdTest) AdUnitParams.AD_TEST: 'on', - }; + AdUnitParams.AD_SLOT: adSlot, + if (adFormat != null) AdUnitParams.AD_FORMAT: adFormat.toString(), + if (adLayout != null) AdUnitParams.AD_LAYOUT: adLayout.toString(), + if (adLayoutKey != null) AdUnitParams.AD_LAYOUT_KEY: adLayoutKey, + if (isFullWidthResponsive != null) + AdUnitParams.FULL_WIDTH_RESPONSIVE: isFullWidthResponsive.toString(), + if (matchedContentUiType != null) + AdUnitParams.MATCHED_CONTENT_UI_TYPE: + matchedContentUiType.toString(), + if (columnsNum != null) + AdUnitParams.MATCHED_CONTENT_COLUMNS_NUM: columnsNum.toString(), + if (rowsNum != null) + AdUnitParams.MATCHED_CONTENT_ROWS_NUM: rowsNum.toString(), + if (isAdTest != null && isAdTest) AdUnitParams.AD_TEST: 'on', + }; /// Creates a configuration object for a Multiplex ad. /// @@ -107,13 +106,14 @@ class AdUnitConfiguration { bool isFullWidthResponsive = true, bool isAdTest = kDebugMode, }) : this._internal( - adSlot: adSlot, - adFormat: adFormat, - matchedContentUiType: matchedContentUiType, - rowsNum: rowsNum, - columnsNum: columnsNum, - isFullWidthResponsive: isFullWidthResponsive, - isAdTest: isAdTest); + adSlot: adSlot, + adFormat: adFormat, + matchedContentUiType: matchedContentUiType, + rowsNum: rowsNum, + columnsNum: columnsNum, + isFullWidthResponsive: isFullWidthResponsive, + isAdTest: isAdTest, + ); /// Creates a configuration object for an In-feed ad. /// @@ -131,11 +131,12 @@ class AdUnitConfiguration { bool isFullWidthResponsive = true, bool isAdTest = kDebugMode, }) : this._internal( - adSlot: adSlot, - adFormat: adFormat, - adLayoutKey: adLayoutKey, - isFullWidthResponsive: isFullWidthResponsive, - isAdTest: isAdTest); + adSlot: adSlot, + adFormat: adFormat, + adLayoutKey: adLayoutKey, + isFullWidthResponsive: isFullWidthResponsive, + isAdTest: isAdTest, + ); /// Creates a configuration object for an In-article ad. /// @@ -153,11 +154,12 @@ class AdUnitConfiguration { bool isFullWidthResponsive = true, bool isAdTest = kDebugMode, }) : this._internal( - adSlot: adSlot, - adFormat: adFormat, - adLayout: adLayout, - isFullWidthResponsive: isFullWidthResponsive, - isAdTest: isAdTest); + adSlot: adSlot, + adFormat: adFormat, + adLayout: adLayout, + isFullWidthResponsive: isFullWidthResponsive, + isAdTest: isAdTest, + ); /// Creates a configuration object for a Display ad. /// @@ -173,10 +175,11 @@ class AdUnitConfiguration { bool isFullWidthResponsive = true, bool isAdTest = kDebugMode, }) : this._internal( - adSlot: adSlot, - adFormat: adFormat, - isFullWidthResponsive: isFullWidthResponsive, - isAdTest: isAdTest); + adSlot: adSlot, + adFormat: adFormat, + isFullWidthResponsive: isFullWidthResponsive, + isAdTest: isAdTest, + ); Map _adUnitParams; 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 f4a06c73a39..0da21547db0 100644 --- a/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart +++ b/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart @@ -34,11 +34,13 @@ class AdUnitWidget extends StatefulWidget { required AdUnitConfiguration configuration, @visibleForTesting String? adClient, @visibleForTesting void Function()? onInjected, - }) : _adClient = adClient ?? adSense.adClient, - _onInjected = onInjected, - _adUnitConfiguration = configuration { - assert(_adClient != null, - 'Attempted to render an AdUnitWidget before calling adSense.initialize'); + }) : _adClient = adClient ?? adSense.adClient, + _onInjected = onInjected, + _adUnitConfiguration = configuration { + assert( + _adClient != null, + 'Attempted to render an AdUnitWidget before calling adSense.initialize', + ); } final String? _adClient; @@ -61,19 +63,19 @@ class _AdUnitWidgetWebState extends State @override bool get wantKeepAlive => true; - web.ResizeObserver get _adSenseResizeObserver => - web.ResizeObserver((JSArray entries, - web.ResizeObserver observer) { - for (final web.ResizeObserverEntry entry in entries.toDart) { - final web.Element target = entry.target; - if (target.isConnected) { - // First time resized since attached to DOM -> attachment callback from Flutter docs by David - _onElementAttached(target as web.HTMLElement); - widget._onInjected?.call(); - observer.disconnect(); - } + web.ResizeObserver get _adSenseResizeObserver => web.ResizeObserver( + (JSArray entries, web.ResizeObserver observer) { + for (final web.ResizeObserverEntry entry in entries.toDart) { + final web.Element target = entry.target; + if (target.isConnected) { + // First time resized since attached to DOM -> attachment callback from Flutter docs by David + _onElementAttached(target as web.HTMLElement); + widget._onInjected?.call(); + observer.disconnect(); } - }.toJS); + } + }.toJS, + ); @override Widget build(BuildContext context) { @@ -83,20 +85,22 @@ class _AdUnitWidgetWebState extends State return const SizedBox.shrink(); } return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - if (!widget._adUnitConfiguration.params - .containsKey(AdUnitParams.AD_FORMAT)) { - _adSize = Size(_adSize.width, constraints.maxHeight); - } - return SizedBox( - height: _adSize.height, - width: _adSize.width, - child: HtmlElementView.fromTagName( - tagName: 'div', - onElementCreated: _onElementCreated, - ), - ); - }); + builder: (BuildContext context, BoxConstraints constraints) { + if (!widget._adUnitConfiguration.params.containsKey( + AdUnitParams.AD_FORMAT, + )) { + _adSize = Size(_adSize.width, constraints.maxHeight); + } + return SizedBox( + height: _adSize.height, + width: _adSize.width, + child: HtmlElementView.fromTagName( + tagName: 'div', + onElementCreated: _onElementCreated, + ), + ); + }, + ); } void _onElementCreated(Object element) { @@ -117,48 +121,55 @@ 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); // Using Mutation Observer to detect when adslot is being loaded based on https://support.google.com/adsense/answer/10762946?hl=en web.MutationObserver( - (JSArray entries, web.MutationObserver observer) { - for (final JSObject entry in entries.toDart) { - final web.HTMLElement target = - (entry as web.MutationRecord).target as web.HTMLElement; - if (_isLoaded(target)) { - if (_isFilled(target)) { - debugLog( - 'Resizing widget based on target $target size of ${target.offsetWidth} x ${target.offsetHeight}'); - _updateWidgetSize(Size( - target.offsetWidth.toDouble(), - // This is always the width of the platform view! - target.offsetHeight.toDouble(), - )); - } else { - // This removes the platform view. - _updateWidgetSize(Size.zero); + (JSArray entries, web.MutationObserver observer) { + for (final JSObject entry in entries.toDart) { + final web.HTMLElement target = + (entry as web.MutationRecord).target as web.HTMLElement; + if (_isLoaded(target)) { + if (_isFilled(target)) { + debugLog( + 'Resizing widget based on target $target size of ${target.offsetWidth} x ${target.offsetHeight}', + ); + _updateWidgetSize( + Size( + target.offsetWidth.toDouble(), + // This is always the width of the platform view! + target.offsetHeight.toDouble(), + ), + ); + } else { + // This removes the platform view. + _updateWidgetSize(Size.zero); + } } } - } - }.toJS) - .observe( - insElement, - web.MutationObserverInit( - attributes: true, - attributeFilter: ['data-ad-status'.toJS].toJS, - )); + }.toJS, + ).observe( + insElement, + web.MutationObserverInit( + attributes: true, + attributeFilter: ['data-ad-status'.toJS].toJS, + ), + ); } static void _onElementAttached(web.HTMLElement element) { debugLog( - '$element attached with w=${element.offsetWidth} and h=${element.offsetHeight}'); + '$element attached with w=${element.offsetWidth} and h=${element.offsetHeight}', + ); debugLog( - '${element.firstChild} size is ${(element.firstChild! as web.HTMLElement).offsetWidth}x${(element.firstChild! as web.HTMLElement).offsetHeight} '); + '${element.firstChild} size is ${(element.firstChild! as web.HTMLElement).offsetWidth}x${(element.firstChild! as web.HTMLElement).offsetHeight} ', + ); adsbygoogle.requestAd(); } diff --git a/packages/google_adsense/lib/src/core/adsense_code_parameters.dart b/packages/google_adsense/lib/src/core/adsense_code_parameters.dart index 3ab48bfbe25..318d9678c37 100644 --- a/packages/google_adsense/lib/src/core/adsense_code_parameters.dart +++ b/packages/google_adsense/lib/src/core/adsense_code_parameters.dart @@ -45,18 +45,18 @@ class AdSenseCodeParameters { String? tagForUnderAgeOfConsent, String? adFrequencyHint, }) : _adSenseCodeParameters = { - if (adHost != null) 'adHost': adHost, - if (admobInterstitialSlot != null) - 'admobInterstitialSlot': admobInterstitialSlot, - if (admobRewardedSlot != null) 'admobRewardedSlot': admobRewardedSlot, - if (adChannel != null) 'adChannel': adChannel, - if (adbreakTest != null) 'adbreakTest': adbreakTest, - if (tagForChildDirectedTreatment != null) - 'tagForChildDirectedTreatment': tagForChildDirectedTreatment, - if (tagForUnderAgeOfConsent != null) - 'tagForUnderAgeOfConsent': tagForUnderAgeOfConsent, - if (adFrequencyHint != null) 'adFrequencyHint': adFrequencyHint, - }; + if (adHost != null) 'adHost': adHost, + if (admobInterstitialSlot != null) + 'admobInterstitialSlot': admobInterstitialSlot, + if (admobRewardedSlot != null) 'admobRewardedSlot': admobRewardedSlot, + if (adChannel != null) 'adChannel': adChannel, + if (adbreakTest != null) 'adbreakTest': adbreakTest, + if (tagForChildDirectedTreatment != null) + 'tagForChildDirectedTreatment': tagForChildDirectedTreatment, + if (tagForUnderAgeOfConsent != null) + 'tagForUnderAgeOfConsent': tagForUnderAgeOfConsent, + if (adFrequencyHint != null) 'adFrequencyHint': adFrequencyHint, + }; final Map _adSenseCodeParameters; 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 12b44eacaa0..131c8f8f4a7 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,18 +33,20 @@ 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'; try { final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy( - trustedTypePolicyName, - web.TrustedTypePolicyOptions( - createScriptURL: ((JSString url) => url).toJS, - )); + trustedTypePolicyName, + web.TrustedTypePolicyOptions( + createScriptURL: ((JSString url) => url).toJS, + ), + ); script.trustedSrc = policy.createScriptURLNoArgs(scriptUrl); } catch (e) { throw TrustedTypesException(e.toString()); @@ -73,10 +75,7 @@ void _applyDataAttributes( // // [target] can be used to specify a different injection target than // `window.document.head`, and is normally used for tests. -bool _sdkAlreadyLoaded( - String adClient, - web.HTMLElement? target, -) { +bool _sdkAlreadyLoaded(String adClient, web.HTMLElement? target) { final String selector = 'script[src*=ca-pub-$adClient]'; return adsbygooglePresent || web.document.querySelector(selector) != null || diff --git a/packages/google_adsense/lib/src/h5/h5.dart b/packages/google_adsense/lib/src/h5/h5.dart index 8b7e0a96842..da844daf1ce 100644 --- a/packages/google_adsense/lib/src/h5/h5.dart +++ b/packages/google_adsense/lib/src/h5/h5.dart @@ -28,9 +28,7 @@ class H5GamesAdsClient { /// Requests an ad placement to the Ad Placement API. /// /// The [placementConfig] defines the configuration of the ad. - void adBreak( - AdBreakPlacement placementConfig, - ) { + void adBreak(AdBreakPlacement placementConfig) { // Delay the call to `adBreak` 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. @@ -48,9 +46,7 @@ class H5GamesAdsClient { /// Call this function as soon as the sound state of your game changes, as the /// Ad Placement API may have to request new creatives, and this gives it the /// maximum amount of time to do so. See `sound` in [AdConfigParameters]. - void adConfig( - AdConfigParameters parameters, - ) { + void adConfig(AdConfigParameters parameters) { adsbygoogle.adConfig(parameters); } } 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 5a0c4342e8e..892f2657766 100644 --- a/packages/google_adsense/lib/src/h5/h5_js_interop.dart +++ b/packages/google_adsense/lib/src/h5/h5_js_interop.dart @@ -117,18 +117,19 @@ 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, @@ -179,10 +180,7 @@ extension type AdBreakPlacement._(JSObject _) implements JSObject { factory AdBreakPlacement.preroll({ required H5AdBreakDoneCallback? adBreakDone, }) { - return AdBreakPlacement( - type: BreakType.preroll, - adBreakDone: adBreakDone, - ); + return AdBreakPlacement(type: BreakType.preroll, adBreakDone: adBreakDone); } /// Convenience factory to create an interstitial ad configuration. @@ -202,8 +200,10 @@ extension type AdBreakPlacement._(JSObject _) implements JSObject { H5AfterAdCallback? afterAd, H5AdBreakDoneCallback? adBreakDone, }) { - assert(interstitialBreakType.contains(type), - '$type is not a valid interstitial placement type.'); + assert( + interstitialBreakType.contains(type), + '$type is not a valid interstitial placement type.', + ); return AdBreakPlacement( type: type, name: name, @@ -224,15 +224,16 @@ extension type AdBreakPlacement._(JSObject _) implements JSObject { JSFunction? adBreakDone, }) { return { - if (type != null) 'type': type, - if (name != null) 'name': name, - if (beforeAd != null) 'beforeAd': beforeAd, - if (afterAd != null) 'afterAd': afterAd, - if (beforeReward != null) 'beforeReward': beforeReward, - if (adDismissed != null) 'adDismissed': adDismissed, - if (adViewed != null) 'adViewed': adViewed, - if (adBreakDone != null) 'adBreakDone': adBreakDone, - }.jsify()! as AdBreakPlacement; + if (type != null) 'type': type, + if (name != null) 'name': name, + if (beforeAd != null) 'beforeAd': beforeAd, + if (afterAd != null) 'afterAd': afterAd, + if (beforeReward != null) 'beforeReward': beforeReward, + if (adDismissed != null) 'adDismissed': adDismissed, + if (adViewed != null) 'adViewed': adViewed, + if (adBreakDone != null) 'adBreakDone': adBreakDone, + }.jsify()! + as AdBreakPlacement; } } @@ -267,10 +268,11 @@ extension type AdConfigParameters._(JSObject _) implements JSObject { JSFunction? onReady, }) { return { - if (sound != null) 'sound': sound, - if (preloadAdBreaks != null) 'preloadAdBreaks': preloadAdBreaks, - if (onReady != null) 'onReady': onReady, - }.jsify()! as AdConfigParameters; + if (sound != null) 'sound': sound, + if (preloadAdBreaks != null) 'preloadAdBreaks': preloadAdBreaks, + if (onReady != null) 'onReady': onReady, + }.jsify()! + as AdConfigParameters; } } @@ -320,8 +322,8 @@ typedef H5BeforeAdCallback = void Function(); typedef H5AfterAdCallback = void Function(); /// The type of the `adBreakDone` callback. -typedef H5AdBreakDoneCallback = void Function( - AdBreakDonePlacementInfo placementInfo); +typedef H5AdBreakDoneCallback = + void Function(AdBreakDonePlacementInfo placementInfo); /// The type of the `beforeReward` callback. typedef H5BeforeRewardCallback = void Function(H5ShowAdFn showAdFn); diff --git a/packages/google_adsense/pubspec.yaml b/packages/google_adsense/pubspec.yaml index 2a90e49ca37..3b2b65b937b 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/google_identity_services_web/CHANGELOG.md b/packages/google_identity_services_web/CHANGELOG.md index f17834a1207..0ab3ba62c3e 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.3.3+1 diff --git a/packages/google_identity_services_web/README.md b/packages/google_identity_services_web/README.md index f82eeb9b372..f5a087f3155 100644 --- a/packages/google_identity_services_web/README.md +++ b/packages/google_identity_services_web/README.md @@ -48,7 +48,7 @@ import 'package:google_identity_services_web/loader.dart' as gis; void main() async { await gis.loadWebSdk(); // Load the GIS SDK // The rest of your code... -// ··· + // ··· } ``` diff --git a/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart b/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart index c49ed40cf3c..ba007927876 100644 --- a/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart +++ b/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart @@ -57,8 +57,8 @@ void main() async { use_fedcm_for_prompt: true, ); - final utils.ExpectConfigValueFn expectConfigValue = - utils.createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils + .createExpectConfigValue(config as JSObject); expectConfigValue('client_id', 'testing_1-2-3'); expectConfigValue('auto_select', false); @@ -66,15 +66,19 @@ void main() async { expectConfigValue('login_uri', 'https://www.example.com/login'); expectConfigValue('native_callback', utils.isAJs('function')); expectConfigValue('cancel_on_tap_outside', false); - expectConfigValue( - 'allowed_parent_origin', ['allowed', 'another']); + expectConfigValue('allowed_parent_origin', [ + 'allowed', + 'another', + ]); expectConfigValue('prompt_parent_id', 'some_dom_id'); expectConfigValue('nonce', 's0m3_r4ndOM_vALu3'); expectConfigValue('context', 'signin'); expectConfigValue('state_cookie_domain', 'subdomain.example.com'); expectConfigValue('ux_mode', 'popup'); expectConfigValue( - 'intermediate_iframe_close_callback', utils.isAJs('function')); + 'intermediate_iframe_close_callback', + utils.isAJs('function'), + ); expectConfigValue('itp_support', true); expectConfigValue('login_hint', 'login-hint@example.com'); expectConfigValue('hd', 'hd_value'); @@ -84,38 +88,41 @@ void main() async { group('prompt', () { testWidgets( - 'supports a moment notification callback with correct type and reason', - (_) async { - id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); - utils.setMockMomentNotification('skipped', 'user_cancel'); + 'supports a moment notification callback with correct type and reason', + (_) async { + id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); + utils.setMockMomentNotification('skipped', 'user_cancel'); - final StreamController controller = - StreamController(); + final StreamController controller = + StreamController(); - id.prompt(controller.add); + id.prompt(controller.add); - final PromptMomentNotification moment = await controller.stream.first; + final PromptMomentNotification moment = await controller.stream.first; - expect(moment.getMomentType(), MomentType.skipped); - expect(moment.getSkippedReason(), MomentSkippedReason.user_cancel); - }); + expect(moment.getMomentType(), MomentType.skipped); + expect(moment.getSkippedReason(), MomentSkippedReason.user_cancel); + }, + ); testWidgets( - 'supports a moment notification callback while handling invalid reason ' - 'value gracefully', (_) async { - id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); - utils.setMockMomentNotification('skipped', 'random_invalid_reason'); + 'supports a moment notification callback while handling invalid reason ' + 'value gracefully', + (_) async { + id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); + utils.setMockMomentNotification('skipped', 'random_invalid_reason'); - final StreamController controller = - StreamController(); + final StreamController controller = + StreamController(); - id.prompt(controller.add); + id.prompt(controller.add); - final PromptMomentNotification moment = await controller.stream.first; + final PromptMomentNotification moment = await controller.stream.first; - expect(moment.getMomentType(), MomentType.skipped); - expect(moment.getSkippedReason(), isNull); - }); + expect(moment.getMomentType(), MomentType.skipped); + expect(moment.getSkippedReason(), isNull); + }, + ); testWidgets('calls config callback with credential response', (_) async { const String expected = 'should_be_a_proper_jwt_token'; @@ -124,10 +131,9 @@ void main() async { final StreamController controller = StreamController(); - id.initialize(IdConfiguration( - client_id: 'testing_1-2-3', - callback: controller.add, - )); + id.initialize( + IdConfiguration(client_id: 'testing_1-2-3', callback: controller.add), + ); id.prompt(); diff --git a/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart b/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart index b65b5d8a8e3..96562f085b3 100644 --- a/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart +++ b/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart @@ -37,8 +37,8 @@ void main() async { error_callback: (GoogleIdentityServicesError? _) {}, ); - final utils.ExpectConfigValueFn expectConfigValue = - utils.createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils + .createExpectConfigValue(config as JSObject); expectConfigValue('client_id', 'testing_1-2-3'); expectConfigValue('callback', utils.isAJs('function')); @@ -62,8 +62,8 @@ void main() async { state: 'some-state', ); - final utils.ExpectConfigValueFn expectConfigValue = - utils.createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils + .createExpectConfigValue(config as JSObject); expectConfigValue('scope', 'one two three'); expectConfigValue('include_granted_scopes', true); @@ -89,8 +89,8 @@ void main() async { error_callback: (GoogleIdentityServicesError? _) {}, ); - final utils.ExpectConfigValueFn expectConfigValue = - utils.createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils + .createExpectConfigValue(config as JSObject); expectConfigValue('scope', 'one two three'); expectConfigValue('include_granted_scopes', true); @@ -108,11 +108,13 @@ void main() async { group('initTokenClient', () { testWidgets('returns a tokenClient', (_) async { - final TokenClient client = oauth2.initTokenClient(TokenClientConfig( - client_id: 'for-tests', - callback: (TokenResponse _) {}, - scope: ['some_scope', 'for_tests', 'not_real'], - )); + final TokenClient client = oauth2.initTokenClient( + TokenClientConfig( + client_id: 'for-tests', + callback: (TokenResponse _) {}, + scope: ['some_scope', 'for_tests', 'not_real'], + ), + ); expect(client, isNotNull); }); @@ -125,11 +127,13 @@ void main() async { final List scopes = ['some_scope', 'another', 'more']; - final TokenClient client = oauth2.initTokenClient(TokenClientConfig( - client_id: 'for-tests', - callback: controller.add, - scope: scopes, - )); + final TokenClient client = oauth2.initTokenClient( + TokenClientConfig( + client_id: 'for-tests', + callback: controller.add, + scope: scopes, + ), + ); utils.setMockTokenResponse(client, 'some-non-null-auth-token-value'); @@ -148,17 +152,17 @@ void main() async { final List scopes = ['some_scope', 'another', 'more']; - final TokenClient client = oauth2.initTokenClient(TokenClientConfig( - client_id: 'for-tests', - callback: controller.add, - scope: ['blank'], - )); + final TokenClient client = oauth2.initTokenClient( + TokenClientConfig( + client_id: 'for-tests', + callback: controller.add, + scope: ['blank'], + ), + ); utils.setMockTokenResponse(client, 'some-non-null-auth-token-value'); - client.requestAccessToken(OverridableTokenClientConfig( - scope: scopes, - )); + client.requestAccessToken(OverridableTokenClientConfig(scope: scopes)); final TokenResponse response = await controller.stream.first; 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 a27cce2f405..63ab5c5f52a 100644 --- a/packages/google_identity_services_web/example/integration_test/utils.dart +++ b/packages/google_identity_services_web/example/integration_test/utils.dart @@ -30,12 +30,13 @@ 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(), - 'Array with matching values', - old); + (JSAny? p0) => + (p0 as JSArray?)?.toDart + .map((JSAny? e) => e.dartify()) + .toList(), + 'Array with matching values', + old, + ); } expect(config[name], matcher, reason: name); }; @@ -44,8 +45,11 @@ ExpectConfigValueFn createExpectConfigValue(JSObject config) { /// A matcher that checks if: value typeof [thing] == true (in JS). /// /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof -Matcher isAJs(String thing) => isA() - .having((JSAny? p0) => p0.typeofEquals(thing), 'typeof "$thing"', isTrue); +Matcher isAJs(String thing) => isA().having( + (JSAny? p0) => p0.typeofEquals(thing), + 'typeof "$thing"', + isTrue, +); /// Installs mock-gis.js in the page. /// Returns a future that completes when the 'load' event of the script fires. @@ -57,10 +61,11 @@ Future installGisMock() { script.src = 'mock-gis.js'; script.type = 'module'; script.addEventListener( - 'load', - (JSAny? _) { - completer.complete(); - }.toJS); + 'load', + (JSAny? _) { + completer.complete(); + }.toJS, + ); web.document.head!.appendChild(script); return completer.future; @@ -70,11 +75,13 @@ Future installGisMock() { Future fakeAuthZWithScopes(List scopes) { final StreamController controller = StreamController(); - final TokenClient client = oauth2.initTokenClient(TokenClientConfig( - client_id: 'for-tests', - callback: controller.add, - scope: scopes, - )); + final TokenClient client = oauth2.initTokenClient( + TokenClientConfig( + client_id: 'for-tests', + callback: controller.add, + scope: scopes, + ), + ); setMockTokenResponse(client, 'some-non-null-auth-token-value'); client.requestAccessToken(); return controller.stream.first; @@ -98,10 +105,7 @@ extension on GoogleAccountsId { JSString select_by, //ignore: non_constant_identifier_names ); - external void setMockMomentNotification( - JSString momentType, - JSString reason, - ); + external void setMockMomentNotification(JSString momentType, JSString reason); } /// Sets a mock credential response in `google.accounts.id`. @@ -111,20 +115,25 @@ void setMockCredentialResponse([String value = 'default_value']) { /// Sets a mock moment notification in `google.accounts.id`. void setMockMomentNotification(String momentType, String reason) { - _getGoogleAccountsId() - .setMockMomentNotification(momentType.toJS, reason.toJS); + _getGoogleAccountsId().setMockMomentNotification( + momentType.toJS, + reason.toJS, + ); } GoogleAccountsId _getGoogleAccountsId() { return _getDeepProperty( - web.window as JSObject, 'google.accounts.id'); + web.window as JSObject, + 'google.accounts.id', + ); } // Attempts to retrieve a deeply nested property from a jsObject (or die tryin') T _getDeepProperty(JSObject jsObject, String deepProperty) { final List properties = deepProperty.split('.'); return properties.fold( - jsObject, - (JSObject? jsObj, String prop) => jsObj?[prop] as JSObject?, - ) as T; + jsObject, + (JSObject? jsObj, String prop) => jsObj?[prop] as JSObject?, + ) + as T; } diff --git a/packages/google_identity_services_web/example/lib/main.dart b/packages/google_identity_services_web/example/lib/main.dart index a8f6239dbff..1373fe1d550 100644 --- a/packages/google_identity_services_web/example/lib/main.dart +++ b/packages/google_identity_services_web/example/lib/main.dart @@ -15,7 +15,7 @@ import 'src/jwt.dart' as jwt; void main() async { await gis.loadWebSdk(); // Load the GIS SDK // The rest of your code... -// #enddocregion use-loader + // #enddocregion use-loader id.setLogLevel('debug'); final IdConfiguration config = IdConfiguration( @@ -26,7 +26,7 @@ void main() async { id.initialize(config); id.prompt(onPromptMoment); -// #docregion use-loader + // #docregion use-loader } // #enddocregion use-loader diff --git a/packages/google_identity_services_web/example/lib/main_oauth.dart b/packages/google_identity_services_web/example/lib/main_oauth.dart index 05fed3ba5f4..5f77a40d09d 100644 --- a/packages/google_identity_services_web/example/lib/main_oauth.dart +++ b/packages/google_identity_services_web/example/lib/main_oauth.dart @@ -43,9 +43,7 @@ void main() async { ); final OverridableTokenClientConfig overridableCfg = - OverridableTokenClientConfig( - scope: scopes + myConnectionsScopes, - ); + OverridableTokenClientConfig(scope: scopes + myConnectionsScopes); final TokenClient client = oauth2.initTokenClient(config); @@ -98,9 +96,12 @@ Future onTokenResponse(TokenResponse token) async { /// Attempts to [jsonDecode] the result. Future get(TokenResponse token, String url) async { final Uri uri = Uri.parse(url); - final http.Response response = await http.get(uri, headers: { - 'Authorization': '${token.token_type} ${token.access_token}', - }); + final http.Response response = await http.get( + uri, + headers: { + 'Authorization': '${token.token_type} ${token.access_token}', + }, + ); if (response.statusCode != 200) { throw http.ClientException(response.body, uri); diff --git a/packages/google_identity_services_web/example/lib/src/jwt.dart b/packages/google_identity_services_web/example/lib/src/jwt.dart index bc17f49a784..6ce76fe7816 100644 --- a/packages/google_identity_services_web/example/lib/src/jwt.dart +++ b/packages/google_identity_services_web/example/lib/src/jwt.dart @@ -17,7 +17,8 @@ final Codec _jwtCodec = json.fuse(utf8).fuse(base64); /// /// More info: https://regexr.com/789qc final RegExp _jwtTokenRegexp = RegExp( - r'^(?
[^\.\s]+)\.(?[^\.\s]+)\.(?[^\.\s]+)$'); + r'^(?
[^\.\s]+)\.(?[^\.\s]+)\.(?[^\.\s]+)$', +); /// Decodes the `claims` of a JWT token and returns them as a Map. /// diff --git a/packages/google_identity_services_web/example/pubspec.yaml b/packages/google_identity_services_web/example/pubspec.yaml index 618751773af..a24849fcfa3 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 7679f8fad1d..0abcf81fd2e 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 @@ -95,12 +95,11 @@ extension type GoogleAccountsId._(JSObject _) implements JSObject { /// /// Method: google.accounts.id.renderButton /// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.renderButton - void renderButton( - Object parent, [ - GsiButtonConfiguration? options, - ]) { - assert(parent is JSObject, - 'parent must be a JSObject. Use package:web to retrieve/create one.'); + void renderButton(Object parent, [GsiButtonConfiguration? options]) { + assert( + parent is JSObject, + 'parent must be a JSObject. Use package:web to retrieve/create one.', + ); parent as JSObject; if (options == null) { return _renderButton(parent); @@ -112,7 +111,9 @@ extension type GoogleAccountsId._(JSObject _) implements JSObject { external void _renderButton(JSObject parent); @JS('renderButton') external void _renderButtonWithOptions( - JSObject parent, GsiButtonConfiguration options); + JSObject parent, + GsiButtonConfiguration options, + ); /// Record when the user signs out of your website in cookies. /// @@ -141,7 +142,9 @@ extension type GoogleAccountsId._(JSObject _) implements JSObject { external void _jsStoreCredential(Credential credential); @JS('storeCredential') external void _jsStoreCredentialWithCallback( - Credential credential, JSFunction callback); + Credential credential, + JSFunction callback, + ); /// Cancels the One Tap flow. /// @@ -381,7 +384,9 @@ extension type PromptMomentNotification._(JSObject _) implements JSObject { /// The detailed reason why the UI isn't displayed. MomentNotDisplayedReason? getNotDisplayedReason() => maybeEnum( - _getNotDisplayedReason()?.toDart, MomentNotDisplayedReason.values); + _getNotDisplayedReason()?.toDart, + MomentNotDisplayedReason.values, + ); @JS('getNotDisplayedReason') external JSString? _getNotDisplayedReason(); @@ -541,19 +546,10 @@ typedef GsiButtonClickListenerFn = void Function(GsiButtonData? gsiButtonData); /// https://developers.google.com/identity/gsi/web/reference/js-reference#type-Credential extension type Credential._(JSObject _) implements JSObject { /// - factory Credential({ - required String id, - required String password, - }) => - Credential._toJS( - id: id.toJS, - password: password.toJS, - ); - - external factory Credential._toJS({ - JSString id, - JSString password, - }); + factory Credential({required String id, required String password}) => + Credential._toJS(id: id.toJS, password: password.toJS); + + external factory Credential._toJS({JSString id, JSString password}); } /// The fields that are contained in the [Credential] object. @@ -583,9 +579,8 @@ typedef NativeCallbackFn = void Function(Credential credential); /// The type of the `callback` function passed to [revoke], to be notified of /// the success of the revocation operation. -typedef RevocationResponseHandlerFn = void Function( - RevocationResponse revocationResponse, -); +typedef RevocationResponseHandlerFn = + void Function(RevocationResponse revocationResponse); /// The parameter passed to the `callback` of the [revoke] function. /// diff --git a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart index 64402069004..928ae871b86 100644 --- a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart +++ b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart @@ -45,8 +45,9 @@ extension type GoogleAccountsOauth2._(JSObject _) implements JSObject { /// Method: google.accounts.oauth2.hasGrantedAllScopes /// https://developers.google.com/identity/oauth2/web/reference/js-reference#google.accounts.oauth2.hasGrantedAllScopes bool hasGrantedAllScopes(TokenResponse tokenResponse, List scopes) { - return scopes - .every((String scope) => _hasGrantedScope(tokenResponse, scope.toJS)); + return scopes.every( + (String scope) => _hasGrantedScope(tokenResponse, scope.toJS), + ); } /// Checks if hte user has granted **all** the specified [scopes]. @@ -56,8 +57,9 @@ extension type GoogleAccountsOauth2._(JSObject _) implements JSObject { /// Method: google.accounts.oauth2.hasGrantedAllScopes /// https://developers.google.com/identity/oauth2/web/reference/js-reference#google.accounts.oauth2.hasGrantedAllScopes bool hasGrantedAnyScopes(TokenResponse tokenResponse, List scopes) { - return scopes - .any((String scope) => _hasGrantedScope(tokenResponse, scope.toJS)); + return scopes.any( + (String scope) => _hasGrantedScope(tokenResponse, scope.toJS), + ); } /// Revokes all of the scopes that the user granted to the app. @@ -69,10 +71,7 @@ extension type GoogleAccountsOauth2._(JSObject _) implements JSObject { /// /// Method: google.accounts.oauth2.revoke /// https://developers.google.com/identity/oauth2/web/reference/js-reference#google.accounts.oauth2.revoke - void revoke( - String accessToken, [ - RevokeTokenDoneFn? done, - ]) { + void revoke(String accessToken, [RevokeTokenDoneFn? done]) { if (done == null) { return _revoke(accessToken.toJS); } @@ -259,9 +258,7 @@ extension type TokenClientConfig._(JSObject _) implements JSObject { /// https://developers.google.com/identity/oauth2/web/reference/js-reference#TokenClient extension type TokenClient._(JSObject _) implements JSObject { /// Starts the OAuth 2.0 Code UX flow. - void requestAccessToken([ - OverridableTokenClientConfig? overrideConfig, - ]) { + void requestAccessToken([OverridableTokenClientConfig? overrideConfig]) { if (overrideConfig == null) { return _requestAccessToken(); } @@ -272,7 +269,8 @@ extension type TokenClient._(JSObject _) implements JSObject { external void _requestAccessToken(); @JS('requestAccessToken') external void _requestAccessTokenWithConfig( - OverridableTokenClientConfig config); + OverridableTokenClientConfig config, + ); } /// The overridable configuration object for the [TokenClientExtension.requestAccessToken] method. diff --git a/packages/google_identity_services_web/lib/src/js_interop/package_web_tweaks.dart b/packages/google_identity_services_web/lib/src/js_interop/package_web_tweaks.dart index e841aaa54d0..be9ca42224e 100644 --- a/packages/google_identity_services_web/lib/src/js_interop/package_web_tweaks.dart +++ b/packages/google_identity_services_web/lib/src/js_interop/package_web_tweaks.dart @@ -30,9 +30,7 @@ extension TrustedTypeSrcAttribute on web.HTMLScriptElement { extension CreateScriptUrlNoArgs on web.TrustedTypePolicy { /// Allows calling `createScriptURL` with only the `input` argument. @JS('createScriptURL') - external web.TrustedScriptURL createScriptURLNoArgs( - String input, - ); + external web.TrustedScriptURL createScriptURLNoArgs(String input); } /// This extension gives web.HTMLScriptElement a nullable getter to the 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 af59526501b..8dc56c81983 100644 --- a/packages/google_identity_services_web/lib/src/js_loader.dart +++ b/packages/google_identity_services_web/lib/src/js_loader.dart @@ -44,19 +44,21 @@ Future loadWebSdk({ ); try { final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy( - trustedTypePolicyName, - web.TrustedTypePolicyOptions( - createScriptURL: ((JSString url) => _url).toJS, - )); + trustedTypePolicyName, + web.TrustedTypePolicyOptions( + createScriptURL: ((JSString url) => _url).toJS, + ), + ); trustedUrl = policy.createScriptURLNoArgs(_url); } catch (e) { throw TrustedTypesException(e.toString()); } } - 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 { @@ -83,8 +85,9 @@ String? _getNonce({String? suppliedNonce, web.Window? window}) { } final web.Window currentWindow = window ?? web.window; - final web.NodeList elements = - currentWindow.document.querySelectorAll('script'); + final web.NodeList elements = currentWindow.document.querySelectorAll( + 'script', + ); for (int i = 0; i < elements.length; i++) { if (elements.item(i) case final web.HTMLScriptElement element) { diff --git a/packages/google_identity_services_web/pubspec.yaml b/packages/google_identity_services_web/pubspec.yaml index 2a7c85f2d09..911900abeeb 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.6.0 + sdk: ^3.7.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 58b73bb9a4f..de854e463f4 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_sign_in/google_sign_in/CHANGELOG.md b/packages/google_sign_in/google_sign_in/CHANGELOG.md index 7b8950b5962..9ae572566f0 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.29/Dart 3.7. + ## 7.1.1 * Adds more documentation about the requirement to call `initialize` exactly diff --git a/packages/google_sign_in/google_sign_in/README.md b/packages/google_sign_in/google_sign_in/README.md index 772977ca322..0a29d0c47da 100644 --- a/packages/google_sign_in/google_sign_in/README.md +++ b/packages/google_sign_in/google_sign_in/README.md @@ -31,18 +31,20 @@ authentication process: ```dart final GoogleSignIn signIn = GoogleSignIn.instance; -unawaited(signIn - .initialize(clientId: clientId, serverClientId: serverClientId) - .then((_) { - signIn.authenticationEvents - .listen(_handleAuthenticationEvent) - .onError(_handleAuthenticationError); - - /// This example always uses the stream-based approach to determining - /// which UI state to show, rather than using the future returned here, - /// if any, to conditionally skip directly to the signed-in state. - signIn.attemptLightweightAuthentication(); -})); +unawaited( + signIn.initialize(clientId: clientId, serverClientId: serverClientId).then(( + _, + ) { + signIn.authenticationEvents + .listen(_handleAuthenticationEvent) + .onError(_handleAuthenticationError); + + /// This example always uses the stream-based approach to determining + /// which UI state to show, rather than using the future returned here, + /// if any, to conditionally skip directly to the signed-in state. + signIn.attemptLightweightAuthentication(); + }), +); ``` If the user isn't signed in by the lightweight method, you can show UI to @@ -69,7 +71,7 @@ else ...[ if (kIsWeb) web.renderButton() // ··· -] +], ``` ## Authorization @@ -85,8 +87,9 @@ const List scopes = [ 'https://www.googleapis.com/auth/contacts.readonly', ]; final GoogleSignInAccount? user = // ... - final GoogleSignInClientAuthorization? authorization = - await user?.authorizationClient.authorizationForScopes(scopes); + final GoogleSignInClientAuthorization? authorization = await user + ?.authorizationClient + .authorizationForScopes(scopes); ``` [Full list of available scopes](https://developers.google.com/identity/protocols/googlescopes). @@ -100,8 +103,9 @@ this request **must be initiated from a user interaction** like a button press. ```dart -final GoogleSignInClientAuthorization authorization = - await user.authorizationClient.authorizeScopes(scopes); +final GoogleSignInClientAuthorization authorization = await user + .authorizationClient + .authorizeScopes(scopes); ``` ### Authorization expiration @@ -123,8 +127,9 @@ request a server auth code to send to the server: ```dart -final GoogleSignInServerAuthorization? serverAuth = - await user.authorizationClient.authorizeServer(scopes); +final GoogleSignInServerAuthorization? serverAuth = await user + .authorizationClient + .authorizeServer(scopes); ``` Server auth codes are not always available on all platforms. For instance, on 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 22c90a96d80..4f64ba1ffbd 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 @@ -30,12 +30,7 @@ const List scopes = [ // #enddocregion CheckAuthorization void main() { - runApp( - const MaterialApp( - title: 'Google Sign In', - home: SignInDemo(), - ), - ); + runApp(const MaterialApp(title: 'Google Sign In', home: SignInDemo())); } /// The SignInDemo app. @@ -60,35 +55,39 @@ class _SignInDemoState extends State { // #docregion Setup final GoogleSignIn signIn = GoogleSignIn.instance; - unawaited(signIn - .initialize(clientId: clientId, serverClientId: serverClientId) - .then((_) { - signIn.authenticationEvents - .listen(_handleAuthenticationEvent) - .onError(_handleAuthenticationError); - - /// This example always uses the stream-based approach to determining - /// which UI state to show, rather than using the future returned here, - /// if any, to conditionally skip directly to the signed-in state. - signIn.attemptLightweightAuthentication(); - })); + unawaited( + signIn.initialize(clientId: clientId, serverClientId: serverClientId).then(( + _, + ) { + signIn.authenticationEvents + .listen(_handleAuthenticationEvent) + .onError(_handleAuthenticationError); + + /// This example always uses the stream-based approach to determining + /// which UI state to show, rather than using the future returned here, + /// if any, to conditionally skip directly to the signed-in state. + signIn.attemptLightweightAuthentication(); + }), + ); // #enddocregion Setup } Future _handleAuthenticationEvent( - GoogleSignInAuthenticationEvent event) async { + GoogleSignInAuthenticationEvent event, + ) async { // #docregion CheckAuthorization final GoogleSignInAccount? user = // ... - // #enddocregion CheckAuthorization - switch (event) { + // #enddocregion CheckAuthorization + switch (event) { GoogleSignInAuthenticationEventSignIn() => event.user, GoogleSignInAuthenticationEventSignOut() => null, }; // Check for existing authorization. // #docregion CheckAuthorization - final GoogleSignInClientAuthorization? authorization = - await user?.authorizationClient.authorizationForScopes(scopes); + final GoogleSignInClientAuthorization? authorization = await user + ?.authorizationClient + .authorizationForScopes(scopes); // #enddocregion CheckAuthorization setState(() { @@ -108,9 +107,10 @@ 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'; }); } @@ -119,8 +119,8 @@ class _SignInDemoState extends State { setState(() { _contactText = 'Loading contact info...'; }); - final Map? headers = - await user.authorizationClient.authorizationHeaders(scopes); + final Map? headers = await user.authorizationClient + .authorizationHeaders(scopes); if (headers == null) { setState(() { _contactText = ''; @@ -129,21 +129,25 @@ class _SignInDemoState extends State { return; } final http.Response response = await http.get( - Uri.parse('https://people.googleapis.com/v1/people/me/connections' - '?requestMask.includeField=person.names'), + Uri.parse( + 'https://people.googleapis.com/v1/people/me/connections' + '?requestMask.includeField=person.names', + ), headers: headers, ); if (response.statusCode != 200) { if (response.statusCode == 401 || response.statusCode == 403) { setState(() { _isAuthorized = false; - _errorMessage = 'People API gave a ${response.statusCode} response. ' + _errorMessage = + 'People API gave a ${response.statusCode} response. ' 'Please re-authorize access.'; }); } else { print('People API ${response.statusCode} response: ${response.body}'); setState(() { - _contactText = 'People API gave a ${response.statusCode} ' + _contactText = + 'People API gave a ${response.statusCode} ' 'response. Check logs for details.'; }); } @@ -163,17 +167,22 @@ class _SignInDemoState extends State { String? _pickFirstNamedContact(Map data) { final List? connections = data['connections'] as List?; - final Map? contact = connections?.firstWhere( - (dynamic contact) => (contact as Map)['names'] != null, - orElse: () => null, - ) as Map?; + final Map? contact = + connections?.firstWhere( + (dynamic contact) => + (contact as Map)['names'] != null, + orElse: () => null, + ) + as Map?; if (contact != null) { final List names = contact['names'] as List; - final Map? name = names.firstWhere( - (dynamic name) => - (name as Map)['displayName'] != null, - orElse: () => null, - ) as Map?; + final Map? name = + names.firstWhere( + (dynamic name) => + (name as Map)['displayName'] != null, + orElse: () => null, + ) + as Map?; if (name != null) { return name['displayName'] as String?; } @@ -189,8 +198,9 @@ class _SignInDemoState extends State { Future _handleAuthorizeScopes(GoogleSignInAccount user) async { try { // #docregion RequestScopes - final GoogleSignInClientAuthorization authorization = - await user.authorizationClient.authorizeScopes(scopes); + final GoogleSignInClientAuthorization authorization = await user + .authorizationClient + .authorizeScopes(scopes); // #enddocregion RequestScopes // The returned tokens are ignored since _handleGetContact uses the @@ -220,8 +230,9 @@ class _SignInDemoState extends State { Future _handleGetAuthCode(GoogleSignInAccount user) async { try { // #docregion RequestServerAuth - final GoogleSignInServerAuthorization? serverAuth = - await user.authorizationClient.authorizeServer(scopes); + final GoogleSignInServerAuthorization? serverAuth = await user + .authorizationClient + .authorizeServer(scopes); // #enddocregion RequestServerAuth setState(() { @@ -257,9 +268,7 @@ class _SignInDemoState extends State { return [ // The user is Authenticated. ListTile( - leading: GoogleUserCircleAvatar( - identity: user, - ), + leading: GoogleUserCircleAvatar(identity: user), title: Text(user.displayName ?? ''), subtitle: Text(user.email), ), @@ -286,10 +295,7 @@ class _SignInDemoState extends State { child: const Text('REQUEST PERMISSIONS'), ), ], - ElevatedButton( - onPressed: _handleSignOut, - child: const Text('SIGN OUT'), - ), + ElevatedButton(onPressed: _handleSignOut, child: const Text('SIGN OUT')), ]; } @@ -317,9 +323,10 @@ class _SignInDemoState extends State { // #enddocregion ExplicitSignIn else const Text( - 'This platform does not have a known authentication method') + 'This platform does not have a known authentication method', + ), // #docregion ExplicitSignIn - ] + ], // #enddocregion ExplicitSignIn ]; } @@ -327,13 +334,12 @@ class _SignInDemoState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Google Sign In'), - ), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - )); + appBar: AppBar(title: const Text('Google Sign In')), + body: ConstrainedBox( + constraints: const BoxConstraints.expand(), + child: _buildBody(), + ), + ); } String _errorMessageFromSignInException(GoogleSignInException 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 12198ea2808..ee2e2e1d4be 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 bf4318bcca9..9d8caafd0ec 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 @@ -31,11 +31,11 @@ class GoogleSignInAccount implements GoogleIdentity { GoogleSignInAccount._( GoogleSignInUserData userData, AuthenticationTokenData tokenData, - ) : displayName = userData.displayName, - email = userData.email, - id = userData.id, - photoUrl = userData.photoUrl, - _authenticationTokens = tokenData; + ) : displayName = userData.displayName, + email = userData.email, + id = userData.id, + photoUrl = userData.photoUrl, + _authenticationTokens = tokenData; @override final String? displayName; @@ -88,7 +88,12 @@ class GoogleSignInAccount implements GoogleIdentity { @override int get hashCode => Object.hash( - displayName, email, id, photoUrl, _authenticationTokens.idToken); + displayName, + email, + id, + photoUrl, + _authenticationTokens.idToken, + ); @override String toString() { @@ -120,8 +125,8 @@ class GoogleSignInAccount implements GoogleIdentity { /// this case. class GoogleSignInAuthorizationClient { GoogleSignInAuthorizationClient._(GoogleIdentity? user) - : _userId = user?.id, - _userEmail = user?.email; + : _userId = user?.id, + _userEmail = user?.email; final String? _userId; final String? _userEmail; @@ -132,7 +137,8 @@ class GoogleSignInAuthorizationClient { /// If authorization would require user interaction, this returns null, in /// which case [authorizeScopes] should be used instead. Future authorizationForScopes( - List scopes) async { + List scopes, + ) async { return _authorizeClient(scopes, promptIfUnauthorized: false); } @@ -145,16 +151,20 @@ class GoogleSignInAuthorizationClient { /// [GoogleSignIn.authorizationRequiresUserInteraction] returns true this /// should only be called from an user interaction handler. Future authorizeScopes( - List scopes) async { - final GoogleSignInClientAuthorization? authz = - await _authorizeClient(scopes, promptIfUnauthorized: true); + List scopes, + ) async { + final GoogleSignInClientAuthorization? authz = await _authorizeClient( + scopes, + promptIfUnauthorized: true, + ); // The platform interface documents that null should only be returned for // cases where prompting isn't requested, so if this happens it's a bug // in the platform implementation. if (authz == null) { throw const GoogleSignInException( - code: GoogleSignInExceptionCode.unknownError, - description: 'Platform returned null unexpectedly.'); + code: GoogleSignInExceptionCode.unknownError, + description: 'Platform returned null unexpectedly.', + ); } return authz; } @@ -167,11 +177,13 @@ class GoogleSignInAuthorizationClient { /// [promptIfNecessary] is false. /// /// See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization. - Future?> authorizationHeaders(List scopes, - {bool promptIfNecessary = false}) async { + Future?> authorizationHeaders( + List scopes, { + bool promptIfNecessary = false, + }) async { final GoogleSignInClientAuthorization? authz = await authorizationForScopes(scopes) ?? - (promptIfNecessary ? await authorizeScopes(scopes) : null); + (promptIfNecessary ? await authorizeScopes(scopes) : null); if (authz == null) { return null; } @@ -196,31 +208,43 @@ class GoogleSignInAuthorizationClient { /// [GoogleSignIn.authorizationRequiresUserInteraction] returns true this /// should only be called from an user interaction handler. Future authorizeServer( - List scopes) async { - final ServerAuthorizationTokenData? tokens = - await GoogleSignInPlatform.instance.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _userId, - email: _userEmail, - promptIfUnauthorized: true))); + List scopes, + ) async { + final ServerAuthorizationTokenData? tokens = await GoogleSignInPlatform + .instance + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _userId, + email: _userEmail, + promptIfUnauthorized: true, + ), + ), + ); return tokens == null ? null : GoogleSignInServerAuthorization( - serverAuthCode: tokens.serverAuthCode); + serverAuthCode: tokens.serverAuthCode, + ); } - Future _authorizeClient(List scopes, - {required bool promptIfUnauthorized}) async { - final ClientAuthorizationTokenData? tokens = - await GoogleSignInPlatform.instance.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _userId, - email: _userEmail, - promptIfUnauthorized: promptIfUnauthorized))); + Future _authorizeClient( + List scopes, { + required bool promptIfUnauthorized, + }) async { + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform + .instance + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _userId, + email: _userEmail, + promptIfUnauthorized: promptIfUnauthorized, + ), + ), + ); return tokens == null ? null : GoogleSignInClientAuthorization(accessToken: tokens.accessToken); @@ -268,12 +292,14 @@ class GoogleSignIn { String? nonce, String? hostedDomain, }) async { - await GoogleSignInPlatform.instance.init(InitParameters( - clientId: clientId, - serverClientId: serverClientId, - nonce: nonce, - hostedDomain: hostedDomain, - )); + await GoogleSignInPlatform.instance.init( + InitParameters( + clientId: clientId, + serverClientId: serverClientId, + nonce: nonce, + hostedDomain: hostedDomain, + ), + ); final Stream? platformAuthEvents = GoogleSignInPlatform.instance.authenticationEvents; @@ -297,12 +323,14 @@ class GoogleSignIn { switch (event) { case AuthenticationEventSignIn(): _authenticationStreamController.add( - GoogleSignInAuthenticationEventSignIn( - user: GoogleSignInAccount._( - event.user, event.authenticationTokens))); + GoogleSignInAuthenticationEventSignIn( + user: GoogleSignInAccount._(event.user, event.authenticationTokens), + ), + ); case AuthenticationEventSignOut(): - _authenticationStreamController - .add(GoogleSignInAuthenticationEventSignOut()); + _authenticationStreamController.add( + GoogleSignInAuthenticationEventSignOut(), + ); case AuthenticationEventException(): _authenticationStreamController.addError(event.exception); } @@ -315,7 +343,7 @@ class GoogleSignIn { } final StreamController - _authenticationStreamController = + _authenticationStreamController = StreamController.broadcast(); // Whether this package is responsible for creating stream events from @@ -362,14 +390,18 @@ class GoogleSignIn { bool reportAllExceptions = false, }) { try { - final Future? future = - GoogleSignInPlatform.instance.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + final Future? future = GoogleSignInPlatform + .instance + .attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); if (future == null) { return null; } - return _resolveLightweightAuthenticationAttempt(future, - reportAllExceptions: reportAllExceptions); + return _resolveLightweightAuthenticationAttempt( + future, + reportAllExceptions: reportAllExceptions, + ); } catch (e, stack) { if (e is GoogleSignInException) { if (_createAuthenticationStreamEvents) { @@ -377,8 +409,10 @@ class GoogleSignIn { } // For exceptions that should not be reported out, just return null. - if (!_shouldRethrowLightweightAuthenticationException(e, - reportAllExceptions: reportAllExceptions)) { + if (!_shouldRethrowLightweightAuthenticationException( + e, + reportAllExceptions: reportAllExceptions, + )) { return Future.value(); } } @@ -402,11 +436,14 @@ class GoogleSignIn { return null; } - final GoogleSignInAccount account = - GoogleSignInAccount._(result.user, result.authenticationTokens); + final GoogleSignInAccount account = GoogleSignInAccount._( + result.user, + result.authenticationTokens, + ); if (_createAuthenticationStreamEvents) { - _authenticationStreamController - .add(GoogleSignInAuthenticationEventSignIn(user: account)); + _authenticationStreamController.add( + GoogleSignInAuthenticationEventSignIn(user: account), + ); } return account; } on GoogleSignInException catch (e, stack) { @@ -414,8 +451,10 @@ class GoogleSignIn { _authenticationStreamController.addError(e, stack); } - if (_shouldRethrowLightweightAuthenticationException(e, - reportAllExceptions: reportAllExceptions)) { + if (_shouldRethrowLightweightAuthenticationException( + e, + reportAllExceptions: reportAllExceptions, + )) { rethrow; } return null; @@ -474,18 +513,20 @@ class GoogleSignIn { /// that do not will ignore [scopeHint]. You should always assume that /// [GoogleSignInAuthorizationClient.authorizationForScopes] could return null /// even if you pass a [scopeHint] here. - Future authenticate( - {List scopeHint = const []}) async { + Future authenticate({ + List scopeHint = const [], + }) async { try { final AuthenticationResults result = await GoogleSignInPlatform.instance - .authenticate(AuthenticateParameters( - scopeHint: scopeHint, - )); - final GoogleSignInAccount account = - GoogleSignInAccount._(result.user, result.authenticationTokens); + .authenticate(AuthenticateParameters(scopeHint: scopeHint)); + final GoogleSignInAccount account = GoogleSignInAccount._( + result.user, + result.authenticationTokens, + ); if (_createAuthenticationStreamEvents) { - _authenticationStreamController - .add(GoogleSignInAuthenticationEventSignIn(user: account)); + _authenticationStreamController.add( + GoogleSignInAuthenticationEventSignIn(user: account), + ); } return account; } on GoogleSignInException catch (e, stack) { @@ -512,8 +553,9 @@ class GoogleSignIn { /// Signs out any currently signed in user(s). Future signOut() { if (_createAuthenticationStreamEvents) { - _authenticationStreamController - .add(GoogleSignInAuthenticationEventSignOut()); + _authenticationStreamController.add( + GoogleSignInAuthenticationEventSignOut(), + ); } return GoogleSignInPlatform.instance.signOut(const SignOutParams()); } @@ -523,8 +565,9 @@ class GoogleSignIn { Future disconnect() async { // Disconnecting also signs out, so synthesize a sign-out if necessary. if (_createAuthenticationStreamEvents) { - _authenticationStreamController - .add(GoogleSignInAuthenticationEventSignOut()); + _authenticationStreamController.add( + GoogleSignInAuthenticationEventSignOut(), + ); } // TODO(stuartmorgan): Consider making a per-user disconnect option once // the Android implementation is available so that we can see how it is 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 ff048e24959..db4e7c72458 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,11 +46,12 @@ 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/testing.dart b/packages/google_sign_in/google_sign_in/lib/testing.dart index 23510a2c4a7..620e0d56452 100644 --- a/packages/google_sign_in/google_sign_in/lib/testing.dart +++ b/packages/google_sign_in/google_sign_in/lib/testing.dart @@ -94,11 +94,11 @@ class FakeUser { final String? accessToken; Map get _asMap => { - 'id': id, - 'email': email, - 'displayName': displayName, - 'photoUrl': photoUrl, - 'serverAuthCode': serverAuthCode, - 'idToken': idToken, - }; + 'id': id, + 'email': email, + 'displayName': displayName, + 'photoUrl': photoUrl, + 'serverAuthCode': serverAuthCode, + 'idToken': idToken, + }; } 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 f5c210b7f57..a3b7855f79f 100644 --- a/packages/google_sign_in/google_sign_in/lib/widgets.dart +++ b/packages/google_sign_in/google_sign_in/lib/widgets.dart @@ -79,10 +79,13 @@ 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), ); @@ -99,30 +102,32 @@ class GoogleUserCircleAvatar extends StatelessWidget { // Fade the photo in over the top of the placeholder. return SizedBox( - width: size, - height: size, - child: ClipOval( - child: Stack(fit: StackFit.expand, children: [ + width: size, + height: size, + child: ClipOval( + child: Stack( + fit: StackFit.expand, + children: [ placeholder, FadeInImage.memoryNetwork( // This creates a transparent placeholder image, so that // [placeholder] shows through. placeholder: _transparentImage, image: sizedPhotoUrl, - ) - ]), - )); + ), + ], + ), + ), + ); } } /// This is an transparent 1x1 gif image. /// /// Those bytes come from `resources/transparentImage.gif`. -final Uint8List _transparentImage = Uint8List.fromList( - [ - 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, // - 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x21, 0xf9, 0x04, 0x01, 0x00, // - 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, // - 0x00, 0x02, 0x01, 0x44, 0x00, 0x3B - ], -); +final Uint8List _transparentImage = Uint8List.fromList([ + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, // + 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x21, 0xf9, 0x04, 0x01, 0x00, // + 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, // + 0x00, 0x02, 0x01, 0x44, 0x00, 0x3B, +]); diff --git a/packages/google_sign_in/google_sign_in/pubspec.yaml b/packages/google_sign_in/google_sign_in/pubspec.yaml index a729c9866b2..3e2a6f7afa2 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.1.1 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/google_sign_in/google_sign_in/test/fife_test.dart b/packages/google_sign_in/google_sign_in/test/fife_test.dart index 5b0524771eb..f99aa98e0ab 100644 --- a/packages/google_sign_in/google_sign_in/test/fife_test.dart +++ b/packages/google_sign_in/google_sign_in/test/fife_test.dart @@ -55,12 +55,14 @@ void main() { expect(addSizeDirectiveToUrl(url, size), expected); }); - test('many directives, sets size and crop, preserves other directives', - () { - const String url = '$base=s120-c-fSoften=1,50,0'; - const String expected = '$base=c-fSoften=1,50,0-s20'; - expect(addSizeDirectiveToUrl(url, size), expected); - }); + test( + 'many directives, sets size and crop, preserves other directives', + () { + const String url = '$base=s120-c-fSoften=1,50,0'; + const String expected = '$base=c-fSoften=1,50,0-s20'; + expect(addSizeDirectiveToUrl(url, size), expected); + }, + ); }); }); } 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 7e13bd71203..b5c29a54c74 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 @@ -24,10 +24,11 @@ class TestMockGoogleSignInPlatform extends MockGoogleSignInPlatform @GenerateMocks([GoogleSignInPlatform]) void main() { const GoogleSignInUserData defaultUser = GoogleSignInUserData( - email: 'john.doe@gmail.com', - id: '8162538176523816253123', - photoUrl: 'https://lh5.googleusercontent.com/photo.jpg', - displayName: 'John Doe'); + email: 'john.doe@gmail.com', + id: '8162538176523816253123', + photoUrl: 'https://lh5.googleusercontent.com/photo.jpg', + displayName: 'John Doe', + ); late MockGoogleSignInPlatform mockPlatform; @@ -44,8 +45,9 @@ void main() { await googleSignIn.initialize(); - final VerificationResult verification = - verify(mockPlatform.init(captureAny)); + final VerificationResult verification = verify( + mockPlatform.init(captureAny), + ); final InitParameters params = verification.captured[0] as InitParameters; expect(params.clientId, null); expect(params.serverClientId, null); @@ -61,13 +63,15 @@ void main() { const String nonce = 'nonce'; const String hostedDomain = 'example.com'; await googleSignIn.initialize( - clientId: clientId, - serverClientId: serverClientId, - nonce: nonce, - hostedDomain: hostedDomain); - - final VerificationResult verification = - verify(mockPlatform.init(captureAny)); + clientId: clientId, + serverClientId: serverClientId, + nonce: nonce, + hostedDomain: hostedDomain, + ); + + final VerificationResult verification = verify( + mockPlatform.init(captureAny), + ); final InitParameters params = verification.captured[0] as InitParameters; expect(params.clientId, clientId); expect(params.serverClientId, serverClientId); @@ -82,9 +86,11 @@ void main() { const String idToken = 'idToken'; when(mockPlatform.attemptLightweightAuthentication(any)).thenAnswer( - (_) async => const AuthenticationResults( - user: defaultUser, - authenticationTokens: AuthenticationTokenData(idToken: idToken))); + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: idToken), + ), + ); final Future eventFuture = googleSignIn.authenticationEvents.first; @@ -99,60 +105,70 @@ void main() { expect(signIn.user.authentication.idToken, idToken); }); - test('reports sync exceptions from attemptLightweightAuthentication', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; - - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenThrow(exception); - - final Completer errorCompleter = Completer(); - final StreamSubscription subscription = - googleSignIn.authenticationEvents - .handleError((Object e) => errorCompleter.complete(e)) - .listen((_) => fail('The only event should be an error')); - await googleSignIn.initialize(); - // This doesn't throw, since reportAllExceptions is false. - await googleSignIn.attemptLightweightAuthentication(); - - final Object e = await errorCompleter.future; - expect(e, exception); - await subscription.cancel(); - }); - - test('reports async exceptions from attemptLightweightAuthentication', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + test( + 'reports sync exceptions from attemptLightweightAuthentication', + () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenAnswer((_) async => throw exception); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.interrupted, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenThrow(exception); + + final Completer errorCompleter = Completer(); + final StreamSubscription subscription = + googleSignIn.authenticationEvents + .handleError((Object e) => errorCompleter.complete(e)) + .listen((_) => fail('The only event should be an error')); + await googleSignIn.initialize(); + // This doesn't throw, since reportAllExceptions is false. + await googleSignIn.attemptLightweightAuthentication(); + + final Object e = await errorCompleter.future; + expect(e, exception); + await subscription.cancel(); + }, + ); - final Completer errorCompleter = Completer(); - final StreamSubscription subscription = - googleSignIn.authenticationEvents - .handleError((Object e) => errorCompleter.complete(e)) - .listen((_) => fail('The only event should be an error')); - await googleSignIn.initialize(); - // This doesn't throw, since reportAllExceptions is false. - await googleSignIn.attemptLightweightAuthentication(); + test( + 'reports async exceptions from attemptLightweightAuthentication', + () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; - final Object e = await errorCompleter.future; - expect(e, exception); - await subscription.cancel(); - }); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.interrupted, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenAnswer((_) async => throw exception); + + final Completer errorCompleter = Completer(); + final StreamSubscription subscription = + googleSignIn.authenticationEvents + .handleError((Object e) => errorCompleter.complete(e)) + .listen((_) => fail('The only event should be an error')); + await googleSignIn.initialize(); + // This doesn't throw, since reportAllExceptions is false. + await googleSignIn.attemptLightweightAuthentication(); + + final Object e = await errorCompleter.future; + expect(e, exception); + await subscription.cancel(); + }, + ); test('reports success from authenticate', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const String idToken = 'idToken'; - when(mockPlatform.authenticate(any)).thenAnswer((_) async => - const AuthenticationResults( - user: defaultUser, - authenticationTokens: AuthenticationTokenData(idToken: idToken))); + when(mockPlatform.authenticate(any)).thenAnswer( + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: idToken), + ), + ); final Future eventFuture = googleSignIn.authenticationEvents.first; @@ -170,8 +186,9 @@ void main() { test('reports sync exceptions from authenticate', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.interrupted, + ); when(mockPlatform.authenticate(any)).thenThrow(exception); final Completer errorCompleter = Completer(); @@ -181,7 +198,9 @@ void main() { .listen((_) => fail('The only event should be an error')); await googleSignIn.initialize(); await expectLater( - googleSignIn.authenticate(), throwsA(isA())); + googleSignIn.authenticate(), + throwsA(isA()), + ); final Object e = await errorCompleter.future; expect(e, exception); @@ -191,10 +210,12 @@ void main() { test('reports async exceptions from authenticate', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); - when(mockPlatform.authenticate(any)) - .thenAnswer((_) async => throw exception); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.interrupted, + ); + when( + mockPlatform.authenticate(any), + ).thenAnswer((_) async => throw exception); final Completer errorCompleter = Completer(); final StreamSubscription subscription = @@ -203,7 +224,9 @@ void main() { .listen((_) => fail('The only event should be an error')); await googleSignIn.initialize(); await expectLater( - googleSignIn.authenticate(), throwsA(isA())); + googleSignIn.authenticate(), + throwsA(isA()), + ); final Object e = await errorCompleter.future; expect(e, exception); @@ -252,8 +275,9 @@ void main() { test('reports $support from platform', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.authorizationRequiresUserInteraction()) - .thenReturn(support); + when( + mockPlatform.authorizationRequiresUserInteraction(), + ).thenReturn(support); expect(googleSignIn.authorizationRequiresUserInteraction(), support); }); @@ -266,9 +290,11 @@ void main() { const String idToken = 'idToken'; when(mockPlatform.attemptLightweightAuthentication(any)).thenAnswer( - (_) async => const AuthenticationResults( - user: defaultUser, - authenticationTokens: AuthenticationTokenData(idToken: idToken))); + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: idToken), + ), + ); final Future? signInFuture = googleSignIn.attemptLightweightAuthentication(); @@ -284,76 +310,104 @@ void main() { test('reports all exceptions when requested - sync', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.canceled); - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenThrow(exception); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.canceled, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenThrow(exception); await googleSignIn.initialize(); expect( - googleSignIn.attemptLightweightAuthentication( - reportAllExceptions: true), - throwsA(isA().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.attemptLightweightAuthentication( + reportAllExceptions: true, + ), + throwsA( + isA().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test( - 'reports serious exceptions even when all exceptions are not requested - sync', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + 'reports serious exceptions even when all exceptions are not requested - sync', + () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = GoogleSignInException( - code: GoogleSignInExceptionCode.clientConfigurationError); - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenThrow(exception); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.clientConfigurationError, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenThrow(exception); - await googleSignIn.initialize(); - expect( + await googleSignIn.initialize(); + expect( googleSignIn.attemptLightweightAuthentication(), - throwsA(isA().having( + throwsA( + isA().having( (GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.clientConfigurationError))); - }); + GoogleSignInExceptionCode.clientConfigurationError, + ), + ), + ); + }, + ); test('reports all exceptions when requested - async', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.canceled); - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenAnswer((_) async => throw exception); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.canceled, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenAnswer((_) async => throw exception); await googleSignIn.initialize(); expect( - googleSignIn.attemptLightweightAuthentication( - reportAllExceptions: true), - throwsA(isA().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.attemptLightweightAuthentication( + reportAllExceptions: true, + ), + throwsA( + isA().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test( - 'reports serious exceptions even when all exceptions are not requested - async', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + 'reports serious exceptions even when all exceptions are not requested - async', + () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = GoogleSignInException( - code: GoogleSignInExceptionCode.clientConfigurationError); - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenAnswer((_) async => throw exception); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.clientConfigurationError, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenAnswer((_) async => throw exception); - await googleSignIn.initialize(); - expect( + await googleSignIn.initialize(); + expect( googleSignIn.attemptLightweightAuthentication(), - throwsA(isA().having( + throwsA( + isA().having( (GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.clientConfigurationError))); - }); + GoogleSignInExceptionCode.clientConfigurationError, + ), + ), + ); + }, + ); test('returns a null future from the platform', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; @@ -368,8 +422,9 @@ void main() { test('returns a future that resolves to null from the platform', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.attemptLightweightAuthentication(any)) - .thenAnswer((_) async => null); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenAnswer((_) async => null); final Future? signInFuture = googleSignIn.attemptLightweightAuthentication(); @@ -384,17 +439,19 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const List scopes = ['scope1', 'scope2']; - when(mockPlatform.authenticate(any)).thenAnswer((_) async => - const AuthenticationResults( - user: defaultUser, - authenticationTokens: - AuthenticationTokenData(idToken: 'idToken'))); + when(mockPlatform.authenticate(any)).thenAnswer( + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), + ), + ); await googleSignIn.initialize(); await googleSignIn.authenticate(scopeHint: scopes); - final VerificationResult verification = - verify(mockPlatform.authenticate(captureAny)); + final VerificationResult verification = verify( + mockPlatform.authenticate(captureAny), + ); final AuthenticateParameters params = verification.captured[0] as AuthenticateParameters; expect(params.scopeHint, scopes); @@ -404,10 +461,12 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const String idToken = 'idToken'; - when(mockPlatform.authenticate(any)).thenAnswer((_) async => - const AuthenticationResults( - user: defaultUser, - authenticationTokens: AuthenticationTokenData(idToken: idToken))); + when(mockPlatform.authenticate(any)).thenAnswer( + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: idToken), + ), + ); final GoogleSignInAccount signIn = await googleSignIn.authenticate(); expect(signIn.displayName, defaultUser.displayName); @@ -420,17 +479,22 @@ void main() { test('reports exceptions', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const GoogleSignInException exception = - GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); + const GoogleSignInException exception = GoogleSignInException( + code: GoogleSignInExceptionCode.interrupted, + ); when(mockPlatform.authenticate(any)).thenThrow(exception); await googleSignIn.initialize(); expect( - googleSignIn.authenticate(), - throwsA(isA().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.interrupted))); + googleSignIn.authenticate(), + throwsA( + isA().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.interrupted, + ), + ), + ); }); }); @@ -438,13 +502,15 @@ void main() { test('passes expected paramaters when called for a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.authenticate(any)).thenAnswer((_) async => - const AuthenticationResults( - user: defaultUser, - authenticationTokens: - AuthenticationTokenData(idToken: 'idToken'))); - when(mockPlatform.clientAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when(mockPlatform.authenticate(any)).thenAnswer( + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), + ), + ); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); await googleSignIn.initialize(); final GoogleSignInAccount authentication = @@ -452,10 +518,12 @@ void main() { const List scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizationForScopes(scopes); - final VerificationResult verification = - verify(mockPlatform.clientAuthorizationTokensForScopes(captureAny)); - final ClientAuthorizationTokensForScopesParameters params = verification - .captured[0] as ClientAuthorizationTokensForScopesParameters; + final VerificationResult verification = verify( + mockPlatform.clientAuthorizationTokensForScopes(captureAny), + ); + final ClientAuthorizationTokensForScopesParameters params = + verification.captured[0] + as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, defaultUser.id); expect(params.request.email, defaultUser.email); @@ -465,16 +533,19 @@ void main() { test('passes expected paramaters when called without a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.clientAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); const List scopes = ['scope1', 'scope2']; await googleSignIn.authorizationClient.authorizationForScopes(scopes); - final VerificationResult verification = - verify(mockPlatform.clientAuthorizationTokensForScopes(captureAny)); - final ClientAuthorizationTokensForScopesParameters params = verification - .captured[0] as ClientAuthorizationTokensForScopesParameters; + final VerificationResult verification = verify( + mockPlatform.clientAuthorizationTokensForScopes(captureAny), + ); + final ClientAuthorizationTokensForScopesParameters params = + verification.captured[0] + as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, null); expect(params.request.email, null); @@ -486,25 +557,29 @@ void main() { const String accessToken = 'accessToken'; when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: accessToken)); + (_) async => + const ClientAuthorizationTokenData(accessToken: accessToken), + ); const List scopes = ['scope1', 'scope2']; - final GoogleSignInClientAuthorization? auth = - await googleSignIn.authorizationClient.authorizationForScopes(scopes); + final GoogleSignInClientAuthorization? auth = await googleSignIn + .authorizationClient + .authorizationForScopes(scopes); expect(auth?.accessToken, accessToken); }); test('reports null', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.clientAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); const List scopes = ['scope1', 'scope2']; expect( - await googleSignIn.authorizationClient.authorizationForScopes(scopes), - null); + await googleSignIn.authorizationClient.authorizationForScopes(scopes), + null, + ); }); }); @@ -512,14 +587,16 @@ void main() { test('passes expected paramaters when called for a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.authenticate(any)).thenAnswer((_) async => - const AuthenticationResults( - user: defaultUser, - authenticationTokens: - AuthenticationTokenData(idToken: 'idToken'))); + when(mockPlatform.authenticate(any)).thenAnswer( + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), + ), + ); when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: 'accessToken')); + (_) async => + const ClientAuthorizationTokenData(accessToken: 'accessToken'), + ); await googleSignIn.initialize(); final GoogleSignInAccount authentication = @@ -527,10 +604,12 @@ void main() { const List scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizeScopes(scopes); - final VerificationResult verification = - verify(mockPlatform.clientAuthorizationTokensForScopes(captureAny)); - final ClientAuthorizationTokensForScopesParameters params = verification - .captured[0] as ClientAuthorizationTokensForScopesParameters; + final VerificationResult verification = verify( + mockPlatform.clientAuthorizationTokensForScopes(captureAny), + ); + final ClientAuthorizationTokensForScopesParameters params = + verification.captured[0] + as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, defaultUser.id); expect(params.request.email, defaultUser.email); @@ -541,16 +620,19 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: 'accessToken')); + (_) async => + const ClientAuthorizationTokenData(accessToken: 'accessToken'), + ); const List scopes = ['scope1', 'scope2']; await googleSignIn.authorizationClient.authorizeScopes(scopes); - final VerificationResult verification = - verify(mockPlatform.clientAuthorizationTokensForScopes(captureAny)); - final ClientAuthorizationTokensForScopesParameters params = verification - .captured[0] as ClientAuthorizationTokensForScopesParameters; + final VerificationResult verification = verify( + mockPlatform.clientAuthorizationTokensForScopes(captureAny), + ); + final ClientAuthorizationTokensForScopesParameters params = + verification.captured[0] + as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, null); expect(params.request.email, null); @@ -562,28 +644,35 @@ void main() { const String accessToken = 'accessToken'; when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: accessToken)); + (_) async => + const ClientAuthorizationTokenData(accessToken: accessToken), + ); const List scopes = ['scope1', 'scope2']; - final GoogleSignInClientAuthorization auth = - await googleSignIn.authorizationClient.authorizeScopes(scopes); + final GoogleSignInClientAuthorization auth = await googleSignIn + .authorizationClient + .authorizeScopes(scopes); expect(auth.accessToken, accessToken); }); test('throws for unexpected null', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.clientAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); const List scopes = ['scope1', 'scope2']; await expectLater( - googleSignIn.authorizationClient.authorizeScopes(scopes), - throwsA(isA().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.authorizationClient.authorizeScopes(scopes), + throwsA( + isA().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); }); @@ -591,13 +680,15 @@ void main() { test('passes expected paramaters when called for a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.authenticate(any)).thenAnswer((_) async => - const AuthenticationResults( - user: defaultUser, - authenticationTokens: - AuthenticationTokenData(idToken: 'idToken'))); - when(mockPlatform.serverAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when(mockPlatform.authenticate(any)).thenAnswer( + (_) async => const AuthenticationResults( + user: defaultUser, + authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), + ), + ); + when( + mockPlatform.serverAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); await googleSignIn.initialize(); final GoogleSignInAccount authentication = @@ -605,10 +696,12 @@ void main() { const List scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizeServer(scopes); - final VerificationResult verification = - verify(mockPlatform.serverAuthorizationTokensForScopes(captureAny)); - final ServerAuthorizationTokensForScopesParameters params = verification - .captured[0] as ServerAuthorizationTokensForScopesParameters; + final VerificationResult verification = verify( + mockPlatform.serverAuthorizationTokensForScopes(captureAny), + ); + final ServerAuthorizationTokensForScopesParameters params = + verification.captured[0] + as ServerAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, defaultUser.id); expect(params.request.email, defaultUser.email); @@ -618,16 +711,19 @@ void main() { test('passes expected paramaters when called without a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.serverAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when( + mockPlatform.serverAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); const List scopes = ['scope1', 'scope2']; await googleSignIn.authorizationClient.authorizeServer(scopes); - final VerificationResult verification = - verify(mockPlatform.serverAuthorizationTokensForScopes(captureAny)); - final ServerAuthorizationTokensForScopesParameters params = verification - .captured[0] as ServerAuthorizationTokensForScopesParameters; + final VerificationResult verification = verify( + mockPlatform.serverAuthorizationTokensForScopes(captureAny), + ); + final ServerAuthorizationTokensForScopesParameters params = + verification.captured[0] + as ServerAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, null); expect(params.request.email, null); @@ -639,24 +735,29 @@ void main() { const String authCode = 'authCode'; when(mockPlatform.serverAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ServerAuthorizationTokenData(serverAuthCode: authCode)); + (_) async => + const ServerAuthorizationTokenData(serverAuthCode: authCode), + ); const List scopes = ['scope1', 'scope2']; - final GoogleSignInServerAuthorization? auth = - await googleSignIn.authorizationClient.authorizeServer(scopes); + final GoogleSignInServerAuthorization? auth = await googleSignIn + .authorizationClient + .authorizeServer(scopes); expect(auth?.serverAuthCode, authCode); }); test('reports null', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.serverAuthorizationTokensForScopes(any)) - .thenAnswer((_) async => null); + when( + mockPlatform.serverAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => null); const List scopes = ['scope1', 'scope2']; expect( - await googleSignIn.authorizationClient.authorizeServer(scopes), null); + await googleSignIn.authorizationClient.authorizeServer(scopes), + null, + ); }); }); } diff --git a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart index 4a3b29c57e8..f7db7677e2a 100644 --- a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart @@ -27,7 +27,7 @@ import 'package:mockito/mockito.dart' as _i1; class _FakeAuthenticationResults_0 extends _i1.SmartFake implements _i2.AuthenticationResults { _FakeAuthenticationResults_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } /// A class which mocks [GoogleSignInPlatform]. @@ -40,78 +40,91 @@ class MockGoogleSignInPlatform extends _i1.Mock } @override - _i4.Future init(_i2.InitParameters? params) => (super.noSuchMethod( - Invocation.method(#init, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future init(_i2.InitParameters? params) => + (super.noSuchMethod( + Invocation.method(#init, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future<_i2.AuthenticationResults?>? attemptLightweightAuthentication( _i2.AttemptLightweightAuthenticationParameters? params, ) => (super.noSuchMethod( - Invocation.method(#attemptLightweightAuthentication, [params]), - ) as _i4.Future<_i2.AuthenticationResults?>?); + Invocation.method(#attemptLightweightAuthentication, [params]), + ) + as _i4.Future<_i2.AuthenticationResults?>?); @override _i4.Future<_i2.AuthenticationResults> authenticate( _i2.AuthenticateParameters? params, ) => (super.noSuchMethod( - Invocation.method(#authenticate, [params]), - returnValue: _i4.Future<_i2.AuthenticationResults>.value( - _FakeAuthenticationResults_0( - this, Invocation.method(#authenticate, [params]), - ), - ), - ) as _i4.Future<_i2.AuthenticationResults>); + returnValue: _i4.Future<_i2.AuthenticationResults>.value( + _FakeAuthenticationResults_0( + this, + Invocation.method(#authenticate, [params]), + ), + ), + ) + as _i4.Future<_i2.AuthenticationResults>); @override - bool supportsAuthenticate() => (super.noSuchMethod( - Invocation.method(#supportsAuthenticate, []), - returnValue: false, - ) as bool); + bool supportsAuthenticate() => + (super.noSuchMethod( + Invocation.method(#supportsAuthenticate, []), + returnValue: false, + ) + as bool); @override - bool authorizationRequiresUserInteraction() => (super.noSuchMethod( - Invocation.method(#authorizationRequiresUserInteraction, []), - returnValue: false, - ) as bool); + bool authorizationRequiresUserInteraction() => + (super.noSuchMethod( + Invocation.method(#authorizationRequiresUserInteraction, []), + returnValue: false, + ) + as bool); @override _i4.Future<_i2.ClientAuthorizationTokenData?> - clientAuthorizationTokensForScopes( + clientAuthorizationTokensForScopes( _i2.ClientAuthorizationTokensForScopesParameters? params, ) => - (super.noSuchMethod( + (super.noSuchMethod( Invocation.method(#clientAuthorizationTokensForScopes, [params]), returnValue: _i4.Future<_i2.ClientAuthorizationTokenData?>.value(), - ) as _i4.Future<_i2.ClientAuthorizationTokenData?>); + ) + as _i4.Future<_i2.ClientAuthorizationTokenData?>); @override _i4.Future<_i2.ServerAuthorizationTokenData?> - serverAuthorizationTokensForScopes( + serverAuthorizationTokensForScopes( _i2.ServerAuthorizationTokensForScopesParameters? params, ) => - (super.noSuchMethod( + (super.noSuchMethod( Invocation.method(#serverAuthorizationTokensForScopes, [params]), returnValue: _i4.Future<_i2.ServerAuthorizationTokenData?>.value(), - ) as _i4.Future<_i2.ServerAuthorizationTokenData?>); + ) + as _i4.Future<_i2.ServerAuthorizationTokenData?>); @override - _i4.Future signOut(_i2.SignOutParams? params) => (super.noSuchMethod( - Invocation.method(#signOut, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future signOut(_i2.SignOutParams? params) => + (super.noSuchMethod( + Invocation.method(#signOut, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future disconnect(_i2.DisconnectParams? params) => (super.noSuchMethod( - Invocation.method(#disconnect, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#disconnect, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/google_sign_in/google_sign_in/test/widgets_test.dart b/packages/google_sign_in/google_sign_in/test/widgets_test.dart index ad34111b377..47054d85119 100644 --- a/packages/google_sign_in/google_sign_in/test/widgets_test.dart +++ b/packages/google_sign_in/google_sign_in/test/widgets_test.dart @@ -12,11 +12,7 @@ import 'package:google_sign_in/google_sign_in.dart'; /// A instantiable class that extends [GoogleIdentity] class _TestGoogleIdentity extends GoogleIdentity { - _TestGoogleIdentity({ - required this.id, - required this.email, - this.photoUrl, - }); + _TestGoogleIdentity({required this.id, required this.email, this.photoUrl}); @override final String id; @@ -55,20 +51,19 @@ class _MockHttpRequest extends Fake implements HttpClientRequest { /// It doesn't have to match the placeholder used in [GoogleUserCircleAvatar]. /// /// Those bytes come from `resources/transparentImage.gif`. -final Uint8List _transparentImage = Uint8List.fromList( - [ - 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, // - 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x21, 0xf9, 0x04, 0x01, 0x00, // - 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, // - 0x00, 0x02, 0x01, 0x44, 0x00, 0x3B - ], -); +final Uint8List _transparentImage = Uint8List.fromList([ + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, // + 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x21, 0xf9, 0x04, 0x01, 0x00, // + 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, // + 0x00, 0x02, 0x01, 0x44, 0x00, 0x3B, +]); /// A mocked [HttpClientResponse] which is empty and has a [statusCode] of 200 /// and returns valid image. class _MockHttpResponse extends Fake implements HttpClientResponse { - final Stream _delegate = - Stream.value(_transparentImage); + final Stream _delegate = Stream.value( + _transparentImage, + ); @override int get contentLength => -1; @@ -79,10 +74,18 @@ class _MockHttpResponse extends Fake implements HttpClientResponse { } @override - StreamSubscription listen(void Function(Uint8List event)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { - return _delegate.listen(onData, - onError: onError, onDone: onDone, cancelOnError: cancelOnError); + StreamSubscription listen( + void Function(Uint8List event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { + return _delegate.listen( + onData, + onError: onError, + onDone: onDone, + cancelOnError: cancelOnError, + ); } @override @@ -90,8 +93,9 @@ class _MockHttpResponse extends Fake implements HttpClientResponse { } void main() { - testWidgets('It should build the GoogleUserCircleAvatar successfully', - (WidgetTester tester) async { + testWidgets('It should build the GoogleUserCircleAvatar successfully', ( + WidgetTester tester, + ) async { final GoogleIdentity identity = _TestGoogleIdentity( email: 'email@email.com', id: 'userId', @@ -101,19 +105,16 @@ void main() { tester.view.physicalSize = const Size(100, 100); addTearDown(tester.view.reset); - await HttpOverrides.runZoned( - () async { - await tester.pumpWidget(MaterialApp( + await HttpOverrides.runZoned(() async { + await tester.pumpWidget( + MaterialApp( home: SizedBox( height: 100, width: 100, - child: GoogleUserCircleAvatar( - identity: identity, - ), + child: GoogleUserCircleAvatar(identity: identity), ), - )); - }, - createHttpClient: (SecurityContext? c) => _MockHttpClient(), - ); + ), + ); + }, createHttpClient: (SecurityContext? c) => _MockHttpClient()); }); } diff --git a/packages/google_sign_in/google_sign_in_android/CHANGELOG.md b/packages/google_sign_in/google_sign_in_android/CHANGELOG.md index 55fa9184592..4602374999c 100644 --- a/packages/google_sign_in/google_sign_in_android/CHANGELOG.md +++ b/packages/google_sign_in/google_sign_in_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 7.0.3 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/google_sign_in/google_sign_in_android/example/lib/main.dart b/packages/google_sign_in/google_sign_in_android/example/lib/main.dart index 3a177c19ff3..a7bdf7da61a 100644 --- a/packages/google_sign_in/google_sign_in_android/example/lib/main.dart +++ b/packages/google_sign_in/google_sign_in_android/example/lib/main.dart @@ -16,12 +16,7 @@ const List _scopes = [ ]; void main() { - runApp( - const MaterialApp( - title: 'Google Sign In', - home: SignInDemo(), - ), - ); + runApp(const MaterialApp(title: 'Google Sign In', home: SignInDemo())); } class SignInDemo extends StatefulWidget { @@ -48,11 +43,11 @@ class SignInDemoState extends State { Future _ensureInitialized() { // The example app uses the parsing of values from google-services.json // to provide the serverClientId, otherwise it would be required here. - return _initialization ??= - GoogleSignInPlatform.instance.init(const InitParameters()) - ..catchError((dynamic _) { - _initialization = null; - }); + return _initialization ??= GoogleSignInPlatform.instance.init( + const InitParameters(), + )..catchError((dynamic _) { + _initialization = null; + }); } void _setUser(GoogleSignInUserData? user) { @@ -70,13 +65,15 @@ class SignInDemoState extends State { try { final AuthenticationResults? result = await GoogleSignInPlatform.instance .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + const AttemptLightweightAuthenticationParameters(), + ); _setUser(result?.user); } on GoogleSignInException catch (e) { setState(() { - _errorMessage = e.code == GoogleSignInExceptionCode.canceled - ? '' - : 'GoogleSignInException ${e.code}: ${e.description}'; + _errorMessage = + e.code == GoogleSignInExceptionCode.canceled + ? '' + : 'GoogleSignInException ${e.code}: ${e.description}'; }); } } @@ -86,12 +83,15 @@ class SignInDemoState extends State { final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform .instance .clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: _scopes, - userId: user.id, - email: user.email, - promptIfUnauthorized: true))); + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: _scopes, + userId: user.id, + email: user.email, + promptIfUnauthorized: true, + ), + ), + ); setState(() { _isAuthorized = tokens != null; @@ -108,15 +108,20 @@ class SignInDemoState extends State { } Future?> _getAuthHeaders( - GoogleSignInUserData user) async { - final ClientAuthorizationTokenData? tokens = - await GoogleSignInPlatform.instance.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: _scopes, - userId: user.id, - email: user.email, - promptIfUnauthorized: false))); + GoogleSignInUserData user, + ) async { + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform + .instance + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: _scopes, + userId: user.id, + email: user.email, + promptIfUnauthorized: false, + ), + ), + ); if (tokens == null) { return null; } @@ -141,13 +146,16 @@ class SignInDemoState extends State { return; } final http.Response response = await http.get( - Uri.parse('https://people.googleapis.com/v1/people/me/connections' - '?requestMask.includeField=person.names'), + Uri.parse( + 'https://people.googleapis.com/v1/people/me/connections' + '?requestMask.includeField=person.names', + ), headers: headers, ); if (response.statusCode != 200) { setState(() { - _contactText = 'People API gave a ${response.statusCode} ' + _contactText = + 'People API gave a ${response.statusCode} ' 'response. Check logs for details.'; }); print('People API ${response.statusCode} response: ${response.body}'); @@ -170,9 +178,10 @@ class SignInDemoState extends State { _setUser(result.user); } on GoogleSignInException catch (e) { setState(() { - _errorMessage = e.code == GoogleSignInExceptionCode.canceled - ? '' - : 'GoogleSignInException ${e.code}: ${e.description}'; + _errorMessage = + e.code == GoogleSignInExceptionCode.canceled + ? '' + : 'GoogleSignInException ${e.code}: ${e.description}'; }); } } @@ -227,12 +236,11 @@ class SignInDemoState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Google Sign In'), - ), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - )); + appBar: AppBar(title: const Text('Google Sign In')), + body: ConstrainedBox( + constraints: const BoxConstraints.expand(), + child: _buildBody(), + ), + ); } } diff --git a/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml b/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml index a8c19eb232a..4fd0ceafa5e 100644 --- a/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Example of Google Sign-In plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart b/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart index 3481f4cf0e5..efe5e8df4cd 100644 --- a/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart +++ b/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart @@ -13,9 +13,8 @@ import 'src/messages.g.dart'; /// Android implementation of [GoogleSignInPlatform]. class GoogleSignInAndroid extends GoogleSignInPlatform { /// Creates a new plugin implementation instance. - GoogleSignInAndroid({ - @visibleForTesting GoogleSignInApi? api, - }) : _hostApi = api ?? GoogleSignInApi(); + GoogleSignInAndroid({@visibleForTesting GoogleSignInApi? api}) + : _hostApi = api ?? GoogleSignInApi(); final GoogleSignInApi _hostApi; @@ -31,7 +30,8 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { @override Future init(InitParameters params) async { _hostedDomain = params.hostedDomain; - _serverClientId = params.serverClientId ?? + _serverClientId = + params.serverClientId ?? await _hostApi.getGoogleServicesJsonServerClientId(); _nonce = params.nonce; // The clientId parameter is not supported on Android. @@ -40,7 +40,8 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { @override Future attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params) async { + AttemptLightweightAuthenticationParameters params, + ) async { // Attempt to auto-sign-in, for single-account or returning users. PlatformGoogleIdTokenCredential? credential = await _authenticate( useButtonFlow: false, @@ -68,7 +69,8 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { @override Future authenticate( - AuthenticateParameters params) async { + AuthenticateParameters params, + ) async { // Attempt to authorize with minimal interaction. final PlatformGoogleIdTokenCredential? credential = await _authenticate( useButtonFlow: true, @@ -83,8 +85,9 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { // no information is available if (credential == null) { throw const GoogleSignInException( - code: GoogleSignInExceptionCode.unknownError, - description: 'Authenticate returned no credential without an error'); + code: GoogleSignInExceptionCode.unknownError, + description: 'Authenticate returned no credential without an error', + ); } return _authenticationResultFromPlatformCredential(credential); } @@ -108,9 +111,12 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { @override Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params) async { - final (:String? accessToken, :String? serverAuthCode) = - await _authorize(params.request, requestOfflineAccess: false); + ClientAuthorizationTokensForScopesParameters params, + ) async { + final (:String? accessToken, :String? serverAuthCode) = await _authorize( + params.request, + requestOfflineAccess: false, + ); return accessToken == null ? null : ClientAuthorizationTokenData(accessToken: accessToken); @@ -118,9 +124,12 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { @override Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params) async { - final (:String? accessToken, :String? serverAuthCode) = - await _authorize(params.request, requestOfflineAccess: true); + ServerAuthorizationTokensForScopesParameters params, + ) async { + final (:String? accessToken, :String? serverAuthCode) = await _authorize( + params.request, + requestOfflineAccess: true, + ); return serverAuthCode == null ? null : ServerAuthorizationTokenData(serverAuthCode: serverAuthCode); @@ -139,13 +148,16 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { bool throwForNoAuth = false, }) async { final GetCredentialResult authnResult = await _hostApi.getCredential( - GetCredentialRequestParams( - useButtonFlow: useButtonFlow, - googleIdOptionParams: GetCredentialRequestGoogleIdOptionParams( - filterToAuthorized: nonButtonFlowOptions.filterToAuthorized, - autoSelectEnabled: nonButtonFlowOptions.autoSelectEnabled), - serverClientId: _serverClientId, - nonce: _nonce)); + GetCredentialRequestParams( + useButtonFlow: useButtonFlow, + googleIdOptionParams: GetCredentialRequestGoogleIdOptionParams( + filterToAuthorized: nonButtonFlowOptions.filterToAuthorized, + autoSelectEnabled: nonButtonFlowOptions.autoSelectEnabled, + ), + serverClientId: _serverClientId, + nonce: _nonce, + ), + ); switch (authnResult) { case GetCredentialFailure(): String? message = authnResult.message; @@ -182,23 +194,29 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { code = GoogleSignInExceptionCode.unknownError; } throw GoogleSignInException( - code: code, description: message, details: authnResult.details); + code: code, + description: message, + details: authnResult.details, + ); case GetCredentialSuccess(): return authnResult.credential; } } Future<({String? accessToken, String? serverAuthCode})> _authorize( - AuthorizationRequestDetails request, - {required bool requestOfflineAccess}) async { + AuthorizationRequestDetails request, { + required bool requestOfflineAccess, + }) async { final AuthorizeResult result = await _hostApi.authorize( - PlatformAuthorizationRequest( - scopes: request.scopes, - accountEmail: request.email, - hostedDomain: _hostedDomain, - serverClientIdForForcedRefreshToken: - requestOfflineAccess ? _serverClientId : null), - promptIfUnauthorized: request.promptIfUnauthorized); + PlatformAuthorizationRequest( + scopes: request.scopes, + accountEmail: request.email, + hostedDomain: _hostedDomain, + serverClientIdForForcedRefreshToken: + requestOfflineAccess ? _serverClientId : null, + ), + promptIfUnauthorized: request.promptIfUnauthorized, + ); switch (result) { case AuthorizeFailure(): String? message = result.message; @@ -220,7 +238,10 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { code = GoogleSignInExceptionCode.uiUnavailable; } throw GoogleSignInException( - code: code, description: message, details: result.details); + code: code, + description: message, + details: result.details, + ); case PlatformAuthorizationResult(): final String? accessToken = result.accessToken; if (accessToken == null) { @@ -234,7 +255,8 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { } AuthenticationResults _authenticationResultFromPlatformCredential( - PlatformGoogleIdTokenCredential credential) { + PlatformGoogleIdTokenCredential credential, + ) { // GoogleIdTokenCredential's ID field is documented to return the // email address, not what the other platform SDKs call an ID. // The account ID returned by other platform SDKs and the legacy @@ -249,12 +271,14 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { return AuthenticationResults( user: GoogleSignInUserData( - email: email, - id: userId, - displayName: credential.displayName, - photoUrl: credential.profilePictureUri), - authenticationTokens: - AuthenticationTokenData(idToken: credential.idToken), + email: email, + id: userId, + displayName: credential.displayName, + photoUrl: credential.profilePictureUri, + ), + authenticationTokens: AuthenticationTokenData( + idToken: credential.idToken, + ), ); } } @@ -269,7 +293,8 @@ final Codec _jwtCodec = json.fuse(utf8).fuse(base64); /// See https://stackoverflow.com/a/78064720 String? _idFromIdToken(String idToken) { final RegExp jwtTokenRegexp = RegExp( - r'^(?
[^\.\s]+)\.(?[^\.\s]+)\.(?[^\.\s]+)$'); + r'^(?
[^\.\s]+)\.(?[^\.\s]+)\.(?[^\.\s]+)$', + ); final RegExpMatch? match = jwtTokenRegexp.firstMatch(idToken); final String? payload = match?.namedGroup('payload'); if (payload != null) { diff --git a/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart b/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart index fa5f335ddbe..b46f99ff9e0 100644 --- a/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart +++ b/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart @@ -173,10 +173,7 @@ class GetCredentialRequestGoogleIdOptionParams { bool autoSelectEnabled; Object encode() { - return [ - filterToAuthorized, - autoSelectEnabled, - ]; + return [filterToAuthorized, autoSelectEnabled]; } static GetCredentialRequestGoogleIdOptionParams decode(Object result) { @@ -245,11 +242,7 @@ sealed class GetCredentialResult {} /// An authentication failure. class GetCredentialFailure extends GetCredentialResult { - GetCredentialFailure({ - required this.type, - this.message, - this.details, - }); + GetCredentialFailure({required this.type, this.message, this.details}); /// The type of failure. GetCredentialFailureType type; @@ -261,11 +254,7 @@ class GetCredentialFailure extends GetCredentialResult { String? details; Object encode() { - return [ - type, - message, - details, - ]; + return [type, message, details]; } static GetCredentialFailure decode(Object result) { @@ -280,16 +269,12 @@ class GetCredentialFailure extends GetCredentialResult { /// A successful authentication result. class GetCredentialSuccess extends GetCredentialResult { - GetCredentialSuccess({ - required this.credential, - }); + GetCredentialSuccess({required this.credential}); PlatformGoogleIdTokenCredential credential; Object encode() { - return [ - credential, - ]; + return [credential]; } static GetCredentialSuccess decode(Object result) { @@ -305,11 +290,7 @@ sealed class AuthorizeResult {} /// An authorization failure class AuthorizeFailure extends AuthorizeResult { - AuthorizeFailure({ - required this.type, - this.message, - this.details, - }); + AuthorizeFailure({required this.type, this.message, this.details}); /// The type of failure. AuthorizeFailureType type; @@ -321,11 +302,7 @@ class AuthorizeFailure extends AuthorizeResult { String? details; Object encode() { - return [ - type, - message, - details, - ]; + return [type, message, details]; } static AuthorizeFailure decode(Object result) { @@ -355,11 +332,7 @@ class PlatformAuthorizationResult extends AuthorizeResult { List grantedScopes; Object encode() { - return [ - accessToken, - serverAuthCode, - grantedScopes, - ]; + return [accessToken, serverAuthCode, grantedScopes]; } static PlatformAuthorizationResult decode(Object result) { @@ -429,7 +402,8 @@ class _PigeonCodec extends StandardMessageCodec { return GetCredentialRequestParams.decode(readValue(buffer)!); case 133: return GetCredentialRequestGoogleIdOptionParams.decode( - readValue(buffer)!); + readValue(buffer)!, + ); case 134: return PlatformGoogleIdTokenCredential.decode(readValue(buffer)!); case 135: @@ -450,11 +424,12 @@ class GoogleSignInApi { /// Constructor for [GoogleSignInApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - GoogleSignInApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + GoogleSignInApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -468,10 +443,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.getGoogleServicesJsonServerClientId$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -491,17 +466,19 @@ class GoogleSignInApi { /// Requests an authentication credential (sign in) via CredentialManager's /// getCredential. Future getCredential( - GetCredentialRequestParams params) async { + GetCredentialRequestParams params, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.getCredential$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [params], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([params]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -528,10 +505,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.clearCredentialState$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -549,18 +526,21 @@ class GoogleSignInApi { } /// Requests authorization tokens via AuthorizationClient. - Future authorize(PlatformAuthorizationRequest params, - {required bool promptIfUnauthorized}) async { + Future authorize( + PlatformAuthorizationRequest params, { + required bool promptIfUnauthorized, + }) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.authorize$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [params, promptIfUnauthorized], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([params, promptIfUnauthorized]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart b/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart index c142b097d6a..59da01fd955 100644 --- a/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart +++ b/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart @@ -4,14 +4,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/googlesignin/Messages.kt', - kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.googlesignin'), - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + kotlinOut: + 'android/src/main/kotlin/io/flutter/plugins/googlesignin/Messages.kt', + kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.googlesignin'), + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// The information necessary to build a an authorization request. /// /// Corresponds to the native AuthorizationRequest object, but only contains @@ -195,6 +196,8 @@ abstract class GoogleSignInApi { /// Requests authorization tokens via AuthorizationClient. @async - AuthorizeResult authorize(PlatformAuthorizationRequest params, - {required bool promptIfUnauthorized}); + AuthorizeResult authorize( + PlatformAuthorizationRequest params, { + required bool promptIfUnauthorized, + }); } diff --git a/packages/google_sign_in/google_sign_in_android/pubspec.yaml b/packages/google_sign_in/google_sign_in_android/pubspec.yaml index 0628fad0ee2..1bb236a7a10 100644 --- a/packages/google_sign_in/google_sign_in_android/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_android/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 7.0.3 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart index 44850e69c3e..4cf0741c004 100644 --- a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart +++ b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart @@ -23,9 +23,8 @@ final AuthenticationTokenData _testAuthnToken = AuthenticationTokenData( // This is just real enough to test the id-from-idToken extraction logic, with // the middle (payload) section having an actual base-64 encoded JSON // dictionary with only the "sub":"id" entry needed by the plugin code. - idToken: 'header.${base64UrlEncode(JsonUtf8Encoder().convert( - {'sub': _testUser.id}, - ))}.signatune', + idToken: + 'header.${base64UrlEncode(JsonUtf8Encoder().convert({'sub': _testUser.id}))}.signatune', ); @GenerateNiceMocks(>[MockSpec()]) @@ -39,10 +38,14 @@ void main() { mockApi = MockGoogleSignInApi(); googleSignIn = GoogleSignInAndroid(api: mockApi); - provideDummy(GetCredentialSuccess( - credential: PlatformGoogleIdTokenCredential(id: '', idToken: ''))); + provideDummy( + GetCredentialSuccess( + credential: PlatformGoogleIdTokenCredential(id: '', idToken: ''), + ), + ); provideDummy( - PlatformAuthorizationResult(grantedScopes: [])); + PlatformAuthorizationResult(grantedScopes: []), + ); }); test('registered instance', () { @@ -64,14 +67,17 @@ void main() { test('passes explicit server client ID', () async { const String serverClientId = 'aServerClient'; - await googleSignIn - .init(const InitParameters(serverClientId: serverClientId)); + await googleSignIn.init( + const InitParameters(serverClientId: serverClientId), + ); await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + const AttemptLightweightAuthenticationParameters(), + ); verifyNever(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = - verify(mockApi.getCredential(captureAny)); + final VerificationResult verification = verify( + mockApi.getCredential(captureAny), + ); final GetCredentialRequestParams hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); @@ -79,18 +85,21 @@ void main() { test('passes JSON server client ID if not overridden', () async { const String serverClientId = 'aServerClient'; - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => serverClientId); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => serverClientId); // Passing no server client ID should cause it to be queried via // getGoogleServicesJsonServerClientId(). await googleSignIn.init(const InitParameters()); await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + const AttemptLightweightAuthenticationParameters(), + ); verify(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = - verify(mockApi.getCredential(captureAny)); + final VerificationResult verification = verify( + mockApi.getCredential(captureAny), + ); final GetCredentialRequestParams hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); @@ -99,44 +108,54 @@ void main() { test('passes nonce if provided', () async { const String nonce = 'nonce'; - await googleSignIn - .init(const InitParameters(nonce: nonce, serverClientId: 'id')); + await googleSignIn.init( + const InitParameters(nonce: nonce, serverClientId: 'id'), + ); await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + const AttemptLightweightAuthenticationParameters(), + ); - final VerificationResult verification = - verify(mockApi.getCredential(captureAny)); + final VerificationResult verification = verify( + mockApi.getCredential(captureAny), + ); final GetCredentialRequestParams hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.nonce, nonce); }); test('passes success data to caller', () async { - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialSuccess( - credential: PlatformGoogleIdTokenCredential( - displayName: _testUser.displayName, - profilePictureUri: _testUser.photoUrl, - id: _testUser.email, - idToken: _testAuthnToken.idToken!))); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialSuccess( + credential: PlatformGoogleIdTokenCredential( + displayName: _testUser.displayName, + profilePictureUri: _testUser.photoUrl, + id: _testUser.email, + idToken: _testAuthnToken.idToken!, + ), + ), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final AuthenticationResults? result = - await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + final AuthenticationResults? result = await googleSignIn + .attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result?.user, _testUser); expect(result?.authenticationTokens, _testAuthnToken); }); test('returns null for missing auth', () async { - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure(type: GetCredentialFailureType.noCredential)); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.noCredential), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final AuthenticationResults? result = - await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + final AuthenticationResults? result = await googleSignIn + .attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result, null); }); @@ -146,13 +165,15 @@ void main() { test('passes explicit server client ID', () async { const String serverClientId = 'aServerClient'; - await googleSignIn - .init(const InitParameters(serverClientId: serverClientId)); + await googleSignIn.init( + const InitParameters(serverClientId: serverClientId), + ); await googleSignIn.authenticate(const AuthenticateParameters()); verifyNever(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = - verify(mockApi.getCredential(captureAny)); + final VerificationResult verification = verify( + mockApi.getCredential(captureAny), + ); final GetCredentialRequestParams hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); @@ -160,8 +181,9 @@ void main() { test('passes JSON server client ID if not overridden', () async { const String serverClientId = 'aServerClient'; - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => serverClientId); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => serverClientId); // Passing no server client ID should cause it to be queried via // getGoogleServicesJsonServerClientId(). @@ -169,8 +191,9 @@ void main() { await googleSignIn.authenticate(const AuthenticateParameters()); verify(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = - verify(mockApi.getCredential(captureAny)); + final VerificationResult verification = verify( + mockApi.getCredential(captureAny), + ); final GetCredentialRequestParams hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); @@ -182,158 +205,235 @@ void main() { await googleSignIn.init(const InitParameters(nonce: nonce)); await googleSignIn.authenticate(const AuthenticateParameters()); - final VerificationResult verification = - verify(mockApi.getCredential(captureAny)); + final VerificationResult verification = verify( + mockApi.getCredential(captureAny), + ); final GetCredentialRequestParams hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.nonce, nonce); }); test('passes success data to caller', () async { - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialSuccess( - credential: PlatformGoogleIdTokenCredential( - displayName: _testUser.displayName, - profilePictureUri: _testUser.photoUrl, - id: _testUser.email, - idToken: _testAuthnToken.idToken!))); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialSuccess( + credential: PlatformGoogleIdTokenCredential( + displayName: _testUser.displayName, + profilePictureUri: _testUser.photoUrl, + id: _testUser.email, + idToken: _testAuthnToken.idToken!, + ), + ), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final AuthenticationResults result = - await googleSignIn.authenticate(const AuthenticateParameters()); + final AuthenticationResults result = await googleSignIn.authenticate( + const AuthenticateParameters(), + ); expect(result.user, _testUser); expect(result.authenticationTokens, _testAuthnToken); }); test('throws unknown for missing auth', () async { - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure(type: GetCredentialFailureType.noCredential)); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.noCredential), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); - test('throws client configuration error for missing server client ID', - () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure( - type: GetCredentialFailureType.missingServerClientId)); - - await googleSignIn.init(const InitParameters()); - expect( + test( + 'throws client configuration error for missing server client ID', + () async { + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialFailure( + type: GetCredentialFailureType.missingServerClientId, + ), + ); + + await googleSignIn.init(const InitParameters()); + expect( googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf() - .having((GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.clientConfigurationError) - .having((GoogleSignInException e) => e.description, 'description', - contains('serverClientId must be provided')))); - }); - - test('throws provider configuration error for wrong credential type', - () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure( - type: GetCredentialFailureType.unexpectedCredentialType)); + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.clientConfigurationError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('serverClientId must be provided'), + ), + ), + ); + }, + ); - await googleSignIn.init(const InitParameters()); - expect( + test( + 'throws provider configuration error for wrong credential type', + () async { + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialFailure( + type: GetCredentialFailureType.unexpectedCredentialType, + ), + ); + + await googleSignIn.init(const InitParameters()); + expect( googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf() - .having((GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.providerConfigurationError) - .having((GoogleSignInException e) => e.description, 'description', - contains('Unexpected credential type')))); - }); + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('Unexpected credential type'), + ), + ), + ); + }, + ); - test( - 'throws provider configuration error if device does not ' + test('throws provider configuration error if device does not ' 'support Credential Manager', () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure(type: GetCredentialFailureType.unsupported)); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.unsupported), + ); await googleSignIn.init(const InitParameters()); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf() - .having((GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.providerConfigurationError) - .having((GoogleSignInException e) => e.description, 'description', - contains('Credential Manager not supported')))); - }); - - test( - 'throws provider configuration error for SDK-reported ' + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('Credential Manager not supported'), + ), + ), + ); + }); + + test('throws provider configuration error for SDK-reported ' 'provider configuration error', () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure( - type: GetCredentialFailureType.providerConfigurationIssue)); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialFailure( + type: GetCredentialFailureType.providerConfigurationIssue, + ), + ); await googleSignIn.init(const InitParameters()); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.providerConfigurationError))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ), + ), + ); }); test('throws interrupted from SDK', () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure(type: GetCredentialFailureType.interrupted)); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.interrupted), + ); await googleSignIn.init(const InitParameters()); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.interrupted))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.interrupted, + ), + ), + ); }); test('throws canceled from SDK', () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure(type: GetCredentialFailureType.canceled)); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.canceled), + ); await googleSignIn.init(const InitParameters()); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test('throws unknown from SDK', () async { - when(mockApi.getGoogleServicesJsonServerClientId()) - .thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer((_) async => - GetCredentialFailure(type: GetCredentialFailureType.unknown)); + when( + mockApi.getGoogleServicesJsonServerClientId(), + ).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.unknown), + ); await googleSignIn.init(const InitParameters()); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); }); @@ -342,11 +442,11 @@ void main() { // the test. const AuthorizationRequestDetails defaultAuthRequest = AuthorizationRequestDetails( - scopes: ['a'], - userId: null, - email: null, - promptIfUnauthorized: false, - ); + scopes: ['a'], + userId: null, + email: null, + promptIfUnauthorized: false, + ); test('passes expected values', () async { const List scopes = ['a', 'b']; @@ -355,25 +455,32 @@ void main() { const bool promptIfUnauthorized = false; const String hostedDomain = 'example.com'; - when(mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)) - .thenAnswer((_) async => - PlatformAuthorizationResult(grantedScopes: [])); + when( + mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), + ).thenAnswer( + (_) async => PlatformAuthorizationResult(grantedScopes: []), + ); - await googleSignIn.init(const InitParameters( - serverClientId: 'id', - hostedDomain: hostedDomain, - )); + await googleSignIn.init( + const InitParameters(serverClientId: 'id', hostedDomain: hostedDomain), + ); await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: userId, - email: userEmail, - promptIfUnauthorized: promptIfUnauthorized, - ))); - - final VerificationResult verification = verify(mockApi - .authorize(captureAny, promptIfUnauthorized: promptIfUnauthorized)); + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: userId, + email: userEmail, + promptIfUnauthorized: promptIfUnauthorized, + ), + ), + ); + + final VerificationResult verification = verify( + mockApi.authorize( + captureAny, + promptIfUnauthorized: promptIfUnauthorized, + ), + ); final PlatformAuthorizationRequest hostParams = verification.captured[0] as PlatformAuthorizationRequest; expect(hostParams.scopes, scopes); @@ -386,115 +493,160 @@ void main() { const List scopes = ['a', 'b']; const bool promptIfUnauthorized = true; - when(mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)) - .thenAnswer((_) async => - PlatformAuthorizationResult(grantedScopes: [])); + when( + mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), + ).thenAnswer( + (_) async => PlatformAuthorizationResult(grantedScopes: []), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: promptIfUnauthorized, - ))); + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: promptIfUnauthorized, + ), + ), + ); verify( - mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)); + mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), + ); }); test('passes success data to caller', () async { const String accessToken = 'token'; when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => PlatformAuthorizationResult( - grantedScopes: [], accessToken: accessToken)); + (_) async => PlatformAuthorizationResult( + grantedScopes: [], + accessToken: accessToken, + ), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final ClientAuthorizationTokenData? result = - await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)); + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ); expect(result?.accessToken, accessToken); }); test('returns null when unauthorized', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.unauthorized)); + (_) async => AuthorizeFailure(type: AuthorizeFailureType.unauthorized), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - null); + await googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + null, + ); }); test('thows canceled if pending intent fails', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure( - type: AuthorizeFailureType.pendingIntentException)); + (_) async => + AuthorizeFailure(type: AuthorizeFailureType.pendingIntentException), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test('throws unknown if authorization fails', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure)); + (_) async => + AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); test('throws unknown for API exception', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.apiException)); + (_) async => AuthorizeFailure(type: AuthorizeFailureType.apiException), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf() - .having((GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.unknownError) - .having((GoogleSignInException e) => e.description, 'description', - contains('SDK reported an exception')))); + googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('SDK reported an exception'), + ), + ), + ); }); test('throws UI unavailable if there is no activity available', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity)); + (_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.uiUnavailable))); + googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.uiUnavailable, + ), + ), + ); }); }); @@ -503,11 +655,11 @@ void main() { // the test. const AuthorizationRequestDetails defaultAuthRequest = AuthorizationRequestDetails( - scopes: ['a'], - userId: null, - email: null, - promptIfUnauthorized: false, - ); + scopes: ['a'], + userId: null, + email: null, + promptIfUnauthorized: false, + ); test('serverAuthorizationTokensForScopes passes expected values', () async { const List scopes = ['a', 'b']; @@ -517,25 +669,35 @@ void main() { const String hostedDomain = 'example.com'; const String serverClientId = 'serverClientId'; - when(mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)) - .thenAnswer((_) async => - PlatformAuthorizationResult(grantedScopes: [])); - - await googleSignIn.init(const InitParameters( - serverClientId: serverClientId, - hostedDomain: hostedDomain, - )); + when( + mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), + ).thenAnswer( + (_) async => PlatformAuthorizationResult(grantedScopes: []), + ); + + await googleSignIn.init( + const InitParameters( + serverClientId: serverClientId, + hostedDomain: hostedDomain, + ), + ); await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: userId, - email: userEmail, - promptIfUnauthorized: promptIfUnauthorized, - ))); - - final VerificationResult verification = verify(mockApi - .authorize(captureAny, promptIfUnauthorized: promptIfUnauthorized)); + const ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: userId, + email: userEmail, + promptIfUnauthorized: promptIfUnauthorized, + ), + ), + ); + + final VerificationResult verification = verify( + mockApi.authorize( + captureAny, + promptIfUnauthorized: promptIfUnauthorized, + ), + ); final PlatformAuthorizationRequest hostParams = verification.captured[0] as PlatformAuthorizationRequest; expect(hostParams.scopes, scopes); @@ -545,130 +707,176 @@ void main() { }); test( - 'serverAuthorizationTokensForScopes passes true promptIfUnauthorized when requested', - () async { - const List scopes = ['a', 'b']; - const bool promptIfUnauthorized = true; - - when(mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)) - .thenAnswer((_) async => - PlatformAuthorizationResult(grantedScopes: [])); - - await googleSignIn.init(const InitParameters(serverClientId: 'id')); - await googleSignIn.serverAuthorizationTokensForScopes( + 'serverAuthorizationTokensForScopes passes true promptIfUnauthorized when requested', + () async { + const List scopes = ['a', 'b']; + const bool promptIfUnauthorized = true; + + when( + mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), + ).thenAnswer( + (_) async => PlatformAuthorizationResult(grantedScopes: []), + ); + + await googleSignIn.init(const InitParameters(serverClientId: 'id')); + await googleSignIn.serverAuthorizationTokensForScopes( const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: promptIfUnauthorized, - ))); - - verify( - mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)); - }); - - test('serverAuthorizationTokensForScopes passes success data to caller', - () async { - const List scopes = ['a', 'b']; - const String authCode = 'code'; + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: promptIfUnauthorized, + ), + ), + ); + + verify( + mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), + ); + }, + ); - when(mockApi.authorize(any, promptIfUnauthorized: false)) - .thenAnswer((_) async => PlatformAuthorizationResult( - grantedScopes: [], - accessToken: 'token', - serverAuthCode: authCode, - )); + test( + 'serverAuthorizationTokensForScopes passes success data to caller', + () async { + const List scopes = ['a', 'b']; + const String authCode = 'code'; - await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final ServerAuthorizationTokenData? result = - await googleSignIn.serverAuthorizationTokensForScopes( + when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( + (_) async => PlatformAuthorizationResult( + grantedScopes: [], + accessToken: 'token', + serverAuthCode: authCode, + ), + ); + + await googleSignIn.init(const InitParameters(serverClientId: 'id')); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ))); - - expect(result?.serverAuthCode, authCode); - }); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); + + expect(result?.serverAuthCode, authCode); + }, + ); test('returns null when unauthorized', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.unauthorized)); + (_) async => AuthorizeFailure(type: AuthorizeFailureType.unauthorized), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - null); + await googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + null, + ); }); test('thows canceled if pending intent fails', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure( - type: AuthorizeFailureType.pendingIntentException)); + (_) async => + AuthorizeFailure(type: AuthorizeFailureType.pendingIntentException), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test('throws unknown if authorization fails', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure)); + (_) async => + AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); test('throws unknown for API exception', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.apiException)); + (_) async => AuthorizeFailure(type: AuthorizeFailureType.apiException), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf() - .having((GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.unknownError) - .having((GoogleSignInException e) => e.description, 'description', - contains('SDK reported an exception')))); + googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('SDK reported an exception'), + ), + ), + ); }); test('throws UI unavailable if there is no activity available', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity)); + (_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity), + ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( - googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.uiUnavailable))); + googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.uiUnavailable, + ), + ), + ); }); }); diff --git a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart index 46f5cf978a5..f3327d75516 100644 --- a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart @@ -28,64 +28,59 @@ import 'package:mockito/src/dummies.dart' as _i3; /// See the documentation for Mockito's code generation for more information. class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi { @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override _i4.Future getGoogleServicesJsonServerClientId() => (super.noSuchMethod( - Invocation.method( - #getGoogleServicesJsonServerClientId, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#getGoogleServicesJsonServerClientId, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future<_i2.GetCredentialResult> getCredential( - _i2.GetCredentialRequestParams? params) => + _i2.GetCredentialRequestParams? params, + ) => (super.noSuchMethod( - Invocation.method( - #getCredential, - [params], - ), - returnValue: _i4.Future<_i2.GetCredentialResult>.value( - _i3.dummyValue<_i2.GetCredentialResult>( - this, - Invocation.method( - #getCredential, - [params], - ), - )), - returnValueForMissingStub: _i4.Future<_i2.GetCredentialResult>.value( - _i3.dummyValue<_i2.GetCredentialResult>( - this, - Invocation.method( - #getCredential, - [params], - ), - )), - ) as _i4.Future<_i2.GetCredentialResult>); + Invocation.method(#getCredential, [params]), + returnValue: _i4.Future<_i2.GetCredentialResult>.value( + _i3.dummyValue<_i2.GetCredentialResult>( + this, + Invocation.method(#getCredential, [params]), + ), + ), + returnValueForMissingStub: + _i4.Future<_i2.GetCredentialResult>.value( + _i3.dummyValue<_i2.GetCredentialResult>( + this, + Invocation.method(#getCredential, [params]), + ), + ), + ) + as _i4.Future<_i2.GetCredentialResult>); @override - _i4.Future clearCredentialState() => (super.noSuchMethod( - Invocation.method( - #clearCredentialState, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future clearCredentialState() => + (super.noSuchMethod( + Invocation.method(#clearCredentialState, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future<_i2.AuthorizeResult> authorize( @@ -93,28 +88,31 @@ class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi { required bool? promptIfUnauthorized, }) => (super.noSuchMethod( - Invocation.method( - #authorize, - [params], - {#promptIfUnauthorized: promptIfUnauthorized}, - ), - returnValue: _i4.Future<_i2.AuthorizeResult>.value( - _i3.dummyValue<_i2.AuthorizeResult>( - this, - Invocation.method( - #authorize, - [params], - {#promptIfUnauthorized: promptIfUnauthorized}, - ), - )), - returnValueForMissingStub: _i4.Future<_i2.AuthorizeResult>.value( - _i3.dummyValue<_i2.AuthorizeResult>( - this, - Invocation.method( - #authorize, - [params], - {#promptIfUnauthorized: promptIfUnauthorized}, - ), - )), - ) as _i4.Future<_i2.AuthorizeResult>); + Invocation.method( + #authorize, + [params], + {#promptIfUnauthorized: promptIfUnauthorized}, + ), + returnValue: _i4.Future<_i2.AuthorizeResult>.value( + _i3.dummyValue<_i2.AuthorizeResult>( + this, + Invocation.method( + #authorize, + [params], + {#promptIfUnauthorized: promptIfUnauthorized}, + ), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.AuthorizeResult>.value( + _i3.dummyValue<_i2.AuthorizeResult>( + this, + Invocation.method( + #authorize, + [params], + {#promptIfUnauthorized: promptIfUnauthorized}, + ), + ), + ), + ) + as _i4.Future<_i2.AuthorizeResult>); } diff --git a/packages/google_sign_in/google_sign_in_ios/CHANGELOG.md b/packages/google_sign_in/google_sign_in_ios/CHANGELOG.md index 20e2e987c4f..0934dd32357 100644 --- a/packages/google_sign_in/google_sign_in_ios/CHANGELOG.md +++ b/packages/google_sign_in/google_sign_in_ios/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 6.1.0 * Updates to `GoogleSignIn` 9.0. diff --git a/packages/google_sign_in/google_sign_in_ios/README.md b/packages/google_sign_in/google_sign_in_ios/README.md index 9d70264a7de..7f6b2300331 100644 --- a/packages/google_sign_in/google_sign_in_ios/README.md +++ b/packages/google_sign_in/google_sign_in_ios/README.md @@ -61,13 +61,15 @@ you can instead configure your app in Dart code. In this case, skip steps 4 and ```dart final GoogleSignInPlatform signIn = GoogleSignInPlatform.instance; -await signIn.init(const InitParameters( - // The OAuth client ID of your app. This is required. - clientId: 'Your Client ID', - // If you need to authenticate to a backend server, specify the server's - // OAuth client ID. This is optional. - serverClientId: 'Your Server ID', -)); +await signIn.init( + const InitParameters( + // The OAuth client ID of your app. This is required. + clientId: 'Your Client ID', + // If you need to authenticate to a backend server, specify the server's + // OAuth client ID. This is optional. + serverClientId: 'Your Server ID', + ), +); ``` Note that step 6 is still required. diff --git a/packages/google_sign_in/google_sign_in_ios/example/integration_test/google_sign_in_test.dart b/packages/google_sign_in/google_sign_in_ios/example/integration_test/google_sign_in_test.dart index 11a312c90f0..a8f4f7c6690 100644 --- a/packages/google_sign_in/google_sign_in_ios/example/integration_test/google_sign_in_test.dart +++ b/packages/google_sign_in/google_sign_in_ios/example/integration_test/google_sign_in_test.dart @@ -21,13 +21,15 @@ void main() { try { // #docregion IDsInCode final GoogleSignInPlatform signIn = GoogleSignInPlatform.instance; - await signIn.init(const InitParameters( - // The OAuth client ID of your app. This is required. - clientId: 'Your Client ID', - // If you need to authenticate to a backend server, specify the server's - // OAuth client ID. This is optional. - serverClientId: 'Your Server ID', - )); + await signIn.init( + const InitParameters( + // The OAuth client ID of your app. This is required. + clientId: 'Your Client ID', + // If you need to authenticate to a backend server, specify the server's + // OAuth client ID. This is optional. + serverClientId: 'Your Server ID', + ), + ); // #enddocregion IDsInCode } catch (e) { fail('Initialization should succeed'); diff --git a/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart b/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart index a821469792d..a703ccc9dc7 100644 --- a/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart +++ b/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart @@ -17,12 +17,7 @@ const List _scopes = [ ]; void main() { - runApp( - const MaterialApp( - title: 'Google Sign In', - home: SignInDemo(), - ), - ); + runApp(const MaterialApp(title: 'Google Sign In', home: SignInDemo())); } class SignInDemo extends StatefulWidget { @@ -47,11 +42,11 @@ class SignInDemoState extends State { } Future _ensureInitialized() { - return _initialization ??= - GoogleSignInPlatform.instance.init(const InitParameters()) - ..catchError((dynamic _) { - _initialization = null; - }); + return _initialization ??= GoogleSignInPlatform.instance.init( + const InitParameters(), + )..catchError((dynamic _) { + _initialization = null; + }); } void _setUser(GoogleSignInUserData? user) { @@ -69,13 +64,15 @@ class SignInDemoState extends State { try { final AuthenticationResults? result = await GoogleSignInPlatform.instance .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + const AttemptLightweightAuthenticationParameters(), + ); _setUser(result?.user); } on GoogleSignInException catch (e) { setState(() { - _errorMessage = e.code == GoogleSignInExceptionCode.canceled - ? '' - : 'GoogleSignInException ${e.code}: ${e.description}'; + _errorMessage = + e.code == GoogleSignInExceptionCode.canceled + ? '' + : 'GoogleSignInException ${e.code}: ${e.description}'; }); } } @@ -85,12 +82,15 @@ class SignInDemoState extends State { final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform .instance .clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: _scopes, - userId: user.id, - email: user.email, - promptIfUnauthorized: true))); + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: _scopes, + userId: user.id, + email: user.email, + promptIfUnauthorized: true, + ), + ), + ); setState(() { _isAuthorized = tokens != null; @@ -107,15 +107,20 @@ class SignInDemoState extends State { } Future?> _getAuthHeaders( - GoogleSignInUserData user) async { - final ClientAuthorizationTokenData? tokens = - await GoogleSignInPlatform.instance.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: _scopes, - userId: user.id, - email: user.email, - promptIfUnauthorized: false))); + GoogleSignInUserData user, + ) async { + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform + .instance + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: _scopes, + userId: user.id, + email: user.email, + promptIfUnauthorized: false, + ), + ), + ); if (tokens == null) { return null; } @@ -140,13 +145,16 @@ class SignInDemoState extends State { return; } final http.Response response = await http.get( - Uri.parse('https://people.googleapis.com/v1/people/me/connections' - '?requestMask.includeField=person.names'), + Uri.parse( + 'https://people.googleapis.com/v1/people/me/connections' + '?requestMask.includeField=person.names', + ), headers: headers, ); if (response.statusCode != 200) { setState(() { - _contactText = 'People API gave a ${response.statusCode} ' + _contactText = + 'People API gave a ${response.statusCode} ' 'response. Check logs for details.'; }); print('People API ${response.statusCode} response: ${response.body}'); @@ -169,9 +177,10 @@ class SignInDemoState extends State { _setUser(result.user); } on GoogleSignInException catch (e) { setState(() { - _errorMessage = e.code == GoogleSignInExceptionCode.canceled - ? '' - : 'GoogleSignInException ${e.code}: ${e.description}'; + _errorMessage = + e.code == GoogleSignInExceptionCode.canceled + ? '' + : 'GoogleSignInException ${e.code}: ${e.description}'; }); } } @@ -226,12 +235,11 @@ class SignInDemoState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Google Sign In'), - ), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - )); + appBar: AppBar(title: const Text('Google Sign In')), + body: ConstrainedBox( + constraints: const BoxConstraints.expand(), + child: _buildBody(), + ), + ); } } diff --git a/packages/google_sign_in/google_sign_in_ios/example/pubspec.yaml b/packages/google_sign_in/google_sign_in_ios/example/pubspec.yaml index 4b53bc236a8..bc12daff1c2 100644 --- a/packages/google_sign_in/google_sign_in_ios/example/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_ios/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Example of Google Sign-In plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart b/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart index b5970ee0a17..5c8cbc2dd2c 100644 --- a/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart +++ b/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart @@ -12,9 +12,8 @@ import 'src/messages.g.dart'; /// iOS implementation of [GoogleSignInPlatform]. class GoogleSignInIOS extends GoogleSignInPlatform { /// Creates a new plugin implementation instance. - GoogleSignInIOS({ - @visibleForTesting GoogleSignInApi? api, - }) : _api = api ?? GoogleSignInApi(); + GoogleSignInIOS({@visibleForTesting GoogleSignInApi? api}) + : _api = api ?? GoogleSignInApi(); final GoogleSignInApi _api; @@ -28,15 +27,19 @@ class GoogleSignInIOS extends GoogleSignInPlatform { @override Future init(InitParameters params) async { _nonce = params.nonce; - await _api.configure(PlatformConfigurationParams( + await _api.configure( + PlatformConfigurationParams( clientId: params.clientId, serverClientId: params.serverClientId, - hostedDomain: params.hostedDomain)); + hostedDomain: params.hostedDomain, + ), + ); } @override Future attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params) async { + AttemptLightweightAuthenticationParameters params, + ) async { final SignInResult result = await _api.restorePreviousSignIn(); if (result.error?.type == GoogleSignInErrorCode.noAuthInKeychain) { @@ -46,9 +49,10 @@ class GoogleSignInIOS extends GoogleSignInPlatform { final SignInFailure? failure = result.error; if (failure != null) { throw GoogleSignInException( - code: _exceptionCodeForErrorPlatformErrorCode(failure.type), - description: failure.message, - details: failure.details); + code: _exceptionCodeForErrorPlatformErrorCode(failure.type), + description: failure.message, + details: failure.details, + ); } // The native code must never return a null success and a null error. @@ -64,23 +68,26 @@ class GoogleSignInIOS extends GoogleSignInPlatform { @override Future authenticate( - AuthenticateParameters params) async { + AuthenticateParameters params, + ) async { final SignInResult result = await _api.signIn(params.scopeHint, _nonce); // This should never happen; the corresponding native error code is // documented as being specific to restorePreviousSignIn. if (result.error?.type == GoogleSignInErrorCode.noAuthInKeychain) { throw const GoogleSignInException( - code: GoogleSignInExceptionCode.unknownError, - description: 'No auth reported during interactive sign in.'); + code: GoogleSignInExceptionCode.unknownError, + description: 'No auth reported during interactive sign in.', + ); } final SignInFailure? failure = result.error; if (failure != null) { throw GoogleSignInException( - code: _exceptionCodeForErrorPlatformErrorCode(failure.type), - description: failure.message, - details: failure.details); + code: _exceptionCodeForErrorPlatformErrorCode(failure.type), + description: failure.message, + details: failure.details, + ); } // The native code must never return a null success and a null error. @@ -107,7 +114,8 @@ class GoogleSignInIOS extends GoogleSignInPlatform { @override Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params) async { + ClientAuthorizationTokensForScopesParameters params, + ) async { final String? accessToken = (await _getAuthorizationTokens(params.request)).accessToken; return accessToken == null @@ -117,7 +125,8 @@ class GoogleSignInIOS extends GoogleSignInPlatform { @override Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params) async { + ServerAuthorizationTokensForScopesParameters params, + ) async { final String? serverAuthCode = (await _getAuthorizationTokens(params.request)).serverAuthCode; return serverAuthCode == null @@ -126,7 +135,7 @@ class GoogleSignInIOS extends GoogleSignInPlatform { } Future<({String? accessToken, String? serverAuthCode})> - _getAuthorizationTokens(AuthorizationRequestDetails request) async { + _getAuthorizationTokens(AuthorizationRequestDetails request) async { String? userId = request.userId; // The Google Sign In SDK requires authentication before authorization, so @@ -155,9 +164,10 @@ class GoogleSignInIOS extends GoogleSignInPlatform { } final bool useExistingAuthorization = !request.promptIfUnauthorized; - SignInResult result = useExistingAuthorization - ? await _api.getRefreshedAuthorizationTokens(userId) - : await _api.addScopes(request.scopes, userId); + SignInResult result = + useExistingAuthorization + ? await _api.getRefreshedAuthorizationTokens(userId) + : await _api.addScopes(request.scopes, userId); if (!useExistingAuthorization && result.error?.type == GoogleSignInErrorCode.scopesAlreadyGranted) { // The Google Sign In SDK returns an error when requesting scopes that are @@ -183,12 +193,14 @@ class GoogleSignInIOS extends GoogleSignInPlatform { const Set openIdConnectScopes = { 'email', 'openid', - 'profile' + 'profile', }; if (success != null) { - if (request.scopes.any((String scope) => - !openIdConnectScopes.contains(scope) && - !success.grantedScopes.contains(scope))) { + if (request.scopes.any( + (String scope) => + !openIdConnectScopes.contains(scope) && + !success.grantedScopes.contains(scope), + )) { return (accessToken: null, serverAuthCode: null); } } @@ -198,42 +210,46 @@ class GoogleSignInIOS extends GoogleSignInPlatform { } Future<({String? accessToken, String? serverAuthCode})> - _processAuthorizationResult(SignInResult result) async { + _processAuthorizationResult(SignInResult result) async { final SignInFailure? failure = result.error; if (failure != null) { throw GoogleSignInException( - code: _exceptionCodeForErrorPlatformErrorCode(failure.type), - description: failure.message, - details: failure.details); + code: _exceptionCodeForErrorPlatformErrorCode(failure.type), + description: failure.message, + details: failure.details, + ); } return _authorizationTokenDataFromSignInSuccess(result.success); } AuthenticationResults _authenticationResultsFromSignInSuccess( - SignInSuccess result) { + SignInSuccess result, + ) { final UserData userData = result.user; final GoogleSignInUserData user = GoogleSignInUserData( - email: userData.email, - id: userData.userId, - displayName: userData.displayName, - photoUrl: userData.photoUrl); + email: userData.email, + id: userData.userId, + displayName: userData.displayName, + photoUrl: userData.photoUrl, + ); return AuthenticationResults( - user: user, - authenticationTokens: - AuthenticationTokenData(idToken: userData.idToken)); + user: user, + authenticationTokens: AuthenticationTokenData(idToken: userData.idToken), + ); } ({String? accessToken, String? serverAuthCode}) - _authorizationTokenDataFromSignInSuccess(SignInSuccess? result) { + _authorizationTokenDataFromSignInSuccess(SignInSuccess? result) { return ( accessToken: result?.accessToken, - serverAuthCode: result?.serverAuthCode + serverAuthCode: result?.serverAuthCode, ); } GoogleSignInExceptionCode _exceptionCodeForErrorPlatformErrorCode( - GoogleSignInErrorCode code) { + GoogleSignInErrorCode code, + ) { return switch (code) { GoogleSignInErrorCode.unknown => GoogleSignInExceptionCode.unknownError, GoogleSignInErrorCode.keychainError => @@ -245,10 +261,14 @@ class GoogleSignInIOS extends GoogleSignInPlatform { GoogleSignInExceptionCode.userMismatch, // These should never be mapped to a GoogleSignInException; the caller // should handle them. - GoogleSignInErrorCode.noAuthInKeychain => throw StateError( - '_exceptionCodeForErrorPlatformErrorCode called with no auth.'), - GoogleSignInErrorCode.scopesAlreadyGranted => throw StateError( - '_exceptionCodeForErrorPlatformErrorCode called with scopes already granted.'), + GoogleSignInErrorCode.noAuthInKeychain => + throw StateError( + '_exceptionCodeForErrorPlatformErrorCode called with no auth.', + ), + GoogleSignInErrorCode.scopesAlreadyGranted => + throw StateError( + '_exceptionCodeForErrorPlatformErrorCode called with scopes already granted.', + ), }; } } diff --git a/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart b/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart index f4e23701c04..8eec846da48 100644 --- a/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart +++ b/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart @@ -63,11 +63,7 @@ class PlatformConfigurationParams { String? hostedDomain; Object encode() { - return [ - clientId, - serverClientId, - hostedDomain, - ]; + return [clientId, serverClientId, hostedDomain]; } static PlatformConfigurationParams decode(Object result) { @@ -103,13 +99,7 @@ class UserData { String? idToken; Object encode() { - return [ - displayName, - email, - userId, - photoUrl, - idToken, - ]; + return [displayName, email, userId, photoUrl, idToken]; } static UserData decode(Object result) { @@ -126,10 +116,7 @@ class UserData { /// The response from an auth call. class SignInResult { - SignInResult({ - this.success, - this.error, - }); + SignInResult({this.success, this.error}); /// The success result, if any. /// @@ -142,10 +129,7 @@ class SignInResult { SignInFailure? error; Object encode() { - return [ - success, - error, - ]; + return [success, error]; } static SignInResult decode(Object result) { @@ -159,11 +143,7 @@ class SignInResult { /// An sign in failure. class SignInFailure { - SignInFailure({ - required this.type, - this.message, - this.details, - }); + SignInFailure({required this.type, this.message, this.details}); /// The type of failure. GoogleSignInErrorCode type; @@ -175,11 +155,7 @@ class SignInFailure { Object? details; Object encode() { - return [ - type, - message, - details, - ]; + return [type, message, details]; } static SignInFailure decode(Object result) { @@ -215,12 +191,7 @@ class SignInSuccess { String? serverAuthCode; Object encode() { - return [ - user, - accessToken, - grantedScopes, - serverAuthCode, - ]; + return [user, accessToken, grantedScopes, serverAuthCode]; } static SignInSuccess decode(Object result) { @@ -290,11 +261,12 @@ class GoogleSignInApi { /// Constructor for [GoogleSignInApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - GoogleSignInApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + GoogleSignInApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -307,10 +279,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.configure$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([params]) as List?; if (pigeonVar_replyList == null) { @@ -333,10 +305,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.restorePreviousSignIn$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -363,12 +335,13 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signIn$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([scopeHint, nonce]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([scopeHint, nonce]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -393,10 +366,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.getRefreshedAuthorizationTokens$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([userId]) as List?; if (pigeonVar_replyList == null) { @@ -423,12 +396,13 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.addScopes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([scopes, userId]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([scopes, userId]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -453,10 +427,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signOut$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -478,10 +452,10 @@ class GoogleSignInApi { 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.disconnect$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { diff --git a/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart b/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart index aae37cdf728..3e410116a18 100644 --- a/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart +++ b/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart @@ -4,18 +4,20 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - objcHeaderOut: - 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/include/google_sign_in_ios/messages.g.h', - objcSourceOut: - 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/messages.g.m', - objcOptions: ObjcOptions( - prefix: 'FSI', - headerIncludePath: './include/google_sign_in_ios/messages.g.h', +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + objcHeaderOut: + 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/include/google_sign_in_ios/messages.g.h', + objcSourceOut: + 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/messages.g.m', + objcOptions: ObjcOptions( + prefix: 'FSI', + headerIncludePath: './include/google_sign_in_ios/messages.g.h', + ), + copyrightHeader: 'pigeons/copyright.txt', ), - copyrightHeader: 'pigeons/copyright.txt', -)) +) class PlatformConfigurationParams { PlatformConfigurationParams({ this.clientId, diff --git a/packages/google_sign_in/google_sign_in_ios/pubspec.yaml b/packages/google_sign_in/google_sign_in_ios/pubspec.yaml index a4f3f2d7baf..eb0b202314f 100644 --- a/packages/google_sign_in/google_sign_in_ios/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_ios/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 6.1.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart index 153a6c239aa..e258b4dd7d1 100644 --- a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart +++ b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart @@ -51,14 +51,17 @@ void main() { const String serverClientId = 'aServerClient'; const String hostedDomain = 'example.com'; - await googleSignIn.init(const InitParameters( - clientId: clientId, - serverClientId: serverClientId, - hostedDomain: hostedDomain, - )); - - final VerificationResult verification = - verify(mockApi.configure(captureAny)); + await googleSignIn.init( + const InitParameters( + clientId: clientId, + serverClientId: serverClientId, + hostedDomain: hostedDomain, + ), + ); + + final VerificationResult verification = verify( + mockApi.configure(captureAny), + ); final PlatformConfigurationParams hostParams = verification.captured[0] as PlatformConfigurationParams; expect(hostParams.clientId, clientId); @@ -70,61 +73,74 @@ void main() { group('attemptLightweightAuthentication', () { test('passes success data to caller', () async { const String idToken = 'idToken'; - when(mockApi.restorePreviousSignIn()) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: idToken, - ), - accessToken: '', - grantedScopes: [], - ))); + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: idToken, + ), + accessToken: '', + grantedScopes: [], + ), + ), + ); - final AuthenticationResults? result = - await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + final AuthenticationResults? result = await googleSignIn + .attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result?.user, _testUser); expect(result?.authenticationTokens.idToken, idToken); }); test('returns null for missing auth', () async { - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); - final AuthenticationResults? result = - await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + final AuthenticationResults? result = await googleSignIn + .attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result, null); }); test('throws for other errors', () async { - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.keychainError))); + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.keychainError), + ), + ); expect( - googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.providerConfigurationError))); + googleSignIn.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ), + ), + ); }); }); group('authenticate', () { test('passes nonce if provided', () async { const String nonce = 'nonce'; - when(mockApi.signIn(any, nonce)).thenAnswer((_) async => SignInResult( - success: SignInSuccess( + when(mockApi.signIn(any, nonce)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( user: UserData( displayName: _testUser.displayName, email: _testUser.email, @@ -134,7 +150,9 @@ void main() { ), accessToken: '', grantedScopes: [], - ))); + ), + ), + ); await googleSignIn.init(const InitParameters(nonce: nonce)); await googleSignIn.authenticate(const AuthenticateParameters()); @@ -144,8 +162,9 @@ void main() { test('passes success data to caller', () async { const String idToken = 'idToken'; - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - success: SignInSuccess( + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( user: UserData( displayName: _testUser.displayName, email: _testUser.email, @@ -155,86 +174,136 @@ void main() { ), accessToken: '', grantedScopes: [], - ))); + ), + ), + ); - final AuthenticationResults result = - await googleSignIn.authenticate(const AuthenticateParameters()); + final AuthenticationResults result = await googleSignIn.authenticate( + const AuthenticateParameters(), + ); expect(result.user, _testUser); expect(result.authenticationTokens.idToken, idToken); }); test('throws unknown for missing auth', () async { - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf() - .having((GoogleSignInException e) => e.code, 'code', - GoogleSignInExceptionCode.unknownError) - .having((GoogleSignInException e) => e.description, 'description', - contains('No auth reported')))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('No auth reported'), + ), + ), + ); }); test('throws provider configuration error for keychain error', () async { - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.keychainError))); + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.keychainError), + ), + ); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.providerConfigurationError))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ), + ), + ); }); test('throws provider configuration error for EEM error', () async { - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.eemError))); + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.eemError), + ), + ); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.providerConfigurationError))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ), + ), + ); }); test('throws canceled from SDK', () async { - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.canceled))); + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.canceled), + ), + ); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test('throws user mismatch from SDK', () async { - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.userMismatch))); + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.userMismatch), + ), + ); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.userMismatch))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.userMismatch, + ), + ), + ); }); test('throws unknown from SDK', () async { - when(mockApi.signIn(any, null)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.unknown))); + when(mockApi.signIn(any, null)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.unknown), + ), + ); expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); }); @@ -243,146 +312,169 @@ void main() { // the test. const AuthorizationRequestDetails defaultAuthRequest = AuthorizationRequestDetails( - scopes: ['a'], - userId: null, - email: null, - promptIfUnauthorized: false, - ); + scopes: ['a'], + userId: null, + email: null, + promptIfUnauthorized: false, + ); - test('passes expected values to addScopes if interaction is allowed', - () async { - const List scopes = ['a', 'b']; - when(mockApi.addScopes(any, _testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: scopes, - ))); + test( + 'passes expected values to addScopes if interaction is allowed', + () async { + const List scopes = ['a', 'b']; + when(mockApi.addScopes(any, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: scopes, + ), + ), + ); - await googleSignIn.clientAuthorizationTokensForScopes( + await googleSignIn.clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); - - final VerificationResult verification = - verify(mockApi.addScopes(captureAny, _testUser.id)); - final List passedScopes = - verification.captured[0] as List; - expect(passedScopes, scopes); - }); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); + + final VerificationResult verification = verify( + mockApi.addScopes(captureAny, _testUser.id), + ); + final List passedScopes = + verification.captured[0] as List; + expect(passedScopes, scopes); + }, + ); - test( - 'passes expected values to getRefreshedAuthorizationTokens if ' + test('passes expected values to getRefreshedAuthorizationTokens if ' 'interaction is not allowed', () async { const List scopes = ['a', 'b']; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: scopes, - ))); + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: scopes, + ), + ), + ); await googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ))); + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, + ), + ), + ); verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); }); - test('attempts to restore previous sign in if no user is provided', - () async { - const List scopes = ['a', 'b']; - final SignInResult signInResult = SignInResult( + test( + 'attempts to restore previous sign in if no user is provided', + () async { + const List scopes = ['a', 'b']; + final SignInResult signInResult = SignInResult( success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: [], - )); - when(mockApi.restorePreviousSignIn()) - .thenAnswer((_) async => signInResult); - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => signInResult); - - await googleSignIn.clientAuthorizationTokensForScopes( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: [], + ), + ); + when( + mockApi.restorePreviousSignIn(), + ).thenAnswer((_) async => signInResult); + when( + mockApi.getRefreshedAuthorizationTokens(_testUser.id), + ).thenAnswer((_) async => signInResult); + + await googleSignIn.clientAuthorizationTokensForScopes( const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ))); - - // With no user ID provided to clientAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that succeeds, get the authorization tokens for that user. - verify(mockApi.restorePreviousSignIn()); - verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); - }); - - test('returns null if unauthenticated and interaction is not allowed', - () async { - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); + + // With no user ID provided to clientAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that succeeds, get the authorization tokens for that user. + verify(mockApi.restorePreviousSignIn()); + verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + }, + ); - final ClientAuthorizationTokenData? result = - await googleSignIn.clientAuthorizationTokensForScopes( + test( + 'returns null if unauthenticated and interaction is not allowed', + () async { + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); + + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: ['a', 'b'], - userId: null, - email: null, - promptIfUnauthorized: false, - ))); - - // With no user ID provided to clientAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that fails, return null since without prompting, there is no way - // to authenticate. - verify(mockApi.restorePreviousSignIn()); - expect(result, null); - }); + request: AuthorizationRequestDetails( + scopes: ['a', 'b'], + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); + + // With no user ID provided to clientAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that fails, return null since without prompting, there is no way + // to authenticate. + verify(mockApi.restorePreviousSignIn()); + expect(result, null); + }, + ); - test( - 'attempts to authenticate if no user is provided or already signed in ' + test('attempts to authenticate if no user is provided or already signed in ' 'and interaction is allowed', () async { const List scopes = ['a', 'b']; - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); - when(mockApi.signIn(scopes, null)).thenAnswer((_) async => SignInResult( - success: SignInSuccess( + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); + when(mockApi.signIn(scopes, null)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( user: UserData( displayName: _testUser.displayName, email: _testUser.email, @@ -392,16 +484,20 @@ void main() { ), accessToken: '', grantedScopes: [], - ))); + ), + ), + ); await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: true, - ))); + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: true, + ), + ), + ); // With no user ID provided to clientAuthorizationTokensForScopes, the // implementation should attempt to restore an existing sign-in, and when @@ -410,99 +506,115 @@ void main() { verify(mockApi.signIn(scopes, null)); }); - test('passes success data to caller when refreshing existing auth', - () async { - const List scopes = ['a', 'b']; - const String accessToken = 'token'; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: scopes, - ))); + test( + 'passes success data to caller when refreshing existing auth', + () async { + const List scopes = ['a', 'b']; + const String accessToken = 'token'; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: accessToken, + grantedScopes: scopes, + ), + ), + ); - final ClientAuthorizationTokenData? result = - await googleSignIn.clientAuthorizationTokensForScopes( + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ))); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, + ), + ), + ); - expect(result?.accessToken, accessToken); - }); + expect(result?.accessToken, accessToken); + }, + ); test('passes success data to caller when calling addScopes', () async { const List scopes = ['a', 'b']; const String accessToken = 'token'; - when(mockApi.addScopes(scopes, _testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: scopes, - ))); + when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: accessToken, + grantedScopes: scopes, + ), + ), + ); - final ClientAuthorizationTokenData? result = - await googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); expect(result?.accessToken, accessToken); }); - test( - 'successfully returns refreshed tokens if addScopes indicates the ' + test('successfully returns refreshed tokens if addScopes indicates the ' 'requested scopes are already granted', () async { const List scopes = ['a', 'b']; const String accessToken = 'token'; - when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer((_) async => - SignInResult( - error: SignInFailure( - type: GoogleSignInErrorCode.scopesAlreadyGranted))); - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: scopes, - ))); + when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure( + type: GoogleSignInErrorCode.scopesAlreadyGranted, + ), + ), + ); + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: accessToken, + grantedScopes: scopes, + ), + ), + ); - final ClientAuthorizationTokenData? result = - await googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); verify(mockApi.addScopes(scopes, _testUser.id)); verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); @@ -510,106 +622,143 @@ void main() { expect(result?.accessToken, accessToken); }); - test('returns null if re-using existing auth and scopes are missing', - () async { - const List requestedScopes = ['a', 'b']; - const List grantedScopes = ['a']; - const String accessToken = 'token'; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: grantedScopes, - ))); + test( + 'returns null if re-using existing auth and scopes are missing', + () async { + const List requestedScopes = ['a', 'b']; + const List grantedScopes = ['a']; + const String accessToken = 'token'; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: accessToken, + grantedScopes: grantedScopes, + ), + ), + ); - final ClientAuthorizationTokenData? result = - await googleSignIn.clientAuthorizationTokensForScopes( + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: requestedScopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ))); + request: AuthorizationRequestDetails( + scopes: requestedScopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, + ), + ), + ); - expect(result, null); - }); + expect(result, null); + }, + ); test('returns null when unauthorized', () async { - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); expect( - await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - null); + await googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + null, + ); }); test('thows canceled from SDK', () async { - when(mockApi.addScopes(any, any)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.canceled))); + when(mockApi.addScopes(any, any)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.canceled), + ), + ); expect( - googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: const ['a'], - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: const ['a'], + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test('throws unknown from SDK', () async { - when(mockApi.addScopes(any, any)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.unknown))); + when(mockApi.addScopes(any, any)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.unknown), + ), + ); expect( - googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: const ['a'], - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: const ['a'], + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); test('throws user mismatch from SDK', () async { - when(mockApi.addScopes(any, any)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.userMismatch))); + when(mockApi.addScopes(any, any)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.userMismatch), + ), + ); expect( - googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: const ['a'], - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.userMismatch))); + googleSignIn.clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: const ['a'], + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.userMismatch, + ), + ), + ); }); }); @@ -618,146 +767,169 @@ void main() { // the test. const AuthorizationRequestDetails defaultAuthRequest = AuthorizationRequestDetails( - scopes: ['a'], - userId: null, - email: null, - promptIfUnauthorized: false, - ); + scopes: ['a'], + userId: null, + email: null, + promptIfUnauthorized: false, + ); - test('passes expected values to addScopes if interaction is allowed', - () async { - const List scopes = ['a', 'b']; - when(mockApi.addScopes(any, _testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: scopes, - ))); + test( + 'passes expected values to addScopes if interaction is allowed', + () async { + const List scopes = ['a', 'b']; + when(mockApi.addScopes(any, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: scopes, + ), + ), + ); - await googleSignIn.serverAuthorizationTokensForScopes( + await googleSignIn.serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); - - final VerificationResult verification = - verify(mockApi.addScopes(captureAny, _testUser.id)); - final List passedScopes = - verification.captured[0] as List; - expect(passedScopes, scopes); - }); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); + + final VerificationResult verification = verify( + mockApi.addScopes(captureAny, _testUser.id), + ); + final List passedScopes = + verification.captured[0] as List; + expect(passedScopes, scopes); + }, + ); - test( - 'passes expected values to getRefreshedAuthorizationTokens if ' + test('passes expected values to getRefreshedAuthorizationTokens if ' 'interaction is not allowed', () async { const List scopes = ['a', 'b']; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: scopes, - ))); + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: scopes, + ), + ), + ); await googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ))); + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, + ), + ), + ); verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); }); - test('attempts to restore previous sign in if no user is provided', - () async { - const List scopes = ['a', 'b']; - final SignInResult signInResult = SignInResult( + test( + 'attempts to restore previous sign in if no user is provided', + () async { + const List scopes = ['a', 'b']; + final SignInResult signInResult = SignInResult( success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: [], - )); - when(mockApi.restorePreviousSignIn()) - .thenAnswer((_) async => signInResult); - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => signInResult); - - await googleSignIn.serverAuthorizationTokensForScopes( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: [], + ), + ); + when( + mockApi.restorePreviousSignIn(), + ).thenAnswer((_) async => signInResult); + when( + mockApi.getRefreshedAuthorizationTokens(_testUser.id), + ).thenAnswer((_) async => signInResult); + + await googleSignIn.serverAuthorizationTokensForScopes( const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ))); - - // With no user ID provided to serverAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that succeeds, get the authorization tokens for that user. - verify(mockApi.restorePreviousSignIn()); - verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); - }); - - test('returns null if unauthenticated and interaction is not allowed', - () async { - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); + + // With no user ID provided to serverAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that succeeds, get the authorization tokens for that user. + verify(mockApi.restorePreviousSignIn()); + verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + }, + ); - final ServerAuthorizationTokenData? result = - await googleSignIn.serverAuthorizationTokensForScopes( + test( + 'returns null if unauthenticated and interaction is not allowed', + () async { + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); + + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: ['a', 'b'], - userId: null, - email: null, - promptIfUnauthorized: false, - ))); - - // With no user ID provided to serverAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that fails, return null since without prompting, there is no way - // to authenticate. - verify(mockApi.restorePreviousSignIn()); - expect(result, null); - }); + request: AuthorizationRequestDetails( + scopes: ['a', 'b'], + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); + + // With no user ID provided to serverAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that fails, return null since without prompting, there is no way + // to authenticate. + verify(mockApi.restorePreviousSignIn()); + expect(result, null); + }, + ); - test( - 'attempts to authenticate if no user is provided or already signed in ' + test('attempts to authenticate if no user is provided or already signed in ' 'and interaction is allowed', () async { const List scopes = ['a', 'b']; - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); - when(mockApi.signIn(scopes, null)).thenAnswer((_) async => SignInResult( - success: SignInSuccess( + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); + when(mockApi.signIn(scopes, null)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( user: UserData( displayName: _testUser.displayName, email: _testUser.email, @@ -767,16 +939,20 @@ void main() { ), accessToken: '', grantedScopes: [], - ))); + ), + ), + ); await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: true, - ))); + const ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: true, + ), + ), + ); // With no user ID provided to serverAuthorizationTokensForScopes, the // implementation should attempt to restore an existing sign-in, and when @@ -785,102 +961,118 @@ void main() { verify(mockApi.signIn(scopes, null)); }); - test('passes success data to caller when refreshing existing auth', - () async { - const List scopes = ['a', 'b']; - const String serverAuthCode = 'authCode'; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: 'token', - serverAuthCode: serverAuthCode, - grantedScopes: scopes, - ))); + test( + 'passes success data to caller when refreshing existing auth', + () async { + const List scopes = ['a', 'b']; + const String serverAuthCode = 'authCode'; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: 'token', + serverAuthCode: serverAuthCode, + grantedScopes: scopes, + ), + ), + ); - final ServerAuthorizationTokenData? result = - await googleSignIn.serverAuthorizationTokensForScopes( + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ))); + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, + ), + ), + ); - expect(result?.serverAuthCode, serverAuthCode); - }); + expect(result?.serverAuthCode, serverAuthCode); + }, + ); test('passes success data to caller when calling addScopes', () async { const List scopes = ['a', 'b']; const String serverAuthCode = 'authCode'; - when(mockApi.addScopes(scopes, _testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: 'token', - serverAuthCode: serverAuthCode, - grantedScopes: scopes, - ))); + when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: 'token', + serverAuthCode: serverAuthCode, + grantedScopes: scopes, + ), + ), + ); - final ServerAuthorizationTokenData? result = - await googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); expect(result?.serverAuthCode, serverAuthCode); }); - test( - 'successfully returns refreshed tokens if addScopes indicates the ' + test('successfully returns refreshed tokens if addScopes indicates the ' 'requested scopes are already granted', () async { const List scopes = ['a', 'b']; const String serverAuthCode = 'authCode'; - when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer((_) async => - SignInResult( - error: SignInFailure( - type: GoogleSignInErrorCode.scopesAlreadyGranted))); - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: 'token', - serverAuthCode: serverAuthCode, - grantedScopes: scopes, - ))); + when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure( + type: GoogleSignInErrorCode.scopesAlreadyGranted, + ), + ), + ); + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: 'token', + serverAuthCode: serverAuthCode, + grantedScopes: scopes, + ), + ), + ); - final ServerAuthorizationTokenData? result = - await googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); verify(mockApi.addScopes(scopes, _testUser.id)); verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); @@ -888,106 +1080,143 @@ void main() { expect(result?.serverAuthCode, serverAuthCode); }); - test('returns null if re-using existing auth and scopes are missing', - () async { - const List requestedScopes = ['a', 'b']; - const List grantedScopes = ['a']; - const String accessToken = 'token'; - when(mockApi.addScopes(requestedScopes, _testUser.id)) - .thenAnswer((_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: grantedScopes, - ))); + test( + 'returns null if re-using existing auth and scopes are missing', + () async { + const List requestedScopes = ['a', 'b']; + const List grantedScopes = ['a']; + const String accessToken = 'token'; + when(mockApi.addScopes(requestedScopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ), + accessToken: accessToken, + grantedScopes: grantedScopes, + ), + ), + ); - final ServerAuthorizationTokenData? result = - await googleSignIn.serverAuthorizationTokensForScopes( + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: requestedScopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))); + request: AuthorizationRequestDetails( + scopes: requestedScopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ); - expect(result, null); - }); + expect(result, null); + }, + ); test('returns null when unauthorized', () async { - when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => - SignInResult( - error: - SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain))); + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + ), + ); expect( - await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest)), - null); + await googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: defaultAuthRequest, + ), + ), + null, + ); }); test('thows canceled from SDK', () async { - when(mockApi.addScopes(any, any)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.canceled))); + when(mockApi.addScopes(any, any)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.canceled), + ), + ); expect( - googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: const ['a'], - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.canceled))); + googleSignIn.serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: const ['a'], + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.canceled, + ), + ), + ); }); test('throws unknown from SDK', () async { - when(mockApi.addScopes(any, any)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.unknown))); + when(mockApi.addScopes(any, any)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.unknown), + ), + ); expect( - googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: const ['a'], - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.unknownError))); + googleSignIn.serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: const ['a'], + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.unknownError, + ), + ), + ); }); test('throws user mismatch from SDK', () async { - when(mockApi.addScopes(any, any)).thenAnswer((_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.userMismatch))); + when(mockApi.addScopes(any, any)).thenAnswer( + (_) async => SignInResult( + error: SignInFailure(type: GoogleSignInErrorCode.userMismatch), + ), + ); expect( - googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: const ['a'], - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ))), - throwsA(isInstanceOf().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.userMismatch))); + googleSignIn.serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: const ['a'], + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, + ), + ), + ), + throwsA( + isInstanceOf().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.userMismatch, + ), + ), + ); }); }); @@ -1000,10 +1229,7 @@ void main() { test('disconnect calls through and also signs out', () async { await googleSignIn.disconnect(const DisconnectParams()); - verifyInOrder(>[ - mockApi.disconnect(), - mockApi.signOut(), - ]); + verifyInOrder(>[mockApi.disconnect(), mockApi.signOut()]); }); // Returning null triggers the app-facing package to create stream events, diff --git a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart index 7c4871506d3..5ffcbc9c631 100644 --- a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart @@ -25,7 +25,7 @@ import 'package:mockito/src/dummies.dart' as _i3; class _FakeSignInResult_0 extends _i1.SmartFake implements _i2.SignInResult { _FakeSignInResult_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + : super(parent, parentInvocation); } /// A class which mocks [GoogleSignInApi]. @@ -37,58 +37,65 @@ class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi { } @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override _i4.Future configure(_i2.PlatformConfigurationParams? params) => (super.noSuchMethod( - Invocation.method(#configure, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#configure, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future<_i2.SignInResult> restorePreviousSignIn() => (super.noSuchMethod( - Invocation.method(#restorePreviousSignIn, []), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, + _i4.Future<_i2.SignInResult> restorePreviousSignIn() => + (super.noSuchMethod( Invocation.method(#restorePreviousSignIn, []), - ), - ), - ) as _i4.Future<_i2.SignInResult>); + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0( + this, + Invocation.method(#restorePreviousSignIn, []), + ), + ), + ) + as _i4.Future<_i2.SignInResult>); @override _i4.Future<_i2.SignInResult> signIn(List? scopeHint, String? nonce) => (super.noSuchMethod( - Invocation.method(#signIn, [scopeHint, nonce]), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, Invocation.method(#signIn, [scopeHint, nonce]), - ), - ), - ) as _i4.Future<_i2.SignInResult>); + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0( + this, + Invocation.method(#signIn, [scopeHint, nonce]), + ), + ), + ) + as _i4.Future<_i2.SignInResult>); @override _i4.Future<_i2.SignInResult> getRefreshedAuthorizationTokens( String? userId, ) => (super.noSuchMethod( - Invocation.method(#getRefreshedAuthorizationTokens, [userId]), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, Invocation.method(#getRefreshedAuthorizationTokens, [userId]), - ), - ), - ) as _i4.Future<_i2.SignInResult>); + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0( + this, + Invocation.method(#getRefreshedAuthorizationTokens, [userId]), + ), + ), + ) + as _i4.Future<_i2.SignInResult>); @override _i4.Future<_i2.SignInResult> addScopes( @@ -96,26 +103,31 @@ class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi { String? userId, ) => (super.noSuchMethod( - Invocation.method(#addScopes, [scopes, userId]), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, Invocation.method(#addScopes, [scopes, userId]), - ), - ), - ) as _i4.Future<_i2.SignInResult>); + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0( + this, + Invocation.method(#addScopes, [scopes, userId]), + ), + ), + ) + as _i4.Future<_i2.SignInResult>); @override - _i4.Future signOut() => (super.noSuchMethod( - Invocation.method(#signOut, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future signOut() => + (super.noSuchMethod( + Invocation.method(#signOut, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future disconnect() => (super.noSuchMethod( - Invocation.method(#disconnect, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future disconnect() => + (super.noSuchMethod( + Invocation.method(#disconnect, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } 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 88805f9eee8..b970b7c1095 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.29/Dart 3.7. + ## 3.0.0 * **BREAKING CHANGE**: Overhauls the entire API surface to better abstract the diff --git a/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart b/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart index a68e6666537..bfcc4ab6e74 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart +++ b/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart @@ -57,7 +57,8 @@ abstract class GoogleSignInPlatform extends PlatformInterface { /// This may be silent, or may show minimal UI, depending on the platform and /// the context. Future? attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params); + AttemptLightweightAuthenticationParameters params, + ); /// Returns true if the platform implementation supports the [authenticate] /// method. @@ -86,14 +87,16 @@ abstract class GoogleSignInPlatform extends PlatformInterface { /// This should only return null if prompting would be necessary but [params] /// do not allow it, otherwise any failure should return an error. Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params); + ClientAuthorizationTokensForScopesParameters params, + ); /// Returns the tokens used to authenticate other API calls from a server. /// /// This should only return null if prompting would be necessary but [params] /// do not allow it, otherwise any failure should return an error. Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params); + ServerAuthorizationTokensForScopesParameters params, + ); /// Signs out previously signed in accounts. Future signOut(SignOutParams params); @@ -131,7 +134,8 @@ class _PlaceholderImplementation extends GoogleSignInPlatform { @override Future attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params) { + AttemptLightweightAuthenticationParameters params, + ) { throw UnimplementedError(); } @@ -152,13 +156,15 @@ class _PlaceholderImplementation extends GoogleSignInPlatform { @override Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params) { + ClientAuthorizationTokensForScopesParameters params, + ) { throw UnimplementedError(); } @override Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params) { + ServerAuthorizationTokensForScopesParameters params, + ) { throw UnimplementedError(); } diff --git a/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart b/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart index 047462fe22e..fca3a630692 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart +++ b/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart @@ -9,8 +9,11 @@ import 'package:flutter/foundation.dart' show immutable; @immutable class GoogleSignInException implements Exception { /// Crceates a new exception with the given information. - const GoogleSignInException( - {required this.code, this.description, this.details}); + const GoogleSignInException({ + required this.code, + this.description, + this.details, + }); /// The type of failure. final GoogleSignInExceptionCode code; @@ -199,9 +202,7 @@ class AuthorizationRequestDetails { @immutable class ClientAuthorizationTokensForScopesParameters { /// Creates a new parameter object with the given details. - const ClientAuthorizationTokensForScopesParameters({ - required this.request, - }); + const ClientAuthorizationTokensForScopesParameters({required this.request}); /// Details about the authorization request. final AuthorizationRequestDetails request; @@ -214,9 +215,7 @@ class ClientAuthorizationTokensForScopesParameters { @immutable class ServerAuthorizationTokensForScopesParameters { /// Creates a new parameter object with the given details. - const ServerAuthorizationTokensForScopesParameters({ - required this.request, - }); + const ServerAuthorizationTokensForScopesParameters({required this.request}); /// Details about the authorization request. final AuthorizationRequestDetails request; @@ -282,9 +281,7 @@ class GoogleSignInUserData { @immutable class AuthenticationTokenData { /// Creates authentication data with the given tokens. - const AuthenticationTokenData({ - required this.idToken, - }); + const AuthenticationTokenData({required this.idToken}); /// A token that can be sent to your own server to verify the authentication /// data. @@ -306,9 +303,7 @@ class AuthenticationTokenData { @immutable class ClientAuthorizationTokenData { /// Creates authorization data with the given tokens. - const ClientAuthorizationTokenData({ - required this.accessToken, - }); + const ClientAuthorizationTokenData({required this.accessToken}); /// The OAuth2 access token used to access Google services. final String accessToken; @@ -330,9 +325,7 @@ class ClientAuthorizationTokenData { @immutable class ServerAuthorizationTokenData { /// Creates authorization data with the given tokens. - const ServerAuthorizationTokenData({ - required this.serverAuthCode, - }); + const ServerAuthorizationTokenData({required this.serverAuthCode}); /// Auth code to provide to a backend server to exchange for access or /// refresh tokens. @@ -358,8 +351,10 @@ class ServerAuthorizationTokenData { @immutable class AuthenticationResults { /// Creates a new result object. - const AuthenticationResults( - {required this.user, required this.authenticationTokens}); + const AuthenticationResults({ + required this.user, + required this.authenticationTokens, + }); /// The user that was authenticated. final GoogleSignInUserData user; @@ -399,8 +394,10 @@ sealed class AuthenticationEvent { @immutable class AuthenticationEventSignIn extends AuthenticationEvent { /// Creates an event for a successful sign in. - const AuthenticationEventSignIn( - {required this.user, required this.authenticationTokens}); + const AuthenticationEventSignIn({ + required this.user, + required this.authenticationTokens, + }); /// The user that was authenticated. final GoogleSignInUserData user; 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 b399bb38f69..c530bd08487 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.0.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart b/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart index f536bd2e6bb..81caacd7108 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart +++ b/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart @@ -72,13 +72,9 @@ void main() { group('ClientAuthorizationTokenData', () { test('can be compared by == operator', () { const ClientAuthorizationTokenData firstInstance = - ClientAuthorizationTokenData( - accessToken: 'accessToken', - ); + ClientAuthorizationTokenData(accessToken: 'accessToken'); const ClientAuthorizationTokenData secondInstance = - ClientAuthorizationTokenData( - accessToken: 'accessToken', - ); + ClientAuthorizationTokenData(accessToken: 'accessToken'); expect(firstInstance == secondInstance, isTrue); }); }); @@ -86,13 +82,9 @@ void main() { group('ServerAuthorizationTokenData', () { test('can be compared by == operator', () { const ServerAuthorizationTokenData firstInstance = - ServerAuthorizationTokenData( - serverAuthCode: 'serverAuthCode', - ); + ServerAuthorizationTokenData(serverAuthCode: 'serverAuthCode'); const ServerAuthorizationTokenData secondInstance = - ServerAuthorizationTokenData( - serverAuthCode: 'serverAuthCode', - ); + ServerAuthorizationTokenData(serverAuthCode: 'serverAuthCode'); expect(firstInstance == secondInstance, isTrue); }); }); @@ -108,7 +100,8 @@ class ImplementsGoogleSignInPlatform extends Mock class ExtendsGoogleSignInPlatform extends GoogleSignInPlatform { @override Future? attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params) async { + AttemptLightweightAuthenticationParameters params, + ) async { return null; } @@ -125,7 +118,8 @@ class ExtendsGoogleSignInPlatform extends GoogleSignInPlatform { @override Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params) async { + ClientAuthorizationTokensForScopesParameters params, + ) async { return null; } @@ -137,7 +131,8 @@ class ExtendsGoogleSignInPlatform extends GoogleSignInPlatform { @override Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params) async { + ServerAuthorizationTokensForScopesParameters params, + ) async { return null; } 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 7e9920d0b8a..86b1a053fd7 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.29/Dart 3.7. + ## 1.0.0 * **BREAKING CHANGE**: Switches to implementing version 3.0 of the platform diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart index 839c9abb5f7..2d06e4478ad 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart @@ -22,20 +22,25 @@ void main() { widgetFactoryNumber++; }); - testWidgets('empty case, calls onElementCreated', - (WidgetTester tester) async { + testWidgets('empty case, calls onElementCreated', ( + WidgetTester tester, + ) async { final Completer viewCreatedCompleter = Completer(); - await pumpResizableWidget(tester, onElementCreated: (Object view) { - viewCreatedCompleter.complete(view); - }); + await pumpResizableWidget( + tester, + onElementCreated: (Object view) { + viewCreatedCompleter.complete(view); + }, + ); await tester.pumpAndSettle(); await expectLater(viewCreatedCompleter.future, completes); }); - testWidgets('empty case, renders with initial size', - (WidgetTester tester) async { + testWidgets('empty case, renders with initial size', ( + WidgetTester tester, + ) async { const Size initialSize = Size(160, 100); final Element element = await pumpResizableWidget( @@ -49,8 +54,9 @@ void main() { expect(element.size!.height, initialSize.height); }); - testWidgets('initialSize null, adopts size of injected element', - (WidgetTester tester) async { + testWidgets('initialSize null, adopts size of injected element', ( + WidgetTester tester, + ) async { const Size childSize = Size(300, 40); final web.HTMLDivElement resizable = @@ -68,8 +74,9 @@ void main() { expect(element.size!.height, childSize.height); }); - testWidgets('with initialSize, adopts size of injected element', - (WidgetTester tester) async { + testWidgets('with initialSize, adopts size of injected element', ( + WidgetTester tester, + ) async { const Size initialSize = Size(160, 100); const Size newSize = Size(300, 40); @@ -89,16 +96,18 @@ void main() { expect(element.size!.height, newSize.height); }); - testWidgets('with injected element that resizes, follows resizes', - (WidgetTester tester) async { + testWidgets('with injected element that resizes, follows resizes', ( + WidgetTester tester, + ) async { const Size initialSize = Size(160, 100); final Size expandedSize = initialSize * 2; final Size contractedSize = initialSize / 2; - final web.HTMLDivElement resizable = web.document.createElement('div') - as web.HTMLDivElement - ..setAttribute( - 'style', 'width: 100%; height: 100%; background: #fabada;'); + final web.HTMLDivElement resizable = + web.document.createElement('div') as web.HTMLDivElement..setAttribute( + 'style', + 'width: 100%; height: 100%; background: #fabada;', + ); final Element element = await pumpResizableWidget( tester, @@ -137,11 +146,13 @@ Future pumpResizableWidget( void Function(Object)? onElementCreated, Size? initialSize, }) async { - await tester.pumpWidget(ResizableFromJs( - instanceId: widgetFactoryNumber, - onElementCreated: onElementCreated, - initialSize: initialSize, - )); + await tester.pumpWidget( + ResizableFromJs( + instanceId: widgetFactoryNumber, + onElementCreated: onElementCreated, + initialSize: initialSize, + ), + ); // Needed for JS to have time to kick-off. await tester.pump(); @@ -164,8 +175,10 @@ class ResizableFromJs extends StatelessWidget { (int viewId) { final web.HTMLDivElement element = web.document.createElement('div') as web.HTMLDivElement; - element.setAttribute('style', - 'width: 100%; height: 100%; overflow: hidden; background: red;'); + element.setAttribute( + 'style', + 'width: 100%; height: 100%; overflow: hidden; background: red;', + ); element.id = 'test_element_$viewId'; return element; }, @@ -195,8 +208,10 @@ class ResizableFromJs extends StatelessWidget { /// Resizes `resizable` to `size`. void resize(web.HTMLElement resizable, Size size) { - resizable.setAttribute('style', - 'width: ${size.width}px; height: ${size.height}px; background: #fabada'); + resizable.setAttribute( + 'style', + 'width: ${size.width}px; height: ${size.height}px; background: #fabada', + ); } /// Returns an `onElementCreated` callback that injects [element]. 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 911c73b3ebf..57fdaa78986 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 @@ -16,9 +16,12 @@ import 'package:web/web.dart' as web; import 'google_sign_in_web_test.mocks.dart'; // Mock GisSdkClient so we can simulate any response from the JS side. -@GenerateMocks([], customMocks: >[ - MockSpec(onMissingStub: OnMissingStub.returnDefault), -]) +@GenerateMocks( + [], + customMocks: >[ + MockSpec(onMissingStub: OnMissingStub.returnDefault), + ], +) void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -65,9 +68,7 @@ void main() { testWidgets('initializes if all is OK', (_) async { await plugin.init( - const InitParameters( - clientId: 'some-non-null-client-id', - ), + const InitParameters(clientId: 'some-non-null-client-id'), ); expect(plugin.initialized, completes); @@ -75,9 +76,7 @@ void main() { testWidgets('asserts clientId is not null', (_) async { expect(() async { - await plugin.init( - const InitParameters(), - ); + await plugin.init(const InitParameters()); }, throwsAssertionError); }); @@ -95,17 +94,21 @@ void main() { testWidgets('must be called for most of the API to work', (_) async { expect(() async { await plugin.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + const AttemptLightweightAuthenticationParameters(), + ); }, throwsStateError); expect(() async { await plugin.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: [], - userId: null, - email: null, - promptIfUnauthorized: false))); + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: [], + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); }, throwsStateError); expect(() async { @@ -127,8 +130,9 @@ void main() { expect(plugin.supportsAuthenticate(), false); }); - testWidgets('reports requirement for user interaction to authorize', - (_) async { + testWidgets('reports requirement for user interaction to authorize', ( + _, + ) async { final GoogleSignInPlugin plugin = GoogleSignInPlugin( debugOverrideLoader: true, ); @@ -162,9 +166,10 @@ void main() { .when(mockGis.requestOneTap()) .thenAnswer((_) => Future.value()); - final Future? future = - plugin.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters()); + final Future? future = plugin + .attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(future, null); @@ -187,30 +192,38 @@ void main() { testWidgets('calls requestScopes on GIS client', (_) async { mockito .when( - mockGis.requestScopes(mockito.any, - promptIfUnauthorized: - mockito.anyNamed('promptIfUnauthorized'), - userHint: mockito.anyNamed('userHint')), + mockGis.requestScopes( + mockito.any, + promptIfUnauthorized: mockito.anyNamed('promptIfUnauthorized'), + userHint: mockito.anyNamed('userHint'), + ), ) .thenAnswer((_) => Future.value(someAccessToken)); - final ClientAuthorizationTokenData? token = - await plugin.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false))); - - final List arguments = mockito - .verify( - mockGis.requestScopes(mockito.captureAny, - promptIfUnauthorized: - mockito.captureAnyNamed('promptIfUnauthorized'), - userHint: mockito.captureAnyNamed('userHint')), - ) - .captured; + final ClientAuthorizationTokenData? token = await plugin + .clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); + + final List arguments = + mockito + .verify( + mockGis.requestScopes( + mockito.captureAny, + promptIfUnauthorized: mockito.captureAnyNamed( + 'promptIfUnauthorized', + ), + userHint: mockito.captureAnyNamed('userHint'), + ), + ) + .captured; expect(token?.accessToken, someAccessToken); @@ -223,30 +236,38 @@ void main() { const String someUserId = 'someUser'; mockito .when( - mockGis.requestScopes(mockito.any, - promptIfUnauthorized: - mockito.anyNamed('promptIfUnauthorized'), - userHint: mockito.anyNamed('userHint')), + mockGis.requestScopes( + mockito.any, + promptIfUnauthorized: mockito.anyNamed('promptIfUnauthorized'), + userHint: mockito.anyNamed('userHint'), + ), ) .thenAnswer((_) => Future.value(someAccessToken)); - final ClientAuthorizationTokenData? token = - await plugin.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: someUserId, - email: 'someone@example.com', - promptIfUnauthorized: true))); - - final List arguments = mockito - .verify( - mockGis.requestScopes(mockito.captureAny, - promptIfUnauthorized: - mockito.captureAnyNamed('promptIfUnauthorized'), - userHint: mockito.captureAnyNamed('userHint')), - ) - .captured; + final ClientAuthorizationTokenData? token = await plugin + .clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: someUserId, + email: 'someone@example.com', + promptIfUnauthorized: true, + ), + ), + ); + + final List arguments = + mockito + .verify( + mockGis.requestScopes( + mockito.captureAny, + promptIfUnauthorized: mockito.captureAnyNamed( + 'promptIfUnauthorized', + ), + userHint: mockito.captureAnyNamed('userHint'), + ), + ) + .captured; expect(token?.accessToken, someAccessToken); @@ -257,14 +278,18 @@ void main() { testWidgets('asserts no scopes have any spaces', (_) async { expect( - plugin.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: ['bad scope', ...scopes], - userId: 'user', - email: 'someone@example.com', - promptIfUnauthorized: true))), - throwsAssertionError); + plugin.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: ['bad scope', ...scopes], + userId: 'user', + email: 'someone@example.com', + promptIfUnauthorized: true, + ), + ), + ), + throwsAssertionError, + ); }); }); @@ -278,24 +303,26 @@ void main() { testWidgets('calls requestServerAuthCode on GIS client', (_) async { mockito - .when( - mockGis.requestServerAuthCode(mockito.any), - ) + .when(mockGis.requestServerAuthCode(mockito.any)) .thenAnswer((_) => Future.value(someAuthCode)); const AuthorizationRequestDetails request = AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: true); - final ServerAuthorizationTokenData? token = - await plugin.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: request)); - - final List arguments = mockito - .verify(mockGis.requestServerAuthCode(mockito.captureAny)) - .captured; + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: true, + ); + final ServerAuthorizationTokenData? token = await plugin + .serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: request, + ), + ); + + final List arguments = + mockito + .verify(mockGis.requestServerAuthCode(mockito.captureAny)) + .captured; expect(token?.serverAuthCode, someAuthCode); @@ -305,19 +332,25 @@ void main() { expect(passedRequest.userId, request.userId); expect(passedRequest.email, request.email); expect( - passedRequest.promptIfUnauthorized, request.promptIfUnauthorized); + passedRequest.promptIfUnauthorized, + request.promptIfUnauthorized, + ); }); testWidgets('asserts no scopes have any spaces', (_) async { expect( - plugin.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: ['bad scope', ...scopes], - userId: 'user', - email: 'someone@example.com', - promptIfUnauthorized: true))), - throwsAssertionError); + plugin.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: ['bad scope', ...scopes], + userId: 'user', + email: 'someone@example.com', + promptIfUnauthorized: true, + ), + ), + ), + throwsAssertionError, + ); }); }); }); @@ -339,20 +372,26 @@ void main() { plugin.authenticationEvents.first; const AuthenticationEvent expected = AuthenticationEventSignIn( - user: - GoogleSignInUserData(email: 'someone@example.com', id: 'user_id'), - authenticationTokens: AuthenticationTokenData(idToken: 'someToken')); + user: GoogleSignInUserData(email: 'someone@example.com', id: 'user_id'), + authenticationTokens: AuthenticationTokenData(idToken: 'someToken'), + ); controller.add(expected); - expect(await event, expected, - reason: 'Sign-in events should be propagated'); + expect( + await event, + expected, + reason: 'Sign-in events should be propagated', + ); final Future nextEvent = plugin.authenticationEvents.first; controller.add(AuthenticationEventSignOut()); - expect(await nextEvent, isA(), - reason: 'Sign-out events can also be propagated'); + expect( + await nextEvent, + isA(), + reason: 'Sign-out events can also be propagated', + ); }); }); } diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart index fd6866e78bb..cf152b6e0c8 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart @@ -31,9 +31,9 @@ import 'package:mockito/mockito.dart' as _i1; class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { @override void requestOneTap() => super.noSuchMethod( - Invocation.method(#requestOneTap, []), - returnValueForMissingStub: null, - ); + Invocation.method(#requestOneTap, []), + returnValueForMissingStub: null, + ); @override _i3.Future renderButton( @@ -41,34 +41,40 @@ class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { _i4.GSIButtonConfiguration? options, ) => (super.noSuchMethod( - Invocation.method(#renderButton, [parent, options]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#renderButton, [parent, options]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future requestServerAuthCode( _i5.AuthorizationRequestDetails? request, ) => (super.noSuchMethod( - Invocation.method(#requestServerAuthCode, [request]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#requestServerAuthCode, [request]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future signOut() => (super.noSuchMethod( - Invocation.method(#signOut, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future signOut() => + (super.noSuchMethod( + Invocation.method(#signOut, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future disconnect() => (super.noSuchMethod( - Invocation.method(#disconnect, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future disconnect() => + (super.noSuchMethod( + Invocation.method(#disconnect, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future requestScopes( @@ -77,15 +83,16 @@ class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { String? userHint, }) => (super.noSuchMethod( - Invocation.method( - #requestScopes, - [scopes], - { - #promptIfUnauthorized: promptIfUnauthorized, - #userHint: userHint, - }, - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method( + #requestScopes, + [scopes], + { + #promptIfUnauthorized: promptIfUnauthorized, + #userHint: userHint, + }, + ), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart index 07515ec1a92..5a8896836ea 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart @@ -7,27 +7,23 @@ import 'package:google_identity_services_web/id.dart'; import 'jsify_as.dart'; /// A CredentialResponse with null `credential`. -final CredentialResponse nullCredential = - jsifyAs({ - 'credential': null, -}); +final CredentialResponse nullCredential = jsifyAs( + {'credential': null}, +); /// A CredentialResponse wrapping a known good JWT Token as its `credential`. -final CredentialResponse goodCredential = - jsifyAs({ - 'credential': goodJwtToken, -}); +final CredentialResponse goodCredential = jsifyAs( + {'credential': goodJwtToken}, +); /// A CredentialResponse wrapping a known good JWT Token as its `credential`. -final CredentialResponse minimalCredential = - jsifyAs({ - 'credential': minimalJwtToken, -}); +final CredentialResponse minimalCredential = jsifyAs( + {'credential': minimalJwtToken}, +); -final CredentialResponse expiredCredential = - jsifyAs({ - 'credential': expiredJwtToken, -}); +final CredentialResponse expiredCredential = jsifyAs( + {'credential': expiredJwtToken}, +); /// A JWT token with predefined values. /// diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart index 0914f762cd6..4bd65227e1c 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart @@ -52,18 +52,20 @@ void main() { }); testWidgets('invalid payload -> null', (_) async { - final CredentialResponse response = - jsifyAs({ - 'credential': 'some-bogus.thing-that-is-not.valid-jwt', - }); + final CredentialResponse response = jsifyAs( + { + 'credential': 'some-bogus.thing-that-is-not.valid-jwt', + }, + ); expect(gisResponsesToAuthenticationEvent(response), isNull); }); }); group('getCredentialResponseExpirationTimestamp', () { testWidgets('Good payload -> data', (_) async { - final DateTime? expiration = - getCredentialResponseExpirationTimestamp(expiredCredential); + final DateTime? expiration = getCredentialResponseExpirationTimestamp( + expiredCredential, + ); expect(expiration, isNotNull); expect(expiration!.millisecondsSinceEpoch, 1430330400 * 1000); @@ -71,14 +73,17 @@ void main() { testWidgets('No expiration -> null', (_) async { expect( - getCredentialResponseExpirationTimestamp(minimalCredential), isNull); + getCredentialResponseExpirationTimestamp(minimalCredential), + isNull, + ); }); testWidgets('Bad data -> null', (_) async { - final CredentialResponse bogus = - jsifyAs({ - 'credential': 'some-bogus.thing-that-is-not.valid-jwt', - }); + final CredentialResponse bogus = jsifyAs( + { + 'credential': 'some-bogus.thing-that-is-not.valid-jwt', + }, + ); expect(getCredentialResponseExpirationTimestamp(bogus), isNull); }); @@ -93,11 +98,12 @@ void main() { expect(data, containsPair('email', 'adultman@example.com')); expect(data, containsPair('sub', '123456')); expect( - data, - containsPair( - 'picture', - 'https://thispersondoesnotexist.com/image?x=.jpg', - )); + data, + containsPair( + 'picture', + 'https://thispersondoesnotexist.com/image?x=.jpg', + ), + ); }); testWidgets('happy case (minimal) -> data', (_) async { @@ -136,11 +142,12 @@ void main() { expect(data, containsPair('email', 'adultman@example.com')); expect(data, containsPair('sub', '123456')); expect( - data, - containsPair( - 'picture', - 'https://thispersondoesnotexist.com/image?x=.jpg', - )); + data, + containsPair( + 'picture', + 'https://thispersondoesnotexist.com/image?x=.jpg', + ), + ); }); testWidgets('Proper JSON payload -> data', (_) async { diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart index f2afcec8f2d..d2bf3448796 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart @@ -16,9 +16,12 @@ import 'package:mockito/mockito.dart'; import 'web_only_test.mocks.dart'; // Mock GisSdkClient so we can simulate any response from the JS side. -@GenerateMocks([], customMocks: >[ - MockSpec(onMissingStub: OnMissingStub.returnDefault), -]) +@GenerateMocks( + [], + customMocks: >[ + MockSpec(onMissingStub: OnMissingStub.returnDefault), + ], +) void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -44,15 +47,14 @@ void main() { debugOverrideGisSdkClient: mockGis, ); await GoogleSignInPlatform.instance.init( - const InitParameters( - clientId: 'does-not-matter', - ), + const InitParameters(clientId: 'does-not-matter'), ); }); testWidgets('renderButton returns successfully', (WidgetTester _) async { - when(mockGis.renderButton(any, any)) - .thenAnswer((_) => Future.value()); + when( + mockGis.renderButton(any, any), + ).thenAnswer((_) => Future.value()); final Widget button = web.renderButton(); @@ -66,7 +68,8 @@ void main() { class NonWebImplementation extends GoogleSignInPlatform { @override Future? attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params) { + AttemptLightweightAuthenticationParameters params, + ) { throw UnimplementedError(); } @@ -77,7 +80,8 @@ class NonWebImplementation extends GoogleSignInPlatform { @override Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params) { + ClientAuthorizationTokensForScopesParameters params, + ) { throw UnimplementedError(); } @@ -93,7 +97,8 @@ class NonWebImplementation extends GoogleSignInPlatform { @override Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params) { + ServerAuthorizationTokensForScopesParameters params, + ) { throw UnimplementedError(); } diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart index b2b181c0cd8..057cc55d480 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart @@ -31,9 +31,9 @@ import 'package:mockito/mockito.dart' as _i1; class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { @override void requestOneTap() => super.noSuchMethod( - Invocation.method(#requestOneTap, []), - returnValueForMissingStub: null, - ); + Invocation.method(#requestOneTap, []), + returnValueForMissingStub: null, + ); @override _i3.Future renderButton( @@ -41,34 +41,40 @@ class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { _i4.GSIButtonConfiguration? options, ) => (super.noSuchMethod( - Invocation.method(#renderButton, [parent, options]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#renderButton, [parent, options]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future requestServerAuthCode( _i5.AuthorizationRequestDetails? request, ) => (super.noSuchMethod( - Invocation.method(#requestServerAuthCode, [request]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#requestServerAuthCode, [request]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future signOut() => (super.noSuchMethod( - Invocation.method(#signOut, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future signOut() => + (super.noSuchMethod( + Invocation.method(#signOut, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future disconnect() => (super.noSuchMethod( - Invocation.method(#disconnect, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future disconnect() => + (super.noSuchMethod( + Invocation.method(#disconnect, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future requestScopes( @@ -77,15 +83,16 @@ class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { String? userHint, }) => (super.noSuchMethod( - Invocation.method( - #requestScopes, - [scopes], - { - #promptIfUnauthorized: promptIfUnauthorized, - #userHint: userHint, - }, - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method( + #requestScopes, + [scopes], + { + #promptIfUnauthorized: promptIfUnauthorized, + #userHint: userHint, + }, + ), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } diff --git a/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart b/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart index 862afe64e91..17625e15bb5 100644 --- a/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart +++ b/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart @@ -14,9 +14,9 @@ import 'src/button_configuration_column.dart'; final GoogleSignInPlatform _platform = GoogleSignInPlatform.instance; Future main() async { - await _platform.init(const InitParameters( - clientId: 'your-client_id.apps.googleusercontent.com', - )); + await _platform.init( + const InitParameters(clientId: 'your-client_id.apps.googleusercontent.com'), + ); runApp( const MaterialApp( title: 'Sign in with Google button Tester', @@ -79,7 +79,7 @@ class _ButtonConfiguratorState extends State { onPressed: _handleSignOut, child: const Text('SIGN OUT'), ), - ] + ], ], ), ), @@ -94,12 +94,11 @@ class _ButtonConfiguratorState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Sign in with Google button Tester'), - ), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - )); + appBar: AppBar(title: const Text('Sign in with Google button Tester')), + body: ConstrainedBox( + constraints: const BoxConstraints.expand(), + child: _buildBody(), + ), + ); } } 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 19009caa436..3559e5e1ad1 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 @@ -9,8 +9,11 @@ import 'package:google_sign_in_web/web_only.dart'; typedef OnWebConfigChangeFn = void Function(GSIButtonConfiguration newConfig); /// The type of the widget builder function for each Card in the ListView builder -typedef CardBuilder = Widget Function( - GSIButtonConfiguration? currentConfig, OnWebConfigChangeFn? onChange); +typedef CardBuilder = + Widget Function( + GSIButtonConfiguration? currentConfig, + OnWebConfigChangeFn? onChange, + ); // (Incomplete) List of the locales that can be used to configure the button. const List _availableLocales = [ @@ -96,8 +99,9 @@ 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), ), ), ); @@ -115,12 +119,15 @@ 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, @@ -150,7 +157,7 @@ Widget _renderMinimumWidthCard({ secondaryTrackValue: actualMax, onChanged: onChanged, divisions: 10, - ) + ), ], ); } @@ -163,17 +170,21 @@ Widget _renderRadioListTileCard({ void Function(T?)? onChanged, }) { return _renderConfigCard( - title: title, - children: values - .map((T value) => RadioListTile( + title: title, + children: + values + .map( + (T value) => RadioListTile( value: value, groupValue: selected, onChanged: onChanged, selected: value == selected, title: Text(value.name), dense: true, - )) - .toList()); + ), + ) + .toList(), + ); } /// Renders a Card where we render some `children` that change config. 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 a471462ed06..f01050554b5 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: cupertino_icons: ^1.0.2 diff --git a/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart b/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart index 1285e60be97..3142536fb5e 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart @@ -49,9 +49,10 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { @visibleForTesting GisSdkClient? debugOverrideGisSdkClient, @visibleForTesting StreamController? debugAuthenticationController, - }) : _gisSdkClient = debugOverrideGisSdkClient, - _authenticationController = debugAuthenticationController ?? - StreamController.broadcast() { + }) : _gisSdkClient = debugOverrideGisSdkClient, + _authenticationController = + debugAuthenticationController ?? + StreamController.broadcast() { autoDetectedClientId = web.document .querySelector(clientIdMetaSelector) ?.getAttribute(clientIdAttributeName); @@ -107,8 +108,10 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { @visibleForTesting Future get initialized { _assertIsInitCalled(); - return Future.wait( - >[_jsSdkLoadedFuture, _initCalled!.future]); + return Future.wait(>[ + _jsSdkLoadedFuture, + _initCalled!.future, + ]); } /// Stores the client ID if it was set in a meta-tag of the page. @@ -124,13 +127,16 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { Future init(InitParameters params) async { final String? appClientId = params.clientId ?? autoDetectedClientId; assert( - appClientId != null, - 'ClientID not set. Either set it on a ' - ' tag,' - ' or pass clientId when initializing GoogleSignIn'); + appClientId != null, + 'ClientID not set. Either set it on a ' + ' tag,' + ' or pass clientId when initializing GoogleSignIn', + ); - assert(params.serverClientId == null, - 'serverClientId is not supported on Web.'); + assert( + params.serverClientId == null, + 'serverClientId is not supported on Web.', + ); _initCalled = Completer(); @@ -149,7 +155,8 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { @override Future? attemptLightweightAuthentication( - AttemptLightweightAuthenticationParameters params) { + AttemptLightweightAuthenticationParameters params, + ) { initialized.then((void value) { _gisClient.requestOneTap(); }); @@ -166,9 +173,12 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { @override Future authenticate( - AuthenticateParameters params) async { - throw UnimplementedError('authenticate is not supported on the web. ' - 'Instead, use renderButton to create a sign-in widget.'); + AuthenticateParameters params, + ) async { + throw UnimplementedError( + 'authenticate is not supported on the web. ' + 'Instead, use renderButton to create a sign-in widget.', + ); } @override @@ -187,13 +197,16 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { @override Future clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters params) async { + ClientAuthorizationTokensForScopesParameters params, + ) async { await initialized; _validateScopes(params.request.scopes); - final String? token = await _gisClient.requestScopes(params.request.scopes, - promptIfUnauthorized: params.request.promptIfUnauthorized, - userHint: params.request.userId); + final String? token = await _gisClient.requestScopes( + params.request.scopes, + promptIfUnauthorized: params.request.promptIfUnauthorized, + userHint: params.request.userId, + ); return token == null ? null : ClientAuthorizationTokenData(accessToken: token); @@ -201,7 +214,8 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { @override Future serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters params) async { + ServerAuthorizationTokensForScopesParameters params, + ) async { await initialized; _validateScopes(params.request.scopes); @@ -222,10 +236,11 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { // scopes must not contain any spaces. // https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#redirecting assert( - !scopes.any((String scope) => scope.contains(' ')), - "OAuth 2.0 Scopes for Google APIs can't contain spaces. " - 'Check https://developers.google.com/identity/protocols/googlescopes ' - 'for a list of valid OAuth 2.0 scopes.'); + !scopes.any((String scope) => scope.contains(' ')), + "OAuth 2.0 Scopes for Google APIs can't contain spaces. " + 'Check https://developers.google.com/identity/protocols/googlescopes ' + 'for a list of valid OAuth 2.0 scopes.', + ); } @override @@ -236,16 +251,17 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { // Register a factory for the Button HtmlElementView. void _registerButtonFactory() { - ui_web.platformViewRegistry.registerViewFactory( - 'gsi_login_button', - (int viewId) { - final web.Element element = web.document.createElement('div'); - element.setAttribute('style', - 'width: 100%; height: 100%; overflow: hidden; display: flex; flex-wrap: wrap; align-content: center; justify-content: center;'); - element.id = 'sign_in_button_$viewId'; - return element; - }, - ); + ui_web.platformViewRegistry.registerViewFactory('gsi_login_button', ( + int viewId, + ) { + final web.Element element = web.document.createElement('div'); + element.setAttribute( + 'style', + 'width: 100%; height: 100%; overflow: hidden; display: flex; flex-wrap: wrap; align-content: center; justify-content: center;', + ); + element.id = 'sign_in_button_$viewId'; + return element; + }); } /// Render the GSI button web experience. @@ -258,10 +274,11 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return FlexHtmlElementView( - viewType: 'gsi_login_button', - onElementCreated: (Object element) { - _gisClient.renderButton(element, config); - }); + viewType: 'gsi_login_button', + onElementCreated: (Object element) { + _gisClient.renderButton(element, config); + }, + ); } return const Text('Getting ready'); }, diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart b/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart index 7869348dfe9..f227f59c445 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart @@ -90,14 +90,14 @@ enum GSIButtonType { standard, /// An icon button without text. - icon; + icon, } const Map _idType = { - GSIButtonType.icon: id.ButtonType.icon, - GSIButtonType.standard: id.ButtonType.standard, -}; + GSIButtonType.icon: id.ButtonType.icon, + GSIButtonType.standard: id.ButtonType.standard, + }; /// The theme of the button to be rendered. /// @@ -111,15 +111,15 @@ enum GSIButtonTheme { filledBlue, /// A black-filled button theme. - filledBlack; + filledBlack, } const Map _idTheme = { - GSIButtonTheme.outline: id.ButtonTheme.outline, - GSIButtonTheme.filledBlue: id.ButtonTheme.filled_blue, - GSIButtonTheme.filledBlack: id.ButtonTheme.filled_black, -}; + GSIButtonTheme.outline: id.ButtonTheme.outline, + GSIButtonTheme.filledBlue: id.ButtonTheme.filled_blue, + GSIButtonTheme.filledBlack: id.ButtonTheme.filled_black, + }; /// The size of the button to be rendered. /// @@ -133,15 +133,15 @@ enum GSIButtonSize { medium, /// A small button (about 20px tall). - small; + small, } const Map _idSize = { - GSIButtonSize.large: id.ButtonSize.large, - GSIButtonSize.medium: id.ButtonSize.medium, - GSIButtonSize.small: id.ButtonSize.small, -}; + GSIButtonSize.large: id.ButtonSize.large, + GSIButtonSize.medium: id.ButtonSize.medium, + GSIButtonSize.small: id.ButtonSize.small, + }; /// The button text. /// @@ -158,16 +158,16 @@ enum GSIButtonText { continueWith, /// The button text is "Sign in". - signin; + signin, } const Map _idText = { - GSIButtonText.signinWith: id.ButtonText.signin_with, - GSIButtonText.signupWith: id.ButtonText.signup_with, - GSIButtonText.continueWith: id.ButtonText.continue_with, - GSIButtonText.signin: id.ButtonText.signin, -}; + GSIButtonText.signinWith: id.ButtonText.signin_with, + GSIButtonText.signupWith: id.ButtonText.signup_with, + GSIButtonText.continueWith: id.ButtonText.continue_with, + GSIButtonText.signin: id.ButtonText.signin, + }; /// The button shape. /// @@ -178,15 +178,15 @@ enum GSIButtonShape { rectangular, /// The circle-shaped button. - pill; + pill, // Does this need circle and square? } const Map _idShape = { - GSIButtonShape.rectangular: id.ButtonShape.rectangular, - GSIButtonShape.pill: id.ButtonShape.pill, -}; + GSIButtonShape.rectangular: id.ButtonShape.rectangular, + GSIButtonShape.pill: id.ButtonShape.pill, + }; /// The alignment of the Google logo. The default value is left. This attribute only applies to the standard button type. /// @@ -197,11 +197,11 @@ enum GSIButtonLogoAlignment { left, /// Center-aligns the Google logo. - center; + center, } const Map _idLogoAlignment = { - GSIButtonLogoAlignment.left: id.ButtonLogoAlignment.left, - GSIButtonLogoAlignment.center: id.ButtonLogoAlignment.center, -}; + GSIButtonLogoAlignment.left: id.ButtonLogoAlignment.left, + GSIButtonLogoAlignment.center: id.ButtonLogoAlignment.center, + }; diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart b/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart index 5d05c5115f7..804584b06f9 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart @@ -61,7 +61,7 @@ class _FlexHtmlElementView extends State { 'Resizing: ', widget.viewType, size.width, - size.height + size.height, ].join(' '); web.console.debug(log.toJS); } @@ -110,12 +110,7 @@ class _FlexHtmlElementView extends State { void _registerListeners(web.Element root) { _mutationObserver = web.MutationObserver(_onMutationRecords.toJS); // Monitor the size of the child element, whenever it's created... - _mutationObserver!.observe( - root, - web.MutationObserverInit( - childList: true, - ), - ); + _mutationObserver!.observe(root, web.MutationObserverInit(childList: true)); } @override @@ -123,16 +118,17 @@ class _FlexHtmlElementView extends State { return SizedBox.fromSize( size: _lastReportedSize ?? widget.initialSize ?? const Size(1, 1), child: HtmlElementView( - viewType: widget.viewType, - onPlatformViewCreated: (int viewId) { - final ElementCreatedCallback? callback = widget.onElementCreated; - final web.Element root = - ui_web.platformViewRegistry.getViewById(viewId) as web.Element; - _registerListeners(root); - if (callback != null) { - callback(root); - } - }), + viewType: widget.viewType, + onPlatformViewCreated: (int viewId) { + final ElementCreatedCallback? callback = widget.onElementCreated; + final web.Element root = + ui_web.platformViewRegistry.getViewById(viewId) as web.Element; + _registerListeners(root); + if (callback != null) { + callback(root); + } + }, + ), ); } } diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart b/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart index 90bfc7c141e..159c35e81fc 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart @@ -25,10 +25,10 @@ class GisSdkClient { bool loggingEnabled = false, String? nonce, String? hostedDomain, - }) : _clientId = clientId, - _hostedDomain = hostedDomain, - _loggingEnabled = loggingEnabled, - _authenticationController = authenticationController { + }) : _clientId = clientId, + _hostedDomain = hostedDomain, + _loggingEnabled = loggingEnabled, + _authenticationController = authenticationController { if (_loggingEnabled) { id.setLogLevel('debug'); } @@ -47,8 +47,11 @@ class GisSdkClient { void _logIfEnabled(String message, [List? more]) { if (_loggingEnabled) { - final String log = - ['[google_sign_in_web]', message, ...?more].join(' '); + final String log = [ + '[google_sign_in_web]', + message, + ...?more, + ].join(' '); web.console.info(log.toJS); } } @@ -73,10 +76,14 @@ class GisSdkClient { if (error is GoogleSignInException) { _authenticationController.add(AuthenticationEventException(error)); } else { - _authenticationController.add(AuthenticationEventException( + _authenticationController.add( + AuthenticationEventException( GoogleSignInException( - code: GoogleSignInExceptionCode.unknownError, - description: error.toString()))); + code: GoogleSignInExceptionCode.unknownError, + description: error.toString(), + ), + ), + ); } } @@ -136,7 +143,7 @@ class GisSdkClient { return oauth2.initTokenClient(tokenConfig); } -// Creates a `oauth2.CodeClient` used for authorization (scope) requests. + // Creates a `oauth2.CodeClient` used for authorization (scope) requests. CodeClient _initializeCodeClient({ String? userHint, required List scopes, @@ -169,9 +176,7 @@ class GisSdkClient { // Handles "prompt moments" of the OneClick card UI. // // See: https://developers.google.com/identity/gsi/web/guides/receive-notifications-prompt-ui-status - Future _onPromptMoment( - PromptMomentNotification moment, - ) async { + Future _onPromptMoment(PromptMomentNotification moment) async { if (moment.isDismissedMoment()) { final MomentDismissedReason? reason = moment.getDismissedReason(); switch (reason) { @@ -179,16 +184,22 @@ class GisSdkClient { // Nothing to do here, as the success handler will run. break; case MomentDismissedReason.cancel_called: - _credentialResponses.addError(const GoogleSignInException( - code: GoogleSignInExceptionCode.canceled)); + _credentialResponses.addError( + const GoogleSignInException( + code: GoogleSignInExceptionCode.canceled, + ), + ); case MomentDismissedReason.flow_restarted: // Ignore, as this is not a final state. break; case MomentDismissedReason.unknown_reason: case null: - _credentialResponses.addError(GoogleSignInException( + _credentialResponses.addError( + GoogleSignInException( code: GoogleSignInExceptionCode.unknownError, - description: 'dismissed: $reason')); + description: 'dismissed: $reason', + ), + ); } return; } @@ -196,8 +207,9 @@ class GisSdkClient { if (moment.isSkippedMoment()) { // getSkippedReason is not used in the exception details here, per // https://developers.google.com/identity/gsi/web/guides/fedcm-migration - _credentialResponses.addError(const GoogleSignInException( - code: GoogleSignInExceptionCode.canceled)); + _credentialResponses.addError( + const GoogleSignInException(code: GoogleSignInExceptionCode.canceled), + ); } // isNotDisplayed is intentionally ignored, per @@ -215,7 +227,8 @@ class GisSdkClient { /// Requests a server auth code per: /// https://developers.google.com/identity/oauth2/web/guides/use-code-model#initialize_a_code_client Future requestServerAuthCode( - AuthorizationRequestDetails request) async { + AuthorizationRequestDetails request, + ) async { final Completer<(String? code, Exception? e)> completer = Completer<(String? code, Exception? e)>(); final CodeClient codeClient = _initializeCodeClient( @@ -228,9 +241,10 @@ class GisSdkClient { completer.complete(( null, GoogleSignInException( - code: GoogleSignInExceptionCode.unknownError, - description: response.error_description, - details: 'code: $error') + code: GoogleSignInExceptionCode.unknownError, + description: response.error_description, + details: 'code: $error', + ), )); } }, @@ -269,8 +283,11 @@ class GisSdkClient { /// authorization token if successful. /// /// Keeps the previously granted scopes. - Future requestScopes(List scopes, - {required bool promptIfUnauthorized, String? userHint}) async { + Future requestScopes( + List scopes, { + required bool promptIfUnauthorized, + String? userHint, + }) async { // If there's a usable cached token, return that. final (TokenResponse? cachedResponse, DateTime? cacheExpiration) = _lastClientAuthorizationByUser[userHint] ?? (null, null); @@ -300,8 +317,9 @@ class GisSdkClient { if (token == null) { _lastClientAuthorizationByUser.remove(userHint); } else { - final DateTime expiration = - DateTime.now().add(Duration(seconds: response.expires_in!)); + final DateTime expiration = DateTime.now().add( + Duration(seconds: response.expires_in!), + ); _lastClientAuthorizationByUser[userHint] = (response, expiration); } completer.complete((response.access_token, null)); @@ -310,9 +328,10 @@ class GisSdkClient { completer.complete(( null, GoogleSignInException( - code: GoogleSignInExceptionCode.unknownError, - description: response.error_description, - details: 'code: $error') + code: GoogleSignInExceptionCode.unknownError, + description: response.error_description, + details: 'code: $error', + ), )); } }, @@ -331,7 +350,8 @@ class GisSdkClient { } GoogleSignInException _exceptionForGisError( - GoogleIdentityServicesError? error) { + GoogleIdentityServicesError? error, + ) { final GoogleSignInExceptionCode code; switch (error?.type) { case GoogleIdentityServicesErrorType.missing_required_parameter: @@ -345,8 +365,9 @@ class GisSdkClient { code = GoogleSignInExceptionCode.unknownError; } return GoogleSignInException( - code: code, - description: error?.message ?? 'SDK returned no error details'); + code: code, + description: error?.message ?? 'SDK returned no error details', + ); } final bool _loggingEnabled; @@ -365,7 +386,7 @@ class GisSdkClient { // request that was not associated with a known user (i.e., no user ID hint // was provided with the request). final Map - _lastClientAuthorizationByUser = + _lastClientAuthorizationByUser = {}; /// The StreamController onto which the GIS Client propagates user authentication events. diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart b/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart index 0f27f04d195..850cfd6c925 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart @@ -20,7 +20,8 @@ final Codec jwtCodec = json.fuse(utf8).fuse(base64); /// /// More info: https://regexr.com/789qc final RegExp jwtTokenRegexp = RegExp( - r'^(?
[^\.\s]+)\.(?[^\.\s]+)\.(?[^\.\s]+)$'); + r'^(?
[^\.\s]+)\.(?[^\.\s]+)\.(?[^\.\s]+)$', +); /// Decodes the `claims` of a JWT token and returns them as a Map. /// @@ -65,14 +66,17 @@ Map? getResponsePayload(CredentialResponse? response) { /// May return `null`, if the `credentialResponse` is null, or its `credential` /// cannot be decoded. AuthenticationEvent? gisResponsesToAuthenticationEvent( - CredentialResponse? credentialResponse) { + CredentialResponse? credentialResponse, +) { final Map? payload = getResponsePayload(credentialResponse); if (payload == null) { return null; } - assert(credentialResponse?.credential != null, - 'The CredentialResponse cannot be null and have a payload.'); + assert( + credentialResponse?.credential != null, + 'The CredentialResponse cannot be null and have a payload.', + ); return AuthenticationEventSignIn( user: GoogleSignInUserData( @@ -81,8 +85,9 @@ AuthenticationEvent? gisResponsesToAuthenticationEvent( displayName: payload['name'] as String?, photoUrl: payload['picture'] as String?, ), - authenticationTokens: - AuthenticationTokenData(idToken: credentialResponse!.credential), + authenticationTokens: AuthenticationTokenData( + idToken: credentialResponse!.credential, + ), ); } @@ -91,7 +96,8 @@ AuthenticationEvent? gisResponsesToAuthenticationEvent( /// May return `null` if the `credentialResponse` is null, its `credential` /// cannot be decoded, or the `exp` field is not set on the JWT payload. DateTime? getCredentialResponseExpirationTimestamp( - CredentialResponse? credentialResponse) { + CredentialResponse? credentialResponse, +) { final Map? payload = getResponsePayload(credentialResponse); // Get the 'exp' field from the payload, if present. final int? exp = (payload != null) ? payload['exp'] as int? : null; diff --git a/packages/google_sign_in/google_sign_in_web/lib/web_only.dart b/packages/google_sign_in/google_sign_in_web/lib/web_only.dart index 899a88cd45a..1f7540b244e 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/web_only.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/web_only.dart @@ -29,8 +29,10 @@ export 'src/button_configuration.dart' // Asserts that the instance of the platform is for the web. GoogleSignInPlugin get _plugin { - assert(GoogleSignInPlatform.instance is GoogleSignInPlugin, - 'The current GoogleSignInPlatform instance is not for web.'); + assert( + GoogleSignInPlatform.instance is GoogleSignInPlugin, + 'The current GoogleSignInPlatform instance is not for web.', + ); return GoogleSignInPlatform.instance as GoogleSignInPlugin; } 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 faffd0143d1..f53d3f0b213 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.0.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/interactive_media_ads/CHANGELOG.md b/packages/interactive_media_ads/CHANGELOG.md index 33c278b7eaf..236e32cde2b 100644 --- a/packages/interactive_media_ads/CHANGELOG.md +++ b/packages/interactive_media_ads/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.2.6+3 * Updates `README` with information about enabling desugaring on Android. diff --git a/packages/interactive_media_ads/README.md b/packages/interactive_media_ads/README.md index 9b4a6db237b..7f6c9453ff0 100644 --- a/packages/interactive_media_ads/README.md +++ b/packages/interactive_media_ads/README.md @@ -140,7 +140,9 @@ class _AdExampleWidgetState extends State Widget build(BuildContext context) { // ··· } + } + ``` ### 4. Add the Video Players @@ -159,29 +161,31 @@ late final AdDisplayContainer _adDisplayContainer = AdDisplayContainer( final AdsManager manager = data.manager; _adsManager = data.manager; - manager.setAdsManagerDelegate(AdsManagerDelegate( - onAdEvent: (AdEvent event) { - debugPrint('OnAdEvent: ${event.type} => ${event.adData}'); - switch (event.type) { - case AdEventType.loaded: - manager.start(); - case AdEventType.contentPauseRequested: - _pauseContent(); - case AdEventType.contentResumeRequested: - _resumeContent(); - case AdEventType.allAdsCompleted: - manager.destroy(); - _adsManager = null; - case AdEventType.clicked: - case AdEventType.complete: - case _: - } - }, - onAdErrorEvent: (AdErrorEvent event) { - debugPrint('AdErrorEvent: ${event.error.message}'); - _resumeContent(); - }, - )); + manager.setAdsManagerDelegate( + AdsManagerDelegate( + onAdEvent: (AdEvent event) { + debugPrint('OnAdEvent: ${event.type} => ${event.adData}'); + switch (event.type) { + case AdEventType.loaded: + manager.start(); + case AdEventType.contentPauseRequested: + _pauseContent(); + case AdEventType.contentResumeRequested: + _resumeContent(); + case AdEventType.allAdsCompleted: + manager.destroy(); + _adsManager = null; + case AdEventType.clicked: + case AdEventType.complete: + case _: + } + }, + onAdErrorEvent: (AdErrorEvent event) { + debugPrint('AdErrorEvent: ${event.error.message}'); + _resumeContent(); + }, + ), + ); manager.init(settings: AdsRenderingSettings(enablePreloading: true)); }, @@ -201,21 +205,22 @@ late final AdDisplayContainer _adDisplayContainer = AdDisplayContainer( void initState() { super.initState(); // ··· - _contentVideoController = VideoPlayerController.networkUrl( - Uri.parse( - 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', - ), - ) - ..addListener(() { - if (_contentVideoController.value.isCompleted) { - _adsLoader.contentComplete(); - } - setState(() {}); - }) - ..initialize().then((_) { - // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. - setState(() {}); - }); + _contentVideoController = + VideoPlayerController.networkUrl( + Uri.parse( + 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', + ), + ) + ..addListener(() { + if (_contentVideoController.value.isCompleted) { + _adsLoader.contentComplete(); + } + setState(() {}); + }) + ..initialize().then((_) { + // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. + setState(() {}); + }); } ``` @@ -231,42 +236,44 @@ Widget build(BuildContext context) { body: Center( child: SizedBox( width: 300, - child: !_contentVideoController.value.isInitialized - ? Container() - : AspectRatio( - aspectRatio: _contentVideoController.value.aspectRatio, - child: Stack( - children: [ - // The display container must be on screen before any Ads can be - // loaded and can't be removed between ads. This handles clicks for - // ads. - _adDisplayContainer, - if (_shouldShowContentVideo) - VideoPlayer(_contentVideoController) - ], + child: + !_contentVideoController.value.isInitialized + ? Container() + : AspectRatio( + aspectRatio: _contentVideoController.value.aspectRatio, + child: Stack( + children: [ + // The display container must be on screen before any Ads can be + // loaded and can't be removed between ads. This handles clicks for + // ads. + _adDisplayContainer, + if (_shouldShowContentVideo) + VideoPlayer(_contentVideoController), + ], + ), ), - ), ), ), floatingActionButton: _contentVideoController.value.isInitialized && _shouldShowContentVideo ? FloatingActionButton( - onPressed: () { - setState(() { - _contentVideoController.value.isPlaying - ? _contentVideoController.pause() - : _contentVideoController.play(); - }); - }, - child: Icon( + onPressed: () { + setState(() { _contentVideoController.value.isPlaying - ? Icons.pause - : Icons.play_arrow, - ), - ) + ? _contentVideoController.pause() + : _contentVideoController.play(); + }); + }, + child: Icon( + _contentVideoController.value.isPlaying + ? Icons.pause + : Icons.play_arrow, + ), + ) : null, ); } + ``` ### 6. Request Ads @@ -276,10 +283,12 @@ Handle requesting ads and add event listeners to handle when content should be d ```dart Future _requestAds(AdDisplayContainer container) { - return _adsLoader.requestAds(AdsRequest( - adTagUrl: _adTagUrl, - contentProgressProvider: _contentProgressProvider, - )); + return _adsLoader.requestAds( + AdsRequest( + adTagUrl: _adTagUrl, + contentProgressProvider: _contentProgressProvider, + ), + ); } Future _resumeContent() async { diff --git a/packages/interactive_media_ads/example/lib/main.dart b/packages/interactive_media_ads/example/lib/main.dart index 1f591fc49ea..da823b7e427 100644 --- a/packages/interactive_media_ads/example/lib/main.dart +++ b/packages/interactive_media_ads/example/lib/main.dart @@ -75,29 +75,31 @@ class _AdExampleWidgetState extends State final AdsManager manager = data.manager; _adsManager = data.manager; - manager.setAdsManagerDelegate(AdsManagerDelegate( - onAdEvent: (AdEvent event) { - debugPrint('OnAdEvent: ${event.type} => ${event.adData}'); - switch (event.type) { - case AdEventType.loaded: - manager.start(); - case AdEventType.contentPauseRequested: - _pauseContent(); - case AdEventType.contentResumeRequested: - _resumeContent(); - case AdEventType.allAdsCompleted: - manager.destroy(); - _adsManager = null; - case AdEventType.clicked: - case AdEventType.complete: - case _: - } - }, - onAdErrorEvent: (AdErrorEvent event) { - debugPrint('AdErrorEvent: ${event.error.message}'); - _resumeContent(); - }, - )); + manager.setAdsManagerDelegate( + AdsManagerDelegate( + onAdEvent: (AdEvent event) { + debugPrint('OnAdEvent: ${event.type} => ${event.adData}'); + switch (event.type) { + case AdEventType.loaded: + manager.start(); + case AdEventType.contentPauseRequested: + _pauseContent(); + case AdEventType.contentResumeRequested: + _resumeContent(); + case AdEventType.allAdsCompleted: + manager.destroy(); + _adsManager = null; + case AdEventType.clicked: + case AdEventType.complete: + case _: + } + }, + onAdErrorEvent: (AdErrorEvent event) { + debugPrint('AdErrorEvent: ${event.error.message}'); + _resumeContent(); + }, + ), + ); manager.init(settings: AdsRenderingSettings(enablePreloading: true)); }, @@ -119,21 +121,22 @@ class _AdExampleWidgetState extends State // Adds this instance as an observer for `AppLifecycleState` changes. WidgetsBinding.instance.addObserver(this); - _contentVideoController = VideoPlayerController.networkUrl( - Uri.parse( - 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', - ), - ) - ..addListener(() { - if (_contentVideoController.value.isCompleted) { - _adsLoader.contentComplete(); - } - setState(() {}); - }) - ..initialize().then((_) { - // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. - setState(() {}); - }); + _contentVideoController = + VideoPlayerController.networkUrl( + Uri.parse( + 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', + ), + ) + ..addListener(() { + if (_contentVideoController.value.isCompleted) { + _adsLoader.contentComplete(); + } + setState(() {}); + }) + ..initialize().then((_) { + // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. + setState(() {}); + }); } @override @@ -160,10 +163,12 @@ class _AdExampleWidgetState extends State } Future _requestAds(AdDisplayContainer container) { - return _adsLoader.requestAds(AdsRequest( - adTagUrl: _adTagUrl, - contentProgressProvider: _contentProgressProvider, - )); + return _adsLoader.requestAds( + AdsRequest( + adTagUrl: _adTagUrl, + contentProgressProvider: _contentProgressProvider, + ), + ); } Future _resumeContent() async { @@ -219,21 +224,22 @@ class _AdExampleWidgetState extends State children: [ SizedBox( width: 300, - child: !_contentVideoController.value.isInitialized - ? Container() - : AspectRatio( - aspectRatio: _contentVideoController.value.aspectRatio, - child: Stack( - children: [ - // The display container must be on screen before any Ads can be - // loaded and can't be removed between ads. This handles clicks for - // ads. - _adDisplayContainer, - if (_shouldShowContentVideo) - VideoPlayer(_contentVideoController) - ], + child: + !_contentVideoController.value.isInitialized + ? Container() + : AspectRatio( + aspectRatio: _contentVideoController.value.aspectRatio, + child: Stack( + children: [ + // The display container must be on screen before any Ads can be + // loaded and can't be removed between ads. This handles clicks for + // ads. + _adDisplayContainer, + if (_shouldShowContentVideo) + VideoPlayer(_contentVideoController), + ], + ), ), - ), ), ColoredBox( color: Colors.green, @@ -249,19 +255,19 @@ class _AdExampleWidgetState extends State floatingActionButton: _contentVideoController.value.isInitialized && _shouldShowContentVideo ? FloatingActionButton( - onPressed: () { - setState(() { - _contentVideoController.value.isPlaying - ? _contentVideoController.pause() - : _contentVideoController.play(); - }); - }, - child: Icon( + onPressed: () { + setState(() { _contentVideoController.value.isPlaying - ? Icons.pause - : Icons.play_arrow, - ), - ) + ? _contentVideoController.pause() + : _contentVideoController.play(); + }); + }, + child: Icon( + _contentVideoController.value.isPlaying + ? Icons.pause + : Icons.play_arrow, + ), + ) : null, ); } diff --git a/packages/interactive_media_ads/example/lib/readme_example.dart b/packages/interactive_media_ads/example/lib/readme_example.dart index 1c2c5f42f60..f79860f4041 100644 --- a/packages/interactive_media_ads/example/lib/readme_example.dart +++ b/packages/interactive_media_ads/example/lib/readme_example.dart @@ -64,29 +64,31 @@ class _AdExampleWidgetState extends State final AdsManager manager = data.manager; _adsManager = data.manager; - manager.setAdsManagerDelegate(AdsManagerDelegate( - onAdEvent: (AdEvent event) { - debugPrint('OnAdEvent: ${event.type} => ${event.adData}'); - switch (event.type) { - case AdEventType.loaded: - manager.start(); - case AdEventType.contentPauseRequested: - _pauseContent(); - case AdEventType.contentResumeRequested: - _resumeContent(); - case AdEventType.allAdsCompleted: - manager.destroy(); - _adsManager = null; - case AdEventType.clicked: - case AdEventType.complete: - case _: - } - }, - onAdErrorEvent: (AdErrorEvent event) { - debugPrint('AdErrorEvent: ${event.error.message}'); - _resumeContent(); - }, - )); + manager.setAdsManagerDelegate( + AdsManagerDelegate( + onAdEvent: (AdEvent event) { + debugPrint('OnAdEvent: ${event.type} => ${event.adData}'); + switch (event.type) { + case AdEventType.loaded: + manager.start(); + case AdEventType.contentPauseRequested: + _pauseContent(); + case AdEventType.contentResumeRequested: + _resumeContent(); + case AdEventType.allAdsCompleted: + manager.destroy(); + _adsManager = null; + case AdEventType.clicked: + case AdEventType.complete: + case _: + } + }, + onAdErrorEvent: (AdErrorEvent event) { + debugPrint('AdErrorEvent: ${event.error.message}'); + _resumeContent(); + }, + ), + ); manager.init(settings: AdsRenderingSettings(enablePreloading: true)); }, @@ -110,21 +112,22 @@ class _AdExampleWidgetState extends State WidgetsBinding.instance.addObserver(this); // #docregion ad_and_content_players - _contentVideoController = VideoPlayerController.networkUrl( - Uri.parse( - 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', - ), - ) - ..addListener(() { - if (_contentVideoController.value.isCompleted) { - _adsLoader.contentComplete(); - } - setState(() {}); - }) - ..initialize().then((_) { - // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. - setState(() {}); - }); + _contentVideoController = + VideoPlayerController.networkUrl( + Uri.parse( + 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', + ), + ) + ..addListener(() { + if (_contentVideoController.value.isCompleted) { + _adsLoader.contentComplete(); + } + setState(() {}); + }) + ..initialize().then((_) { + // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. + setState(() {}); + }); } // #enddocregion ad_and_content_players @@ -153,10 +156,12 @@ class _AdExampleWidgetState extends State // #docregion request_ads Future _requestAds(AdDisplayContainer container) { - return _adsLoader.requestAds(AdsRequest( - adTagUrl: _adTagUrl, - contentProgressProvider: _contentProgressProvider, - )); + return _adsLoader.requestAds( + AdsRequest( + adTagUrl: _adTagUrl, + contentProgressProvider: _contentProgressProvider, + ), + ); } Future _resumeContent() async { @@ -216,43 +221,46 @@ class _AdExampleWidgetState extends State body: Center( child: SizedBox( width: 300, - child: !_contentVideoController.value.isInitialized - ? Container() - : AspectRatio( - aspectRatio: _contentVideoController.value.aspectRatio, - child: Stack( - children: [ - // The display container must be on screen before any Ads can be - // loaded and can't be removed between ads. This handles clicks for - // ads. - _adDisplayContainer, - if (_shouldShowContentVideo) - VideoPlayer(_contentVideoController) - ], + child: + !_contentVideoController.value.isInitialized + ? Container() + : AspectRatio( + aspectRatio: _contentVideoController.value.aspectRatio, + child: Stack( + children: [ + // The display container must be on screen before any Ads can be + // loaded and can't be removed between ads. This handles clicks for + // ads. + _adDisplayContainer, + if (_shouldShowContentVideo) + VideoPlayer(_contentVideoController), + ], + ), ), - ), ), ), floatingActionButton: _contentVideoController.value.isInitialized && _shouldShowContentVideo ? FloatingActionButton( - onPressed: () { - setState(() { - _contentVideoController.value.isPlaying - ? _contentVideoController.pause() - : _contentVideoController.play(); - }); - }, - child: Icon( + onPressed: () { + setState(() { _contentVideoController.value.isPlaying - ? Icons.pause - : Icons.play_arrow, - ), - ) + ? _contentVideoController.pause() + : _contentVideoController.play(); + }); + }, + child: Icon( + _contentVideoController.value.isPlaying + ? Icons.pause + : Icons.play_arrow, + ), + ) : null, ); // #docregion example_widget } -// #enddocregion widget_build + + // #enddocregion widget_build } + // #enddocregion example_widget diff --git a/packages/interactive_media_ads/example/pubspec.yaml b/packages/interactive_media_ads/example/pubspec.yaml index 03a616bfc77..f47472464a1 100644 --- a/packages/interactive_media_ads/example/pubspec.yaml +++ b/packages/interactive_media_ads/example/pubspec.yaml @@ -3,8 +3,8 @@ description: "Demonstrates how to use the interactive_media_ads plugin." publish_to: 'none' # Remove this line if you wish to publish to pub.dev environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/interactive_media_ads/lib/src/ad_display_container.dart b/packages/interactive_media_ads/lib/src/ad_display_container.dart index 6a814f1b365..fc20b30f0f6 100644 --- a/packages/interactive_media_ads/lib/src/ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/ad_display_container.dart @@ -40,19 +40,19 @@ class AdDisplayContainer extends StatelessWidget { Iterable companionSlots = const [], TextDirection layoutDirection = TextDirection.ltr, }) : this.fromPlatformCreationParams( - key: key, - params: PlatformAdDisplayContainerCreationParams( - onContainerAdded: (PlatformAdDisplayContainer container) { - onContainerAdded(AdDisplayContainer.fromPlatform( - platform: container, - )); - }, - companionSlots: companionSlots.map( - (CompanionAdSlot slot) => slot.platform, - ), - layoutDirection: layoutDirection, - ), - ); + key: key, + params: PlatformAdDisplayContainerCreationParams( + onContainerAdded: (PlatformAdDisplayContainer container) { + onContainerAdded( + AdDisplayContainer.fromPlatform(platform: container), + ); + }, + companionSlots: companionSlots.map( + (CompanionAdSlot slot) => slot.platform, + ), + layoutDirection: layoutDirection, + ), + ); /// Constructs an [AdDisplayContainer] from creation params for a specific platform. /// @@ -85,9 +85,9 @@ class AdDisplayContainer extends StatelessWidget { Key? key, required PlatformAdDisplayContainerCreationParams params, }) : this.fromPlatform( - key: key, - platform: PlatformAdDisplayContainer(params), - ); + key: key, + platform: PlatformAdDisplayContainer(params), + ); /// Constructs an [AdDisplayContainer] from a specific platform /// implementation. diff --git a/packages/interactive_media_ads/lib/src/ads_loader.dart b/packages/interactive_media_ads/lib/src/ads_loader.dart index 6855810c054..6050b8c195a 100644 --- a/packages/interactive_media_ads/lib/src/ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/ads_loader.dart @@ -45,15 +45,15 @@ class AdsLoader { required void Function(AdsLoadErrorData data) onAdsLoadError, ImaSettings? settings, }) : this.fromPlatformCreationParams( - PlatformAdsLoaderCreationParams( - container: container.platform, - settings: settings?.platform ?? ImaSettings().platform, - onAdsLoaded: (PlatformOnAdsLoadedData data) { - onAdsLoaded(OnAdsLoadedData._(platform: data)); - }, - onAdsLoadError: onAdsLoadError, - ), - ); + PlatformAdsLoaderCreationParams( + container: container.platform, + settings: settings?.platform ?? ImaSettings().platform, + onAdsLoaded: (PlatformOnAdsLoadedData data) { + onAdsLoaded(OnAdsLoadedData._(platform: data)); + }, + onAdsLoadError: onAdsLoadError, + ), + ); /// Constructs an [AdsLoader] from creation params for a specific platform. /// @@ -82,9 +82,8 @@ class AdsLoader { /// ); /// ``` /// {@endtemplate} - AdsLoader.fromPlatformCreationParams( - PlatformAdsLoaderCreationParams params, - ) : this.fromPlatform(PlatformAdsLoader(params)); + AdsLoader.fromPlatformCreationParams(PlatformAdsLoaderCreationParams params) + : this.fromPlatform(PlatformAdsLoader(params)); /// Constructs a [AdsLoader] from a specific platform implementation. AdsLoader.fromPlatform(this.platform); diff --git a/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart b/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart index c04cf5c9c52..b240634302e 100644 --- a/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart +++ b/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart @@ -36,11 +36,11 @@ class AdsManagerDelegate { void Function(AdEvent event)? onAdEvent, void Function(AdErrorEvent event)? onAdErrorEvent, }) : this.fromPlatformCreationParams( - PlatformAdsManagerDelegateCreationParams( - onAdEvent: onAdEvent, - onAdErrorEvent: onAdErrorEvent, - ), - ); + PlatformAdsManagerDelegateCreationParams( + onAdEvent: onAdEvent, + onAdErrorEvent: onAdErrorEvent, + ), + ); /// Constructs an [AdsManagerDelegate] from creation params for a specific platform. /// diff --git a/packages/interactive_media_ads/lib/src/ads_rendering_settings.dart b/packages/interactive_media_ads/lib/src/ads_rendering_settings.dart index ecae23f404a..6d99b5fc22a 100644 --- a/packages/interactive_media_ads/lib/src/ads_rendering_settings.dart +++ b/packages/interactive_media_ads/lib/src/ads_rendering_settings.dart @@ -15,16 +15,18 @@ class AdsRenderingSettings { List? mimeTypes, Duration? playAdsAfterTime, Set? uiElements, - }) : this.fromPlatform(PlatformAdsRenderingSettings( - PlatformAdsRenderingSettingsCreationParams( - bitrate: bitrate, - enablePreloading: enablePreloading, - loadVideoTimeout: loadVideoTimeout, - mimeTypes: mimeTypes, - playAdsAfterTime: playAdsAfterTime, - uiElements: uiElements, - ), - )); + }) : this.fromPlatform( + PlatformAdsRenderingSettings( + PlatformAdsRenderingSettingsCreationParams( + bitrate: bitrate, + enablePreloading: enablePreloading, + loadVideoTimeout: loadVideoTimeout, + mimeTypes: mimeTypes, + playAdsAfterTime: playAdsAfterTime, + uiElements: uiElements, + ), + ), + ); /// Constructs an [AdsRenderingSettings] from a specific platform /// implementation. diff --git a/packages/interactive_media_ads/lib/src/ads_request.dart b/packages/interactive_media_ads/lib/src/ads_request.dart index a22d69320c1..77e81487d5d 100644 --- a/packages/interactive_media_ads/lib/src/ads_request.dart +++ b/packages/interactive_media_ads/lib/src/ads_request.dart @@ -20,19 +20,19 @@ class AdsRequest { Duration? liveStreamPrefetchMaxWaitTime, Duration? vastLoadTimeout, }) : this.fromPlatform( - PlatformAdsRequest.withAdTagUrl( - adTagUrl: adTagUrl, - contentProgressProvider: contentProgressProvider?.platform, - adWillAutoPlay: adWillAutoPlay, - adWillPlayMuted: adWillPlayMuted, - continuousPlayback: continuousPlayback, - contentDuration: contentDuration, - contentKeywords: contentKeywords, - contentTitle: contentTitle, - liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, - vastLoadTimeout: vastLoadTimeout, - ), - ); + PlatformAdsRequest.withAdTagUrl( + adTagUrl: adTagUrl, + contentProgressProvider: contentProgressProvider?.platform, + adWillAutoPlay: adWillAutoPlay, + adWillPlayMuted: adWillPlayMuted, + continuousPlayback: continuousPlayback, + contentDuration: contentDuration, + contentKeywords: contentKeywords, + contentTitle: contentTitle, + liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, + vastLoadTimeout: vastLoadTimeout, + ), + ); /// Creates an [AdsRequest] with the given canned ads response. AdsRequest.withAdsResponse({ @@ -47,19 +47,19 @@ class AdsRequest { Duration? liveStreamPrefetchMaxWaitTime, Duration? vastLoadTimeout, }) : this.fromPlatform( - PlatformAdsRequest.withAdsResponse( - adsResponse: adsResponse, - contentProgressProvider: contentProgressProvider?.platform, - adWillAutoPlay: adWillAutoPlay, - adWillPlayMuted: adWillPlayMuted, - continuousPlayback: continuousPlayback, - contentDuration: contentDuration, - contentKeywords: contentKeywords, - contentTitle: contentTitle, - liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, - vastLoadTimeout: vastLoadTimeout, - ), - ); + PlatformAdsRequest.withAdsResponse( + adsResponse: adsResponse, + contentProgressProvider: contentProgressProvider?.platform, + adWillAutoPlay: adWillAutoPlay, + adWillPlayMuted: adWillPlayMuted, + continuousPlayback: continuousPlayback, + contentDuration: contentDuration, + contentKeywords: contentKeywords, + contentTitle: contentTitle, + liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, + vastLoadTimeout: vastLoadTimeout, + ), + ); /// Constructs an [AdsRequest] from a specific platform implementation. AdsRequest.fromPlatform(this.platform); @@ -69,27 +69,28 @@ class AdsRequest { /// The URL from which ads will be requested. String get adTagUrl => switch (platform) { - final PlatformAdsRequestWithAdTagUrl request => request.adTagUrl, - // TODO(bparrishMines): This returns an empty string rather than null - // to prevent a breaking change. This should be updated to return null - // on the next major release. - PlatformAdsRequestWithAdsResponse() => '', - }; + final PlatformAdsRequestWithAdTagUrl request => request.adTagUrl, + // TODO(bparrishMines): This returns an empty string rather than null + // to prevent a breaking change. This should be updated to return null + // on the next major release. + PlatformAdsRequestWithAdsResponse() => '', + }; /// Specifies a VAST, VMAP, or ad rules response to be used instead of making /// a request through an ad tag URL. String? get adsResponse => switch (platform) { - final PlatformAdsRequestWithAdsResponse request => request.adsResponse, - PlatformAdsRequestWithAdTagUrl() => null, - }; + final PlatformAdsRequestWithAdsResponse request => request.adsResponse, + PlatformAdsRequestWithAdTagUrl() => null, + }; /// A [ContentProgressProvider] instance to allow scheduling of ad breaks /// based on content progress (cue points). - ContentProgressProvider? get contentProgressProvider => platform - .contentProgressProvider != - null - ? ContentProgressProvider.fromPlatform(platform.contentProgressProvider!) - : null; + ContentProgressProvider? get contentProgressProvider => + platform.contentProgressProvider != null + ? ContentProgressProvider.fromPlatform( + platform.contentProgressProvider!, + ) + : null; /// Notifies the SDK whether the player intends to start the content and ad in /// response to a user action or whether it will be automatically played. diff --git a/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart b/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart index 57751746173..d333f9d3135 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart @@ -24,10 +24,10 @@ final class AndroidAdDisplayContainerCreationParams super.companionSlots, @visibleForTesting InteractiveMediaAdsProxy? imaProxy, @visibleForTesting PlatformViewsServiceProxy? platformViewsProxy, - }) : _imaProxy = imaProxy ?? const InteractiveMediaAdsProxy(), - _platformViewsProxy = - platformViewsProxy ?? const PlatformViewsServiceProxy(), - super(); + }) : _imaProxy = imaProxy ?? const InteractiveMediaAdsProxy(), + _platformViewsProxy = + platformViewsProxy ?? const PlatformViewsServiceProxy(), + super(); /// Creates a [AndroidAdDisplayContainerCreationParams] from an instance of /// [PlatformAdDisplayContainerCreationParams]. @@ -131,8 +131,9 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { late final AndroidAdDisplayContainerCreationParams _androidParams = params is AndroidAdDisplayContainerCreationParams ? params as AndroidAdDisplayContainerCreationParams - : AndroidAdDisplayContainerCreationParams - .fromPlatformAdDisplayContainerCreationParams(params); + : AndroidAdDisplayContainerCreationParams.fromPlatformAdDisplayContainerCreationParams( + params, + ); @override Widget build(BuildContext context) { @@ -144,18 +145,16 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { onPlatformViewCreated: () async { adDisplayContainer = await _androidParams._imaProxy .createAdDisplayContainerImaSdkFactory( - _frameLayout, - _videoAdPlayer, - ); + _frameLayout, + _videoAdPlayer, + ); final Iterable nativeCompanionSlots = await Future.wait( - _androidParams.companionSlots.map( - (PlatformCompanionAdSlot slot) { - return (slot as AndroidCompanionAdSlot) - .getNativeCompanionAdSlot(); - }, - ), - ); + _androidParams.companionSlots.map((PlatformCompanionAdSlot slot) { + return (slot as AndroidCompanionAdSlot) + .getNativeCompanionAdSlot(); + }), + ); await adDisplayContainer!.setCompanionSlots( nativeCompanionSlots.toList(), ); @@ -183,24 +182,19 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { _adProgressTimer = Timer.periodic( const Duration(milliseconds: _progressPollingMs), (Timer timer) async { - final ima.VideoProgressUpdate currentProgress = - _androidParams._imaProxy.newVideoProgressUpdate( - currentTimeMs: await _videoView.getCurrentPosition(), - durationMs: _adDuration!, - ); - await Future.wait( - >[ - _videoAdPlayer.setAdProgress(currentProgress), - ...videoAdPlayerCallbacks.map( - (ima.VideoAdPlayerCallback callback) async { - await callback.onAdProgress( - _loadedAdMediaInfo!, - currentProgress, - ); - }, - ), - ], - ); + final ima.VideoProgressUpdate currentProgress = _androidParams._imaProxy + .newVideoProgressUpdate( + currentTimeMs: await _videoView.getCurrentPosition(), + durationMs: _adDuration!, + ); + await Future.wait(>[ + _videoAdPlayer.setAdProgress(currentProgress), + ...videoAdPlayerCallbacks.map(( + ima.VideoAdPlayerCallback callback, + ) async { + await callback.onAdProgress(_loadedAdMediaInfo!, currentProgress); + }), + ]); }, ); } diff --git a/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart b/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart index 9c2ecc9308e..a6fb4638667 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart @@ -25,8 +25,8 @@ final class AndroidAdsLoaderCreationParams required super.onAdsLoaded, required super.onAdsLoadError, @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [AndroidAdsLoaderCreationParams] from an instance of /// [PlatformAdsLoaderCreationParams]. @@ -50,13 +50,13 @@ final class AndroidAdsLoaderCreationParams base class AndroidAdsLoader extends PlatformAdsLoader { /// Constructs an [AndroidAdsLoader]. AndroidAdsLoader(super.params) - : assert(params.container is AndroidAdDisplayContainer), - assert( - (params.container as AndroidAdDisplayContainer).adDisplayContainer != - null, - 'Ensure the AdDisplayContainer has been added to the Widget tree before creating an AdsLoader.', - ), - super.implementation() { + : assert(params.container is AndroidAdDisplayContainer), + assert( + (params.container as AndroidAdDisplayContainer).adDisplayContainer != + null, + 'Ensure the AdDisplayContainer has been added to the Widget tree before creating an AdsLoader.', + ), + super.implementation() { _adsLoaderFuture = _createAdsLoader(); } @@ -68,8 +68,8 @@ base class AndroidAdsLoader extends PlatformAdsLoader { params is AndroidAdsLoaderCreationParams ? params as AndroidAdsLoaderCreationParams : AndroidAdsLoaderCreationParams.fromPlatformAdsLoaderCreationParams( - params, - ); + params, + ); @override Future contentComplete() async { @@ -101,7 +101,8 @@ base class AndroidAdsLoader extends PlatformAdsLoader { androidRequest.setContinuousPlayback(continuousPlayback), if (request.contentDuration case final Duration contentDuration) androidRequest.setContentDuration( - contentDuration.inMilliseconds / Duration.millisecondsPerSecond), + contentDuration.inMilliseconds / Duration.millisecondsPerSecond, + ), if (request.contentKeywords case final List contentKeywords) androidRequest.setContentKeywords(contentKeywords), if (request.contentTitle case final String contentTitle) @@ -113,8 +114,9 @@ base class AndroidAdsLoader extends PlatformAdsLoader { Duration.millisecondsPerSecond, ), if (request.vastLoadTimeout case final Duration vastLoadTimeout) - androidRequest - .setVastLoadTimeout(vastLoadTimeout.inMilliseconds.toDouble()), + androidRequest.setVastLoadTimeout( + vastLoadTimeout.inMilliseconds.toDouble(), + ), if (request.contentProgressProvider case final PlatformContentProgressProvider contentProgressProvider) androidRequest.setContentProgressProvider( @@ -151,30 +153,34 @@ base class AndroidAdsLoader extends PlatformAdsLoader { final InteractiveMediaAdsProxy proxy = weakThis.target!._androidParams._proxy; adsLoader - ..addAdsLoadedListener(proxy.newAdsLoadedListener( - onAdsManagerLoaded: (_, ima.AdsManagerLoadedEvent event) { - weakThis.target?.params.onAdsLoaded( - PlatformOnAdsLoadedData( - manager: AndroidAdsManager( - event.manager, - proxy: weakThis.target?._androidParams._proxy, + ..addAdsLoadedListener( + proxy.newAdsLoadedListener( + onAdsManagerLoaded: (_, ima.AdsManagerLoadedEvent event) { + weakThis.target?.params.onAdsLoaded( + PlatformOnAdsLoadedData( + manager: AndroidAdsManager( + event.manager, + proxy: weakThis.target?._androidParams._proxy, + ), ), - ), - ); - }, - )) - ..addAdErrorListener(proxy.newAdErrorListener( - onAdError: (_, ima.AdErrorEvent event) { - weakThis.target?.params.onAdsLoadError( - AdsLoadErrorData( - error: AdError( - type: toInterfaceErrorType(event.error.errorType), - code: toInterfaceErrorCode(event.error.errorCode), - message: event.error.message, + ); + }, + ), + ) + ..addAdErrorListener( + proxy.newAdErrorListener( + onAdError: (_, ima.AdErrorEvent event) { + weakThis.target?.params.onAdsLoadError( + AdsLoadErrorData( + error: AdError( + type: toInterfaceErrorType(event.error.errorType), + code: toInterfaceErrorCode(event.error.errorCode), + message: event.error.message, + ), ), - ), - ); - }, - )); + ); + }, + ), + ); } } diff --git a/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart b/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart index ad1953bfc78..b9fab053aba 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart @@ -16,11 +16,9 @@ import 'interactive_media_ads_proxy.dart'; class AndroidAdsManager extends PlatformAdsManager { /// Constructs an [AndroidAdsManager]. @internal - AndroidAdsManager( - ima.AdsManager manager, { - InteractiveMediaAdsProxy? proxy, - }) : _manager = manager, - _proxy = proxy ?? const InteractiveMediaAdsProxy(); + AndroidAdsManager(ima.AdsManager manager, {InteractiveMediaAdsProxy? proxy}) + : _manager = manager, + _proxy = proxy ?? const InteractiveMediaAdsProxy(); final ima.AdsManager _manager; final InteractiveMediaAdsProxy _proxy; @@ -36,9 +34,12 @@ class AndroidAdsManager extends PlatformAdsManager { Future init({PlatformAdsRenderingSettings? settings}) async { ima.AdsRenderingSettings? nativeSettings; if (settings != null) { - nativeSettings = settings is AndroidAdsRenderingSettings - ? await settings.nativeSettings - : await AndroidAdsRenderingSettings(settings.params).nativeSettings; + nativeSettings = + settings is AndroidAdsRenderingSettings + ? await settings.nativeSettings + : await AndroidAdsRenderingSettings( + settings.params, + ).nativeSettings; } await _manager.init(nativeSettings); diff --git a/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart b/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart index 581ae3ff86c..3c56277a3bc 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart @@ -23,8 +23,8 @@ final class AndroidAdsRenderingSettingsCreationParams super.uiElements, this.enableCustomTabs = false, @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [AndroidAdsRenderingSettingsCreationParams] from an instance of /// [PlatformAdsRenderingSettingsCreationParams]. @@ -62,37 +62,37 @@ base class AndroidAdsRenderingSettings extends PlatformAdsRenderingSettings { .instanceImaSdkFactory() .createAdsRenderingSettings() .then((ima.AdsRenderingSettings nativeSettings) async { - await Future.wait(>[ - if (_androidParams.bitrate != null) - nativeSettings.setBitrateKbps(params.bitrate!), - if (_androidParams.enablePreloading != null) - nativeSettings.setEnablePreloading(_androidParams.enablePreloading!), - nativeSettings.setLoadVideoTimeout( - _androidParams.loadVideoTimeout.inMilliseconds, - ), - if (_androidParams.mimeTypes != null) - nativeSettings.setMimeTypes(_androidParams.mimeTypes!), - if (_androidParams.playAdsAfterTime != null) - nativeSettings.setPlayAdsAfterTime( - _androidParams.playAdsAfterTime!.inMicroseconds / - Duration.microsecondsPerSecond, - ), - if (_androidParams.uiElements != null) - nativeSettings.setUiElements( - _androidParams.uiElements!.map( - (AdUIElement element) { - return switch (element) { - AdUIElement.adAttribution => ima.UiElement.adAttribution, - AdUIElement.countdown => ima.UiElement.countdown, - }; - }, - ).toList(), - ), - nativeSettings.setEnableCustomTabs(_androidParams.enableCustomTabs) - ]); + await Future.wait(>[ + if (_androidParams.bitrate != null) + nativeSettings.setBitrateKbps(params.bitrate!), + if (_androidParams.enablePreloading != null) + nativeSettings.setEnablePreloading( + _androidParams.enablePreloading!, + ), + nativeSettings.setLoadVideoTimeout( + _androidParams.loadVideoTimeout.inMilliseconds, + ), + if (_androidParams.mimeTypes != null) + nativeSettings.setMimeTypes(_androidParams.mimeTypes!), + if (_androidParams.playAdsAfterTime != null) + nativeSettings.setPlayAdsAfterTime( + _androidParams.playAdsAfterTime!.inMicroseconds / + Duration.microsecondsPerSecond, + ), + if (_androidParams.uiElements != null) + nativeSettings.setUiElements( + _androidParams.uiElements!.map((AdUIElement element) { + return switch (element) { + AdUIElement.adAttribution => ima.UiElement.adAttribution, + AdUIElement.countdown => ima.UiElement.countdown, + }; + }).toList(), + ), + nativeSettings.setEnableCustomTabs(_androidParams.enableCustomTabs), + ]); - nativeSettingsCompleter.complete(nativeSettings); - }); + nativeSettingsCompleter.complete(nativeSettings); + }); } /// The native Android AdsRenderingSettings. @@ -106,8 +106,7 @@ base class AndroidAdsRenderingSettings extends PlatformAdsRenderingSettings { late final AndroidAdsRenderingSettingsCreationParams _androidParams = params is AndroidAdsRenderingSettingsCreationParams ? params as AndroidAdsRenderingSettingsCreationParams - : AndroidAdsRenderingSettingsCreationParams - .fromPlatformAdsRenderingSettingsCreationParams( - params, - ); + : AndroidAdsRenderingSettingsCreationParams.fromPlatformAdsRenderingSettingsCreationParams( + params, + ); } diff --git a/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart index 2ce3fbf2bbc..d2d9b936dd0 100644 --- a/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart @@ -22,10 +22,10 @@ final class AndroidCompanionAdSlotCreationParams super.onClicked, @visibleForTesting InteractiveMediaAdsProxy? proxy, @visibleForTesting PlatformViewsServiceProxy? platformViewsProxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - _platformViewsProxy = - platformViewsProxy ?? const PlatformViewsServiceProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + _platformViewsProxy = + platformViewsProxy ?? const PlatformViewsServiceProxy(), + super(); /// Creates a [AndroidCompanionAdSlotCreationParams] from an instance of /// [PlatformCompanionAdSlotCreationParams]. @@ -81,20 +81,24 @@ base class AndroidCompanionAdSlot extends PlatformCompanionAdSlot { return params; } - return AndroidCompanionAdSlotCreationParams - .fromPlatformCompanionAdSlotCreationParamsSize(params); + return AndroidCompanionAdSlotCreationParams.fromPlatformCompanionAdSlotCreationParamsSize( + params, + ); } Future _initCompanionAdSlot() async { - final ima.CompanionAdSlot adSlot = await _androidParams._proxy - .instanceImaSdkFactory() - .createCompanionAdSlot(); + final ima.CompanionAdSlot adSlot = + await _androidParams._proxy + .instanceImaSdkFactory() + .createCompanionAdSlot(); await Future.wait(>[ adSlot.setContainer(_frameLayout), switch (params.size) { - final CompanionAdSlotSizeFixed size => - adSlot.setSize(size.width, size.height), + final CompanionAdSlotSizeFixed size => adSlot.setSize( + size.width, + size.height, + ), CompanionAdSlotSizeFluid() => adSlot.setFluidSize(), }, if (params.onClicked != null) @@ -116,9 +120,9 @@ base class AndroidCompanionAdSlot extends PlatformCompanionAdSlot { ) { return weakThis.target!._androidParams._proxy .newCompanionAdSlotClickListener( - onCompanionAdClick: (_) { - weakThis.target?.params.onClicked!.call(); - }, - ); + onCompanionAdClick: (_) { + weakThis.target?.params.onClicked!.call(); + }, + ); } } diff --git a/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart b/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart index e3f4d57c295..5d7cf609512 100644 --- a/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart @@ -16,8 +16,8 @@ final class AndroidContentProgressProviderCreationParams /// Constructs a [AndroidContentProgressProviderCreationParams]. const AndroidContentProgressProviderCreationParams({ @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [AndroidContentProgressProviderCreationParams] from an instance of /// [PlatformContentProgressProviderCreationParams]. @@ -50,10 +50,9 @@ base class AndroidContentProgressProvider late final AndroidContentProgressProviderCreationParams _androidParams = params is AndroidContentProgressProviderCreationParams ? params as AndroidContentProgressProviderCreationParams - : AndroidContentProgressProviderCreationParams - .fromPlatformContentProgressProviderCreationParams( - params, - ); + : AndroidContentProgressProviderCreationParams.fromPlatformContentProgressProviderCreationParams( + params, + ); @override Future setProgress({ diff --git a/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart b/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart index 2b382216ef8..70d4e2a0437 100644 --- a/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart +++ b/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart @@ -21,8 +21,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -48,7 +51,8 @@ class PigeonOverrides { static VideoProgressUpdate Function({ required int currentTimeMs, required int durationMs, - })? videoProgressUpdate_new; + })? + videoProgressUpdate_new; /// Overrides [FrameLayout.new]. static FrameLayout Function()? frameLayout_new; @@ -60,72 +64,80 @@ class PigeonOverrides { MediaPlayer player, int what, int extra, - ) onError, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onPrepared, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onCompletion, - })? videoView_new; + ) + onError, + void Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared, + void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion, + })? + videoView_new; /// Overrides [VideoAdPlayer.new]. static VideoAdPlayer Function({ required void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - ) addCallback, + ) + addCallback, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, AdPodInfo adPodInfo, - ) loadAd, + ) + loadAd, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, - ) pauseAd, + ) + pauseAd, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, - ) playAd, + ) + playAd, required void Function(VideoAdPlayer pigeon_instance) release, required void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - ) removeCallback, + ) + removeCallback, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, - ) stopAd, - })? videoAdPlayer_new; + ) + stopAd, + })? + videoAdPlayer_new; /// Overrides [AdsLoadedListener.new]. - static AdsLoadedListener Function( - {required void Function( - AdsLoadedListener pigeon_instance, - AdsManagerLoadedEvent event, - ) onAdsManagerLoaded})? adsLoadedListener_new; + static AdsLoadedListener Function({ + required void Function( + AdsLoadedListener pigeon_instance, + AdsManagerLoadedEvent event, + ) + onAdsManagerLoaded, + })? + adsLoadedListener_new; /// Overrides [AdErrorListener.new]. - static AdErrorListener Function( - {required void Function( - AdErrorListener pigeon_instance, - AdErrorEvent event, - ) onAdError})? adErrorListener_new; + static AdErrorListener Function({ + required void Function(AdErrorListener pigeon_instance, AdErrorEvent event) + onAdError, + })? + adErrorListener_new; /// Overrides [AdEventListener.new]. - static AdEventListener Function( - {required void Function( - AdEventListener pigeon_instance, - AdEvent event, - ) onAdEvent})? adEventListener_new; + static AdEventListener Function({ + required void Function(AdEventListener pigeon_instance, AdEvent event) + onAdEvent, + })? + adEventListener_new; /// Overrides [CompanionAdSlotClickListener.new]. - static CompanionAdSlotClickListener Function( - {required void Function(CompanionAdSlotClickListener pigeon_instance) - onCompanionAdClick})? companionAdSlotClickListener_new; + static CompanionAdSlotClickListener Function({ + required void Function(CompanionAdSlotClickListener pigeon_instance) + onCompanionAdClick, + })? + companionAdSlotClickListener_new; /// Overrides [ImaSdkFactory.instance]. static ImaSdkFactory? imaSdkFactory_instance; @@ -134,10 +146,8 @@ class PigeonOverrides { static VideoProgressUpdate? videoProgressUpdate_videoTimeNotReady; /// Overrides [ImaSdkFactory.createAdDisplayContainer]. - static Future Function( - ViewGroup, - VideoAdPlayer, - )? imaSdkFactory_createAdDisplayContainer; + static Future Function(ViewGroup, VideoAdPlayer)? + imaSdkFactory_createAdDisplayContainer; /// Sets all overridden ProxyApi class members to null. static void pigeon_reset() { @@ -168,7 +178,7 @@ abstract class PigeonInternalProxyApiBaseClass { this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -239,7 +249,7 @@ class PigeonInstanceManager { // HashMap). final Expando _identifiers = Expando(); final Map> - _weakInstances = >{}; + _weakInstances = >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -264,71 +274,103 @@ class PigeonInstanceManager { }, ); _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager); + instanceManager: instanceManager, + ); BaseDisplayContainer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdDisplayContainer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdsLoader.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdsManagerLoadedEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdErrorEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdsRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ContentProgressProvider.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdsManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); BaseManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ImaSdkFactory.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ImaSdkSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); VideoProgressUpdate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdMediaInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdPodInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); FrameLayout.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ViewGroup.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); VideoView.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); View.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); MediaPlayer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); VideoAdPlayerCallback.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); VideoAdPlayer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdsLoadedListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdErrorListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdEventListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdsRenderingSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AdProgressInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); CompanionAd.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); UniversalAdId.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); Ad.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); CompanionAdSlotClickListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); CompanionAdSlot.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); return instanceManager; } @@ -345,8 +387,9 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = - WeakReference(instance); + _weakInstances[identifier] = WeakReference( + instance, + ); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -408,7 +451,8 @@ class PigeonInstanceManager { /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. T? getInstanceWithWeakReference( - int identifier) { + int identifier, + ) { final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; @@ -443,7 +487,9 @@ class PigeonInstanceManager { /// Throws assertion error if the instance or its identifier has already been /// added. void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, int identifier) { + PigeonInternalProxyApiBaseClass instance, + int identifier, + ) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -472,7 +518,7 @@ class PigeonInstanceManager { class _PigeonInternalInstanceManagerApi { /// Constructor for [_PigeonInternalInstanceManagerApi]. _PigeonInternalInstanceManagerApi({BinaryMessenger? binaryMessenger}) - : pigeonVar_binaryMessenger = binaryMessenger; + : pigeonVar_binaryMessenger = binaryMessenger; final BinaryMessenger? pigeonVar_binaryMessenger; @@ -484,31 +530,37 @@ class _PigeonInternalInstanceManagerApi { PigeonInstanceManager? instanceManager, }) { { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null.', + ); final List args = (message as List?)!; final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.'); + assert( + arg_identifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', + ); try { - (instanceManager ?? PigeonInstanceManager.instance) - .remove(arg_identifier!); + (instanceManager ?? PigeonInstanceManager.instance).remove( + arg_identifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -520,12 +572,13 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [identifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([identifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -549,10 +602,10 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.clear'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -587,8 +640,9 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager - .getInstanceWithWeakReference(readValue(buffer)! as int); + return instanceManager.getInstanceWithWeakReference( + readValue(buffer)! as int, + ); default: return super.readValueOfType(type, buffer); } @@ -858,8 +912,9 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecBaseDisplayContainer = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecBaseDisplayContainer = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -869,41 +924,47 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - BaseDisplayContainer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + BaseDisplayContainer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -921,12 +982,13 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.setCompanionSlots'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, companionSlots], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, companionSlots]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -973,41 +1035,47 @@ class AdDisplayContainer extends BaseDisplayContainer { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdDisplayContainer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + AdDisplayContainer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1049,41 +1117,47 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsLoader.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + AdsLoader.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1099,12 +1173,13 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.addAdErrorListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, listener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, listener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1129,12 +1204,13 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.addAdsLoadedListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, listener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, listener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1159,12 +1235,13 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.requestAds'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, request], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, request]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1216,45 +1293,53 @@ class AdsManagerLoadedEvent extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance was null, expected non-null int.', + ); final AdsManager? arg_manager = (args[1] as AdsManager?); - assert(arg_manager != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance was null, expected non-null AdsManager.'); + assert( + arg_manager != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManagerLoadedEvent.pigeon_newInstance was null, expected non-null AdsManager.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_manager!) ?? - AdsManagerLoadedEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - manager: arg_manager!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_manager!) ?? + AdsManagerLoadedEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + manager: arg_manager!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1297,45 +1382,53 @@ class AdErrorEvent extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null, expected non-null int.', + ); final AdError? arg_error = (args[1] as AdError?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null, expected non-null AdError.'); + assert( + arg_error != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null, expected non-null AdError.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_error!) ?? - AdErrorEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - error: arg_error!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_error!) ?? + AdErrorEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + error: arg_error!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1391,62 +1484,81 @@ class AdError extends PigeonInternalProxyApiBaseClass { int errorCodeNumber, AdErrorType errorType, String message, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null int.', + ); final AdErrorCode? arg_errorCode = (args[1] as AdErrorCode?); - assert(arg_errorCode != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null AdErrorCode.'); + assert( + arg_errorCode != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null AdErrorCode.', + ); final int? arg_errorCodeNumber = (args[2] as int?); - assert(arg_errorCodeNumber != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_errorCodeNumber != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null int.', + ); final AdErrorType? arg_errorType = (args[3] as AdErrorType?); - assert(arg_errorType != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null AdErrorType.'); + assert( + arg_errorType != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null AdErrorType.', + ); final String? arg_message = (args[4] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_errorCode!, arg_errorCodeNumber!, - arg_errorType!, arg_message!) ?? - AdError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - errorCode: arg_errorCode!, - errorCodeNumber: arg_errorCodeNumber!, - errorType: arg_errorType!, - message: arg_message!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_errorCode!, + arg_errorCodeNumber!, + arg_errorType!, + arg_message!, + ) ?? + AdError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: arg_errorCode!, + errorCodeNumber: arg_errorCodeNumber!, + errorType: arg_errorType!, + message: arg_message!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1491,41 +1603,47 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + AdsRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1541,12 +1659,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdTagUrl'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adTagUrl], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adTagUrl]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1565,7 +1684,8 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Attaches a ContentProgressProvider instance to allow scheduling ad breaks /// based on content progress (cue points). Future setContentProgressProvider( - ContentProgressProvider provider) async { + ContentProgressProvider provider, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1573,12 +1693,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentProgressProvider'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, provider], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, provider]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1607,12 +1728,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdWillAutoPlay'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, willAutoPlay], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, willAutoPlay]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1641,12 +1763,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdWillPlayMuted'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, willPlayMuted], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, willPlayMuted]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1672,12 +1795,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdsResponse'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, cannedAdResponse], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, cannedAdResponse]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1705,12 +1829,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentDuration'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, duration], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, duration]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1738,12 +1863,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentKeywords'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, keywords], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, keywords]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1771,12 +1897,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentTitle'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, title], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, title]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1805,12 +1932,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContinuousPlayback'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, continuousPlayback], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, continuousPlayback]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1839,12 +1967,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setLiveStreamPrefetchSeconds'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, prefetchTime], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, prefetchTime]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1872,12 +2001,13 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setVastLoadTimeout'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, timeout], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, timeout]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1924,8 +2054,8 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecContentProgressProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1933,12 +2063,13 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1967,8 +2098,9 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecContentProgressProvider = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecContentProgressProvider = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -1978,41 +2110,47 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ContentProgressProvider.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ContentProgressProvider.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2031,12 +2169,13 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.setContentProgress'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, update], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, update]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2087,41 +2226,47 @@ class AdsManager extends BaseManager { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + AdsManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2137,12 +2282,13 @@ class AdsManager extends BaseManager { 'dev.flutter.pigeon.interactive_media_ads.AdsManager.discardAdBreak'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2167,12 +2313,13 @@ class AdsManager extends BaseManager { 'dev.flutter.pigeon.interactive_media_ads.AdsManager.pause'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2197,12 +2344,13 @@ class AdsManager extends BaseManager { 'dev.flutter.pigeon.interactive_media_ads.AdsManager.start'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2229,12 +2377,13 @@ class AdsManager extends BaseManager { 'dev.flutter.pigeon.interactive_media_ads.AdsManager.getAdCuePoints'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2264,12 +2413,13 @@ class AdsManager extends BaseManager { 'dev.flutter.pigeon.interactive_media_ads.AdsManager.resume'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2297,12 +2447,13 @@ class AdsManager extends BaseManager { 'dev.flutter.pigeon.interactive_media_ads.AdsManager.skip'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2352,41 +2503,47 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - BaseManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + BaseManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2403,12 +2560,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.addAdErrorListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, errorListener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, errorListener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2434,12 +2592,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.addAdEventListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adEventListener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adEventListener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2465,12 +2624,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.destroy'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2495,12 +2655,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.init'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, settings], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, settings]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2525,12 +2686,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.focus'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2555,12 +2717,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.getAdProgressInfo'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2585,12 +2748,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.getCurrentAd'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2615,12 +2779,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.removeAdErrorListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, errorListener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, errorListener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2645,12 +2810,13 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.BaseManager.removeAdEventListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adEventListener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adEventListener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2701,55 +2867,61 @@ class AdEvent extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - AdEvent Function( - AdEventType type, - Map? adData, - )? pigeon_newInstance, + AdEvent Function(AdEventType type, Map? adData)? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null, expected non-null int.', + ); final AdEventType? arg_type = (args[1] as AdEventType?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null, expected non-null AdEventType.'); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null, expected non-null AdEventType.', + ); final Map? arg_adData = (args[2] as Map?)?.cast(); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_type!, arg_adData) ?? - AdEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - adData: arg_adData, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_type!, arg_adData) ?? + AdEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + adData: arg_adData, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2797,41 +2969,47 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ImaSdkFactory.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ImaSdkFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2851,12 +3029,13 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.instance'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2888,18 +3067,20 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { } final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdDisplayContainer'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [container, player], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([container, player]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2929,12 +3110,13 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createCompanionAdSlot'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2964,12 +3146,13 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createImaSdkSettings'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3003,12 +3186,13 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdsLoader'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, settings, container], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, settings, container]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3038,12 +3222,13 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdsRequest'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3074,12 +3259,13 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdsRenderingSettings'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3134,41 +3320,47 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ImaSdkSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ImaSdkSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3184,12 +3376,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setAutoPlayAdBreaks'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, autoPlayAdBreaks], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, autoPlayAdBreaks]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3214,12 +3407,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setDebugMode'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, debugMode], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, debugMode]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3248,12 +3442,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setFeatureFlags'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, featureFlags], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, featureFlags]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3284,12 +3479,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setLanguage'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, language], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, language]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3317,12 +3513,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setMaxRedirects'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, maxRedirects], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, maxRedirects]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3350,12 +3547,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPlayerType'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, playerType], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, playerType]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3382,12 +3580,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPlayerVersion'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, playerVersion], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, playerVersion]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3412,12 +3611,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPpid'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, ppid], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, ppid]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3445,12 +3645,13 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setSessionId'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, sessionId], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, sessionId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3506,8 +3707,8 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { required int currentTimeMs, required int durationMs, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoProgressUpdate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3515,12 +3716,13 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, currentTimeMs, durationMs]); + [pigeonVar_instanceIdentifier, currentTimeMs, durationMs], + ); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3549,8 +3751,9 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecVideoProgressUpdate = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecVideoProgressUpdate = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// Value to use for cases when progress is not yet defined, such as video /// initialization. @@ -3571,41 +3774,47 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoProgressUpdate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + VideoProgressUpdate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3626,12 +3835,13 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.videoTimeNotReady'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3683,45 +3893,53 @@ class AdMediaInfo extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_url = (args[1] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_url!) ?? - AdMediaInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - url: arg_url!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_url!) ?? + AdMediaInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + url: arg_url!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3796,75 +4014,95 @@ class AdPodInfo extends PigeonInternalProxyApiBaseClass { double timeOffset, int totalAds, bool isBumper, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_adPosition = (args[1] as int?); - assert(arg_adPosition != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_adPosition != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_maxDuration = (args[2] as double?); - assert(arg_maxDuration != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_maxDuration != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_podIndex = (args[3] as int?); - assert(arg_podIndex != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_podIndex != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_timeOffset = (args[4] as double?); - assert(arg_timeOffset != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_timeOffset != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_totalAds = (args[5] as int?); - assert(arg_totalAds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_totalAds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final bool? arg_isBumper = (args[6] as bool?); - assert(arg_isBumper != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_isBumper != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null bool.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adPosition!, - arg_maxDuration!, - arg_podIndex!, - arg_timeOffset!, - arg_totalAds!, - arg_isBumper!) ?? - AdPodInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adPosition: arg_adPosition!, - maxDuration: arg_maxDuration!, - podIndex: arg_podIndex!, - timeOffset: arg_timeOffset!, - totalAds: arg_totalAds!, - isBumper: arg_isBumper!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_adPosition!, + arg_maxDuration!, + arg_podIndex!, + arg_timeOffset!, + arg_totalAds!, + arg_isBumper!, + ) ?? + AdPodInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adPosition: arg_adPosition!, + maxDuration: arg_maxDuration!, + podIndex: arg_podIndex!, + timeOffset: arg_timeOffset!, + totalAds: arg_totalAds!, + isBumper: arg_isBumper!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3909,8 +4147,8 @@ class FrameLayout extends ViewGroup { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFrameLayout; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3918,12 +4156,13 @@ class FrameLayout extends ViewGroup { 'dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3962,41 +4201,47 @@ class FrameLayout extends ViewGroup { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - FrameLayout.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + FrameLayout.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4037,41 +4282,47 @@ class ViewGroup extends View { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ViewGroup.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ViewGroup.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4087,12 +4338,13 @@ class ViewGroup extends View { 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.addView'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, view], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, view]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4119,12 +4371,13 @@ class ViewGroup extends View { 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.removeView'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, view], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, view]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4156,20 +4409,15 @@ class VideoView extends View { factory VideoView({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onPrepared, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onCompletion, + void Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared, + void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion, required void Function( VideoView pigeon_instance, MediaPlayer player, int what, int extra, - ) onError, + ) + onError, }) { if (PigeonOverrides.videoView_new != null) { return PigeonOverrides.videoView_new!( @@ -4195,8 +4443,8 @@ class VideoView extends View { this.onCompletion, required this.onError, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4204,12 +4452,13 @@ class VideoView extends View { 'dev.flutter.pigeon.interactive_media_ads.VideoView.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4262,10 +4511,8 @@ class VideoView extends View { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onPrepared; + final void Function(VideoView pigeon_instance, MediaPlayer player)? + onPrepared; /// Callback to be invoked when playback of a media source has completed. /// @@ -4286,10 +4533,8 @@ class VideoView extends View { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onCompletion; + final void Function(VideoView pigeon_instance, MediaPlayer player)? + onCompletion; /// Callback to be invoked when there has been an error during an asynchronous /// operation. @@ -4316,59 +4561,66 @@ class VideoView extends View { MediaPlayer player, int what, int extra, - ) onError; + ) + onError; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onPrepared, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - )? onCompletion, + void Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared, + void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion, void Function( VideoView pigeon_instance, MediaPlayer player, int what, int extra, - )? onError, + )? + onError, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared was null.', + ); final List args = (message as List?)!; final VideoView? arg_pigeon_instance = (args[0] as VideoView?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared was null, expected non-null VideoView.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared was null, expected non-null VideoView.', + ); final MediaPlayer? arg_player = (args[1] as MediaPlayer?); - assert(arg_player != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared was null, expected non-null MediaPlayer.'); + assert( + arg_player != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onPrepared was null, expected non-null MediaPlayer.', + ); try { - (onPrepared ?? arg_pigeon_instance!.onPrepared) - ?.call(arg_pigeon_instance!, arg_player!); + (onPrepared ?? arg_pigeon_instance!.onPrepared)?.call( + arg_pigeon_instance!, + arg_player!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4377,31 +4629,41 @@ class VideoView extends View { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion was null.', + ); final List args = (message as List?)!; final VideoView? arg_pigeon_instance = (args[0] as VideoView?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion was null, expected non-null VideoView.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion was null, expected non-null VideoView.', + ); final MediaPlayer? arg_player = (args[1] as MediaPlayer?); - assert(arg_player != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion was null, expected non-null MediaPlayer.'); + assert( + arg_player != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onCompletion was null, expected non-null MediaPlayer.', + ); try { - (onCompletion ?? arg_pigeon_instance!.onCompletion) - ?.call(arg_pigeon_instance!, arg_player!); + (onCompletion ?? arg_pigeon_instance!.onCompletion)?.call( + arg_pigeon_instance!, + arg_player!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4410,37 +4672,53 @@ class VideoView extends View { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoView.onError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoView.onError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null.', + ); final List args = (message as List?)!; final VideoView? arg_pigeon_instance = (args[0] as VideoView?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null VideoView.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null VideoView.', + ); final MediaPlayer? arg_player = (args[1] as MediaPlayer?); - assert(arg_player != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null MediaPlayer.'); + assert( + arg_player != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null MediaPlayer.', + ); final int? arg_what = (args[2] as int?); - assert(arg_what != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null int.'); + assert( + arg_what != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null int.', + ); final int? arg_extra = (args[3] as int?); - assert(arg_extra != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null int.'); + assert( + arg_extra != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoView.onError was null, expected non-null int.', + ); try { - (onError ?? arg_pigeon_instance!.onError) - .call(arg_pigeon_instance!, arg_player!, arg_what!, arg_extra!); + (onError ?? arg_pigeon_instance!.onError).call( + arg_pigeon_instance!, + arg_player!, + arg_what!, + arg_extra!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4456,12 +4734,13 @@ class VideoView extends View { 'dev.flutter.pigeon.interactive_media_ads.VideoView.setVideoUri'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, uri], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, uri]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4488,12 +4767,13 @@ class VideoView extends View { 'dev.flutter.pigeon.interactive_media_ads.VideoView.getCurrentPosition'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4548,41 +4828,47 @@ class View extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - View.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + View.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4624,41 +4910,47 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - MediaPlayer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + MediaPlayer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4674,12 +4966,13 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.getDuration'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4709,12 +5002,13 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.seekTo'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, mSec], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, mSec]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4739,12 +5033,13 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.start'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4769,12 +5064,13 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pause'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4799,12 +5095,13 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.stop'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4844,8 +5141,9 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecVideoAdPlayerCallback = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecVideoAdPlayerCallback = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4855,41 +5153,47 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoAdPlayerCallback.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + VideoAdPlayerCallback.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4908,12 +5212,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onAdProgress'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo, videoProgressUpdate], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([this, adMediaInfo, videoProgressUpdate]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4938,12 +5243,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onBuffering'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4968,12 +5274,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onContentComplete'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4998,12 +5305,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onEnded'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5028,12 +5336,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5058,12 +5367,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onLoaded'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5088,12 +5398,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onPause'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5118,12 +5429,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onPlay'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5148,12 +5460,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onResume'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5170,10 +5483,7 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { } /// Fire this callback when the playback volume changes. - Future onVolumeChanged( - AdMediaInfo adMediaInfo, - int percentage, - ) async { + Future onVolumeChanged(AdMediaInfo adMediaInfo, int percentage) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoAdPlayerCallback; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5181,12 +5491,13 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.onVolumeChanged'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adMediaInfo, percentage], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adMediaInfo, percentage]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5222,29 +5533,35 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { required void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - ) addCallback, + ) + addCallback, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, AdPodInfo adPodInfo, - ) loadAd, + ) + loadAd, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, - ) pauseAd, + ) + pauseAd, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, - ) playAd, + ) + playAd, required void Function(VideoAdPlayer pigeon_instance) release, required void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - ) removeCallback, + ) + removeCallback, required void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, - ) stopAd, + ) + stopAd, }) { if (PigeonOverrides.videoAdPlayer_new != null) { return PigeonOverrides.videoAdPlayer_new!( @@ -5282,8 +5599,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { required this.removeCallback, required this.stopAd, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoAdPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5291,12 +5608,13 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -5356,7 +5674,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { final void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - ) addCallback; + ) + addCallback; /// Loads a video ad hosted at AdMediaInfo. /// @@ -5381,7 +5700,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, AdPodInfo adPodInfo, - ) loadAd; + ) + loadAd; /// Pauses playing the current ad. /// @@ -5402,10 +5722,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) pauseAd; + final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) + pauseAd; /// Starts or resumes playing the video ad referenced by the AdMediaInfo, /// provided loadAd has already been called for it. @@ -5427,10 +5745,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) playAd; + final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) + playAd; /// Cleans up and releases all resources used by the `VideoAdPlayer`. /// @@ -5475,7 +5791,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { final void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - ) removeCallback; + ) + removeCallback; /// Stops playing the current ad. /// @@ -5496,10 +5813,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) stopAd; + final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) + stopAd; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5508,65 +5823,72 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - )? addCallback, + )? + addCallback, void Function( VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, AdPodInfo adPodInfo, - )? loadAd, - void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - )? pauseAd, - void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - )? playAd, + )? + loadAd, + void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? + pauseAd, + void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? + playAd, void Function(VideoAdPlayer pigeon_instance)? release, void Function( VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback, - )? removeCallback, - void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - )? stopAd, + )? + removeCallback, + void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? + stopAd, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null, expected non-null VideoAdPlayer.', + ); final VideoAdPlayerCallback? arg_callback = (args[1] as VideoAdPlayerCallback?); - assert(arg_callback != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null, expected non-null VideoAdPlayerCallback.'); + assert( + arg_callback != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null, expected non-null VideoAdPlayerCallback.', + ); try { - (addCallback ?? arg_pigeon_instance!.addCallback) - .call(arg_pigeon_instance!, arg_callback!); + (addCallback ?? arg_pigeon_instance!.addCallback).call( + arg_pigeon_instance!, + arg_callback!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5575,35 +5897,48 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null VideoAdPlayer.', + ); final AdMediaInfo? arg_adMediaInfo = (args[1] as AdMediaInfo?); - assert(arg_adMediaInfo != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null AdMediaInfo.'); + assert( + arg_adMediaInfo != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null AdMediaInfo.', + ); final AdPodInfo? arg_adPodInfo = (args[2] as AdPodInfo?); - assert(arg_adPodInfo != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null AdPodInfo.'); + assert( + arg_adPodInfo != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null AdPodInfo.', + ); try { - (loadAd ?? arg_pigeon_instance!.loadAd) - .call(arg_pigeon_instance!, arg_adMediaInfo!, arg_adPodInfo!); + (loadAd ?? arg_pigeon_instance!.loadAd).call( + arg_pigeon_instance!, + arg_adMediaInfo!, + arg_adPodInfo!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5612,32 +5947,42 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null, expected non-null VideoAdPlayer.', + ); final AdMediaInfo? arg_adMediaInfo = (args[1] as AdMediaInfo?); - assert(arg_adMediaInfo != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null, expected non-null AdMediaInfo.'); + assert( + arg_adMediaInfo != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null, expected non-null AdMediaInfo.', + ); try { - (pauseAd ?? arg_pigeon_instance!.pauseAd) - .call(arg_pigeon_instance!, arg_adMediaInfo!); + (pauseAd ?? arg_pigeon_instance!.pauseAd).call( + arg_pigeon_instance!, + arg_adMediaInfo!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5646,32 +5991,42 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null, expected non-null VideoAdPlayer.', + ); final AdMediaInfo? arg_adMediaInfo = (args[1] as AdMediaInfo?); - assert(arg_adMediaInfo != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null, expected non-null AdMediaInfo.'); + assert( + arg_adMediaInfo != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null, expected non-null AdMediaInfo.', + ); try { - (playAd ?? arg_pigeon_instance!.playAd) - .call(arg_pigeon_instance!, arg_adMediaInfo!); + (playAd ?? arg_pigeon_instance!.playAd).call( + arg_pigeon_instance!, + arg_adMediaInfo!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5680,65 +6035,81 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release was null, expected non-null VideoAdPlayer.', + ); try { - (release ?? arg_pigeon_instance!.release) - .call(arg_pigeon_instance!); + (release ?? arg_pigeon_instance!.release).call( + arg_pigeon_instance!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null, expected non-null VideoAdPlayer.', + ); final VideoAdPlayerCallback? arg_callback = (args[1] as VideoAdPlayerCallback?); - assert(arg_callback != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null, expected non-null VideoAdPlayerCallback.'); + assert( + arg_callback != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null, expected non-null VideoAdPlayerCallback.', + ); try { - (removeCallback ?? arg_pigeon_instance!.removeCallback) - .call(arg_pigeon_instance!, arg_callback!); + (removeCallback ?? arg_pigeon_instance!.removeCallback).call( + arg_pigeon_instance!, + arg_callback!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5747,32 +6118,42 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null.', + ); final List args = (message as List?)!; final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null, expected non-null VideoAdPlayer.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null, expected non-null VideoAdPlayer.', + ); final AdMediaInfo? arg_adMediaInfo = (args[1] as AdMediaInfo?); - assert(arg_adMediaInfo != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null, expected non-null AdMediaInfo.'); + assert( + arg_adMediaInfo != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null, expected non-null AdMediaInfo.', + ); try { - (stopAd ?? arg_pigeon_instance!.stopAd) - .call(arg_pigeon_instance!, arg_adMediaInfo!); + (stopAd ?? arg_pigeon_instance!.stopAd).call( + arg_pigeon_instance!, + arg_adMediaInfo!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5788,12 +6169,13 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.setVolume'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5819,12 +6201,13 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.setAdProgress'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, progress], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, progress]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5866,11 +6249,13 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { required void Function( AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event, - ) onAdsManagerLoaded, + ) + onAdsManagerLoaded, }) { if (PigeonOverrides.adsLoadedListener_new != null) { return PigeonOverrides.adsLoadedListener_new!( - onAdsManagerLoaded: onAdsManagerLoaded); + onAdsManagerLoaded: onAdsManagerLoaded, + ); } return AdsLoadedListener.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -5885,8 +6270,8 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onAdsManagerLoaded, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsLoadedListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5894,12 +6279,13 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -5929,8 +6315,9 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecAdsLoadedListener = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecAdsLoadedListener = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// Called once the AdsManager or StreamManager has been loaded. /// @@ -5954,7 +6341,8 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { final void Function( AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event, - ) onAdsManagerLoaded; + ) + onAdsManagerLoaded; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5963,34 +6351,42 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { void Function( AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event, - )? onAdsManagerLoaded, + )? + onAdsManagerLoaded, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null.', + ); final List args = (message as List?)!; final AdsLoadedListener? arg_pigeon_instance = (args[0] as AdsLoadedListener?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null, expected non-null AdsLoadedListener.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null, expected non-null AdsLoadedListener.', + ); final AdsManagerLoadedEvent? arg_event = (args[1] as AdsManagerLoadedEvent?); - assert(arg_event != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null, expected non-null AdsManagerLoadedEvent.'); + assert( + arg_event != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null, expected non-null AdsManagerLoadedEvent.', + ); try { (onAdsManagerLoaded ?? arg_pigeon_instance!.onAdsManagerLoaded) .call(arg_pigeon_instance!, arg_event!); @@ -5999,7 +6395,8 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6023,10 +6420,8 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { factory AdErrorListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - AdErrorListener pigeon_instance, - AdErrorEvent event, - ) onAdError, + required void Function(AdErrorListener pigeon_instance, AdErrorEvent event) + onAdError, }) { if (PigeonOverrides.adErrorListener_new != null) { return PigeonOverrides.adErrorListener_new!(onAdError: onAdError); @@ -6044,8 +6439,8 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onAdError, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdErrorListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6053,12 +6448,13 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdErrorListener.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -6109,54 +6505,60 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - AdErrorListener pigeon_instance, - AdErrorEvent event, - ) onAdError; + final void Function(AdErrorListener pigeon_instance, AdErrorEvent event) + onAdError; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - AdErrorListener pigeon_instance, - AdErrorEvent event, - )? onAdError, + void Function(AdErrorListener pigeon_instance, AdErrorEvent event)? + onAdError, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null.', + ); final List args = (message as List?)!; final AdErrorListener? arg_pigeon_instance = (args[0] as AdErrorListener?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null, expected non-null AdErrorListener.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null, expected non-null AdErrorListener.', + ); final AdErrorEvent? arg_event = (args[1] as AdErrorEvent?); - assert(arg_event != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null, expected non-null AdErrorEvent.'); + assert( + arg_event != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null, expected non-null AdErrorEvent.', + ); try { - (onAdError ?? arg_pigeon_instance!.onAdError) - .call(arg_pigeon_instance!, arg_event!); + (onAdError ?? arg_pigeon_instance!.onAdError).call( + arg_pigeon_instance!, + arg_event!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6180,10 +6582,8 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { factory AdEventListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - AdEventListener pigeon_instance, - AdEvent event, - ) onAdEvent, + required void Function(AdEventListener pigeon_instance, AdEvent event) + onAdEvent, }) { if (PigeonOverrides.adEventListener_new != null) { return PigeonOverrides.adEventListener_new!(onAdEvent: onAdEvent); @@ -6201,8 +6601,8 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onAdEvent, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdEventListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6210,12 +6610,13 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdEventListener.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -6266,54 +6667,58 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - AdEventListener pigeon_instance, - AdEvent event, - ) onAdEvent; + final void Function(AdEventListener pigeon_instance, AdEvent event) onAdEvent; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - AdEventListener pigeon_instance, - AdEvent event, - )? onAdEvent, + void Function(AdEventListener pigeon_instance, AdEvent event)? onAdEvent, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null.', + ); final List args = (message as List?)!; final AdEventListener? arg_pigeon_instance = (args[0] as AdEventListener?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null, expected non-null AdEventListener.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null, expected non-null AdEventListener.', + ); final AdEvent? arg_event = (args[1] as AdEvent?); - assert(arg_event != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null, expected non-null AdEvent.'); + assert( + arg_event != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null, expected non-null AdEvent.', + ); try { - (onAdEvent ?? arg_pigeon_instance!.onAdEvent) - .call(arg_pigeon_instance!, arg_event!); + (onAdEvent ?? arg_pigeon_instance!.onAdEvent).call( + arg_pigeon_instance!, + arg_event!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6345,8 +6750,9 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecAdsRenderingSettings = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecAdsRenderingSettings = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -6356,41 +6762,47 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsRenderingSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + AdsRenderingSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6406,12 +6818,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.getBitrateKbps'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6442,12 +6855,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.getEnableCustomTabs'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6478,12 +6892,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.getEnablePreloading'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6516,12 +6931,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.getFocusSkipButtonWhenAvailable'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6551,12 +6967,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.getMimeTypes'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6589,12 +7006,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setBitrateKbps'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, bitrate], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, bitrate]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6622,12 +7040,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setEnableCustomTabs'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enableCustomTabs], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enableCustomTabs]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6656,12 +7075,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setEnablePreloading'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enablePreloading], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enablePreloading]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6684,7 +7104,8 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { /// /// Default is true. Future setFocusSkipButtonWhenAvailable( - bool enableFocusSkipButton) async { + bool enableFocusSkipButton, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRenderingSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6692,12 +7113,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setFocusSkipButtonWhenAvailable'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enableFocusSkipButton], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enableFocusSkipButton]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6727,12 +7149,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setLoadVideoTimeout'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, loadVideoTimeout], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, loadVideoTimeout]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6758,12 +7181,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setMimeTypes'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, mimeTypes], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, mimeTypes]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6789,12 +7213,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setPlayAdsAfterTime'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, time], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, time]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6819,12 +7244,13 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.setUiElements'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, uiElements], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, uiElements]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6898,75 +7324,95 @@ class AdProgressInfo extends PigeonInternalProxyApiBaseClass { double currentTime, double duration, int totalAds, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_adBreakDuration = (args[1] as double?); - assert(arg_adBreakDuration != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_adBreakDuration != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.', + ); final double? arg_adPeriodDuration = (args[2] as double?); - assert(arg_adPeriodDuration != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_adPeriodDuration != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_adPosition = (args[3] as int?); - assert(arg_adPosition != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_adPosition != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_currentTime = (args[4] as double?); - assert(arg_currentTime != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_currentTime != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.', + ); final double? arg_duration = (args[5] as double?); - assert(arg_duration != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_duration != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_totalAds = (args[6] as int?); - assert(arg_totalAds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_totalAds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adBreakDuration!, - arg_adPeriodDuration!, - arg_adPosition!, - arg_currentTime!, - arg_duration!, - arg_totalAds!) ?? - AdProgressInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adBreakDuration: arg_adBreakDuration!, - adPeriodDuration: arg_adPeriodDuration!, - adPosition: arg_adPosition!, - currentTime: arg_currentTime!, - duration: arg_duration!, - totalAds: arg_totalAds!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_adBreakDuration!, + arg_adPeriodDuration!, + arg_adPosition!, + arg_currentTime!, + arg_duration!, + arg_totalAds!, + ) ?? + AdProgressInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adBreakDuration: arg_adBreakDuration!, + adPeriodDuration: arg_adPeriodDuration!, + adPosition: arg_adPosition!, + currentTime: arg_currentTime!, + duration: arg_duration!, + totalAds: arg_totalAds!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7031,60 +7477,77 @@ class CompanionAd extends PigeonInternalProxyApiBaseClass { int height, String resourceValue, int width, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_apiFramework = (args[1] as String?); final int? arg_height = (args[2] as int?); - assert(arg_height != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_height != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_resourceValue = (args[3] as String?); - assert(arg_resourceValue != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_resourceValue != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null String.', + ); final int? arg_width = (args[4] as int?); - assert(arg_width != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_width != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_apiFramework, arg_height!, - arg_resourceValue!, arg_width!) ?? - CompanionAd.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - apiFramework: arg_apiFramework, - height: arg_height!, - resourceValue: arg_resourceValue!, - width: arg_width!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_apiFramework, + arg_height!, + arg_resourceValue!, + arg_width!, + ) ?? + CompanionAd.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + apiFramework: arg_apiFramework, + height: arg_height!, + resourceValue: arg_resourceValue!, + width: arg_width!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7134,56 +7597,64 @@ class UniversalAdId extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - UniversalAdId Function( - String adIdRegistry, - String adIdValue, - )? pigeon_newInstance, + UniversalAdId Function(String adIdRegistry, String adIdValue)? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_adIdRegistry = (args[1] as String?); - assert(arg_adIdRegistry != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_adIdRegistry != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null String.', + ); final String? arg_adIdValue = (args[2] as String?); - assert(arg_adIdValue != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_adIdValue != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adIdRegistry!, arg_adIdValue!) ?? - UniversalAdId.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adIdRegistry: arg_adIdRegistry!, - adIdValue: arg_adIdValue!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_adIdRegistry!, arg_adIdValue!) ?? + UniversalAdId.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adIdRegistry: arg_adIdRegistry!, + adIdValue: arg_adIdValue!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7361,177 +7832,232 @@ class Ad extends PigeonInternalProxyApiBaseClass { int width, bool isLinear, bool isSkippable, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + 'dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_adId = (args[1] as String?); - assert(arg_adId != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_adId != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final AdPodInfo? arg_adPodInfo = (args[2] as AdPodInfo?); - assert(arg_adPodInfo != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null AdPodInfo.'); + assert( + arg_adPodInfo != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null AdPodInfo.', + ); final String? arg_adSystem = (args[3] as String?); - assert(arg_adSystem != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_adSystem != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final List? arg_adWrapperCreativeIds = (args[4] as List?)?.cast(); - assert(arg_adWrapperCreativeIds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_adWrapperCreativeIds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', + ); final List? arg_adWrapperIds = (args[5] as List?)?.cast(); - assert(arg_adWrapperIds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_adWrapperIds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', + ); final List? arg_adWrapperSystems = (args[6] as List?)?.cast(); - assert(arg_adWrapperSystems != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_adWrapperSystems != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', + ); final String? arg_advertiserName = (args[7] as String?); - assert(arg_advertiserName != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_advertiserName != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final List? arg_companionAds = (args[8] as List?)?.cast(); - assert(arg_companionAds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_companionAds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', + ); final String? arg_contentType = (args[9] as String?); final String? arg_creativeAdId = (args[10] as String?); - assert(arg_creativeAdId != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_creativeAdId != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final String? arg_creativeId = (args[11] as String?); - assert(arg_creativeId != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_creativeId != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final String? arg_dealId = (args[12] as String?); - assert(arg_dealId != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_dealId != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final String? arg_description = (args[13] as String?); final double? arg_duration = (args[14] as double?); - assert(arg_duration != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_duration != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_height = (args[15] as int?); - assert(arg_height != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_height != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_skipTimeOffset = (args[16] as double?); - assert(arg_skipTimeOffset != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_skipTimeOffset != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null double.', + ); final String? arg_surveyUrl = (args[17] as String?); final String? arg_title = (args[18] as String?); final String? arg_traffickingParameters = (args[19] as String?); - assert(arg_traffickingParameters != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_traffickingParameters != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', + ); final List? arg_uiElements = (args[20] as List?)?.cast(); - assert(arg_uiElements != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_uiElements != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', + ); final List? arg_universalAdIds = (args[21] as List?)?.cast(); - assert(arg_universalAdIds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_universalAdIds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', + ); final int? arg_vastMediaBitrate = (args[22] as int?); - assert(arg_vastMediaBitrate != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_vastMediaBitrate != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_vastMediaHeight = (args[23] as int?); - assert(arg_vastMediaHeight != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_vastMediaHeight != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_vastMediaWidth = (args[24] as int?); - assert(arg_vastMediaWidth != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_vastMediaWidth != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_width = (args[25] as int?); - assert(arg_width != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_width != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null int.', + ); final bool? arg_isLinear = (args[26] as bool?); - assert(arg_isLinear != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_isLinear != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null bool.', + ); final bool? arg_isSkippable = (args[27] as bool?); - assert(arg_isSkippable != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_isSkippable != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null bool.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adId!, - arg_adPodInfo!, - arg_adSystem!, - arg_adWrapperCreativeIds!, - arg_adWrapperIds!, - arg_adWrapperSystems!, - arg_advertiserName!, - arg_companionAds!, - arg_contentType, - arg_creativeAdId!, - arg_creativeId!, - arg_dealId!, - arg_description, - arg_duration!, - arg_height!, - arg_skipTimeOffset!, - arg_surveyUrl, - arg_title, - arg_traffickingParameters!, - arg_uiElements!, - arg_universalAdIds!, - arg_vastMediaBitrate!, - arg_vastMediaHeight!, - arg_vastMediaWidth!, - arg_width!, - arg_isLinear!, - arg_isSkippable!) ?? - Ad.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adId: arg_adId!, - adPodInfo: arg_adPodInfo!, - adSystem: arg_adSystem!, - adWrapperCreativeIds: arg_adWrapperCreativeIds!, - adWrapperIds: arg_adWrapperIds!, - adWrapperSystems: arg_adWrapperSystems!, - advertiserName: arg_advertiserName!, - companionAds: arg_companionAds!, - contentType: arg_contentType, - creativeAdId: arg_creativeAdId!, - creativeId: arg_creativeId!, - dealId: arg_dealId!, - description: arg_description, - duration: arg_duration!, - height: arg_height!, - skipTimeOffset: arg_skipTimeOffset!, - surveyUrl: arg_surveyUrl, - title: arg_title, - traffickingParameters: arg_traffickingParameters!, - uiElements: arg_uiElements!, - universalAdIds: arg_universalAdIds!, - vastMediaBitrate: arg_vastMediaBitrate!, - vastMediaHeight: arg_vastMediaHeight!, - vastMediaWidth: arg_vastMediaWidth!, - width: arg_width!, - isLinear: arg_isLinear!, - isSkippable: arg_isSkippable!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_adId!, + arg_adPodInfo!, + arg_adSystem!, + arg_adWrapperCreativeIds!, + arg_adWrapperIds!, + arg_adWrapperSystems!, + arg_advertiserName!, + arg_companionAds!, + arg_contentType, + arg_creativeAdId!, + arg_creativeId!, + arg_dealId!, + arg_description, + arg_duration!, + arg_height!, + arg_skipTimeOffset!, + arg_surveyUrl, + arg_title, + arg_traffickingParameters!, + arg_uiElements!, + arg_universalAdIds!, + arg_vastMediaBitrate!, + arg_vastMediaHeight!, + arg_vastMediaWidth!, + arg_width!, + arg_isLinear!, + arg_isSkippable!, + ) ?? + Ad.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adId: arg_adId!, + adPodInfo: arg_adPodInfo!, + adSystem: arg_adSystem!, + adWrapperCreativeIds: arg_adWrapperCreativeIds!, + adWrapperIds: arg_adWrapperIds!, + adWrapperSystems: arg_adWrapperSystems!, + advertiserName: arg_advertiserName!, + companionAds: arg_companionAds!, + contentType: arg_contentType, + creativeAdId: arg_creativeAdId!, + creativeId: arg_creativeId!, + dealId: arg_dealId!, + description: arg_description, + duration: arg_duration!, + height: arg_height!, + skipTimeOffset: arg_skipTimeOffset!, + surveyUrl: arg_surveyUrl, + title: arg_title, + traffickingParameters: arg_traffickingParameters!, + uiElements: arg_uiElements!, + universalAdIds: arg_universalAdIds!, + vastMediaBitrate: arg_vastMediaBitrate!, + vastMediaHeight: arg_vastMediaHeight!, + vastMediaWidth: arg_vastMediaWidth!, + width: arg_width!, + isLinear: arg_isLinear!, + isSkippable: arg_isSkippable!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7582,11 +8108,12 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, required void Function(CompanionAdSlotClickListener pigeon_instance) - onCompanionAdClick, + onCompanionAdClick, }) { if (PigeonOverrides.companionAdSlotClickListener_new != null) { return PigeonOverrides.companionAdSlotClickListener_new!( - onCompanionAdClick: onCompanionAdClick); + onCompanionAdClick: onCompanionAdClick, + ); } return CompanionAdSlotClickListener.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -7601,8 +8128,8 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onCompanionAdClick, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlotClickListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -7610,12 +8137,13 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -7645,7 +8173,7 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCompanionAdSlotClickListener = + _pigeonVar_codecCompanionAdSlotClickListener = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Respond to a click on this companion ad slot. @@ -7668,37 +8196,42 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final void Function(CompanionAdSlotClickListener pigeon_instance) - onCompanionAdClick; + onCompanionAdClick; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, void Function(CompanionAdSlotClickListener pigeon_instance)? - onCompanionAdClick, + onCompanionAdClick, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick was null.', + ); final List args = (message as List?)!; final CompanionAdSlotClickListener? arg_pigeon_instance = (args[0] as CompanionAdSlotClickListener?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick was null, expected non-null CompanionAdSlotClickListener.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick was null, expected non-null CompanionAdSlotClickListener.', + ); try { (onCompanionAdClick ?? arg_pigeon_instance!.onCompanionAdClick) .call(arg_pigeon_instance!); @@ -7707,7 +8240,8 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7749,41 +8283,47 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CompanionAdSlot.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + CompanionAdSlot.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7792,7 +8332,8 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { /// Registers a listener for companion clicks. Future addClickListener( - CompanionAdSlotClickListener clickListener) async { + CompanionAdSlotClickListener clickListener, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -7800,12 +8341,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.addClickListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, clickListener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, clickListener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7830,12 +8372,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.getContainer'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7865,12 +8408,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.getHeight'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7900,12 +8444,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.getWidth'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7935,12 +8480,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.isFilled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7963,7 +8509,8 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { /// Removes a listener for companion clicks. Future removeClickListener( - CompanionAdSlotClickListener clickListener) async { + CompanionAdSlotClickListener clickListener, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -7971,12 +8518,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.removeClickListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, clickListener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, clickListener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8003,12 +8551,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.setContainer'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, container], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, container]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8027,10 +8576,7 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { /// Sets the size of the slot. /// /// Only companions matching the slot size will be displayed in the slot. - Future setSize( - int width, - int height, - ) async { + Future setSize(int width, int height) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -8038,12 +8584,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.setSize'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, width, height], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, width, height]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8071,12 +8618,13 @@ class CompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.setFluidSize'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/interactive_media_ads/lib/src/android/interactive_media_ads_proxy.dart b/packages/interactive_media_ads/lib/src/android/interactive_media_ads_proxy.dart index e2349ec2fa8..812c4b77ce7 100644 --- a/packages/interactive_media_ads/lib/src/android/interactive_media_ads_proxy.dart +++ b/packages/interactive_media_ads/lib/src/android/interactive_media_ads_proxy.dart @@ -39,7 +39,8 @@ class InteractiveMediaAdsProxy { final VideoProgressUpdate Function({ required int currentTimeMs, required int durationMs, - }) newVideoProgressUpdate; + }) + newVideoProgressUpdate; /// Constructs [FrameLayout]. final FrameLayout Function() newFrameLayout; @@ -49,7 +50,8 @@ class InteractiveMediaAdsProxy { required void Function(VideoView, MediaPlayer, int, int) onError, void Function(VideoView, MediaPlayer)? onPrepared, void Function(VideoView, MediaPlayer)? onCompletion, - }) newVideoView; + }) + newVideoView; /// Constructs [VideoAdPlayer]. final VideoAdPlayer Function({ @@ -60,32 +62,37 @@ class InteractiveMediaAdsProxy { required void Function(VideoAdPlayer) release, required void Function(VideoAdPlayer, VideoAdPlayerCallback) removeCallback, required void Function(VideoAdPlayer, AdMediaInfo) stopAd, - }) newVideoAdPlayer; + }) + newVideoAdPlayer; /// Constructs [AdsLoadedListener]. final AdsLoadedListener Function({ required void Function(AdsLoadedListener, AdsManagerLoadedEvent) - onAdsManagerLoaded, - }) newAdsLoadedListener; + onAdsManagerLoaded, + }) + newAdsLoadedListener; /// Constructs [AdErrorListener]. final AdErrorListener Function({ required void Function(AdErrorListener, AdErrorEvent) onAdError, - }) newAdErrorListener; + }) + newAdErrorListener; /// Constructs [AdEventListener]. final AdEventListener Function({ required void Function(AdEventListener, AdEvent) onAdEvent, - }) newAdEventListener; + }) + newAdEventListener; /// Constructs [CompanionAdSlotClickListener]. final CompanionAdSlotClickListener Function({ required void Function(CompanionAdSlotClickListener) onCompanionAdClick, - }) newCompanionAdSlotClickListener; + }) + newCompanionAdSlotClickListener; /// Calls to [ImaSdkFactory.createAdDisplayContainer]. final Future Function(ViewGroup, VideoAdPlayer) - createAdDisplayContainerImaSdkFactory; + createAdDisplayContainerImaSdkFactory; /// Calls to [ImaSdkFactory.instance]. final ImaSdkFactory Function() instanceImaSdkFactory; diff --git a/packages/interactive_media_ads/lib/src/companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/companion_ad_slot.dart index 407bf2332df..ccc9a961122 100644 --- a/packages/interactive_media_ads/lib/src/companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/companion_ad_slot.dart @@ -37,11 +37,11 @@ class CompanionAdSlot { required CompanionAdSlotSize size, void Function()? onClicked, }) : this.fromPlatformCreationParams( - params: PlatformCompanionAdSlotCreationParams( - size: size, - onClicked: onClicked, - ), - ); + params: PlatformCompanionAdSlotCreationParams( + size: size, + onClicked: onClicked, + ), + ); /// Constructs a [CompanionAdSlot] from creation params for a specific /// platform. diff --git a/packages/interactive_media_ads/lib/src/content_progress_provider.dart b/packages/interactive_media_ads/lib/src/content_progress_provider.dart index 0b0f0e6df8b..55e8b21f57d 100644 --- a/packages/interactive_media_ads/lib/src/content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/content_progress_provider.dart @@ -35,9 +35,9 @@ class ContentProgressProvider { /// See [ContentProgressProvider.fromPlatformCreationParams] for setting /// parameters for a specific platform. ContentProgressProvider() - : this.fromPlatformCreationParams( - const PlatformContentProgressProviderCreationParams(), - ); + : this.fromPlatformCreationParams( + const PlatformContentProgressProviderCreationParams(), + ); /// Constructs an [ContentProgressProvider] from creation params for a /// specific platform. diff --git a/packages/interactive_media_ads/lib/src/ima_settings.dart b/packages/interactive_media_ads/lib/src/ima_settings.dart index e9e41133bd7..637218fb617 100644 --- a/packages/interactive_media_ads/lib/src/ima_settings.dart +++ b/packages/interactive_media_ads/lib/src/ima_settings.dart @@ -33,9 +33,9 @@ import 'platform_interface/platform_interface.dart'; class ImaSettings { /// Creates an [ImaSettings]. ImaSettings({String? language}) - : this.fromPlatformCreationParams( - PlatformImaSettingsCreationParams(language: language), - ); + : this.fromPlatformCreationParams( + PlatformImaSettingsCreationParams(language: language), + ); /// Constructs an [ImaSettings] from creation params for a specific platform. /// diff --git a/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart b/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart index 0b3b490a609..4b62ebad694 100644 --- a/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart +++ b/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart @@ -21,8 +21,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -46,17 +49,18 @@ class PigeonOverrides { required UIView adContainer, List? companionSlots, UIViewController? adContainerViewController, - })? iMAAdDisplayContainer_new; + })? + iMAAdDisplayContainer_new; /// Overrides [UIView.new]. static UIView Function()? uIView_new; /// Overrides [UIViewController.new]. - static UIViewController Function( - {void Function( - UIViewController pigeon_instance, - bool animated, - )? viewDidAppear})? uIViewController_new; + static UIViewController Function({ + void Function(UIViewController pigeon_instance, bool animated)? + viewDidAppear, + })? + uIViewController_new; /// Overrides [IMAContentPlayhead.new]. static IMAContentPlayhead Function()? iMAContentPlayhead_new; @@ -72,14 +76,16 @@ class PigeonOverrides { required String adTagUrl, required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, - })? iMAAdsRequest_new; + })? + iMAAdsRequest_new; /// Overrides [IMAAdsRequest.withAdsResponse]. static IMAAdsRequest Function({ required String adsResponse, required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, - })? iMAAdsRequest_withAdsResponse; + })? + iMAAdsRequest_withAdsResponse; /// Overrides [IMAAdsLoaderDelegate.new]. static IMAAdsLoaderDelegate Function({ @@ -87,13 +93,16 @@ class PigeonOverrides { IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData, - ) adLoaderLoadedWith, + ) + adLoaderLoadedWith, required void Function( IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdLoadingErrorData adErrorData, - ) adsLoaderFailedWithErrorData, - })? iMAAdsLoaderDelegate_new; + ) + adsLoaderFailedWithErrorData, + })? + iMAAdsLoaderDelegate_new; /// Overrides [IMAAdsManagerDelegate.new]. static IMAAdsManagerDelegate Function({ @@ -101,21 +110,26 @@ class PigeonOverrides { IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdEvent event, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdError error, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - ) didRequestContentPause, + ) + didRequestContentPause, required void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - ) didRequestContentResume, - })? iMAAdsManagerDelegate_new; + ) + didRequestContentResume, + })? + iMAAdsManagerDelegate_new; /// Overrides [IMAAdsRenderingSettings.new]. static IMAAdsRenderingSettings Function()? iMAAdsRenderingSettings_new; @@ -125,18 +139,20 @@ class PigeonOverrides { required UIView view, required FriendlyObstructionPurpose purpose, String? detailedReason, - })? iMAFriendlyObstruction_new; + })? + iMAFriendlyObstruction_new; /// Overrides [IMACompanionAdSlot.new]. static IMACompanionAdSlot Function({required UIView view})? - iMACompanionAdSlot_new; + iMACompanionAdSlot_new; /// Overrides [IMACompanionAdSlot.size]. static IMACompanionAdSlot Function({ required UIView view, required int width, required int height, - })? iMACompanionAdSlot_size; + })? + iMACompanionAdSlot_size; /// Overrides [IMACompanionDelegate.new]. static IMACompanionDelegate Function({ @@ -144,12 +160,15 @@ class PigeonOverrides { IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled, - )? companionAdSlotFilled, + )? + companionAdSlotFilled, void Function( IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, - )? companionSlotWasClicked, - })? iMACompanionDelegate_new; + )? + companionSlotWasClicked, + })? + iMACompanionDelegate_new; /// Sets all overridden ProxyApi class members to null. static void pigeon_reset() { @@ -183,7 +202,7 @@ abstract class PigeonInternalProxyApiBaseClass { this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -254,7 +273,7 @@ class PigeonInstanceManager { // HashMap). final Expando _identifiers = Expando(); final Map> - _weakInstances = >{}; + _weakInstances = >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -279,48 +298,69 @@ class PigeonInstanceManager { }, ); _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager); + instanceManager: instanceManager, + ); IMAAdDisplayContainer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); UIView.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); UIViewController.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAContentPlayhead.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsLoader.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMASettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsLoaderDelegate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsLoadedData.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdLoadingErrorData.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsManagerDelegate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdsRenderingSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); NSObject.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAFriendlyObstruction.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMACompanionAd.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMACompanionAdSlot.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMACompanionDelegate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); IMAAdPodInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); return instanceManager; } @@ -337,8 +377,9 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = - WeakReference(instance); + _weakInstances[identifier] = WeakReference( + instance, + ); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -400,7 +441,8 @@ class PigeonInstanceManager { /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. T? getInstanceWithWeakReference( - int identifier) { + int identifier, + ) { final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; @@ -435,7 +477,9 @@ class PigeonInstanceManager { /// Throws assertion error if the instance or its identifier has already been /// added. void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, int identifier) { + PigeonInternalProxyApiBaseClass instance, + int identifier, + ) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -464,7 +508,7 @@ class PigeonInstanceManager { class _PigeonInternalInstanceManagerApi { /// Constructor for [_PigeonInternalInstanceManagerApi]. _PigeonInternalInstanceManagerApi({BinaryMessenger? binaryMessenger}) - : pigeonVar_binaryMessenger = binaryMessenger; + : pigeonVar_binaryMessenger = binaryMessenger; final BinaryMessenger? pigeonVar_binaryMessenger; @@ -476,31 +520,37 @@ class _PigeonInternalInstanceManagerApi { PigeonInstanceManager? instanceManager, }) { { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null.', + ); final List args = (message as List?)!; final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.'); + assert( + arg_identifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', + ); try { - (instanceManager ?? PigeonInstanceManager.instance) - .remove(arg_identifier!); + (instanceManager ?? PigeonInstanceManager.instance).remove( + arg_identifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -512,12 +562,13 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [identifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([identifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -541,10 +592,10 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.clear'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -579,8 +630,9 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager - .getInstanceWithWeakReference(readValue(buffer)! as int); + return instanceManager.getInstanceWithWeakReference( + readValue(buffer)! as int, + ); default: return super.readValueOfType(type, buffer); } @@ -979,8 +1031,8 @@ class IMAAdDisplayContainer extends NSObject { this.companionSlots, UIViewController? adContainerViewController, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdDisplayContainer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -988,17 +1040,17 @@ class IMAAdDisplayContainer extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([ - pigeonVar_instanceIdentifier, - adContainer, - companionSlots, - adContainerViewController - ]); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + adContainer, + companionSlots, + adContainerViewController, + ]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1029,8 +1081,9 @@ class IMAAdDisplayContainer extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdDisplayContainer = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMAAdDisplayContainer = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// View containing the video display and ad related UI. /// @@ -1048,52 +1101,64 @@ class IMAAdDisplayContainer extends NSObject { IMAAdDisplayContainer Function( UIView adContainer, List? companionSlots, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null, expected non-null int.', + ); final UIView? arg_adContainer = (args[1] as UIView?); - assert(arg_adContainer != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null, expected non-null UIView.'); + assert( + arg_adContainer != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null, expected non-null UIView.', + ); final List? arg_companionSlots = (args[2] as List?)?.cast(); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adContainer!, arg_companionSlots) ?? - IMAAdDisplayContainer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adContainer: arg_adContainer!, - companionSlots: arg_companionSlots, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_adContainer!, + arg_companionSlots, + ) ?? + IMAAdDisplayContainer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adContainer: arg_adContainer!, + companionSlots: arg_companionSlots, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1102,7 +1167,8 @@ class IMAAdDisplayContainer extends NSObject { /// View controller containing the ad container. Future setAdContainerViewController( - UIViewController? controller) async { + UIViewController? controller, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdDisplayContainer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1110,12 +1176,13 @@ class IMAAdDisplayContainer extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.setAdContainerViewController'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, controller], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, controller]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1140,12 +1207,13 @@ class IMAAdDisplayContainer extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.getAdContainerViewController'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1164,7 +1232,8 @@ class IMAAdDisplayContainer extends NSObject { /// Registers a view that overlays or obstructs this container as “friendly” /// for viewability measurement purposes. Future registerFriendlyObstruction( - IMAFriendlyObstruction friendlyObstruction) async { + IMAFriendlyObstruction friendlyObstruction, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdDisplayContainer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1172,12 +1241,13 @@ class IMAAdDisplayContainer extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.registerFriendlyObstruction'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, friendlyObstruction], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, friendlyObstruction]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1202,12 +1272,13 @@ class IMAAdDisplayContainer extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.unregisterAllFriendlyObstructions'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1256,8 +1327,8 @@ class UIView extends NSObject { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecUIView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1265,12 +1336,13 @@ class UIView extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1309,41 +1381,47 @@ class UIView extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - UIView.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + UIView.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1366,14 +1444,13 @@ class UIViewController extends NSObject { factory UIViewController({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - UIViewController pigeon_instance, - bool animated, - )? viewDidAppear, + void Function(UIViewController pigeon_instance, bool animated)? + viewDidAppear, }) { if (PigeonOverrides.uIViewController_new != null) { return PigeonOverrides.uIViewController_new!( - viewDidAppear: viewDidAppear); + viewDidAppear: viewDidAppear, + ); } return UIViewController.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -1388,8 +1465,8 @@ class UIViewController extends NSObject { super.pigeon_instanceManager, this.viewDidAppear, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecUIViewController; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1397,12 +1474,13 @@ class UIViewController extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1453,10 +1531,8 @@ class UIViewController extends NSObject { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - UIViewController pigeon_instance, - bool animated, - )? viewDidAppear; + final void Function(UIViewController pigeon_instance, bool animated)? + viewDidAppear; /// Retrieves the view that the controller manages. /// @@ -1471,83 +1547,96 @@ class UIViewController extends NSObject { BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, UIViewController Function()? pigeon_newInstance, - void Function( - UIViewController pigeon_instance, - bool animated, - )? viewDidAppear, + void Function(UIViewController pigeon_instance, bool animated)? + viewDidAppear, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - UIViewController.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + UIViewController.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null.', + ); final List args = (message as List?)!; final UIViewController? arg_pigeon_instance = (args[0] as UIViewController?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null, expected non-null UIViewController.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null, expected non-null UIViewController.', + ); final bool? arg_animated = (args[1] as bool?); - assert(arg_animated != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null, expected non-null bool.'); + assert( + arg_animated != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null, expected non-null bool.', + ); try { - (viewDidAppear ?? arg_pigeon_instance!.viewDidAppear) - ?.call(arg_pigeon_instance!, arg_animated!); + (viewDidAppear ?? arg_pigeon_instance!.viewDidAppear)?.call( + arg_pigeon_instance!, + arg_animated!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1562,19 +1651,20 @@ class UIViewController extends NSObject { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecUIViewController; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(pigeonVar_instance); () async { const String pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.UIViewController.view'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1625,8 +1715,8 @@ class IMAContentPlayhead extends NSObject { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAContentPlayhead; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1634,12 +1724,13 @@ class IMAContentPlayhead extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1668,8 +1759,9 @@ class IMAContentPlayhead extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAContentPlayhead = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMAContentPlayhead = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -1679,41 +1771,47 @@ class IMAContentPlayhead extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAContentPlayhead.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMAContentPlayhead.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1729,12 +1827,13 @@ class IMAContentPlayhead extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.setCurrentTime'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, timeInterval], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, timeInterval]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1784,8 +1883,8 @@ class IMAAdsLoader extends NSObject { super.pigeon_instanceManager, IMASettings? settings, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1793,12 +1892,13 @@ class IMAAdsLoader extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, settings], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([pigeonVar_instanceIdentifier, settings]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1837,41 +1937,47 @@ class IMAAdsLoader extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsLoader.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMAAdsLoader.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1887,12 +1993,13 @@ class IMAAdsLoader extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.contentComplete'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1917,12 +2024,13 @@ class IMAAdsLoader extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.requestAds'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, request], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, request]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1949,12 +2057,13 @@ class IMAAdsLoader extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.setDelegate'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, delegate], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, delegate]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2001,8 +2110,8 @@ class IMASettings extends NSObject { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -2010,12 +2119,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -2054,41 +2164,47 @@ class IMASettings extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMASettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMASettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2104,12 +2220,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPPID'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, ppid], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, ppid]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2140,12 +2257,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setLanguage'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, language], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, language]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2176,12 +2294,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setMaxRedirects'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, max], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, max]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2206,12 +2325,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setFeatureFlags'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, flags], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, flags]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2238,12 +2358,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setEnableBackgroundPlayback'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2270,12 +2391,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setAutoPlayAdBreaks'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, autoPlay], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, autoPlay]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2305,12 +2427,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setDisableNowPlayingInfo'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, disable], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, disable]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2335,12 +2458,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPlayerType'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, type], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, type]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2365,12 +2489,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPlayerVersion'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, version], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, version]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2399,12 +2524,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setSessionID'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, sessionID], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, sessionID]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2433,12 +2559,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setSameAppKeyEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2469,12 +2596,13 @@ class IMASettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setEnableDebugMode'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enable], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enable]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2548,8 +2676,8 @@ class IMAAdsRequest extends NSObject { required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -2557,17 +2685,18 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [ + pigeonVar_instanceIdentifier, + adTagUrl, + adDisplayContainer, + contentPlayhead, + ], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - adTagUrl, - adDisplayContainer, - contentPlayhead - ]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -2630,8 +2759,8 @@ class IMAAdsRequest extends NSObject { required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -2639,17 +2768,18 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.withAdsResponse'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [ + pigeonVar_instanceIdentifier, + adsResponse, + adDisplayContainer, + contentPlayhead, + ], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - adsResponse, - adDisplayContainer, - contentPlayhead - ]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -2688,41 +2818,47 @@ class IMAAdsRequest extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMAAdsRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2740,12 +2876,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.getAdTagUrl'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2771,12 +2908,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.getAdsResponse'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2801,12 +2939,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.getAdDisplayContainer'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2839,12 +2978,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setAdWillAutoPlay'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adWillAutoPlay], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adWillAutoPlay]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2872,12 +3012,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setAdWillPlayMuted'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adWillPlayMuted], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adWillPlayMuted]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2906,12 +3047,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContinuousPlayback'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, continuousPlayback], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, continuousPlayback]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2938,12 +3080,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentDuration'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, duration], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, duration]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2970,12 +3113,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentKeywords'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, keywords], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, keywords]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3002,12 +3146,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentTitle'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, title], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, title]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3036,12 +3181,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentURL'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, contentURL], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, contentURL]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3069,12 +3215,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setVastLoadTimeout'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, timeout], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, timeout]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3103,12 +3250,13 @@ class IMAAdsRequest extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setLiveStreamPrefetchSeconds'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, seconds], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, seconds]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3144,12 +3292,14 @@ class IMAAdsLoaderDelegate extends NSObject { IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData, - ) adLoaderLoadedWith, + ) + adLoaderLoadedWith, required void Function( IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdLoadingErrorData adErrorData, - ) adsLoaderFailedWithErrorData, + ) + adsLoaderFailedWithErrorData, }) { if (PigeonOverrides.iMAAdsLoaderDelegate_new != null) { return PigeonOverrides.iMAAdsLoaderDelegate_new!( @@ -3172,8 +3322,8 @@ class IMAAdsLoaderDelegate extends NSObject { required this.adLoaderLoadedWith, required this.adsLoaderFailedWithErrorData, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoaderDelegate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3181,12 +3331,13 @@ class IMAAdsLoaderDelegate extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3217,8 +3368,9 @@ class IMAAdsLoaderDelegate extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdsLoaderDelegate = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMAAdsLoaderDelegate = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// Called when ads are successfully loaded from the ad servers by the loader. /// @@ -3243,7 +3395,8 @@ class IMAAdsLoaderDelegate extends NSObject { IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData, - ) adLoaderLoadedWith; + ) + adLoaderLoadedWith; /// Error reported by the ads loader when loading or requesting an ad fails. /// @@ -3268,7 +3421,8 @@ class IMAAdsLoaderDelegate extends NSObject { IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdLoadingErrorData adErrorData, - ) adsLoaderFailedWithErrorData; + ) + adsLoaderFailedWithErrorData; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -3278,42 +3432,53 @@ class IMAAdsLoaderDelegate extends NSObject { IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData, - )? adLoaderLoadedWith, + )? + adLoaderLoadedWith, void Function( IMAAdsLoaderDelegate pigeon_instance, IMAAdsLoader loader, IMAAdLoadingErrorData adErrorData, - )? adsLoaderFailedWithErrorData, + )? + adsLoaderFailedWithErrorData, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null.', + ); final List args = (message as List?)!; final IMAAdsLoaderDelegate? arg_pigeon_instance = (args[0] as IMAAdsLoaderDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoaderDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoaderDelegate.', + ); final IMAAdsLoader? arg_loader = (args[1] as IMAAdsLoader?); - assert(arg_loader != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoader.'); + assert( + arg_loader != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoader.', + ); final IMAAdsLoadedData? arg_adsLoadedData = (args[2] as IMAAdsLoadedData?); - assert(arg_adsLoadedData != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoadedData.'); + assert( + arg_adsLoadedData != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoadedData.', + ); try { (adLoaderLoadedWith ?? arg_pigeon_instance!.adLoaderLoadedWith) .call(arg_pigeon_instance!, arg_loader!, arg_adsLoadedData!); @@ -3322,37 +3487,46 @@ class IMAAdsLoaderDelegate extends NSObject { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null.', + ); final List args = (message as List?)!; final IMAAdsLoaderDelegate? arg_pigeon_instance = (args[0] as IMAAdsLoaderDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdsLoaderDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdsLoaderDelegate.', + ); final IMAAdsLoader? arg_loader = (args[1] as IMAAdsLoader?); - assert(arg_loader != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdsLoader.'); + assert( + arg_loader != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdsLoader.', + ); final IMAAdLoadingErrorData? arg_adErrorData = (args[2] as IMAAdLoadingErrorData?); - assert(arg_adErrorData != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdLoadingErrorData.'); + assert( + arg_adErrorData != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdLoadingErrorData.', + ); try { (adsLoaderFailedWithErrorData ?? arg_pigeon_instance!.adsLoaderFailedWithErrorData) @@ -3362,7 +3536,8 @@ class IMAAdsLoaderDelegate extends NSObject { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3408,43 +3583,49 @@ class IMAAdsLoadedData extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoadedData.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoadedData.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoadedData.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoadedData.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoadedData.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoadedData.pigeon_newInstance was null, expected non-null int.', + ); final IMAAdsManager? arg_adsManager = (args[1] as IMAAdsManager?); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adsManager) ?? - IMAAdsLoadedData.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adsManager: arg_adsManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_adsManager) ?? + IMAAdsLoadedData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adsManager: arg_adsManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3487,45 +3668,53 @@ class IMAAdLoadingErrorData extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null, expected non-null int.', + ); final IMAAdError? arg_adError = (args[1] as IMAAdError?); - assert(arg_adError != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null, expected non-null IMAAdError.'); + assert( + arg_adError != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null, expected non-null IMAAdError.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adError!) ?? - IMAAdLoadingErrorData.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adError: arg_adError!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_adError!) ?? + IMAAdLoadingErrorData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adError: arg_adError!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3572,59 +3761,66 @@ class IMAAdError extends NSObject { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - IMAAdError Function( - AdErrorType type, - AdErrorCode code, - String? message, - )? pigeon_newInstance, + IMAAdError Function(AdErrorType type, AdErrorCode code, String? message)? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null, expected non-null int.', + ); final AdErrorType? arg_type = (args[1] as AdErrorType?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null, expected non-null AdErrorType.'); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null, expected non-null AdErrorType.', + ); final AdErrorCode? arg_code = (args[2] as AdErrorCode?); - assert(arg_code != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null, expected non-null AdErrorCode.'); + assert( + arg_code != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdError.pigeon_newInstance was null, expected non-null AdErrorCode.', + ); final String? arg_message = (args[3] as String?); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_type!, arg_code!, arg_message) ?? - IMAAdError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - code: arg_code!, - message: arg_message, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_type!, arg_code!, arg_message) ?? + IMAAdError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + code: arg_code!, + message: arg_message, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3668,41 +3864,47 @@ class IMAAdsManager extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMAAdsManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3718,12 +3920,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.setDelegate'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, delegate], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, delegate]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3748,12 +3951,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.initialize'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, adsRenderingSettings], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, adsRenderingSettings]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3778,12 +3982,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.start'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3808,12 +4013,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pause'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3838,12 +4044,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.resume'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3869,12 +4076,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.skip'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3899,12 +4107,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.discardAdBreak'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3929,12 +4138,13 @@ class IMAAdsManager extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.destroy'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3970,20 +4180,24 @@ class IMAAdsManagerDelegate extends NSObject { IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdEvent event, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdError error, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - ) didRequestContentPause, + ) + didRequestContentPause, required void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - ) didRequestContentResume, + ) + didRequestContentResume, }) { if (PigeonOverrides.iMAAdsManagerDelegate_new != null) { return PigeonOverrides.iMAAdsManagerDelegate_new!( @@ -4012,8 +4226,8 @@ class IMAAdsManagerDelegate extends NSObject { required this.didRequestContentPause, required this.didRequestContentResume, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManagerDelegate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4021,12 +4235,13 @@ class IMAAdsManagerDelegate extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4059,8 +4274,9 @@ class IMAAdsManagerDelegate extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdsManagerDelegate = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMAAdsManagerDelegate = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// Called when there is an IMAAdEvent. /// @@ -4085,7 +4301,8 @@ class IMAAdsManagerDelegate extends NSObject { IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdEvent event, - ) didReceiveAdEvent; + ) + didReceiveAdEvent; /// Called when there was an error playing the ad. /// @@ -4110,7 +4327,8 @@ class IMAAdsManagerDelegate extends NSObject { IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdError error, - ) didReceiveAdError; + ) + didReceiveAdError; /// Called when an ad is ready to play. /// @@ -4134,7 +4352,8 @@ class IMAAdsManagerDelegate extends NSObject { final void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - ) didRequestContentPause; + ) + didRequestContentPause; /// Called when an ad has finished or an error occurred during the playback. /// @@ -4158,7 +4377,8 @@ class IMAAdsManagerDelegate extends NSObject { final void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - ) didRequestContentResume; + ) + didRequestContentResume; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4168,122 +4388,157 @@ class IMAAdsManagerDelegate extends NSObject { IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdEvent event, - )? didReceiveAdEvent, + )? + didReceiveAdEvent, void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, IMAAdError error, - )? didReceiveAdError, + )? + didReceiveAdError, void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - )? didRequestContentPause, + )? + didRequestContentPause, void Function( IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager, - )? didRequestContentResume, + )? + didRequestContentResume, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null.', + ); final List args = (message as List?)!; final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdsManagerDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdsManagerDelegate.', + ); final IMAAdsManager? arg_adsManager = (args[1] as IMAAdsManager?); - assert(arg_adsManager != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdsManager.'); + assert( + arg_adsManager != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdsManager.', + ); final IMAAdEvent? arg_event = (args[2] as IMAAdEvent?); - assert(arg_event != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdEvent.'); + assert( + arg_event != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdEvent.', + ); try { - (didReceiveAdEvent ?? arg_pigeon_instance!.didReceiveAdEvent) - .call(arg_pigeon_instance!, arg_adsManager!, arg_event!); + (didReceiveAdEvent ?? arg_pigeon_instance!.didReceiveAdEvent).call( + arg_pigeon_instance!, + arg_adsManager!, + arg_event!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null.', + ); final List args = (message as List?)!; final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdsManagerDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdsManagerDelegate.', + ); final IMAAdsManager? arg_adsManager = (args[1] as IMAAdsManager?); - assert(arg_adsManager != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdsManager.'); + assert( + arg_adsManager != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdsManager.', + ); final IMAAdError? arg_error = (args[2] as IMAAdError?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdError.'); + assert( + arg_error != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdError.', + ); try { - (didReceiveAdError ?? arg_pigeon_instance!.didReceiveAdError) - .call(arg_pigeon_instance!, arg_adsManager!, arg_error!); + (didReceiveAdError ?? arg_pigeon_instance!.didReceiveAdError).call( + arg_pigeon_instance!, + arg_adsManager!, + arg_error!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null.', + ); final List args = (message as List?)!; final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null, expected non-null IMAAdsManagerDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null, expected non-null IMAAdsManagerDelegate.', + ); final IMAAdsManager? arg_adsManager = (args[1] as IMAAdsManager?); - assert(arg_adsManager != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null, expected non-null IMAAdsManager.'); + assert( + arg_adsManager != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null, expected non-null IMAAdsManager.', + ); try { (didRequestContentPause ?? arg_pigeon_instance!.didRequestContentPause) @@ -4293,33 +4548,40 @@ class IMAAdsManagerDelegate extends NSObject { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null.', + ); final List args = (message as List?)!; final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null, expected non-null IMAAdsManagerDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null, expected non-null IMAAdsManagerDelegate.', + ); final IMAAdsManager? arg_adsManager = (args[1] as IMAAdsManager?); - assert(arg_adsManager != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null, expected non-null IMAAdsManager.'); + assert( + arg_adsManager != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null, expected non-null IMAAdsManager.', + ); try { (didRequestContentResume ?? arg_pigeon_instance!.didRequestContentResume) @@ -4329,7 +4591,8 @@ class IMAAdsManagerDelegate extends NSObject { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4383,57 +4646,71 @@ class IMAAdEvent extends NSObject { AdEventType type, String typeString, Map? adData, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null int.', + ); final AdEventType? arg_type = (args[1] as AdEventType?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null AdEventType.'); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null AdEventType.', + ); final String? arg_typeString = (args[2] as String?); - assert(arg_typeString != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_typeString != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null String.', + ); final Map? arg_adData = (args[3] as Map?)?.cast(); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_type!, arg_typeString!, arg_adData) ?? - IMAAdEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - typeString: arg_typeString!, - adData: arg_adData, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_type!, + arg_typeString!, + arg_adData, + ) ?? + IMAAdEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + typeString: arg_typeString!, + adData: arg_adData, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4474,8 +4751,8 @@ class IMAAdsRenderingSettings extends NSObject { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRenderingSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4483,12 +4760,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4517,8 +4795,9 @@ class IMAAdsRenderingSettings extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdsRenderingSettings = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMAAdsRenderingSettings = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4528,41 +4807,47 @@ class IMAAdsRenderingSettings extends NSObject { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsRenderingSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMAAdsRenderingSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4578,12 +4863,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setMimeTypes'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, types], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, types]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4610,12 +4896,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setBitrate'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, bitrate], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, bitrate]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4642,12 +4929,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setLoadVideoTimeout'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, seconds], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, seconds]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4673,12 +4961,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setPlayAdsAfterTime'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, seconds], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, seconds]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4703,12 +4992,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setUIElements'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, types], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, types]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4735,12 +5025,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setEnablePreloading'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enable], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enable]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4759,7 +5050,8 @@ class IMAAdsRenderingSettings extends NSObject { /// Specifies the optional UIViewController that will be used to open links /// in-app. Future setLinkOpenerPresentingController( - UIViewController controller) async { + UIViewController controller, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRenderingSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4767,12 +5059,13 @@ class IMAAdsRenderingSettings extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.setLinkOpenerPresentingController'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, controller], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, controller]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4821,41 +5114,47 @@ class NSObject extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - NSObject.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + NSObject.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4909,8 +5208,8 @@ class IMAFriendlyObstruction extends NSObject { required this.purpose, this.detailedReason, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAFriendlyObstruction; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4918,12 +5217,13 @@ class IMAFriendlyObstruction extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, view, purpose, detailedReason]); + [pigeonVar_instanceIdentifier, view, purpose, detailedReason], + ); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4955,8 +5255,9 @@ class IMAFriendlyObstruction extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAFriendlyObstruction = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMAFriendlyObstruction = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// The view causing the obstruction. final UIView view; @@ -4979,57 +5280,71 @@ class IMAFriendlyObstruction extends NSObject { UIView view, FriendlyObstructionPurpose purpose, String? detailedReason, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null int.', + ); final UIView? arg_view = (args[1] as UIView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null UIView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null UIView.', + ); final FriendlyObstructionPurpose? arg_purpose = (args[2] as FriendlyObstructionPurpose?); - assert(arg_purpose != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null FriendlyObstructionPurpose.'); + assert( + arg_purpose != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null FriendlyObstructionPurpose.', + ); final String? arg_detailedReason = (args[3] as String?); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_view!, arg_purpose!, arg_detailedReason) ?? - IMAFriendlyObstruction.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - view: arg_view!, - purpose: arg_purpose!, - detailedReason: arg_detailedReason, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_view!, + arg_purpose!, + arg_detailedReason, + ) ?? + IMAFriendlyObstruction.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + view: arg_view!, + purpose: arg_purpose!, + detailedReason: arg_detailedReason, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5091,58 +5406,73 @@ class IMACompanionAd extends NSObject { String? apiFramework, int width, int height, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_resourceValue = (args[1] as String?); final String? arg_apiFramework = (args[2] as String?); final int? arg_width = (args[3] as int?); - assert(arg_width != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_width != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_height = (args[4] as int?); - assert(arg_height != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_height != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_resourceValue, arg_apiFramework, - arg_width!, arg_height!) ?? - IMACompanionAd.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resourceValue: arg_resourceValue, - apiFramework: arg_apiFramework, - width: arg_width!, - height: arg_height!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_resourceValue, + arg_apiFramework, + arg_width!, + arg_height!, + ) ?? + IMACompanionAd.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resourceValue: arg_resourceValue, + apiFramework: arg_apiFramework, + width: arg_width!, + height: arg_height!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5189,8 +5519,8 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.view, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5198,12 +5528,13 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, view], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier, view]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -5260,8 +5591,8 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { required int width, required int height, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5269,12 +5600,13 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.size'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, view, width, height], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([pigeonVar_instanceIdentifier, view, width, height]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -5304,8 +5636,9 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMACompanionAdSlot = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMACompanionAdSlot = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// The view the companion will be rendered in. /// @@ -5320,45 +5653,53 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null, expected non-null int.', + ); final UIView? arg_view = (args[1] as UIView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null, expected non-null UIView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null, expected non-null UIView.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_view!) ?? - IMACompanionAdSlot.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - view: arg_view!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_view!) ?? + IMACompanionAdSlot.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + view: arg_view!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5377,12 +5718,13 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.setDelegate'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, delegate], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, delegate]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5407,12 +5749,13 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.width'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5442,12 +5785,13 @@ class IMACompanionAdSlot extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.height'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5489,11 +5833,13 @@ class IMACompanionDelegate extends NSObject { IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled, - )? companionAdSlotFilled, + )? + companionAdSlotFilled, void Function( IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, - )? companionSlotWasClicked, + )? + companionSlotWasClicked, }) { if (PigeonOverrides.iMACompanionDelegate_new != null) { return PigeonOverrides.iMACompanionDelegate_new!( @@ -5516,8 +5862,8 @@ class IMACompanionDelegate extends NSObject { this.companionAdSlotFilled, this.companionSlotWasClicked, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionDelegate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5525,12 +5871,13 @@ class IMACompanionDelegate extends NSObject { 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -5561,8 +5908,9 @@ class IMACompanionDelegate extends NSObject { }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMACompanionDelegate = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecIMACompanionDelegate = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// Called when the slot is either filled or not filled. /// @@ -5587,7 +5935,8 @@ class IMACompanionDelegate extends NSObject { IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled, - )? companionAdSlotFilled; + )? + companionAdSlotFilled; /// Called when the slot is clicked on by the user and will successfully /// navigate away. @@ -5612,7 +5961,8 @@ class IMACompanionDelegate extends NSObject { final void Function( IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, - )? companionSlotWasClicked; + )? + companionSlotWasClicked; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5623,78 +5973,94 @@ class IMACompanionDelegate extends NSObject { IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled, - )? companionAdSlotFilled, + )? + companionAdSlotFilled, void Function( IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, - )? companionSlotWasClicked, + )? + companionSlotWasClicked, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMACompanionDelegate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + IMACompanionDelegate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null.', + ); final List args = (message as List?)!; final IMACompanionDelegate? arg_pigeon_instance = (args[0] as IMACompanionDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null IMACompanionDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null IMACompanionDelegate.', + ); final IMACompanionAdSlot? arg_slot = (args[1] as IMACompanionAdSlot?); - assert(arg_slot != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null IMACompanionAdSlot.'); + assert( + arg_slot != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null IMACompanionAdSlot.', + ); final bool? arg_filled = (args[2] as bool?); - assert(arg_filled != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null bool.'); + assert( + arg_filled != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null bool.', + ); try { (companionAdSlotFilled ?? arg_pigeon_instance!.companionAdSlotFilled) @@ -5704,33 +6070,40 @@ class IMACompanionDelegate extends NSObject { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null.', + ); final List args = (message as List?)!; final IMACompanionDelegate? arg_pigeon_instance = (args[0] as IMACompanionDelegate?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null, expected non-null IMACompanionDelegate.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null, expected non-null IMACompanionDelegate.', + ); final IMACompanionAdSlot? arg_slot = (args[1] as IMACompanionAdSlot?); - assert(arg_slot != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null, expected non-null IMACompanionAdSlot.'); + assert( + arg_slot != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null, expected non-null IMACompanionAdSlot.', + ); try { (companionSlotWasClicked ?? arg_pigeon_instance!.companionSlotWasClicked) @@ -5740,7 +6113,8 @@ class IMACompanionDelegate extends NSObject { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5830,75 +6204,95 @@ class IMAAdPodInfo extends PigeonInternalProxyApiBaseClass { double timeOffset, int totalAds, bool isBumper, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_adPosition = (args[1] as int?); - assert(arg_adPosition != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_adPosition != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_maxDuration = (args[2] as double?); - assert(arg_maxDuration != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_maxDuration != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_podIndex = (args[3] as int?); - assert(arg_podIndex != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_podIndex != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final double? arg_timeOffset = (args[4] as double?); - assert(arg_timeOffset != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null double.'); + assert( + arg_timeOffset != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null double.', + ); final int? arg_totalAds = (args[5] as int?); - assert(arg_totalAds != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_totalAds != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null int.', + ); final bool? arg_isBumper = (args[6] as bool?); - assert(arg_isBumper != null, - 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_isBumper != null, + 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null bool.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adPosition!, - arg_maxDuration!, - arg_podIndex!, - arg_timeOffset!, - arg_totalAds!, - arg_isBumper!) ?? - IMAAdPodInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adPosition: arg_adPosition!, - maxDuration: arg_maxDuration!, - podIndex: arg_podIndex!, - timeOffset: arg_timeOffset!, - totalAds: arg_totalAds!, - isBumper: arg_isBumper!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_adPosition!, + arg_maxDuration!, + arg_podIndex!, + arg_timeOffset!, + arg_totalAds!, + arg_isBumper!, + ) ?? + IMAAdPodInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adPosition: arg_adPosition!, + maxDuration: arg_maxDuration!, + podIndex: arg_podIndex!, + timeOffset: arg_timeOffset!, + totalAds: arg_totalAds!, + isBumper: arg_isBumper!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/interactive_media_ads/lib/src/ios/interactive_media_ads_proxy.dart b/packages/interactive_media_ads/lib/src/ios/interactive_media_ads_proxy.dart index 3acc304a261..11d63f33074 100644 --- a/packages/interactive_media_ads/lib/src/ios/interactive_media_ads_proxy.dart +++ b/packages/interactive_media_ads/lib/src/ios/interactive_media_ads_proxy.dart @@ -33,7 +33,8 @@ class InteractiveMediaAdsProxy { required UIView adContainer, UIViewController? adContainerViewController, List? companionSlots, - }) newIMAAdDisplayContainer; + }) + newIMAAdDisplayContainer; /// Constructs [UIView]. final UIView Function() newUIView; @@ -41,7 +42,8 @@ class InteractiveMediaAdsProxy { /// Constructs [UIViewController]. final UIViewController Function({ void Function(UIViewController, bool)? viewDidAppear, - }) newUIViewController; + }) + newUIViewController; /// Constructs [IMAContentPlayhead]. final IMAContentPlayhead Function() newIMAContentPlayhead; @@ -54,30 +56,34 @@ class InteractiveMediaAdsProxy { required String adTagUrl, required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, - }) newIMAAdsRequest; + }) + newIMAAdsRequest; /// Constructs [IMAAdsLoaderDelegate]. final IMAAdsLoaderDelegate Function({ required void Function(IMAAdsLoaderDelegate, IMAAdsLoader, IMAAdsLoadedData) - adLoaderLoadedWith, + adLoaderLoadedWith, required void Function( IMAAdsLoaderDelegate, IMAAdsLoader, IMAAdLoadingErrorData, - ) adsLoaderFailedWithErrorData, - }) newIMAAdsLoaderDelegate; + ) + adsLoaderFailedWithErrorData, + }) + newIMAAdsLoaderDelegate; /// Constructs [IMAAdsManagerDelegate]. final IMAAdsManagerDelegate Function({ required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdEvent) - didReceiveAdEvent, + didReceiveAdEvent, required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdError) - didReceiveAdError, + didReceiveAdError, required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentPause, + didRequestContentPause, required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentResume, - }) newIMAAdsManagerDelegate; + didRequestContentResume, + }) + newIMAAdsManagerDelegate; /// Constructs [IMAAdsRenderingSettings]. final IMAAdsRenderingSettings Function() newIMAAdsRenderingSettings; @@ -87,29 +93,27 @@ class InteractiveMediaAdsProxy { required UIView view, required FriendlyObstructionPurpose purpose, String? detailedReason, - }) newIMAFriendlyObstruction; + }) + newIMAFriendlyObstruction; /// Constructs [IMACompanionAdSlot]. final IMACompanionAdSlot Function({required UIView view}) - newIMACompanionAdSlot; + newIMACompanionAdSlot; /// Constructs [IMACompanionAdSlot]. final IMACompanionAdSlot Function({ required int width, required int height, required UIView view, - }) sizeIMACompanionAdSlot; + }) + sizeIMACompanionAdSlot; /// Constructs [IMACompanionDelegate]. final IMACompanionDelegate Function({ - void Function( - IMACompanionDelegate, - IMACompanionAdSlot, - bool, - )? companionAdSlotFilled, - void Function( - IMACompanionDelegate, - IMACompanionAdSlot, - )? companionSlotWasClicked, - }) newIMACompanionDelegate; + void Function(IMACompanionDelegate, IMACompanionAdSlot, bool)? + companionAdSlotFilled, + void Function(IMACompanionDelegate, IMACompanionAdSlot)? + companionSlotWasClicked, + }) + newIMACompanionDelegate; } diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart b/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart index 002f1ba65c3..a0b6f7d935d 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart @@ -22,8 +22,8 @@ final class IOSAdDisplayContainerCreationParams required super.onContainerAdded, super.companionSlots, @visibleForTesting InteractiveMediaAdsProxy? imaProxy, - }) : _imaProxy = imaProxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _imaProxy = imaProxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [IOSAdDisplayContainerCreationParams] from an instance of /// [PlatformAdDisplayContainerCreationParams]. @@ -63,8 +63,9 @@ base class IOSAdDisplayContainer extends PlatformAdDisplayContainer { late final IOSAdDisplayContainerCreationParams _iosParams = params is IOSAdDisplayContainerCreationParams ? params as IOSAdDisplayContainerCreationParams - : IOSAdDisplayContainerCreationParams - .fromPlatformAdDisplayContainerCreationParams(params); + : IOSAdDisplayContainerCreationParams.fromPlatformAdDisplayContainerCreationParams( + params, + ); @override Widget build(BuildContext context) { @@ -75,17 +76,19 @@ base class IOSAdDisplayContainer extends PlatformAdDisplayContainer { adDisplayContainer = _iosParams._imaProxy.newIMAAdDisplayContainer( adContainer: _controller.view, adContainerViewController: _controller, - companionSlots: _iosParams.companionSlots - .cast() - .map((IOSCompanionAdSlot slot) => slot.nativeCompanionAdSlot) - .toList(), + companionSlots: + _iosParams.companionSlots + .cast() + .map((IOSCompanionAdSlot slot) => slot.nativeCompanionAdSlot) + .toList(), ); await _viewDidAppearCompleter.future; params.onContainerAdded(this); }, layoutDirection: params.layoutDirection, - creationParams: _controller.view.pigeon_instanceManager - .getIdentifier(_controller.view), + creationParams: _controller.view.pigeon_instanceManager.getIdentifier( + _controller.view, + ), creationParamsCodec: const StandardMessageCodec(), ); } diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart index 5fbca3d2292..259a8b1e657 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart @@ -24,8 +24,8 @@ final class IOSAdsLoaderCreationParams extends PlatformAdsLoaderCreationParams { required super.onAdsLoaded, required super.onAdsLoadError, @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [IOSAdsLoaderCreationParams] from an instance of /// [PlatformAdsLoaderCreationParams]. @@ -49,23 +49,24 @@ final class IOSAdsLoaderCreationParams extends PlatformAdsLoaderCreationParams { base class IOSAdsLoader extends PlatformAdsLoader { /// Constructs an [IOSAdsLoader]. IOSAdsLoader(super.params) - : assert(params.container is IOSAdDisplayContainer), - assert( - (params.container as IOSAdDisplayContainer).adDisplayContainer != - null, - 'Ensure the AdDisplayContainer has been added to the Widget tree before creating an AdsLoader.', - ), - super.implementation(); + : assert(params.container is IOSAdDisplayContainer), + assert( + (params.container as IOSAdDisplayContainer).adDisplayContainer != null, + 'Ensure the AdDisplayContainer has been added to the Widget tree before creating an AdsLoader.', + ), + super.implementation(); late final IMAAdsLoader _adsLoader = _initAdsLoader(); late final IMAAdsLoaderDelegate _delegate = _createAdsLoaderDelegate( WeakReference(this), ); - late final IOSAdsLoaderCreationParams _iosParams = params - is IOSAdsLoaderCreationParams - ? params as IOSAdsLoaderCreationParams - : IOSAdsLoaderCreationParams.fromPlatformAdsLoaderCreationParams(params); + late final IOSAdsLoaderCreationParams _iosParams = + params is IOSAdsLoaderCreationParams + ? params as IOSAdsLoaderCreationParams + : IOSAdsLoaderCreationParams.fromPlatformAdsLoaderCreationParams( + params, + ); @override Future contentComplete() { @@ -84,15 +85,15 @@ base class IOSAdsLoader extends PlatformAdsLoader { final IMAAdsRequest adsRequest = switch (request) { final PlatformAdsRequestWithAdTagUrl request => IMAAdsRequest( - adTagUrl: request.adTagUrl, - adDisplayContainer: adDisplayContainer, - contentPlayhead: contentProgressProvider, - ), + adTagUrl: request.adTagUrl, + adDisplayContainer: adDisplayContainer, + contentPlayhead: contentProgressProvider, + ), PlatformAdsRequestWithAdsResponse() => IMAAdsRequest.withAdsResponse( - adsResponse: request.adsResponse, - adDisplayContainer: adDisplayContainer, - contentPlayhead: contentProgressProvider, - ), + adsResponse: request.adsResponse, + adDisplayContainer: adDisplayContainer, + contentPlayhead: contentProgressProvider, + ), }; return Future.wait(>[ diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart index 740d568c9dd..e94f2dd46be 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart @@ -35,9 +35,10 @@ class IOSAdsManager extends PlatformAdsManager { Future init({PlatformAdsRenderingSettings? settings}) { IMAAdsRenderingSettings? nativeSettings; if (settings != null) { - nativeSettings = settings is IOSAdsRenderingSettings - ? settings.nativeSettings - : IOSAdsRenderingSettings(settings.params).nativeSettings; + nativeSettings = + settings is IOSAdsRenderingSettings + ? settings.nativeSettings + : IOSAdsRenderingSettings(settings.params).nativeSettings; } return _manager.initialize(nativeSettings); diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart index d055805064a..7b194ca107d 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart @@ -17,8 +17,8 @@ final class IOSAdsManagerDelegateCreationParams super.onAdEvent, super.onAdErrorEvent, @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates an [IOSAdsManagerDelegateCreationParams] from an instance of /// [PlatformAdsManagerDelegateCreationParams]. @@ -53,8 +53,9 @@ final class IOSAdsManagerDelegate extends PlatformAdsManagerDelegate { late final IOSAdsManagerDelegateCreationParams _iosParams = params is IOSAdsManagerDelegateCreationParams ? params as IOSAdsManagerDelegateCreationParams - : IOSAdsManagerDelegateCreationParams - .fromPlatformAdsManagerDelegateCreationParams(params); + : IOSAdsManagerDelegateCreationParams.fromPlatformAdsManagerDelegateCreationParams( + params, + ); // This value is created in a static method because the callback methods for // any wrapped classes must not reference the encapsulating object. This is to @@ -67,11 +68,10 @@ final class IOSAdsManagerDelegate extends PlatformAdsManagerDelegate { interfaceDelegate.target?.params.onAdEvent?.call( AdEvent( type: toInterfaceEventType(event.type), - adData: event.adData?.map( - (String? key, Object? value) { - return MapEntry(key!, value.toString()); - }, - ) ?? + adData: + event.adData?.map((String? key, Object? value) { + return MapEntry(key!, value.toString()); + }) ?? {}, ), ); diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart index 6ce5048ec82..0e4ccb1fd2c 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart @@ -20,8 +20,8 @@ final class IOSAdsRenderingSettingsCreationParams super.playAdsAfterTime, super.uiElements, @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [IOSAdsRenderingSettingsCreationParams] from an instance of /// [PlatformAdsRenderingSettingsCreationParams]. @@ -66,14 +66,12 @@ base class IOSAdsRenderingSettings extends PlatformAdsRenderingSettings { } if (_iosParams.uiElements != null) { nativeSettings.setUIElements( - _iosParams.uiElements!.map( - (AdUIElement element) { - return switch (element) { - AdUIElement.adAttribution => UIElementType.adAttribution, - AdUIElement.countdown => UIElementType.countdown, - }; - }, - ).toList(), + _iosParams.uiElements!.map((AdUIElement element) { + return switch (element) { + AdUIElement.adAttribution => UIElementType.adAttribution, + AdUIElement.countdown => UIElementType.countdown, + }; + }).toList(), ); } } @@ -86,8 +84,7 @@ base class IOSAdsRenderingSettings extends PlatformAdsRenderingSettings { late final IOSAdsRenderingSettingsCreationParams _iosParams = params is IOSAdsRenderingSettingsCreationParams ? params as IOSAdsRenderingSettingsCreationParams - : IOSAdsRenderingSettingsCreationParams - .fromPlatformAdsRenderingSettingsCreationParams( - params, - ); + : IOSAdsRenderingSettingsCreationParams.fromPlatformAdsRenderingSettingsCreationParams( + params, + ); } diff --git a/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart index 3bb096bb0fa..36f5da62aea 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart @@ -20,8 +20,8 @@ final class IOSCompanionAdSlotCreationParams required super.size, super.onClicked, @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates an [IOSCompanionAdSlotCreationParams] from an instance of /// [PlatformCompanionAdSlotCreationParams]. @@ -44,8 +44,9 @@ base class IOSCompanionAdSlot extends PlatformCompanionAdSlot { /// Constructs an [IOSCompanionAdSlot]. IOSCompanionAdSlot(super.params) : super.implementation(); - late final IOSCompanionAdSlotCreationParams _iosParams = - _initIOSParams(params); + late final IOSCompanionAdSlotCreationParams _iosParams = _initIOSParams( + params, + ); // View used to display the Ad. late final UIView _view = _iosParams._proxy.newUIView(); @@ -76,20 +77,22 @@ base class IOSCompanionAdSlot extends PlatformCompanionAdSlot { return params; } - return IOSCompanionAdSlotCreationParams - .fromPlatformCompanionAdSlotCreationParamsSize(params); + return IOSCompanionAdSlotCreationParams.fromPlatformCompanionAdSlotCreationParamsSize( + params, + ); } IMACompanionAdSlot _initCompanionAdSlot() { final IMACompanionAdSlot adSlot = switch (params.size) { - final CompanionAdSlotSizeFixed size => - _iosParams._proxy.sizeIMACompanionAdSlot( - view: _view, - width: size.width, - height: size.height, - ), - CompanionAdSlotSizeFluid() => - _iosParams._proxy.newIMACompanionAdSlot(view: _view), + final CompanionAdSlotSizeFixed size => _iosParams._proxy + .sizeIMACompanionAdSlot( + view: _view, + width: size.width, + height: size.height, + ), + CompanionAdSlotSizeFluid() => _iosParams._proxy.newIMACompanionAdSlot( + view: _view, + ), }; if (params.onClicked != null) { diff --git a/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart b/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart index 9b75466ae54..3e7c8e74fd0 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart @@ -16,8 +16,8 @@ final class IOSContentProgressProviderCreationParams /// Constructs an [IOSContentProgressProviderCreationParams]. const IOSContentProgressProviderCreationParams({ @visibleForTesting InteractiveMediaAdsProxy? proxy, - }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), - super(); + }) : _proxy = proxy ?? const InteractiveMediaAdsProxy(), + super(); /// Creates a [IOSContentProgressProviderCreationParams] from an instance of /// [PlatformContentProgressProviderCreationParams]. @@ -49,10 +49,9 @@ base class IOSContentProgressProvider extends PlatformContentProgressProvider { late final IOSContentProgressProviderCreationParams _iosParams = params is IOSContentProgressProviderCreationParams ? params as IOSContentProgressProviderCreationParams - : IOSContentProgressProviderCreationParams - .fromPlatformContentProgressProviderCreationParams( - params, - ); + : IOSContentProgressProviderCreationParams.fromPlatformContentProgressProviderCreationParams( + params, + ); @override Future setProgress({ diff --git a/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart b/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart index cbaeb4416ca..0a507b5757d 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart @@ -10,10 +10,7 @@ sealed class CompanionAdSlotSize { const CompanionAdSlotSize._(); /// A slot for a companion ad with a fixed with and height. - factory CompanionAdSlotSize.fixed({ - required int width, - required int height, - }) { + factory CompanionAdSlotSize.fixed({required int width, required int height}) { return CompanionAdSlotSizeFixed._(width: width, height: height); } @@ -27,10 +24,8 @@ sealed class CompanionAdSlotSize { /// A slot for a companion ad with a fixed with and height. @immutable class CompanionAdSlotSizeFixed extends CompanionAdSlotSize { - const CompanionAdSlotSizeFixed._({ - required this.width, - required this.height, - }) : super._(); + const CompanionAdSlotSizeFixed._({required this.width, required this.height}) + : super._(); /// The width of the ad slot in pixels. final int width; diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart index 9478afbacb3..7f1171c0dd4 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart @@ -83,8 +83,9 @@ abstract base class PlatformAdDisplayContainer { 'your own test implementation.', ); final PlatformAdDisplayContainer implementation = - InteractiveMediaAdsPlatform.instance! - .createPlatformAdDisplayContainer(params); + InteractiveMediaAdsPlatform.instance!.createPlatformAdDisplayContainer( + params, + ); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart index dea71a828b3..94f55a33cec 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart @@ -72,9 +72,7 @@ base class PlatformAdsLoaderCreationParams { /// handles events from ads request responses. abstract base class PlatformAdsLoader { /// Creates a new [PlatformAdsLoader] - factory PlatformAdsLoader( - PlatformAdsLoaderCreationParams params, - ) { + factory PlatformAdsLoader(PlatformAdsLoaderCreationParams params) { assert( InteractiveMediaAdsPlatform.instance != null, 'A platform implementation for `interactive_media_ads` has not been set. ' @@ -83,8 +81,9 @@ abstract base class PlatformAdsLoader { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformAdsLoader implementation = - InteractiveMediaAdsPlatform.instance!.createPlatformAdsLoader(params); + final PlatformAdsLoader implementation = InteractiveMediaAdsPlatform + .instance! + .createPlatformAdsLoader(params); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart index 146e5d1914e..ab2b835c310 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart @@ -70,8 +70,9 @@ abstract base class PlatformAdsManagerDelegate { 'your own test implementation.', ); final PlatformAdsManagerDelegate implementation = - InteractiveMediaAdsPlatform.instance! - .createPlatformAdsManagerDelegate(params); + InteractiveMediaAdsPlatform.instance!.createPlatformAdsManagerDelegate( + params, + ); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_request.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_request.dart index 2bf8605d3cc..363730acf92 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_request.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_request.dart @@ -30,19 +30,18 @@ sealed class PlatformAdsRequest { String? contentTitle, Duration? liveStreamPrefetchMaxWaitTime, Duration? vastLoadTimeout, - }) => - PlatformAdsRequestWithAdTagUrl._( - adTagUrl: adTagUrl, - contentProgressProvider: contentProgressProvider, - adWillAutoPlay: adWillAutoPlay, - adWillPlayMuted: adWillPlayMuted, - continuousPlayback: continuousPlayback, - contentDuration: contentDuration, - contentKeywords: contentKeywords, - contentTitle: contentTitle, - liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, - vastLoadTimeout: vastLoadTimeout, - ); + }) => PlatformAdsRequestWithAdTagUrl._( + adTagUrl: adTagUrl, + contentProgressProvider: contentProgressProvider, + adWillAutoPlay: adWillAutoPlay, + adWillPlayMuted: adWillPlayMuted, + continuousPlayback: continuousPlayback, + contentDuration: contentDuration, + contentKeywords: contentKeywords, + contentTitle: contentTitle, + liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, + vastLoadTimeout: vastLoadTimeout, + ); /// Creates a [PlatformAdsRequest] with the given canned ads response. factory PlatformAdsRequest.withAdsResponse({ @@ -56,19 +55,18 @@ sealed class PlatformAdsRequest { String? contentTitle, Duration? liveStreamPrefetchMaxWaitTime, Duration? vastLoadTimeout, - }) => - PlatformAdsRequestWithAdsResponse._( - adsResponse: adsResponse, - contentProgressProvider: contentProgressProvider, - adWillAutoPlay: adWillAutoPlay, - adWillPlayMuted: adWillPlayMuted, - continuousPlayback: continuousPlayback, - contentDuration: contentDuration, - contentKeywords: contentKeywords, - contentTitle: contentTitle, - liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, - vastLoadTimeout: vastLoadTimeout, - ); + }) => PlatformAdsRequestWithAdsResponse._( + adsResponse: adsResponse, + contentProgressProvider: contentProgressProvider, + adWillAutoPlay: adWillAutoPlay, + adWillPlayMuted: adWillPlayMuted, + continuousPlayback: continuousPlayback, + contentDuration: contentDuration, + contentKeywords: contentKeywords, + contentTitle: contentTitle, + liveStreamPrefetchMaxWaitTime: liveStreamPrefetchMaxWaitTime, + vastLoadTimeout: vastLoadTimeout, + ); /// A [PlatformContentProgressProvider] instance to allow scheduling of ad /// breaks based on content progress (cue points). diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart index 42cedd36a11..414ad6ff5ea 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart @@ -62,8 +62,9 @@ abstract base class PlatformImaSettings { /// Creates a new [PlatformImaSettings]. factory PlatformImaSettings(PlatformImaSettingsCreationParams params) { assert(InteractiveMediaAdsPlatform.instance != null); - final PlatformImaSettings implementation = - InteractiveMediaAdsPlatform.instance!.createPlatformImaSettings(params); + final PlatformImaSettings implementation = InteractiveMediaAdsPlatform + .instance! + .createPlatformImaSettings(params); return implementation; } diff --git a/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart b/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart index fed150aaa2d..505793011d2 100644 --- a/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart +++ b/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart @@ -17,7 +17,6 @@ import 'package:pigeon/pigeon.dart'; ), ), ) - /// The types of error that can be encountered. /// /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/AdError.AdErrorCode.html. @@ -682,9 +681,7 @@ abstract class FrameLayout extends ViewGroup { /// /// See https://developer.android.com/reference/android/view/ViewGroup. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.view.ViewGroup', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.view.ViewGroup'), ) abstract class ViewGroup extends View { /// Adds a child view. diff --git a/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart b/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart index ebf2bac37e7..a56118fbb1c 100644 --- a/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart +++ b/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart @@ -14,7 +14,6 @@ import 'package:pigeon/pigeon.dart'; 'ios/interactive_media_ads/Sources/interactive_media_ads/InteractiveMediaAdsLibrary.g.swift', ), ) - /// Possible error types while loading or playing ads. /// /// See https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Enums/IMAErrorType.html. @@ -580,16 +579,15 @@ abstract class IMAAdsLoaderDelegate extends NSObject { IMAAdsLoaderDelegate(); /// Called when ads are successfully loaded from the ad servers by the loader. - late final void Function( - IMAAdsLoader loader, - IMAAdsLoadedData adsLoadedData, - ) adLoaderLoadedWith; + late final void Function(IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData) + adLoaderLoadedWith; /// Error reported by the ads loader when loading or requesting an ad fails. late final void Function( IMAAdsLoader loader, IMAAdLoadingErrorData adErrorData, - ) adsLoaderFailedWithErrorData; + ) + adsLoaderFailedWithErrorData; } /// Ad data that is returned when the ads loader loads the ad. @@ -666,16 +664,12 @@ abstract class IMAAdsManagerDelegate extends NSObject { IMAAdsManagerDelegate(); /// Called when there is an IMAAdEvent. - late final void Function( - IMAAdsManager adsManager, - IMAAdEvent event, - ) didReceiveAdEvent; + late final void Function(IMAAdsManager adsManager, IMAAdEvent event) + didReceiveAdEvent; /// Called when there was an error playing the ad. - late final void Function( - IMAAdsManager adsManager, - IMAAdError error, - ) didReceiveAdError; + late final void Function(IMAAdsManager adsManager, IMAAdError error) + didReceiveAdError; /// Called when an ad is ready to play. late final void Function(IMAAdsManager adsManager) didRequestContentPause; @@ -829,10 +823,8 @@ abstract class IMACompanionDelegate extends NSObject { IMACompanionDelegate(); /// Called when the slot is either filled or not filled. - late void Function( - IMACompanionAdSlot slot, - bool filled, - )? companionAdSlotFilled; + late void Function(IMACompanionAdSlot slot, bool filled)? + companionAdSlotFilled; /// Called when the slot is clicked on by the user and will successfully /// navigate away. diff --git a/packages/interactive_media_ads/pubspec.yaml b/packages/interactive_media_ads/pubspec.yaml index 376d105b1bf..0550c8c3a74 100644 --- a/packages/interactive_media_ads/pubspec.yaml +++ b/packages/interactive_media_ads/pubspec.yaml @@ -7,8 +7,8 @@ version: 0.2.6+3 # This must match the version in # `ios/interactive_media_ads/Sources/interactive_media_ads/AdsRequestProxyAPIDelegate.swift` environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/interactive_media_ads/test/ad_display_container_test.dart b/packages/interactive_media_ads/test/ad_display_container_test.dart index c237424a806..466ed144958 100644 --- a/packages/interactive_media_ads/test/ad_display_container_test.dart +++ b/packages/interactive_media_ads/test/ad_display_container_test.dart @@ -16,46 +16,50 @@ void main() { testWidgets('build', (WidgetTester tester) async { final TestPlatformAdDisplayContainer adDisplayContainer = TestPlatformAdDisplayContainer( - PlatformAdDisplayContainerCreationParams( - onContainerAdded: (_) {}, - ), - onBuild: (_) => Container(), - ); + PlatformAdDisplayContainerCreationParams(onContainerAdded: (_) {}), + onBuild: (_) => Container(), + ); - await tester.pumpWidget(AdDisplayContainer.fromPlatform( - platform: adDisplayContainer, - )); + await tester.pumpWidget( + AdDisplayContainer.fromPlatform(platform: adDisplayContainer), + ); expect(find.byType(Container), findsOneWidget); }); - testWidgets('constructor parameters are correctly passed to creation params', - (WidgetTester tester) async { - InteractiveMediaAdsPlatform.instance = - TestInteractiveMediaAdsPlatform(onCreatePlatformAdDisplayContainer: ( - PlatformAdDisplayContainerCreationParams params, - ) { - return TestPlatformAdDisplayContainer( - params, - onBuild: (_) => Container(), + testWidgets( + 'constructor parameters are correctly passed to creation params', + (WidgetTester tester) async { + InteractiveMediaAdsPlatform.instance = TestInteractiveMediaAdsPlatform( + onCreatePlatformAdDisplayContainer: ( + PlatformAdDisplayContainerCreationParams params, + ) { + return TestPlatformAdDisplayContainer( + params, + onBuild: (_) => Container(), + ); + }, + onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { + throw UnimplementedError(); + }, + onCreatePlatformAdsManagerDelegate: ( + PlatformAdsManagerDelegateCreationParams params, + ) { + throw UnimplementedError(); + }, + onCreatePlatformContentProgressProvider: (_) { + throw UnimplementedError(); + }, ); - }, onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { - throw UnimplementedError(); - }, onCreatePlatformAdsManagerDelegate: ( - PlatformAdsManagerDelegateCreationParams params, - ) { - throw UnimplementedError(); - }, onCreatePlatformContentProgressProvider: (_) { - throw UnimplementedError(); - }); - - final AdDisplayContainer adDisplayContainer = AdDisplayContainer( - key: GlobalKey(), - onContainerAdded: (_) {}, - ); - // The key passed to the default constructor is used by the super class - // and not passed to the platform implementation. - expect(adDisplayContainer.platform.params.key, isNull); - }); + final AdDisplayContainer adDisplayContainer = AdDisplayContainer( + key: GlobalKey(), + onContainerAdded: (_) {}, + ); + + // The key passed to the default constructor is used by the super class + // and not passed to the platform implementation. + expect(adDisplayContainer.platform.params.key, isNull); + }, + ); } diff --git a/packages/interactive_media_ads/test/ads_loader_test.dart b/packages/interactive_media_ads/test/ads_loader_test.dart index 2eb2d4bd166..03ac9487f85 100644 --- a/packages/interactive_media_ads/test/ads_loader_test.dart +++ b/packages/interactive_media_ads/test/ads_loader_test.dart @@ -74,29 +74,29 @@ void main() { ); final AdsLoader loader = AdsLoader.fromPlatform(adsLoader); - await loader.requestAds(AdsRequest( - adTagUrl: (platformRequest as PlatformAdsRequestWithAdTagUrl).adTagUrl, - adWillAutoPlay: platformRequest.adWillAutoPlay, - adWillPlayMuted: platformRequest.adWillPlayMuted, - continuousPlayback: platformRequest.continuousPlayback, - contentDuration: platformRequest.contentDuration, - contentKeywords: platformRequest.contentKeywords, - contentTitle: platformRequest.contentTitle, - liveStreamPrefetchMaxWaitTime: - platformRequest.liveStreamPrefetchMaxWaitTime, - vastLoadTimeout: platformRequest.vastLoadTimeout, - contentProgressProvider: ContentProgressProvider.fromPlatform( - platformRequest.contentProgressProvider!, + await loader.requestAds( + AdsRequest( + adTagUrl: (platformRequest as PlatformAdsRequestWithAdTagUrl).adTagUrl, + adWillAutoPlay: platformRequest.adWillAutoPlay, + adWillPlayMuted: platformRequest.adWillPlayMuted, + continuousPlayback: platformRequest.continuousPlayback, + contentDuration: platformRequest.contentDuration, + contentKeywords: platformRequest.contentKeywords, + contentTitle: platformRequest.contentTitle, + liveStreamPrefetchMaxWaitTime: + platformRequest.liveStreamPrefetchMaxWaitTime, + vastLoadTimeout: platformRequest.vastLoadTimeout, + contentProgressProvider: ContentProgressProvider.fromPlatform( + platformRequest.contentProgressProvider!, + ), ), - )); + ); }); } TestPlatformAdDisplayContainer createTestAdDisplayContainer() { return TestPlatformAdDisplayContainer( - PlatformAdDisplayContainerCreationParams( - onContainerAdded: (_) {}, - ), + PlatformAdDisplayContainerCreationParams(onContainerAdded: (_) {}), onBuild: (_) => Container(), ); } diff --git a/packages/interactive_media_ads/test/ads_manager_delegate_test.dart b/packages/interactive_media_ads/test/ads_manager_delegate_test.dart index a0d519864c4..6082cde442b 100644 --- a/packages/interactive_media_ads/test/ads_manager_delegate_test.dart +++ b/packages/interactive_media_ads/test/ads_manager_delegate_test.dart @@ -11,19 +11,21 @@ import 'test_stubs.dart'; void main() { test('passes params to platform instance', () async { InteractiveMediaAdsPlatform.instance = TestInteractiveMediaAdsPlatform( - onCreatePlatformAdsManagerDelegate: - (PlatformAdsManagerDelegateCreationParams params) { + onCreatePlatformAdsManagerDelegate: ( + PlatformAdsManagerDelegateCreationParams params, + ) { return TestPlatformAdsManagerDelegate(params); }, onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { throw UnimplementedError(); }, - onCreatePlatformAdDisplayContainer: - (PlatformAdDisplayContainerCreationParams params) { + onCreatePlatformAdDisplayContainer: ( + PlatformAdDisplayContainerCreationParams params, + ) { throw UnimplementedError(); }, - onCreatePlatformContentProgressProvider: (_) => - throw UnimplementedError(), + onCreatePlatformContentProgressProvider: + (_) => throw UnimplementedError(), ); void onAdEvent(AdEvent event) {} diff --git a/packages/interactive_media_ads/test/ads_manager_test.dart b/packages/interactive_media_ads/test/ads_manager_test.dart index 38591913171..9e9ba25dc32 100644 --- a/packages/interactive_media_ads/test/ads_manager_test.dart +++ b/packages/interactive_media_ads/test/ads_manager_test.dart @@ -15,10 +15,10 @@ void main() { test('init', () async { final AdsRenderingSettings adsRenderingSettings = AdsRenderingSettings.fromPlatform( - TestAdsRenderingSettings( - const PlatformAdsRenderingSettingsCreationParams(), - ), - ); + TestAdsRenderingSettings( + const PlatformAdsRenderingSettingsCreationParams(), + ), + ); final Completer settingsCompleter = Completer(); @@ -49,11 +49,13 @@ void main() { ); final AdsManager manager = createAdsManager(platformManager); - await manager.setAdsManagerDelegate(AdsManagerDelegate.fromPlatform( - TestPlatformAdsManagerDelegate( - const PlatformAdsManagerDelegateCreationParams(), + await manager.setAdsManagerDelegate( + AdsManagerDelegate.fromPlatform( + TestPlatformAdsManagerDelegate( + const PlatformAdsManagerDelegateCreationParams(), + ), ), - )); + ); }); test('discardAdBreak', () async { @@ -105,16 +107,20 @@ void main() { AdsManager createAdsManager(PlatformAdsManager platformManager) { InteractiveMediaAdsPlatform.instance = TestInteractiveMediaAdsPlatform( onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { - return TestPlatformAdsLoader(params, - onContentComplete: () async {}, - onRequestAds: (PlatformAdsRequest request) async {}); + return TestPlatformAdsLoader( + params, + onContentComplete: () async {}, + onRequestAds: (PlatformAdsRequest request) async {}, + ); }, - onCreatePlatformAdsManagerDelegate: - (PlatformAdsManagerDelegateCreationParams params) { + onCreatePlatformAdsManagerDelegate: ( + PlatformAdsManagerDelegateCreationParams params, + ) { throw UnimplementedError(); }, - onCreatePlatformAdDisplayContainer: - (PlatformAdDisplayContainerCreationParams params) { + onCreatePlatformAdDisplayContainer: ( + PlatformAdDisplayContainerCreationParams params, + ) { throw UnimplementedError(); }, onCreatePlatformContentProgressProvider: (_) => throw UnimplementedError(), @@ -125,9 +131,7 @@ AdsManager createAdsManager(PlatformAdsManager platformManager) { final AdsLoader loader = AdsLoader( container: AdDisplayContainer.fromPlatform( platform: TestPlatformAdDisplayContainer( - PlatformAdDisplayContainerCreationParams( - onContainerAdded: (_) {}, - ), + PlatformAdDisplayContainerCreationParams(onContainerAdded: (_) {}), onBuild: (_) => Container(), ), ), @@ -137,9 +141,9 @@ AdsManager createAdsManager(PlatformAdsManager platformManager) { onAdsLoadError: (_) {}, ); - loader.platform.params.onAdsLoaded(PlatformOnAdsLoadedData( - manager: platformManager, - )); + loader.platform.params.onAdsLoaded( + PlatformOnAdsLoadedData(manager: platformManager), + ); return manager; } diff --git a/packages/interactive_media_ads/test/android/ad_display_container_test.dart b/packages/interactive_media_ads/test/android/ad_display_container_test.dart index 460ad337557..371226acd8d 100644 --- a/packages/interactive_media_ads/test/android/ad_display_container_test.dart +++ b/packages/interactive_media_ads/test/android/ad_display_container_test.dart @@ -46,9 +46,9 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); expect(find.byType(PlatformViewLink), findsOneWidget); expect(find.byKey(const Key('testKey')), findsOneWidget); @@ -57,28 +57,25 @@ void main() { testWidgets('onContainerAdded is called', (WidgetTester tester) async { final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), - newVideoView: ({ - required dynamic onError, - dynamic onPrepared, - dynamic onCompletion, - }) => - MockVideoView(), - createAdDisplayContainerImaSdkFactory: ( - _, - __, - ) async { + newVideoView: + ({ + required dynamic onError, + dynamic onPrepared, + dynamic onCompletion, + }) => MockVideoView(), + createAdDisplayContainerImaSdkFactory: (_, __) async { return MockAdDisplayContainer(); }, - newVideoAdPlayer: ({ - required dynamic addCallback, - required dynamic loadAd, - required dynamic pauseAd, - required dynamic playAd, - required dynamic release, - required dynamic removeCallback, - required dynamic stopAd, - }) => - MockVideoAdPlayer(), + newVideoAdPlayer: + ({ + required dynamic addCallback, + required dynamic loadAd, + required dynamic pauseAd, + required dynamic playAd, + required dynamic release, + required dynamic removeCallback, + required dynamic stopAd, + }) => MockVideoAdPlayer(), ); final MockPlatformViewsServiceProxy mockPlatformViewsProxy = @@ -109,14 +106,17 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); - final void Function(int) onPlatformCreatedCallback = verify( - mockAndroidViewController - .addOnPlatformViewCreatedListener(captureAny)) - .captured[0] as void Function(int); + final void Function(int) onPlatformCreatedCallback = + verify( + mockAndroidViewController.addOnPlatformViewCreatedListener( + captureAny, + ), + ).captured[0] + as void Function(int); onPlatformCreatedCallback(platformViewId); @@ -128,47 +128,37 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAdCallback; + ) + loadAdCallback; - late final void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallbackCallback; - late final void Function( - ima.VideoView, - ima.MediaPlayer, - ) onCompletionCallback; + late final void Function(ima.VideoView, ima.MediaPlayer) + onCompletionCallback; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), newVideoView: ({ required dynamic onError, dynamic onPrepared, - void Function( - ima.VideoView, - ima.MediaPlayer, - )? onCompletion, + void Function(ima.VideoView, ima.MediaPlayer)? onCompletion, }) { onCompletionCallback = onCompletion!; return MockVideoView(); }, - createAdDisplayContainerImaSdkFactory: ( - _, - __, - ) async { + createAdDisplayContainerImaSdkFactory: (_, __) async { return MockAdDisplayContainer(); }, newVideoAdPlayer: ({ - required void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallback, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallback, required void Function( ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAd, + ) + loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -205,51 +195,38 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAdCallback; + ) + loadAdCallback; - late final void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallbackCallback; - late final void Function( - ima.VideoView, - ima.MediaPlayer, - int, - int, - ) onErrorCallback; + late final void Function(ima.VideoView, ima.MediaPlayer, int, int) + onErrorCallback; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), newVideoView: ({ - required void Function( - ima.VideoView, - ima.MediaPlayer, - int, - int, - ) onError, + required void Function(ima.VideoView, ima.MediaPlayer, int, int) + onError, dynamic onPrepared, dynamic onCompletion, }) { onErrorCallback = onError; return MockVideoView(); }, - createAdDisplayContainerImaSdkFactory: ( - _, - __, - ) async { + createAdDisplayContainerImaSdkFactory: (_, __) async { return MockAdDisplayContainer(); }, newVideoAdPlayer: ({ - required void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallback, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallback, required void Function( ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAd, + ) + loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -286,17 +263,14 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAdCallback; + ) + loadAdCallback; - late final void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallbackCallback; - late final Future Function( - ima.VideoView, - ima.MediaPlayer, - ) onPreparedCallback; + late final Future Function(ima.VideoView, ima.MediaPlayer) + onPreparedCallback; const int adDuration = 100; const int adProgress = 10; @@ -310,29 +284,27 @@ void main() { }) { // VideoView.onPrepared returns void, but the implementation uses an // async callback method. - onPreparedCallback = onPrepared! as Future Function( - ima.VideoView, - ima.MediaPlayer, - ); + onPreparedCallback = + onPrepared! + as Future Function(ima.VideoView, ima.MediaPlayer); final MockVideoView mockVideoView = MockVideoView(); - when(mockVideoView.getCurrentPosition()).thenAnswer( - (_) async => adProgress, - ); + when( + mockVideoView.getCurrentPosition(), + ).thenAnswer((_) async => adProgress); return mockVideoView; }, createAdDisplayContainerImaSdkFactory: (_, __) async { return MockAdDisplayContainer(); }, newVideoAdPlayer: ({ - required void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallback, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallback, required void Function( ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAd, + ) + loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -385,34 +357,27 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAdCallback; + ) + loadAdCallback; - late final Future Function( - ima.VideoView, - ima.MediaPlayer, - ) onPreparedCallback; + late final Future Function(ima.VideoView, ima.MediaPlayer) + onPreparedCallback; - late final Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) pauseAdCallback; + late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) + pauseAdCallback; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), newVideoView: ({ dynamic onError, - void Function( - ima.VideoView, - ima.MediaPlayer, - )? onPrepared, + void Function(ima.VideoView, ima.MediaPlayer)? onPrepared, dynamic onCompletion, }) { // VideoView.onPrepared returns void, but the implementation uses an // async callback method. - onPreparedCallback = onPrepared! as Future Function( - ima.VideoView, - ima.MediaPlayer, - ); + onPreparedCallback = + onPrepared! + as Future Function(ima.VideoView, ima.MediaPlayer); final MockVideoView mockVideoView = MockVideoView(); when(mockVideoView.getCurrentPosition()).thenAnswer((_) async => 10); return mockVideoView; @@ -426,7 +391,8 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAd, + ) + loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -436,10 +402,9 @@ void main() { loadAdCallback = loadAd; // VideoAdPlayer.pauseAd returns void, but the implementation uses an // async callback method. - pauseAdCallback = pauseAd as Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ); + pauseAdCallback = + pauseAd + as Future Function(ima.VideoAdPlayer, ima.AdMediaInfo); return MockVideoAdPlayer(); }, newVideoProgressUpdate: ({ @@ -475,39 +440,30 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAdCallback; + ) + loadAdCallback; - late final Future Function( - ima.VideoView, - ima.MediaPlayer, - ) onPreparedCallback; + late final Future Function(ima.VideoView, ima.MediaPlayer) + onPreparedCallback; - late final Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) pauseAdCallback; + late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) + pauseAdCallback; - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) playAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) + playAdCallback; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), newVideoView: ({ dynamic onError, - void Function( - ima.VideoView, - ima.MediaPlayer, - )? onPrepared, + void Function(ima.VideoView, ima.MediaPlayer)? onPrepared, dynamic onCompletion, }) { // VideoView.onPrepared returns void, but the implementation uses an // async callback method. - onPreparedCallback = onPrepared! as Future Function( - ima.VideoView, - ima.MediaPlayer, - ); + onPreparedCallback = + onPrepared! + as Future Function(ima.VideoView, ima.MediaPlayer); final MockVideoView mockVideoView = MockVideoView(); when(mockVideoView.getCurrentPosition()).thenAnswer((_) async => 10); return mockVideoView; @@ -521,12 +477,10 @@ void main() { ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo, - ) loadAd, + ) + loadAd, required dynamic pauseAd, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) playAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAd, required dynamic release, required dynamic removeCallback, required dynamic stopAd, @@ -534,10 +488,9 @@ void main() { loadAdCallback = loadAd; // VideoAdPlayer.pauseAd returns void, but the implementation uses an // async callback method. - pauseAdCallback = pauseAd as Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ); + pauseAdCallback = + pauseAd + as Future Function(ima.VideoAdPlayer, ima.AdMediaInfo); playAdCallback = playAd; return MockVideoAdPlayer(); }, @@ -580,10 +533,8 @@ void main() { }); test('play ad', () async { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) playAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) + playAdCallback; final MockVideoView mockVideoView = MockVideoView(); final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( @@ -602,10 +553,7 @@ void main() { required dynamic addCallback, required dynamic loadAd, required dynamic pauseAd, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) playAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAd, required dynamic release, required dynamic removeCallback, required dynamic stopAd, @@ -631,10 +579,8 @@ void main() { }); test('stop ad creates and sets a new VideoView', () async { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ) stopAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) + stopAdCallback; final MockFrameLayout mockFrameLayout = MockFrameLayout(); late final MockVideoView mockVideoView = MockVideoView(); @@ -688,40 +634,38 @@ void main() { verify(mockFrameLayout.addView(mockVideoView2)); }); - testWidgets('AdDisplayContainer adds CompanionAdSlots', - (WidgetTester tester) async { + testWidgets('AdDisplayContainer adds CompanionAdSlots', ( + WidgetTester tester, + ) async { final MockAdDisplayContainer mockAdDisplayContainer = MockAdDisplayContainer(); final MockCompanionAdSlot mockCompanionAdSlot = MockCompanionAdSlot(); final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), - newVideoView: ({ - required dynamic onError, - dynamic onPrepared, - dynamic onCompletion, - }) => - MockVideoView(), - createAdDisplayContainerImaSdkFactory: ( - _, - __, - ) async { + newVideoView: + ({ + required dynamic onError, + dynamic onPrepared, + dynamic onCompletion, + }) => MockVideoView(), + createAdDisplayContainerImaSdkFactory: (_, __) async { return mockAdDisplayContainer; }, - newVideoAdPlayer: ({ - required dynamic addCallback, - required dynamic loadAd, - required dynamic pauseAd, - required dynamic playAd, - required dynamic release, - required dynamic removeCallback, - required dynamic stopAd, - }) => - MockVideoAdPlayer(), + newVideoAdPlayer: + ({ + required dynamic addCallback, + required dynamic loadAd, + required dynamic pauseAd, + required dynamic playAd, + required dynamic release, + required dynamic removeCallback, + required dynamic stopAd, + }) => MockVideoAdPlayer(), instanceImaSdkFactory: () { final MockImaSdkFactory mockFactory = MockImaSdkFactory(); - when(mockFactory.createCompanionAdSlot()).thenAnswer( - (_) async => mockCompanionAdSlot, - ); + when( + mockFactory.createCompanionAdSlot(), + ).thenAnswer((_) async => mockCompanionAdSlot); return mockFactory; }, ); @@ -758,20 +702,23 @@ void main() { size: CompanionAdSlotSize.fixed(width: 300, height: 444), proxy: imaProxy, ), - ) + ), ], imaProxy: imaProxy, ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); - final void Function(int) onPlatformCreatedCallback = verify( - mockAndroidViewController - .addOnPlatformViewCreatedListener(captureAny)) - .captured[0] as void Function(int); + final void Function(int) onPlatformCreatedCallback = + verify( + mockAndroidViewController.addOnPlatformViewCreatedListener( + captureAny, + ), + ).captured[0] + as void Function(int); onPlatformCreatedCallback(platformViewId); @@ -780,9 +727,9 @@ void main() { await onContainerAddedCompleter.future; verify( - mockAdDisplayContainer.setCompanionSlots( - [mockCompanionAdSlot], - ), + mockAdDisplayContainer.setCompanionSlots([ + mockCompanionAdSlot, + ]), ); }); }); diff --git a/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart b/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart index 94a84b02604..61d22c45816 100644 --- a/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart @@ -30,199 +30,104 @@ import 'package:mockito/src/dummies.dart' as _i6; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdDisplayContainer_1 extends _i1.SmartFake implements _i2.AdDisplayContainer { - _FakeAdDisplayContainer_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdDisplayContainer_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdMediaInfo_2 extends _i1.SmartFake implements _i2.AdMediaInfo { - _FakeAdMediaInfo_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdMediaInfo_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdPodInfo_3 extends _i1.SmartFake implements _i2.AdPodInfo { - _FakeAdPodInfo_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdPodInfo_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeViewGroup_4 extends _i1.SmartFake implements _i2.ViewGroup { - _FakeViewGroup_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeViewGroup_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCompanionAdSlot_5 extends _i1.SmartFake implements _i2.CompanionAdSlot { - _FakeCompanionAdSlot_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCompanionAdSlot_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFrameLayout_6 extends _i1.SmartFake implements _i2.FrameLayout { - _FakeFrameLayout_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFrameLayout_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkSettings_7 extends _i1.SmartFake implements _i2.ImaSdkSettings { - _FakeImaSdkSettings_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkSettings_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsLoader_8 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsLoader_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRequest_9 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRequest_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRenderingSettings_10 extends _i1.SmartFake implements _i2.AdsRenderingSettings { - _FakeAdsRenderingSettings_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRenderingSettings_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkFactory_11 extends _i1.SmartFake implements _i2.ImaSdkFactory { - _FakeImaSdkFactory_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkFactory_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMediaPlayer_12 extends _i1.SmartFake implements _i2.MediaPlayer { - _FakeMediaPlayer_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMediaPlayer_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoAdPlayer_13 extends _i1.SmartFake implements _i2.VideoAdPlayer { - _FakeVideoAdPlayer_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoAdPlayer_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoAdPlayerCallback_14 extends _i1.SmartFake implements _i2.VideoAdPlayerCallback { - _FakeVideoAdPlayerCallback_14( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoAdPlayerCallback_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoProgressUpdate_15 extends _i1.SmartFake implements _i2.VideoProgressUpdate { - _FakeVideoProgressUpdate_15( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoProgressUpdate_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoView_16 extends _i1.SmartFake implements _i2.VideoView { - _FakeVideoView_16( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoView_16(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOffset_17 extends _i1.SmartFake implements _i3.Offset { - _FakeOffset_17( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOffset_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSize_18 extends _i1.SmartFake implements _i3.Size { - _FakeSize_18( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSize_18(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExpensiveAndroidViewController_19 extends _i1.SmartFake @@ -230,10 +135,7 @@ class _FakeExpensiveAndroidViewController_19 extends _i1.SmartFake _FakeExpensiveAndroidViewController_19( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeSurfaceAndroidViewController_20 extends _i1.SmartFake @@ -241,10 +143,7 @@ class _FakeSurfaceAndroidViewController_20 extends _i1.SmartFake _FakeSurfaceAndroidViewController_20( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } /// A class which mocks [AdDisplayContainer]. @@ -253,51 +152,45 @@ class _FakeSurfaceAndroidViewController_20 extends _i1.SmartFake class MockAdDisplayContainer extends _i1.Mock implements _i2.AdDisplayContainer { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdDisplayContainer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdDisplayContainer_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdDisplayContainer_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdDisplayContainer); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdDisplayContainer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdDisplayContainer_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdDisplayContainer_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdDisplayContainer); @override _i5.Future setCompanionSlots( - List<_i2.CompanionAdSlot>? companionSlots) => - (super.noSuchMethod( - Invocation.method( - #setCompanionSlots, - [companionSlots], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + List<_i2.CompanionAdSlot>? companionSlots, + ) => + (super.noSuchMethod( + Invocation.method(#setCompanionSlots, [companionSlots]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [AdMediaInfo]. @@ -305,52 +198,46 @@ class MockAdDisplayContainer extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockAdMediaInfo extends _i1.Mock implements _i2.AdMediaInfo { @override - String get url => (super.noSuchMethod( - Invocation.getter(#url), - returnValue: _i6.dummyValue( - this, - Invocation.getter(#url), - ), - returnValueForMissingStub: _i6.dummyValue( - this, - Invocation.getter(#url), - ), - ) as String); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdMediaInfo pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdMediaInfo_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdMediaInfo_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdMediaInfo); + String get url => + (super.noSuchMethod( + Invocation.getter(#url), + returnValue: _i6.dummyValue(this, Invocation.getter(#url)), + returnValueForMissingStub: _i6.dummyValue( + this, + Invocation.getter(#url), + ), + ) + as String); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdMediaInfo pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdMediaInfo_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdMediaInfo_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdMediaInfo); } /// A class which mocks [AdPodInfo]. @@ -358,81 +245,88 @@ class MockAdMediaInfo extends _i1.Mock implements _i2.AdMediaInfo { /// See the documentation for Mockito's code generation for more information. class MockAdPodInfo extends _i1.Mock implements _i2.AdPodInfo { @override - int get adPosition => (super.noSuchMethod( - Invocation.getter(#adPosition), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); - - @override - double get maxDuration => (super.noSuchMethod( - Invocation.getter(#maxDuration), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) as double); - - @override - int get podIndex => (super.noSuchMethod( - Invocation.getter(#podIndex), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); - - @override - double get timeOffset => (super.noSuchMethod( - Invocation.getter(#timeOffset), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) as double); - - @override - int get totalAds => (super.noSuchMethod( - Invocation.getter(#totalAds), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); - - @override - bool get isBumper => (super.noSuchMethod( - Invocation.getter(#isBumper), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdPodInfo pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdPodInfo_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdPodInfo_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdPodInfo); + int get adPosition => + (super.noSuchMethod( + Invocation.getter(#adPosition), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); + + @override + double get maxDuration => + (super.noSuchMethod( + Invocation.getter(#maxDuration), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) + as double); + + @override + int get podIndex => + (super.noSuchMethod( + Invocation.getter(#podIndex), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); + + @override + double get timeOffset => + (super.noSuchMethod( + Invocation.getter(#timeOffset), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) + as double); + + @override + int get totalAds => + (super.noSuchMethod( + Invocation.getter(#totalAds), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); + + @override + bool get isBumper => + (super.noSuchMethod( + Invocation.getter(#isBumper), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdPodInfo pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdPodInfo_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdPodInfo_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdPodInfo); } /// A class which mocks [CompanionAdSlot]. @@ -440,154 +334,123 @@ class MockAdPodInfo extends _i1.Mock implements _i2.AdPodInfo { /// See the documentation for Mockito's code generation for more information. class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future addClickListener( - _i2.CompanionAdSlotClickListener? clickListener) => - (super.noSuchMethod( - Invocation.method( - #addClickListener, - [clickListener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future<_i2.ViewGroup> getContainer() => (super.noSuchMethod( - Invocation.method( - #getContainer, - [], - ), - returnValue: _i5.Future<_i2.ViewGroup>.value(_FakeViewGroup_4( - this, - Invocation.method( - #getContainer, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.ViewGroup>.value(_FakeViewGroup_4( - this, - Invocation.method( - #getContainer, - [], - ), - )), - ) as _i5.Future<_i2.ViewGroup>); - - @override - _i5.Future getHeight() => (super.noSuchMethod( - Invocation.method( - #getHeight, - [], - ), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) as _i5.Future); - - @override - _i5.Future getWidth() => (super.noSuchMethod( - Invocation.method( - #getWidth, - [], - ), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) as _i5.Future); - - @override - _i5.Future isFilled() => (super.noSuchMethod( - Invocation.method( - #isFilled, - [], - ), - returnValue: _i5.Future.value(false), - returnValueForMissingStub: _i5.Future.value(false), - ) as _i5.Future); + _i2.CompanionAdSlotClickListener? clickListener, + ) => + (super.noSuchMethod( + Invocation.method(#addClickListener, [clickListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i2.ViewGroup> getContainer() => + (super.noSuchMethod( + Invocation.method(#getContainer, []), + returnValue: _i5.Future<_i2.ViewGroup>.value( + _FakeViewGroup_4(this, Invocation.method(#getContainer, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.ViewGroup>.value( + _FakeViewGroup_4(this, Invocation.method(#getContainer, [])), + ), + ) + as _i5.Future<_i2.ViewGroup>); + + @override + _i5.Future getHeight() => + (super.noSuchMethod( + Invocation.method(#getHeight, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) + as _i5.Future); + + @override + _i5.Future getWidth() => + (super.noSuchMethod( + Invocation.method(#getWidth, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) + as _i5.Future); + + @override + _i5.Future isFilled() => + (super.noSuchMethod( + Invocation.method(#isFilled, []), + returnValue: _i5.Future.value(false), + returnValueForMissingStub: _i5.Future.value(false), + ) + as _i5.Future); @override _i5.Future removeClickListener( - _i2.CompanionAdSlotClickListener? clickListener) => + _i2.CompanionAdSlotClickListener? clickListener, + ) => (super.noSuchMethod( - Invocation.method( - #removeClickListener, - [clickListener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#removeClickListener, [clickListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setContainer(_i2.ViewGroup? container) => (super.noSuchMethod( - Invocation.method( - #setContainer, - [container], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setContainer, [container]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future setSize( - int? width, - int? height, - ) => + _i5.Future setSize(int? width, int? height) => (super.noSuchMethod( - Invocation.method( - #setSize, - [ - width, - height, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setFluidSize() => (super.noSuchMethod( - Invocation.method( - #setFluidSize, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.CompanionAdSlot pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeCompanionAdSlot_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeCompanionAdSlot_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.CompanionAdSlot); + Invocation.method(#setSize, [width, height]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setFluidSize() => + (super.noSuchMethod( + Invocation.method(#setFluidSize, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.CompanionAdSlot pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCompanionAdSlot_5( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCompanionAdSlot_5( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.CompanionAdSlot); } /// A class which mocks [FrameLayout]. @@ -595,59 +458,52 @@ class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { /// See the documentation for Mockito's code generation for more information. class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.FrameLayout pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeFrameLayout_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeFrameLayout_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.FrameLayout); - - @override - _i5.Future addView(_i2.View? view) => (super.noSuchMethod( - Invocation.method( - #addView, - [view], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future removeView(_i2.View? view) => (super.noSuchMethod( - Invocation.method( - #removeView, - [view], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.FrameLayout pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFrameLayout_6( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeFrameLayout_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.FrameLayout); + + @override + _i5.Future addView(_i2.View? view) => + (super.noSuchMethod( + Invocation.method(#addView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future removeView(_i2.View? view) => + (super.noSuchMethod( + Invocation.method(#removeView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [ImaSdkFactory]. @@ -655,65 +511,57 @@ class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( - Invocation.method( - #createCompanionAdSlot, - [], - ), - returnValue: - _i5.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_5( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_5( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - ) as _i5.Future<_i2.CompanionAdSlot>); - - @override - _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( - Invocation.method( - #createImaSdkSettings, - [], - ), - returnValue: _i5.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_7( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_7( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - ) as _i5.Future<_i2.ImaSdkSettings>); + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_5( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_5( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + ) + as _i5.Future<_i2.CompanionAdSlot>); + + @override + _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => + (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_7( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_7( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + ) + as _i5.Future<_i2.ImaSdkSettings>); @override _i5.Future<_i2.AdsLoader> createAdsLoader( @@ -721,105 +569,69 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { _i2.AdDisplayContainer? container, ) => (super.noSuchMethod( - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - returnValue: _i5.Future<_i2.AdsLoader>.value(_FakeAdsLoader_8( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.AdsLoader>.value(_FakeAdsLoader_8( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - ) as _i5.Future<_i2.AdsLoader>); - - @override - _i5.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( - Invocation.method( - #createAdsRequest, - [], - ), - returnValue: _i5.Future<_i2.AdsRequest>.value(_FakeAdsRequest_9( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.AdsRequest>.value(_FakeAdsRequest_9( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - ) as _i5.Future<_i2.AdsRequest>); + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_8( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_8( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + ) + as _i5.Future<_i2.AdsLoader>); + + @override + _i5.Future<_i2.AdsRequest> createAdsRequest() => + (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), + ), + ) + as _i5.Future<_i2.AdsRequest>); @override _i5.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( - Invocation.method( - #createAdsRenderingSettings, - [], - ), - returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_10( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - returnValueForMissingStub: _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_10( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - ) as _i5.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkFactory_11( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkFactory_11( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkFactory); + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_10( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + returnValueForMissingStub: + _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_10( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + ) + as _i5.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_11( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkFactory_11( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkFactory); } /// A class which mocks [MediaPlayer]. @@ -827,89 +639,79 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockMediaPlayer extends _i1.Mock implements _i2.MediaPlayer { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future getDuration() => (super.noSuchMethod( - Invocation.method( - #getDuration, - [], - ), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) as _i5.Future); - - @override - _i5.Future seekTo(int? mSec) => (super.noSuchMethod( - Invocation.method( - #seekTo, - [mSec], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future start() => (super.noSuchMethod( - Invocation.method( - #start, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future stop() => (super.noSuchMethod( - Invocation.method( - #stop, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.MediaPlayer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeMediaPlayer_12( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeMediaPlayer_12( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.MediaPlayer); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future getDuration() => + (super.noSuchMethod( + Invocation.method(#getDuration, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) + as _i5.Future); + + @override + _i5.Future seekTo(int? mSec) => + (super.noSuchMethod( + Invocation.method(#seekTo, [mSec]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future start() => + (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future pause() => + (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future stop() => + (super.noSuchMethod( + Invocation.method(#stop, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.MediaPlayer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeMediaPlayer_12( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeMediaPlayer_12( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.MediaPlayer); } /// A class which mocks [VideoAdPlayer]. @@ -917,185 +719,166 @@ class MockMediaPlayer extends _i1.Mock implements _i2.MediaPlayer { /// See the documentation for Mockito's code generation for more information. class MockVideoAdPlayer extends _i1.Mock implements _i2.VideoAdPlayer { @override - void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - ) get addCallback => (super.noSuchMethod( - Invocation.getter(#addCallback), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - _i2.AdPodInfo, - ) get loadAd => (super.noSuchMethod( - Invocation.getter(#loadAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - _i2.AdPodInfo, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - ) get pauseAd => (super.noSuchMethod( - Invocation.getter(#pauseAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - ) get playAd => (super.noSuchMethod( - Invocation.getter(#playAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - )); - - @override - void Function(_i2.VideoAdPlayer) get release => (super.noSuchMethod( - Invocation.getter(#release), - returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, - returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, - ) as void Function(_i2.VideoAdPlayer)); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - ) get removeCallback => (super.noSuchMethod( - Invocation.getter(#removeCallback), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - ) get stopAd => (super.noSuchMethod( - Invocation.getter(#stopAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future setVolume(int? value) => (super.noSuchMethod( - Invocation.method( - #setVolume, - [value], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) get addCallback => + (super.noSuchMethod( + Invocation.getter(#addCallback), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo) get loadAd => + (super.noSuchMethod( + Invocation.getter(#loadAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get pauseAd => + (super.noSuchMethod( + Invocation.getter(#pauseAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get playAd => + (super.noSuchMethod( + Invocation.getter(#playAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer) get release => + (super.noSuchMethod( + Invocation.getter(#release), + returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, + ) + as void Function(_i2.VideoAdPlayer)); + + @override + void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) + get removeCallback => + (super.noSuchMethod( + Invocation.getter(#removeCallback), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get stopAd => + (super.noSuchMethod( + Invocation.getter(#stopAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future setVolume(int? value) => + (super.noSuchMethod( + Invocation.method(#setVolume, [value]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setAdProgress(_i2.VideoProgressUpdate? progress) => (super.noSuchMethod( - Invocation.method( - #setAdProgress, - [progress], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.VideoAdPlayer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoAdPlayer_13( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoAdPlayer_13( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoAdPlayer); + Invocation.method(#setAdProgress, [progress]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.VideoAdPlayer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayer_13( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoAdPlayer_13( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoAdPlayer); } /// A class which mocks [VideoAdPlayerCallback]. @@ -1104,17 +887,19 @@ class MockVideoAdPlayer extends _i1.Mock implements _i2.VideoAdPlayer { class MockVideoAdPlayerCallback extends _i1.Mock implements _i2.VideoAdPlayerCallback { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future onAdProgress( @@ -1122,99 +907,86 @@ class MockVideoAdPlayerCallback extends _i1.Mock _i2.VideoProgressUpdate? videoProgressUpdate, ) => (super.noSuchMethod( - Invocation.method( - #onAdProgress, - [ - adMediaInfo, - videoProgressUpdate, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onAdProgress, [ + adMediaInfo, + videoProgressUpdate, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onBuffering(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onBuffering, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future onContentComplete() => (super.noSuchMethod( - Invocation.method( - #onContentComplete, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onEnded, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onError, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onBuffering, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future onContentComplete() => + (super.noSuchMethod( + Invocation.method(#onContentComplete, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onEnded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onError, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onLoaded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onLoaded, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onLoaded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onPause, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onPause, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onPlay, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onPlay, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onResume(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onResume, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onResume, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onVolumeChanged( @@ -1222,38 +994,26 @@ class MockVideoAdPlayerCallback extends _i1.Mock int? percentage, ) => (super.noSuchMethod( - Invocation.method( - #onVolumeChanged, - [ - adMediaInfo, - percentage, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.VideoAdPlayerCallback pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoAdPlayerCallback_14( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoAdPlayerCallback_14( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoAdPlayerCallback); + Invocation.method(#onVolumeChanged, [adMediaInfo, percentage]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.VideoAdPlayerCallback pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayerCallback_14( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoAdPlayerCallback_14( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoAdPlayerCallback); } /// A class which mocks [VideoProgressUpdate]. @@ -1262,39 +1022,34 @@ class MockVideoAdPlayerCallback extends _i1.Mock class MockVideoProgressUpdate extends _i1.Mock implements _i2.VideoProgressUpdate { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.VideoProgressUpdate pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoProgressUpdate_15( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoProgressUpdate_15( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoProgressUpdate); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.VideoProgressUpdate pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoProgressUpdate_15( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoProgressUpdate_15( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoProgressUpdate); } /// A class which mocks [VideoView]. @@ -1302,86 +1057,73 @@ class MockVideoProgressUpdate extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockVideoView extends _i1.Mock implements _i2.VideoView { @override - void Function( - _i2.VideoView, - _i2.MediaPlayer, - int, - int, - ) get onError => (super.noSuchMethod( - Invocation.getter(#onError), - returnValue: ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - returnValueForMissingStub: ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - ) as void Function( - _i2.VideoView, - _i2.MediaPlayer, - int, - int, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future setVideoUri(String? uri) => (super.noSuchMethod( - Invocation.method( - #setVideoUri, - [uri], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future getCurrentPosition() => (super.noSuchMethod( - Invocation.method( - #getCurrentPosition, - [], - ), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) as _i5.Future); - - @override - _i2.VideoView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoView_16( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoView_16( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoView); + void Function(_i2.VideoView, _i2.MediaPlayer, int, int) get onError => + (super.noSuchMethod( + Invocation.getter(#onError), + returnValue: + ( + _i2.VideoView pigeon_instance, + _i2.MediaPlayer player, + int what, + int extra, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoView pigeon_instance, + _i2.MediaPlayer player, + int what, + int extra, + ) {}, + ) + as void Function(_i2.VideoView, _i2.MediaPlayer, int, int)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future setVideoUri(String? uri) => + (super.noSuchMethod( + Invocation.method(#setVideoUri, [uri]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future getCurrentPosition() => + (super.noSuchMethod( + Invocation.method(#getCurrentPosition, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) + as _i5.Future); + + @override + _i2.VideoView pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoView_16( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoView_16( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoView); } /// A class which mocks [SurfaceAndroidViewController]. @@ -1390,187 +1132,160 @@ class MockVideoView extends _i1.Mock implements _i2.VideoView { class MockSurfaceAndroidViewController extends _i1.Mock implements _i4.SurfaceAndroidViewController { @override - bool get requiresViewComposition => (super.noSuchMethod( - Invocation.getter(#requiresViewComposition), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); - - @override - int get viewId => (super.noSuchMethod( - Invocation.getter(#viewId), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + bool get requiresViewComposition => + (super.noSuchMethod( + Invocation.getter(#requiresViewComposition), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - bool get awaitingCreation => (super.noSuchMethod( - Invocation.getter(#awaitingCreation), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + int get viewId => + (super.noSuchMethod( + Invocation.getter(#viewId), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override - _i4.PointTransformer get pointTransformer => (super.noSuchMethod( - Invocation.getter(#pointTransformer), - returnValue: (_i3.Offset position) => _FakeOffset_17( - this, - Invocation.getter(#pointTransformer), - ), - returnValueForMissingStub: (_i3.Offset position) => _FakeOffset_17( - this, - Invocation.getter(#pointTransformer), - ), - ) as _i4.PointTransformer); + bool get awaitingCreation => + (super.noSuchMethod( + Invocation.getter(#awaitingCreation), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - bool get isCreated => (super.noSuchMethod( - Invocation.getter(#isCreated), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + _i4.PointTransformer get pointTransformer => + (super.noSuchMethod( + Invocation.getter(#pointTransformer), + returnValue: + (_i3.Offset position) => + _FakeOffset_17(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: + (_i3.Offset position) => + _FakeOffset_17(this, Invocation.getter(#pointTransformer)), + ) + as _i4.PointTransformer); + + @override + bool get isCreated => + (super.noSuchMethod( + Invocation.getter(#isCreated), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override List<_i4.PlatformViewCreatedCallback> get createdCallbacks => (super.noSuchMethod( - Invocation.getter(#createdCallbacks), - returnValue: <_i4.PlatformViewCreatedCallback>[], - returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], - ) as List<_i4.PlatformViewCreatedCallback>); + Invocation.getter(#createdCallbacks), + returnValue: <_i4.PlatformViewCreatedCallback>[], + returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], + ) + as List<_i4.PlatformViewCreatedCallback>); @override set pointTransformer(_i4.PointTransformer? transformer) => super.noSuchMethod( - Invocation.setter( - #pointTransformer, - transformer, - ), - returnValueForMissingStub: null, - ); - - @override - _i5.Future setOffset(_i3.Offset? off) => (super.noSuchMethod( - Invocation.method( - #setOffset, - [off], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future create({ - _i3.Size? size, - _i3.Offset? position, - }) => + Invocation.setter(#pointTransformer, transformer), + returnValueForMissingStub: null, + ); + + @override + _i5.Future setOffset(_i3.Offset? off) => (super.noSuchMethod( - Invocation.method( - #create, - [], - { - #size: size, - #position: position, - }, - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future<_i3.Size> setSize(_i3.Size? size) => (super.noSuchMethod( - Invocation.method( - #setSize, - [size], - ), - returnValue: _i5.Future<_i3.Size>.value(_FakeSize_18( - this, - Invocation.method( - #setSize, - [size], - ), - )), - returnValueForMissingStub: _i5.Future<_i3.Size>.value(_FakeSize_18( - this, - Invocation.method( - #setSize, - [size], - ), - )), - ) as _i5.Future<_i3.Size>); + Invocation.method(#setOffset, [off]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future create({_i3.Size? size, _i3.Offset? position}) => + (super.noSuchMethod( + Invocation.method(#create, [], {#size: size, #position: position}), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i3.Size> setSize(_i3.Size? size) => + (super.noSuchMethod( + Invocation.method(#setSize, [size]), + returnValue: _i5.Future<_i3.Size>.value( + _FakeSize_18(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i5.Future<_i3.Size>.value( + _FakeSize_18(this, Invocation.method(#setSize, [size])), + ), + ) + as _i5.Future<_i3.Size>); @override _i5.Future sendMotionEvent(_i4.AndroidMotionEvent? event) => (super.noSuchMethod( - Invocation.method( - #sendMotionEvent, - [event], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#sendMotionEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override void addOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #addOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i4.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override void removeOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #removeOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i4.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override _i5.Future setLayoutDirection(_i3.TextDirection? layoutDirection) => (super.noSuchMethod( - Invocation.method( - #setLayoutDirection, - [layoutDirection], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setLayoutDirection, [layoutDirection]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future dispatchPointerEvent(_i4.PointerEvent? event) => (super.noSuchMethod( - Invocation.method( - #dispatchPointerEvent, - [event], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future clearFocus() => (super.noSuchMethod( - Invocation.method( - #clearFocus, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#dispatchPointerEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future clearFocus() => + (super.noSuchMethod( + Invocation.method(#clearFocus, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future dispose() => + (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [PlatformViewsServiceProxy]. @@ -1589,49 +1304,38 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i3.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - returnValue: _FakeExpensiveAndroidViewController_19( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { + Invocation.method(#initExpensiveAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - ), - returnValueForMissingStub: _FakeExpensiveAndroidViewController_19( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - ), - ) as _i4.ExpensiveAndroidViewController); + }), + returnValue: _FakeExpensiveAndroidViewController_19( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeExpensiveAndroidViewController_19( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) + as _i4.ExpensiveAndroidViewController); @override _i4.SurfaceAndroidViewController initSurfaceAndroidView({ @@ -1643,47 +1347,36 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i3.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - returnValue: _FakeSurfaceAndroidViewController_20( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - ), - returnValueForMissingStub: _FakeSurfaceAndroidViewController_20( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { + Invocation.method(#initSurfaceAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - ), - ) as _i4.SurfaceAndroidViewController); + }), + returnValue: _FakeSurfaceAndroidViewController_20( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeSurfaceAndroidViewController_20( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) + as _i4.SurfaceAndroidViewController); } diff --git a/packages/interactive_media_ads/test/android/ads_loader_test.dart b/packages/interactive_media_ads/test/android/ads_loader_test.dart index 90a76e86aa1..9b38eb1dc1d 100644 --- a/packages/interactive_media_ads/test/android/ads_loader_test.dart +++ b/packages/interactive_media_ads/test/android/ads_loader_test.dart @@ -47,8 +47,9 @@ void main() { }); testWidgets('instantiate AndroidAdsLoader', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); final MockImaSdkSettings mockImaSdkSettings = MockImaSdkSettings(); final MockImaSdkFactory mockSdkFactory = _mockImaSdkFactoryInstance( @@ -69,10 +70,12 @@ void main() { ); expect(await settings.nativeSettingsFuture, mockImaSdkSettings); - verify(mockSdkFactory.createAdsLoader( - mockImaSdkSettings, - container.adDisplayContainer, - )); + verify( + mockSdkFactory.createAdsLoader( + mockImaSdkSettings, + container.adDisplayContainer, + ), + ); }); testWidgets('contentComplete', (WidgetTester tester) async { @@ -101,8 +104,9 @@ void main() { }); testWidgets('requestAds', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); final MockAdsLoader mockAdsLoader = MockAdsLoader(); final MockAdsRequest mockAdsRequest = MockAdsRequest(); @@ -112,8 +116,8 @@ void main() { ); final InteractiveMediaAdsProxy proxy = InteractiveMediaAdsProxy( - newContentProgressProvider: () => - ima.ContentProgressProvider.pigeon_detached(), + newContentProgressProvider: + () => ima.ContentProgressProvider.pigeon_detached(), ); final AndroidAdsLoader adsLoader = AndroidAdsLoader( @@ -130,8 +134,8 @@ void main() { final AndroidContentProgressProvider progressProvider = AndroidContentProgressProvider( - AndroidContentProgressProviderCreationParams(proxy: proxy), - ); + AndroidContentProgressProviderCreationParams(proxy: proxy), + ); await adsLoader.requestAds( PlatformAdsRequest.withAdTagUrl( adTagUrl: 'url', @@ -166,8 +170,9 @@ void main() { }); testWidgets('requestAds with adsResponse', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); final MockAdsLoader mockAdsLoader = MockAdsLoader(); final MockAdsRequest mockAdsRequest = MockAdsRequest(); @@ -177,8 +182,8 @@ void main() { ); final InteractiveMediaAdsProxy proxy = InteractiveMediaAdsProxy( - newContentProgressProvider: () => - ima.ContentProgressProvider.pigeon_detached(), + newContentProgressProvider: + () => ima.ContentProgressProvider.pigeon_detached(), ); final AndroidAdsLoader adsLoader = AndroidAdsLoader( @@ -195,8 +200,8 @@ void main() { final AndroidContentProgressProvider progressProvider = AndroidContentProgressProvider( - AndroidContentProgressProviderCreationParams(proxy: proxy), - ); + AndroidContentProgressProviderCreationParams(proxy: proxy), + ); await adsLoader.requestAds( PlatformAdsRequest.withAdsResponse( adsResponse: 'url', @@ -231,8 +236,9 @@ void main() { }); testWidgets('onAdsLoaded', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); final MockAdsLoader mockAdsLoader = MockAdsLoader(); final Completer addEventListenerCompleter = Completer(); @@ -241,17 +247,16 @@ void main() { }); _mockImaSdkFactoryInstance(adsLoader: mockAdsLoader); - late final void Function( - ima.AdsLoadedListener, - ima.AdsManagerLoadedEvent, - ) onAdsManagerLoadedCallback; + late final void Function(ima.AdsLoadedListener, ima.AdsManagerLoadedEvent) + onAdsManagerLoadedCallback; final InteractiveMediaAdsProxy proxy = InteractiveMediaAdsProxy( newAdsLoadedListener: ({ required void Function( ima.AdsLoadedListener, ima.AdsManagerLoadedEvent, - ) onAdsManagerLoaded, + ) + onAdsManagerLoaded, }) { onAdsManagerLoadedCallback = onAdsManagerLoaded; return MockAdsLoadedListener(); @@ -283,8 +288,9 @@ void main() { }); testWidgets('onAdError', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); final MockAdsLoader mockAdsLoader = MockAdsLoader(); final Completer addErrorListenerCompleter = Completer(); @@ -293,20 +299,16 @@ void main() { }); _mockImaSdkFactoryInstance(adsLoader: mockAdsLoader); - late final void Function( - ima.AdErrorListener, - ima.AdErrorEvent, - ) onAdErrorCallback; + late final void Function(ima.AdErrorListener, ima.AdErrorEvent) + onAdErrorCallback; final InteractiveMediaAdsProxy proxy = InteractiveMediaAdsProxy( newAdsLoadedListener: ({required dynamic onAdsManagerLoaded}) { return MockAdsLoadedListener(); }, newAdErrorListener: ({ - required void Function( - ima.AdErrorListener, - ima.AdErrorEvent, - ) onAdError, + required void Function(ima.AdErrorListener, ima.AdErrorEvent) + onAdError, }) { onAdErrorCallback = onAdError; return MockAdErrorListener(); @@ -328,8 +330,9 @@ void main() { final MockAdErrorEvent mockErrorEvent = MockAdErrorEvent(); final MockAdError mockError = MockAdError(); when(mockError.errorType).thenReturn(ima.AdErrorType.load); - when(mockError.errorCode) - .thenReturn(ima.AdErrorCode.adsRequestNetworkError); + when( + mockError.errorCode, + ).thenReturn(ima.AdErrorCode.adsRequestNetworkError); when(mockError.message).thenReturn('error message'); when(mockErrorEvent.error).thenReturn(mockError); @@ -365,23 +368,18 @@ Future _pumpAdDisplayContainer( }) async { final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newFrameLayout: () => MockFrameLayout(), - newVideoView: ({ - required dynamic onError, - dynamic onPrepared, - dynamic onCompletion, - }) => - MockVideoView(), - createAdDisplayContainerImaSdkFactory: ( - _, - __, - ) async { + newVideoView: + ({ + required dynamic onError, + dynamic onPrepared, + dynamic onCompletion, + }) => MockVideoView(), + createAdDisplayContainerImaSdkFactory: (_, __) async { return MockAdDisplayContainer(); }, newVideoAdPlayer: ({ - required void Function( - ima.VideoAdPlayer, - ima.VideoAdPlayerCallback, - ) addCallback, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) + addCallback, required dynamic loadAd, required dynamic pauseAd, required dynamic playAd, @@ -431,14 +429,17 @@ Future _pumpAdDisplayContainer( ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); - final void Function(int) onPlatformCreatedCallback = verify( - mockAndroidViewController - .addOnPlatformViewCreatedListener(captureAny)) - .captured[0] as void Function(int); + final void Function(int) onPlatformCreatedCallback = + verify( + mockAndroidViewController.addOnPlatformViewCreatedListener( + captureAny, + ), + ).captured[0] + as void Function(int); onPlatformCreatedCallback(platformViewId); diff --git a/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart b/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart index beb7cf9d8e4..acfc952cc79 100644 --- a/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart @@ -30,211 +30,111 @@ import 'package:mockito/src/dummies.dart' as _i6; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdDisplayContainer_1 extends _i1.SmartFake implements _i2.AdDisplayContainer { - _FakeAdDisplayContainer_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdDisplayContainer_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdError_2 extends _i1.SmartFake implements _i2.AdError { - _FakeAdError_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdError_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdErrorEvent_3 extends _i1.SmartFake implements _i2.AdErrorEvent { - _FakeAdErrorEvent_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdErrorEvent_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdErrorListener_4 extends _i1.SmartFake implements _i2.AdErrorListener { - _FakeAdErrorListener_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdErrorListener_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsLoadedListener_5 extends _i1.SmartFake implements _i2.AdsLoadedListener { - _FakeAdsLoadedListener_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsLoadedListener_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsManager_6 extends _i1.SmartFake implements _i2.AdsManager { - _FakeAdsManager_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsManager_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsManagerLoadedEvent_7 extends _i1.SmartFake implements _i2.AdsManagerLoadedEvent { - _FakeAdsManagerLoadedEvent_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsManagerLoadedEvent_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsLoader_8 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsLoader_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRequest_9 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRequest_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFrameLayout_10 extends _i1.SmartFake implements _i2.FrameLayout { - _FakeFrameLayout_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFrameLayout_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCompanionAdSlot_11 extends _i1.SmartFake implements _i2.CompanionAdSlot { - _FakeCompanionAdSlot_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCompanionAdSlot_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkSettings_12 extends _i1.SmartFake implements _i2.ImaSdkSettings { - _FakeImaSdkSettings_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkSettings_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRenderingSettings_13 extends _i1.SmartFake implements _i2.AdsRenderingSettings { - _FakeAdsRenderingSettings_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRenderingSettings_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkFactory_14 extends _i1.SmartFake implements _i2.ImaSdkFactory { - _FakeImaSdkFactory_14( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkFactory_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoAdPlayer_15 extends _i1.SmartFake implements _i2.VideoAdPlayer { - _FakeVideoAdPlayer_15( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoAdPlayer_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoAdPlayerCallback_16 extends _i1.SmartFake implements _i2.VideoAdPlayerCallback { - _FakeVideoAdPlayerCallback_16( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoAdPlayerCallback_16(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVideoView_17 extends _i1.SmartFake implements _i2.VideoView { - _FakeVideoView_17( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVideoView_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOffset_18 extends _i1.SmartFake implements _i3.Offset { - _FakeOffset_18( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOffset_18(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSize_19 extends _i1.SmartFake implements _i3.Size { - _FakeSize_19( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSize_19(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExpensiveAndroidViewController_20 extends _i1.SmartFake @@ -242,10 +142,7 @@ class _FakeExpensiveAndroidViewController_20 extends _i1.SmartFake _FakeExpensiveAndroidViewController_20( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeSurfaceAndroidViewController_21 extends _i1.SmartFake @@ -253,10 +150,7 @@ class _FakeSurfaceAndroidViewController_21 extends _i1.SmartFake _FakeSurfaceAndroidViewController_21( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } /// A class which mocks [AdDisplayContainer]. @@ -265,51 +159,45 @@ class _FakeSurfaceAndroidViewController_21 extends _i1.SmartFake class MockAdDisplayContainer extends _i1.Mock implements _i2.AdDisplayContainer { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdDisplayContainer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdDisplayContainer_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdDisplayContainer_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdDisplayContainer); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdDisplayContainer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdDisplayContainer_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdDisplayContainer_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdDisplayContainer); @override _i5.Future setCompanionSlots( - List<_i2.CompanionAdSlot>? companionSlots) => - (super.noSuchMethod( - Invocation.method( - #setCompanionSlots, - [companionSlots], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + List<_i2.CompanionAdSlot>? companionSlots, + ) => + (super.noSuchMethod( + Invocation.method(#setCompanionSlots, [companionSlots]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [AdError]. @@ -317,73 +205,76 @@ class MockAdDisplayContainer extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockAdError extends _i1.Mock implements _i2.AdError { @override - _i2.AdErrorCode get errorCode => (super.noSuchMethod( - Invocation.getter(#errorCode), - returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, - returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, - ) as _i2.AdErrorCode); - - @override - int get errorCodeNumber => (super.noSuchMethod( - Invocation.getter(#errorCodeNumber), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); - - @override - _i2.AdErrorType get errorType => (super.noSuchMethod( - Invocation.getter(#errorType), - returnValue: _i2.AdErrorType.load, - returnValueForMissingStub: _i2.AdErrorType.load, - ) as _i2.AdErrorType); - - @override - String get message => (super.noSuchMethod( - Invocation.getter(#message), - returnValue: _i6.dummyValue( - this, - Invocation.getter(#message), - ), - returnValueForMissingStub: _i6.dummyValue( - this, - Invocation.getter(#message), - ), - ) as String); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdError pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdError_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdError_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdError); + _i2.AdErrorCode get errorCode => + (super.noSuchMethod( + Invocation.getter(#errorCode), + returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, + returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, + ) + as _i2.AdErrorCode); + + @override + int get errorCodeNumber => + (super.noSuchMethod( + Invocation.getter(#errorCodeNumber), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); + + @override + _i2.AdErrorType get errorType => + (super.noSuchMethod( + Invocation.getter(#errorType), + returnValue: _i2.AdErrorType.load, + returnValueForMissingStub: _i2.AdErrorType.load, + ) + as _i2.AdErrorType); + + @override + String get message => + (super.noSuchMethod( + Invocation.getter(#message), + returnValue: _i6.dummyValue( + this, + Invocation.getter(#message), + ), + returnValueForMissingStub: _i6.dummyValue( + this, + Invocation.getter(#message), + ), + ) + as String); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdError pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdError_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdError_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdError); } /// A class which mocks [AdErrorEvent]. @@ -391,52 +282,46 @@ class MockAdError extends _i1.Mock implements _i2.AdError { /// See the documentation for Mockito's code generation for more information. class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { @override - _i2.AdError get error => (super.noSuchMethod( - Invocation.getter(#error), - returnValue: _FakeAdError_2( - this, - Invocation.getter(#error), - ), - returnValueForMissingStub: _FakeAdError_2( - this, - Invocation.getter(#error), - ), - ) as _i2.AdError); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorEvent pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdErrorEvent_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdErrorEvent_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdErrorEvent); + _i2.AdError get error => + (super.noSuchMethod( + Invocation.getter(#error), + returnValue: _FakeAdError_2(this, Invocation.getter(#error)), + returnValueForMissingStub: _FakeAdError_2( + this, + Invocation.getter(#error), + ), + ) + as _i2.AdError); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorEvent pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorEvent_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdErrorEvent_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdErrorEvent); } /// A class which mocks [AdErrorListener]. @@ -444,58 +329,51 @@ class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { /// See the documentation for Mockito's code generation for more information. class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { @override - void Function( - _i2.AdErrorListener, - _i2.AdErrorEvent, - ) get onAdError => (super.noSuchMethod( - Invocation.getter(#onAdError), - returnValue: ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - returnValueForMissingStub: ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - ) as void Function( - _i2.AdErrorListener, - _i2.AdErrorEvent, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdErrorListener_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdErrorListener_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdErrorListener); + void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => + (super.noSuchMethod( + Invocation.getter(#onAdError), + returnValue: + ( + _i2.AdErrorListener pigeon_instance, + _i2.AdErrorEvent event, + ) {}, + returnValueForMissingStub: + ( + _i2.AdErrorListener pigeon_instance, + _i2.AdErrorEvent event, + ) {}, + ) + as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorListener pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorListener_4( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdErrorListener_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdErrorListener); } /// A class which mocks [AdsLoadedListener]. @@ -503,58 +381,52 @@ class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { /// See the documentation for Mockito's code generation for more information. class MockAdsLoadedListener extends _i1.Mock implements _i2.AdsLoadedListener { @override - void Function( - _i2.AdsLoadedListener, - _i2.AdsManagerLoadedEvent, - ) get onAdsManagerLoaded => (super.noSuchMethod( - Invocation.getter(#onAdsManagerLoaded), - returnValue: ( - _i2.AdsLoadedListener pigeon_instance, - _i2.AdsManagerLoadedEvent event, - ) {}, - returnValueForMissingStub: ( - _i2.AdsLoadedListener pigeon_instance, - _i2.AdsManagerLoadedEvent event, - ) {}, - ) as void Function( - _i2.AdsLoadedListener, - _i2.AdsManagerLoadedEvent, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdsLoadedListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsLoadedListener_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsLoadedListener_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsLoadedListener); + void Function(_i2.AdsLoadedListener, _i2.AdsManagerLoadedEvent) + get onAdsManagerLoaded => + (super.noSuchMethod( + Invocation.getter(#onAdsManagerLoaded), + returnValue: + ( + _i2.AdsLoadedListener pigeon_instance, + _i2.AdsManagerLoadedEvent event, + ) {}, + returnValueForMissingStub: + ( + _i2.AdsLoadedListener pigeon_instance, + _i2.AdsManagerLoadedEvent event, + ) {}, + ) + as void Function(_i2.AdsLoadedListener, _i2.AdsManagerLoadedEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdsLoadedListener pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsLoadedListener_5( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsLoadedListener_5( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsLoadedListener); } /// A class which mocks [AdsManager]. @@ -562,195 +434,173 @@ class MockAdsLoadedListener extends _i1.Mock implements _i2.AdsLoadedListener { /// See the documentation for Mockito's code generation for more information. class MockAdsManager extends _i1.Mock implements _i2.AdsManager { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future discardAdBreak() => (super.noSuchMethod( - Invocation.method( - #discardAdBreak, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future start() => (super.noSuchMethod( - Invocation.method( - #start, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future> getAdCuePoints() => (super.noSuchMethod( - Invocation.method( - #getAdCuePoints, - [], - ), - returnValue: _i5.Future>.value([]), - returnValueForMissingStub: _i5.Future>.value([]), - ) as _i5.Future>); - - @override - _i5.Future resume() => (super.noSuchMethod( - Invocation.method( - #resume, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future skip() => (super.noSuchMethod( - Invocation.method( - #skip, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.AdsManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsManager_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsManager_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future discardAdBreak() => + (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future pause() => + (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future start() => + (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future> getAdCuePoints() => + (super.noSuchMethod( + Invocation.method(#getAdCuePoints, []), + returnValue: _i5.Future>.value([]), + returnValueForMissingStub: _i5.Future>.value( + [], + ), + ) + as _i5.Future>); + + @override + _i5.Future resume() => + (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future skip() => + (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.AdsManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManager_6( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsManager_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsManager); @override _i5.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( - Invocation.method( - #addAdErrorListener, - [errorListener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#addAdErrorListener, [errorListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future addAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( - Invocation.method( - #addAdEventListener, - [adEventListener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#addAdEventListener, [adEventListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future destroy() => + (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future init(_i2.AdsRenderingSettings? settings) => (super.noSuchMethod( - Invocation.method( - #init, - [settings], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future focus() => (super.noSuchMethod( - Invocation.method( - #focus, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future<_i2.AdProgressInfo?> getAdProgressInfo() => (super.noSuchMethod( - Invocation.method( - #getAdProgressInfo, - [], - ), - returnValue: _i5.Future<_i2.AdProgressInfo?>.value(), - returnValueForMissingStub: _i5.Future<_i2.AdProgressInfo?>.value(), - ) as _i5.Future<_i2.AdProgressInfo?>); - - @override - _i5.Future<_i2.Ad?> getCurrentAd() => (super.noSuchMethod( - Invocation.method( - #getCurrentAd, - [], - ), - returnValue: _i5.Future<_i2.Ad?>.value(), - returnValueForMissingStub: _i5.Future<_i2.Ad?>.value(), - ) as _i5.Future<_i2.Ad?>); + Invocation.method(#init, [settings]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future focus() => + (super.noSuchMethod( + Invocation.method(#focus, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i2.AdProgressInfo?> getAdProgressInfo() => + (super.noSuchMethod( + Invocation.method(#getAdProgressInfo, []), + returnValue: _i5.Future<_i2.AdProgressInfo?>.value(), + returnValueForMissingStub: _i5.Future<_i2.AdProgressInfo?>.value(), + ) + as _i5.Future<_i2.AdProgressInfo?>); + + @override + _i5.Future<_i2.Ad?> getCurrentAd() => + (super.noSuchMethod( + Invocation.method(#getCurrentAd, []), + returnValue: _i5.Future<_i2.Ad?>.value(), + returnValueForMissingStub: _i5.Future<_i2.Ad?>.value(), + ) + as _i5.Future<_i2.Ad?>); @override _i5.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( - Invocation.method( - #removeAdErrorListener, - [errorListener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#removeAdErrorListener, [errorListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future removeAdEventListener( - _i2.AdEventListener? adEventListener) => - (super.noSuchMethod( - Invocation.method( - #removeAdEventListener, - [adEventListener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i2.AdEventListener? adEventListener, + ) => + (super.noSuchMethod( + Invocation.method(#removeAdEventListener, [adEventListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [AdsManagerLoadedEvent]. @@ -759,52 +609,46 @@ class MockAdsManager extends _i1.Mock implements _i2.AdsManager { class MockAdsManagerLoadedEvent extends _i1.Mock implements _i2.AdsManagerLoadedEvent { @override - _i2.AdsManager get manager => (super.noSuchMethod( - Invocation.getter(#manager), - returnValue: _FakeAdsManager_6( - this, - Invocation.getter(#manager), - ), - returnValueForMissingStub: _FakeAdsManager_6( - this, - Invocation.getter(#manager), - ), - ) as _i2.AdsManager); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdsManagerLoadedEvent pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsManagerLoadedEvent_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsManagerLoadedEvent_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsManagerLoadedEvent); + _i2.AdsManager get manager => + (super.noSuchMethod( + Invocation.getter(#manager), + returnValue: _FakeAdsManager_6(this, Invocation.getter(#manager)), + returnValueForMissingStub: _FakeAdsManager_6( + this, + Invocation.getter(#manager), + ), + ) + as _i2.AdsManager); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdsManagerLoadedEvent pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManagerLoadedEvent_7( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsManagerLoadedEvent_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsManagerLoadedEvent); } /// A class which mocks [AdsLoader]. @@ -812,71 +656,61 @@ class MockAdsManagerLoadedEvent extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockAdsLoader extends _i1.Mock implements _i2.AdsLoader { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future addAdErrorListener(_i2.AdErrorListener? listener) => (super.noSuchMethod( - Invocation.method( - #addAdErrorListener, - [listener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#addAdErrorListener, [listener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future addAdsLoadedListener(_i2.AdsLoadedListener? listener) => (super.noSuchMethod( - Invocation.method( - #addAdsLoadedListener, - [listener], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future requestAds(_i2.AdsRequest? request) => (super.noSuchMethod( - Invocation.method( - #requestAds, - [request], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.AdsLoader pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsLoader_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsLoader_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsLoader); + Invocation.method(#addAdsLoadedListener, [listener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future requestAds(_i2.AdsRequest? request) => + (super.noSuchMethod( + Invocation.method(#requestAds, [request]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.AdsLoader pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsLoader_8( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsLoader_8( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsLoader); } /// A class which mocks [AdsRequest]. @@ -884,156 +718,135 @@ class MockAdsLoader extends _i1.Mock implements _i2.AdsLoader { /// See the documentation for Mockito's code generation for more information. class MockAdsRequest extends _i1.Mock implements _i2.AdsRequest { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future setAdTagUrl(String? adTagUrl) => (super.noSuchMethod( - Invocation.method( - #setAdTagUrl, - [adTagUrl], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future setAdTagUrl(String? adTagUrl) => + (super.noSuchMethod( + Invocation.method(#setAdTagUrl, [adTagUrl]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setContentProgressProvider( - _i2.ContentProgressProvider? provider) => + _i2.ContentProgressProvider? provider, + ) => (super.noSuchMethod( - Invocation.method( - #setContentProgressProvider, - [provider], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setContentProgressProvider, [provider]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future setAdWillAutoPlay(bool? willAutoPlay) => (super.noSuchMethod( - Invocation.method( - #setAdWillAutoPlay, - [willAutoPlay], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future setAdWillAutoPlay(bool? willAutoPlay) => + (super.noSuchMethod( + Invocation.method(#setAdWillAutoPlay, [willAutoPlay]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setAdWillPlayMuted(bool? willPlayMuted) => (super.noSuchMethod( - Invocation.method( - #setAdWillPlayMuted, - [willPlayMuted], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setAdWillPlayMuted, [willPlayMuted]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setAdsResponse(String? cannedAdResponse) => (super.noSuchMethod( - Invocation.method( - #setAdsResponse, - [cannedAdResponse], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setAdsResponse, [cannedAdResponse]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future setContentDuration(double? duration) => (super.noSuchMethod( - Invocation.method( - #setContentDuration, - [duration], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future setContentDuration(double? duration) => + (super.noSuchMethod( + Invocation.method(#setContentDuration, [duration]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setContentKeywords(List? keywords) => (super.noSuchMethod( - Invocation.method( - #setContentKeywords, - [keywords], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setContentKeywords, [keywords]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future setContentTitle(String? title) => (super.noSuchMethod( - Invocation.method( - #setContentTitle, - [title], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future setContentTitle(String? title) => + (super.noSuchMethod( + Invocation.method(#setContentTitle, [title]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setContinuousPlayback(bool? continuousPlayback) => (super.noSuchMethod( - Invocation.method( - #setContinuousPlayback, - [continuousPlayback], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setContinuousPlayback, [continuousPlayback]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setLiveStreamPrefetchSeconds(double? prefetchTime) => (super.noSuchMethod( - Invocation.method( - #setLiveStreamPrefetchSeconds, - [prefetchTime], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setVastLoadTimeout(double? timeout) => (super.noSuchMethod( - Invocation.method( - #setVastLoadTimeout, - [timeout], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.AdsRequest pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsRequest_9( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsRequest_9( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsRequest); + Invocation.method(#setLiveStreamPrefetchSeconds, [prefetchTime]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setVastLoadTimeout(double? timeout) => + (super.noSuchMethod( + Invocation.method(#setVastLoadTimeout, [timeout]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.AdsRequest pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsRequest_9( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsRequest_9( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsRequest); } /// A class which mocks [FrameLayout]. @@ -1041,59 +854,52 @@ class MockAdsRequest extends _i1.Mock implements _i2.AdsRequest { /// See the documentation for Mockito's code generation for more information. class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.FrameLayout pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeFrameLayout_10( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeFrameLayout_10( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.FrameLayout); - - @override - _i5.Future addView(_i2.View? view) => (super.noSuchMethod( - Invocation.method( - #addView, - [view], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future removeView(_i2.View? view) => (super.noSuchMethod( - Invocation.method( - #removeView, - [view], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.FrameLayout pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFrameLayout_10( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeFrameLayout_10( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.FrameLayout); + + @override + _i5.Future addView(_i2.View? view) => + (super.noSuchMethod( + Invocation.method(#addView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future removeView(_i2.View? view) => + (super.noSuchMethod( + Invocation.method(#removeView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [ImaSdkFactory]. @@ -1101,66 +907,57 @@ class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( - Invocation.method( - #createCompanionAdSlot, - [], - ), - returnValue: - _i5.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_11( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_11( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - ) as _i5.Future<_i2.CompanionAdSlot>); - - @override - _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( - Invocation.method( - #createImaSdkSettings, - [], - ), - returnValue: - _i5.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_12( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_12( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - ) as _i5.Future<_i2.ImaSdkSettings>); + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_11( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_11( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + ) + as _i5.Future<_i2.CompanionAdSlot>); + + @override + _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => + (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_12( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_12( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + ) + as _i5.Future<_i2.ImaSdkSettings>); @override _i5.Future<_i2.AdsLoader> createAdsLoader( @@ -1168,105 +965,69 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { _i2.AdDisplayContainer? container, ) => (super.noSuchMethod( - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - returnValue: _i5.Future<_i2.AdsLoader>.value(_FakeAdsLoader_8( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.AdsLoader>.value(_FakeAdsLoader_8( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - ) as _i5.Future<_i2.AdsLoader>); - - @override - _i5.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( - Invocation.method( - #createAdsRequest, - [], - ), - returnValue: _i5.Future<_i2.AdsRequest>.value(_FakeAdsRequest_9( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - returnValueForMissingStub: - _i5.Future<_i2.AdsRequest>.value(_FakeAdsRequest_9( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - ) as _i5.Future<_i2.AdsRequest>); + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_8( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_8( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + ) + as _i5.Future<_i2.AdsLoader>); + + @override + _i5.Future<_i2.AdsRequest> createAdsRequest() => + (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), + ), + ) + as _i5.Future<_i2.AdsRequest>); @override _i5.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( - Invocation.method( - #createAdsRenderingSettings, - [], - ), - returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_13( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - returnValueForMissingStub: _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_13( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - ) as _i5.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkFactory_14( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkFactory_14( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkFactory); + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_13( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + returnValueForMissingStub: + _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_13( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + ) + as _i5.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_14( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkFactory_14( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkFactory); } /// A class which mocks [ImaSdkSettings]. @@ -1274,132 +1035,115 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockImaSdkSettings extends _i1.Mock implements _i2.ImaSdkSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future setAutoPlayAdBreaks(bool? autoPlayAdBreaks) => (super.noSuchMethod( - Invocation.method( - #setAutoPlayAdBreaks, - [autoPlayAdBreaks], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setAutoPlayAdBreaks, [autoPlayAdBreaks]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future setDebugMode(bool? debugMode) => (super.noSuchMethod( - Invocation.method( - #setDebugMode, - [debugMode], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future setDebugMode(bool? debugMode) => + (super.noSuchMethod( + Invocation.method(#setDebugMode, [debugMode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setFeatureFlags(Map? featureFlags) => (super.noSuchMethod( - Invocation.method( - #setFeatureFlags, - [featureFlags], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setLanguage(String? language) => (super.noSuchMethod( - Invocation.method( - #setLanguage, - [language], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setMaxRedirects(int? maxRedirects) => (super.noSuchMethod( - Invocation.method( - #setMaxRedirects, - [maxRedirects], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setPlayerType(String? playerType) => (super.noSuchMethod( - Invocation.method( - #setPlayerType, - [playerType], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setFeatureFlags, [featureFlags]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setLanguage(String? language) => + (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setMaxRedirects(int? maxRedirects) => + (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [maxRedirects]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setPlayerType(String? playerType) => + (super.noSuchMethod( + Invocation.method(#setPlayerType, [playerType]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setPlayerVersion(String? playerVersion) => (super.noSuchMethod( - Invocation.method( - #setPlayerVersion, - [playerVersion], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setPpid(String? ppid) => (super.noSuchMethod( - Invocation.method( - #setPpid, - [ppid], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setSessionId(String? sessionId) => (super.noSuchMethod( - Invocation.method( - #setSessionId, - [sessionId], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.ImaSdkSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkSettings_12( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkSettings_12( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkSettings); + Invocation.method(#setPlayerVersion, [playerVersion]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setPpid(String? ppid) => + (super.noSuchMethod( + Invocation.method(#setPpid, [ppid]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setSessionId(String? sessionId) => + (super.noSuchMethod( + Invocation.method(#setSessionId, [sessionId]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.ImaSdkSettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkSettings_12( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkSettings_12( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkSettings); } /// A class which mocks [VideoAdPlayer]. @@ -1407,185 +1151,166 @@ class MockImaSdkSettings extends _i1.Mock implements _i2.ImaSdkSettings { /// See the documentation for Mockito's code generation for more information. class MockVideoAdPlayer extends _i1.Mock implements _i2.VideoAdPlayer { @override - void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - ) get addCallback => (super.noSuchMethod( - Invocation.getter(#addCallback), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - _i2.AdPodInfo, - ) get loadAd => (super.noSuchMethod( - Invocation.getter(#loadAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - _i2.AdPodInfo, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - ) get pauseAd => (super.noSuchMethod( - Invocation.getter(#pauseAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - ) get playAd => (super.noSuchMethod( - Invocation.getter(#playAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - )); - - @override - void Function(_i2.VideoAdPlayer) get release => (super.noSuchMethod( - Invocation.getter(#release), - returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, - returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, - ) as void Function(_i2.VideoAdPlayer)); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - ) get removeCallback => (super.noSuchMethod( - Invocation.getter(#removeCallback), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.VideoAdPlayerCallback, - )); - - @override - void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - ) get stopAd => (super.noSuchMethod( - Invocation.getter(#stopAd), - returnValue: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) as void Function( - _i2.VideoAdPlayer, - _i2.AdMediaInfo, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future setVolume(int? value) => (super.noSuchMethod( - Invocation.method( - #setVolume, - [value], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) get addCallback => + (super.noSuchMethod( + Invocation.getter(#addCallback), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo) get loadAd => + (super.noSuchMethod( + Invocation.getter(#loadAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get pauseAd => + (super.noSuchMethod( + Invocation.getter(#pauseAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get playAd => + (super.noSuchMethod( + Invocation.getter(#playAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer) get release => + (super.noSuchMethod( + Invocation.getter(#release), + returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, + ) + as void Function(_i2.VideoAdPlayer)); + + @override + void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) + get removeCallback => + (super.noSuchMethod( + Invocation.getter(#removeCallback), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get stopAd => + (super.noSuchMethod( + Invocation.getter(#stopAd), + returnValue: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + ) {}, + ) + as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future setVolume(int? value) => + (super.noSuchMethod( + Invocation.method(#setVolume, [value]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setAdProgress(_i2.VideoProgressUpdate? progress) => (super.noSuchMethod( - Invocation.method( - #setAdProgress, - [progress], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.VideoAdPlayer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoAdPlayer_15( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoAdPlayer_15( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoAdPlayer); + Invocation.method(#setAdProgress, [progress]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.VideoAdPlayer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayer_15( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoAdPlayer_15( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoAdPlayer); } /// A class which mocks [VideoAdPlayerCallback]. @@ -1594,17 +1319,19 @@ class MockVideoAdPlayer extends _i1.Mock implements _i2.VideoAdPlayer { class MockVideoAdPlayerCallback extends _i1.Mock implements _i2.VideoAdPlayerCallback { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.Future onAdProgress( @@ -1612,99 +1339,86 @@ class MockVideoAdPlayerCallback extends _i1.Mock _i2.VideoProgressUpdate? videoProgressUpdate, ) => (super.noSuchMethod( - Invocation.method( - #onAdProgress, - [ - adMediaInfo, - videoProgressUpdate, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onAdProgress, [ + adMediaInfo, + videoProgressUpdate, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onBuffering(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onBuffering, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future onContentComplete() => (super.noSuchMethod( - Invocation.method( - #onContentComplete, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onEnded, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onError, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onBuffering, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future onContentComplete() => + (super.noSuchMethod( + Invocation.method(#onContentComplete, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onEnded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onError, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onLoaded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onLoaded, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onLoaded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onPause, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onPause, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onPlay, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => + (super.noSuchMethod( + Invocation.method(#onPlay, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onResume(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( - Invocation.method( - #onResume, - [adMediaInfo], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#onResume, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future onVolumeChanged( @@ -1712,38 +1426,26 @@ class MockVideoAdPlayerCallback extends _i1.Mock int? percentage, ) => (super.noSuchMethod( - Invocation.method( - #onVolumeChanged, - [ - adMediaInfo, - percentage, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.VideoAdPlayerCallback pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoAdPlayerCallback_16( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoAdPlayerCallback_16( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoAdPlayerCallback); + Invocation.method(#onVolumeChanged, [adMediaInfo, percentage]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.VideoAdPlayerCallback pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayerCallback_16( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoAdPlayerCallback_16( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoAdPlayerCallback); } /// A class which mocks [VideoView]. @@ -1751,86 +1453,73 @@ class MockVideoAdPlayerCallback extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockVideoView extends _i1.Mock implements _i2.VideoView { @override - void Function( - _i2.VideoView, - _i2.MediaPlayer, - int, - int, - ) get onError => (super.noSuchMethod( - Invocation.getter(#onError), - returnValue: ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - returnValueForMissingStub: ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - ) as void Function( - _i2.VideoView, - _i2.MediaPlayer, - int, - int, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i5.Future setVideoUri(String? uri) => (super.noSuchMethod( - Invocation.method( - #setVideoUri, - [uri], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future getCurrentPosition() => (super.noSuchMethod( - Invocation.method( - #getCurrentPosition, - [], - ), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) as _i5.Future); - - @override - _i2.VideoView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeVideoView_17( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeVideoView_17( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.VideoView); + void Function(_i2.VideoView, _i2.MediaPlayer, int, int) get onError => + (super.noSuchMethod( + Invocation.getter(#onError), + returnValue: + ( + _i2.VideoView pigeon_instance, + _i2.MediaPlayer player, + int what, + int extra, + ) {}, + returnValueForMissingStub: + ( + _i2.VideoView pigeon_instance, + _i2.MediaPlayer player, + int what, + int extra, + ) {}, + ) + as void Function(_i2.VideoView, _i2.MediaPlayer, int, int)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i5.Future setVideoUri(String? uri) => + (super.noSuchMethod( + Invocation.method(#setVideoUri, [uri]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future getCurrentPosition() => + (super.noSuchMethod( + Invocation.method(#getCurrentPosition, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) + as _i5.Future); + + @override + _i2.VideoView pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoView_17( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoView_17( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.VideoView); } /// A class which mocks [SurfaceAndroidViewController]. @@ -1839,187 +1528,160 @@ class MockVideoView extends _i1.Mock implements _i2.VideoView { class MockSurfaceAndroidViewController extends _i1.Mock implements _i4.SurfaceAndroidViewController { @override - bool get requiresViewComposition => (super.noSuchMethod( - Invocation.getter(#requiresViewComposition), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); - - @override - int get viewId => (super.noSuchMethod( - Invocation.getter(#viewId), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + bool get requiresViewComposition => + (super.noSuchMethod( + Invocation.getter(#requiresViewComposition), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - bool get awaitingCreation => (super.noSuchMethod( - Invocation.getter(#awaitingCreation), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + int get viewId => + (super.noSuchMethod( + Invocation.getter(#viewId), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override - _i4.PointTransformer get pointTransformer => (super.noSuchMethod( - Invocation.getter(#pointTransformer), - returnValue: (_i3.Offset position) => _FakeOffset_18( - this, - Invocation.getter(#pointTransformer), - ), - returnValueForMissingStub: (_i3.Offset position) => _FakeOffset_18( - this, - Invocation.getter(#pointTransformer), - ), - ) as _i4.PointTransformer); + bool get awaitingCreation => + (super.noSuchMethod( + Invocation.getter(#awaitingCreation), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - bool get isCreated => (super.noSuchMethod( - Invocation.getter(#isCreated), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + _i4.PointTransformer get pointTransformer => + (super.noSuchMethod( + Invocation.getter(#pointTransformer), + returnValue: + (_i3.Offset position) => + _FakeOffset_18(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: + (_i3.Offset position) => + _FakeOffset_18(this, Invocation.getter(#pointTransformer)), + ) + as _i4.PointTransformer); + + @override + bool get isCreated => + (super.noSuchMethod( + Invocation.getter(#isCreated), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override List<_i4.PlatformViewCreatedCallback> get createdCallbacks => (super.noSuchMethod( - Invocation.getter(#createdCallbacks), - returnValue: <_i4.PlatformViewCreatedCallback>[], - returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], - ) as List<_i4.PlatformViewCreatedCallback>); + Invocation.getter(#createdCallbacks), + returnValue: <_i4.PlatformViewCreatedCallback>[], + returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], + ) + as List<_i4.PlatformViewCreatedCallback>); @override set pointTransformer(_i4.PointTransformer? transformer) => super.noSuchMethod( - Invocation.setter( - #pointTransformer, - transformer, - ), - returnValueForMissingStub: null, - ); - - @override - _i5.Future setOffset(_i3.Offset? off) => (super.noSuchMethod( - Invocation.method( - #setOffset, - [off], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future create({ - _i3.Size? size, - _i3.Offset? position, - }) => + Invocation.setter(#pointTransformer, transformer), + returnValueForMissingStub: null, + ); + + @override + _i5.Future setOffset(_i3.Offset? off) => + (super.noSuchMethod( + Invocation.method(#setOffset, [off]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future create({_i3.Size? size, _i3.Offset? position}) => (super.noSuchMethod( - Invocation.method( - #create, - [], - { - #size: size, - #position: position, - }, - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future<_i3.Size> setSize(_i3.Size? size) => (super.noSuchMethod( - Invocation.method( - #setSize, - [size], - ), - returnValue: _i5.Future<_i3.Size>.value(_FakeSize_19( - this, - Invocation.method( - #setSize, - [size], - ), - )), - returnValueForMissingStub: _i5.Future<_i3.Size>.value(_FakeSize_19( - this, - Invocation.method( - #setSize, - [size], - ), - )), - ) as _i5.Future<_i3.Size>); + Invocation.method(#create, [], {#size: size, #position: position}), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i3.Size> setSize(_i3.Size? size) => + (super.noSuchMethod( + Invocation.method(#setSize, [size]), + returnValue: _i5.Future<_i3.Size>.value( + _FakeSize_19(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i5.Future<_i3.Size>.value( + _FakeSize_19(this, Invocation.method(#setSize, [size])), + ), + ) + as _i5.Future<_i3.Size>); @override _i5.Future sendMotionEvent(_i4.AndroidMotionEvent? event) => (super.noSuchMethod( - Invocation.method( - #sendMotionEvent, - [event], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#sendMotionEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override void addOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #addOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i4.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override void removeOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #removeOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i4.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override _i5.Future setLayoutDirection(_i3.TextDirection? layoutDirection) => (super.noSuchMethod( - Invocation.method( - #setLayoutDirection, - [layoutDirection], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setLayoutDirection, [layoutDirection]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future dispatchPointerEvent(_i4.PointerEvent? event) => (super.noSuchMethod( - Invocation.method( - #dispatchPointerEvent, - [event], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future clearFocus() => (super.noSuchMethod( - Invocation.method( - #clearFocus, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#dispatchPointerEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future clearFocus() => + (super.noSuchMethod( + Invocation.method(#clearFocus, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future dispose() => + (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } /// A class which mocks [PlatformViewsServiceProxy]. @@ -2038,49 +1700,38 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i3.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - returnValue: _FakeExpensiveAndroidViewController_20( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - ), - returnValueForMissingStub: _FakeExpensiveAndroidViewController_20( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { + Invocation.method(#initExpensiveAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - ), - ) as _i4.ExpensiveAndroidViewController); + }), + returnValue: _FakeExpensiveAndroidViewController_20( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeExpensiveAndroidViewController_20( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) + as _i4.ExpensiveAndroidViewController); @override _i4.SurfaceAndroidViewController initSurfaceAndroidView({ @@ -2092,47 +1743,36 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i3.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - returnValue: _FakeSurfaceAndroidViewController_21( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - ), - returnValueForMissingStub: _FakeSurfaceAndroidViewController_21( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { + Invocation.method(#initSurfaceAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - ), - ) as _i4.SurfaceAndroidViewController); + }), + returnValue: _FakeSurfaceAndroidViewController_21( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeSurfaceAndroidViewController_21( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) + as _i4.SurfaceAndroidViewController); } diff --git a/packages/interactive_media_ads/test/android/ads_manager_test.dart b/packages/interactive_media_ads/test/android/ads_manager_test.dart index 90e2ed9ad5f..9dc926c20f9 100644 --- a/packages/interactive_media_ads/test/android/ads_manager_test.dart +++ b/packages/interactive_media_ads/test/android/ads_manager_test.dart @@ -69,9 +69,9 @@ void main() { mockAdsRenderingSettings.setLoadVideoTimeout(2000), mockAdsRenderingSettings.setMimeTypes(['value']), mockAdsRenderingSettings.setPlayAdsAfterTime(5.0), - mockAdsRenderingSettings.setUiElements( - [ima.UiElement.countdown], - ), + mockAdsRenderingSettings.setUiElements([ + ima.UiElement.countdown, + ]), mockAdsRenderingSettings.setEnableCustomTabs(true), mockAdsManager.init(mockAdsRenderingSettings), ]); @@ -120,17 +120,12 @@ void main() { test('onAdEvent', () async { final MockAdsManager mockAdsManager = MockAdsManager(); - late final void Function( - ima.AdEventListener, - ima.AdEvent, - ) onAdEventCallback; + late final void Function(ima.AdEventListener, ima.AdEvent) + onAdEventCallback; final InteractiveMediaAdsProxy proxy = InteractiveMediaAdsProxy( newAdEventListener: ({ - required void Function( - ima.AdEventListener, - ima.AdEvent, - ) onAdEvent, + required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent, }) { onAdEventCallback = onAdEvent; return MockAdEventListener(); @@ -164,20 +159,16 @@ void main() { test('onAdErrorEvent', () async { final MockAdsManager mockAdsManager = MockAdsManager(); - late final void Function( - ima.AdErrorListener, - ima.AdErrorEvent, - ) onAdErrorCallback; + late final void Function(ima.AdErrorListener, ima.AdErrorEvent) + onAdErrorCallback; final InteractiveMediaAdsProxy proxy = InteractiveMediaAdsProxy( newAdEventListener: ({required dynamic onAdEvent}) { return MockAdEventListener(); }, newAdErrorListener: ({ - required void Function( - ima.AdErrorListener, - ima.AdErrorEvent, - ) onAdError, + required void Function(ima.AdErrorListener, ima.AdErrorEvent) + onAdError, }) { onAdErrorCallback = onAdError; return MockAdErrorListener(); @@ -199,8 +190,9 @@ void main() { final MockAdErrorEvent mockErrorEvent = MockAdErrorEvent(); final MockAdError mockError = MockAdError(); when(mockError.errorType).thenReturn(ima.AdErrorType.load); - when(mockError.errorCode) - .thenReturn(ima.AdErrorCode.adsRequestNetworkError); + when( + mockError.errorCode, + ).thenReturn(ima.AdErrorCode.adsRequestNetworkError); when(mockError.message).thenReturn('error message'); when(mockErrorEvent.error).thenReturn(mockError); onAdErrorCallback(MockAdErrorListener(), mockErrorEvent); diff --git a/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart b/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart index 8610a224046..92af7ae343e 100644 --- a/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart @@ -26,138 +26,73 @@ import 'package:mockito/src/dummies.dart' as _i3; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdError_1 extends _i1.SmartFake implements _i2.AdError { - _FakeAdError_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdError_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdErrorEvent_2 extends _i1.SmartFake implements _i2.AdErrorEvent { - _FakeAdErrorEvent_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdErrorEvent_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdErrorListener_3 extends _i1.SmartFake implements _i2.AdErrorListener { - _FakeAdErrorListener_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdErrorListener_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdEvent_4 extends _i1.SmartFake implements _i2.AdEvent { - _FakeAdEvent_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdEvent_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdEventListener_5 extends _i1.SmartFake implements _i2.AdEventListener { - _FakeAdEventListener_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdEventListener_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsManager_6 extends _i1.SmartFake implements _i2.AdsManager { - _FakeAdsManager_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsManager_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRenderingSettings_7 extends _i1.SmartFake implements _i2.AdsRenderingSettings { - _FakeAdsRenderingSettings_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRenderingSettings_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCompanionAdSlot_8 extends _i1.SmartFake implements _i2.CompanionAdSlot { - _FakeCompanionAdSlot_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCompanionAdSlot_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkSettings_9 extends _i1.SmartFake implements _i2.ImaSdkSettings { - _FakeImaSdkSettings_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkSettings_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsLoader_10 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsLoader_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRequest_11 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRequest_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkFactory_12 extends _i1.SmartFake implements _i2.ImaSdkFactory { - _FakeImaSdkFactory_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkFactory_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AdError]. @@ -165,73 +100,76 @@ class _FakeImaSdkFactory_12 extends _i1.SmartFake implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockAdError extends _i1.Mock implements _i2.AdError { @override - _i2.AdErrorCode get errorCode => (super.noSuchMethod( - Invocation.getter(#errorCode), - returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, - returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, - ) as _i2.AdErrorCode); - - @override - int get errorCodeNumber => (super.noSuchMethod( - Invocation.getter(#errorCodeNumber), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); - - @override - _i2.AdErrorType get errorType => (super.noSuchMethod( - Invocation.getter(#errorType), - returnValue: _i2.AdErrorType.load, - returnValueForMissingStub: _i2.AdErrorType.load, - ) as _i2.AdErrorType); - - @override - String get message => (super.noSuchMethod( - Invocation.getter(#message), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#message), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#message), - ), - ) as String); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdError pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdError_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdError_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdError); + _i2.AdErrorCode get errorCode => + (super.noSuchMethod( + Invocation.getter(#errorCode), + returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, + returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, + ) + as _i2.AdErrorCode); + + @override + int get errorCodeNumber => + (super.noSuchMethod( + Invocation.getter(#errorCodeNumber), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); + + @override + _i2.AdErrorType get errorType => + (super.noSuchMethod( + Invocation.getter(#errorType), + returnValue: _i2.AdErrorType.load, + returnValueForMissingStub: _i2.AdErrorType.load, + ) + as _i2.AdErrorType); + + @override + String get message => + (super.noSuchMethod( + Invocation.getter(#message), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#message), + ), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#message), + ), + ) + as String); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdError pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdError_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdError_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdError); } /// A class which mocks [AdErrorEvent]. @@ -239,52 +177,46 @@ class MockAdError extends _i1.Mock implements _i2.AdError { /// See the documentation for Mockito's code generation for more information. class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { @override - _i2.AdError get error => (super.noSuchMethod( - Invocation.getter(#error), - returnValue: _FakeAdError_1( - this, - Invocation.getter(#error), - ), - returnValueForMissingStub: _FakeAdError_1( - this, - Invocation.getter(#error), - ), - ) as _i2.AdError); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorEvent pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdErrorEvent_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdErrorEvent_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdErrorEvent); + _i2.AdError get error => + (super.noSuchMethod( + Invocation.getter(#error), + returnValue: _FakeAdError_1(this, Invocation.getter(#error)), + returnValueForMissingStub: _FakeAdError_1( + this, + Invocation.getter(#error), + ), + ) + as _i2.AdError); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorEvent pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorEvent_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdErrorEvent_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdErrorEvent); } /// A class which mocks [AdErrorListener]. @@ -292,58 +224,51 @@ class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { /// See the documentation for Mockito's code generation for more information. class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { @override - void Function( - _i2.AdErrorListener, - _i2.AdErrorEvent, - ) get onAdError => (super.noSuchMethod( - Invocation.getter(#onAdError), - returnValue: ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - returnValueForMissingStub: ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - ) as void Function( - _i2.AdErrorListener, - _i2.AdErrorEvent, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdErrorListener_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdErrorListener_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdErrorListener); + void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => + (super.noSuchMethod( + Invocation.getter(#onAdError), + returnValue: + ( + _i2.AdErrorListener pigeon_instance, + _i2.AdErrorEvent event, + ) {}, + returnValueForMissingStub: + ( + _i2.AdErrorListener pigeon_instance, + _i2.AdErrorEvent event, + ) {}, + ) + as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorListener pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorListener_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdErrorListener_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdErrorListener); } /// A class which mocks [AdEvent]. @@ -351,46 +276,43 @@ class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { /// See the documentation for Mockito's code generation for more information. class MockAdEvent extends _i1.Mock implements _i2.AdEvent { @override - _i2.AdEventType get type => (super.noSuchMethod( - Invocation.getter(#type), - returnValue: _i2.AdEventType.adBreakEnded, - returnValueForMissingStub: _i2.AdEventType.adBreakEnded, - ) as _i2.AdEventType); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdEvent pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdEvent_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdEvent_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdEvent); + _i2.AdEventType get type => + (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.AdEventType.adBreakEnded, + returnValueForMissingStub: _i2.AdEventType.adBreakEnded, + ) + as _i2.AdEventType); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdEvent pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdEvent_4( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdEvent_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdEvent); } /// A class which mocks [AdEventListener]. @@ -398,58 +320,45 @@ class MockAdEvent extends _i1.Mock implements _i2.AdEvent { /// See the documentation for Mockito's code generation for more information. class MockAdEventListener extends _i1.Mock implements _i2.AdEventListener { @override - void Function( - _i2.AdEventListener, - _i2.AdEvent, - ) get onAdEvent => (super.noSuchMethod( - Invocation.getter(#onAdEvent), - returnValue: ( - _i2.AdEventListener pigeon_instance, - _i2.AdEvent event, - ) {}, - returnValueForMissingStub: ( - _i2.AdEventListener pigeon_instance, - _i2.AdEvent event, - ) {}, - ) as void Function( - _i2.AdEventListener, - _i2.AdEvent, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.AdEventListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdEventListener_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdEventListener_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdEventListener); + void Function(_i2.AdEventListener, _i2.AdEvent) get onAdEvent => + (super.noSuchMethod( + Invocation.getter(#onAdEvent), + returnValue: + (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, + returnValueForMissingStub: + (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, + ) + as void Function(_i2.AdEventListener, _i2.AdEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.AdEventListener pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdEventListener_5( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdEventListener_5( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdEventListener); } /// A class which mocks [AdsManager]. @@ -457,195 +366,173 @@ class MockAdEventListener extends _i1.Mock implements _i2.AdEventListener { /// See the documentation for Mockito's code generation for more information. class MockAdsManager extends _i1.Mock implements _i2.AdsManager { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i4.Future discardAdBreak() => (super.noSuchMethod( - Invocation.method( - #discardAdBreak, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future start() => (super.noSuchMethod( - Invocation.method( - #start, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future> getAdCuePoints() => (super.noSuchMethod( - Invocation.method( - #getAdCuePoints, - [], - ), - returnValue: _i4.Future>.value([]), - returnValueForMissingStub: _i4.Future>.value([]), - ) as _i4.Future>); - - @override - _i4.Future resume() => (super.noSuchMethod( - Invocation.method( - #resume, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future skip() => (super.noSuchMethod( - Invocation.method( - #skip, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.AdsManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsManager_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsManager_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i4.Future discardAdBreak() => + (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future pause() => + (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future start() => + (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future> getAdCuePoints() => + (super.noSuchMethod( + Invocation.method(#getAdCuePoints, []), + returnValue: _i4.Future>.value([]), + returnValueForMissingStub: _i4.Future>.value( + [], + ), + ) + as _i4.Future>); + + @override + _i4.Future resume() => + (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future skip() => + (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.AdsManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManager_6( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsManager_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsManager); @override _i4.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( - Invocation.method( - #addAdErrorListener, - [errorListener], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#addAdErrorListener, [errorListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future addAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( - Invocation.method( - #addAdEventListener, - [adEventListener], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#addAdEventListener, [adEventListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future destroy() => + (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future init(_i2.AdsRenderingSettings? settings) => (super.noSuchMethod( - Invocation.method( - #init, - [settings], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future focus() => (super.noSuchMethod( - Invocation.method( - #focus, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future<_i2.AdProgressInfo?> getAdProgressInfo() => (super.noSuchMethod( - Invocation.method( - #getAdProgressInfo, - [], - ), - returnValue: _i4.Future<_i2.AdProgressInfo?>.value(), - returnValueForMissingStub: _i4.Future<_i2.AdProgressInfo?>.value(), - ) as _i4.Future<_i2.AdProgressInfo?>); - - @override - _i4.Future<_i2.Ad?> getCurrentAd() => (super.noSuchMethod( - Invocation.method( - #getCurrentAd, - [], - ), - returnValue: _i4.Future<_i2.Ad?>.value(), - returnValueForMissingStub: _i4.Future<_i2.Ad?>.value(), - ) as _i4.Future<_i2.Ad?>); + Invocation.method(#init, [settings]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future focus() => + (super.noSuchMethod( + Invocation.method(#focus, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future<_i2.AdProgressInfo?> getAdProgressInfo() => + (super.noSuchMethod( + Invocation.method(#getAdProgressInfo, []), + returnValue: _i4.Future<_i2.AdProgressInfo?>.value(), + returnValueForMissingStub: _i4.Future<_i2.AdProgressInfo?>.value(), + ) + as _i4.Future<_i2.AdProgressInfo?>); + + @override + _i4.Future<_i2.Ad?> getCurrentAd() => + (super.noSuchMethod( + Invocation.method(#getCurrentAd, []), + returnValue: _i4.Future<_i2.Ad?>.value(), + returnValueForMissingStub: _i4.Future<_i2.Ad?>.value(), + ) + as _i4.Future<_i2.Ad?>); @override _i4.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( - Invocation.method( - #removeAdErrorListener, - [errorListener], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#removeAdErrorListener, [errorListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future removeAdEventListener( - _i2.AdEventListener? adEventListener) => - (super.noSuchMethod( - Invocation.method( - #removeAdEventListener, - [adEventListener], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i2.AdEventListener? adEventListener, + ) => + (super.noSuchMethod( + Invocation.method(#removeAdEventListener, [adEventListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } /// A class which mocks [AdsRenderingSettings]. @@ -654,175 +541,157 @@ class MockAdsManager extends _i1.Mock implements _i2.AdsManager { class MockAdsRenderingSettings extends _i1.Mock implements _i2.AdsRenderingSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i4.Future getBitrateKbps() => (super.noSuchMethod( - Invocation.method( - #getBitrateKbps, - [], - ), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) as _i4.Future); - - @override - _i4.Future getEnableCustomTabs() => (super.noSuchMethod( - Invocation.method( - #getEnableCustomTabs, - [], - ), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) as _i4.Future); - - @override - _i4.Future getEnablePreloading() => (super.noSuchMethod( - Invocation.method( - #getEnablePreloading, - [], - ), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) as _i4.Future); - - @override - _i4.Future getFocusSkipButtonWhenAvailable() => (super.noSuchMethod( - Invocation.method( - #getFocusSkipButtonWhenAvailable, - [], - ), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) as _i4.Future); - - @override - _i4.Future> getMimeTypes() => (super.noSuchMethod( - Invocation.method( - #getMimeTypes, - [], - ), - returnValue: _i4.Future>.value([]), - returnValueForMissingStub: _i4.Future>.value([]), - ) as _i4.Future>); - - @override - _i4.Future setBitrateKbps(int? bitrate) => (super.noSuchMethod( - Invocation.method( - #setBitrateKbps, - [bitrate], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i4.Future getBitrateKbps() => + (super.noSuchMethod( + Invocation.method(#getBitrateKbps, []), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) + as _i4.Future); + + @override + _i4.Future getEnableCustomTabs() => + (super.noSuchMethod( + Invocation.method(#getEnableCustomTabs, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future getEnablePreloading() => + (super.noSuchMethod( + Invocation.method(#getEnablePreloading, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future getFocusSkipButtonWhenAvailable() => + (super.noSuchMethod( + Invocation.method(#getFocusSkipButtonWhenAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future> getMimeTypes() => + (super.noSuchMethod( + Invocation.method(#getMimeTypes, []), + returnValue: _i4.Future>.value([]), + returnValueForMissingStub: _i4.Future>.value( + [], + ), + ) + as _i4.Future>); + + @override + _i4.Future setBitrateKbps(int? bitrate) => + (super.noSuchMethod( + Invocation.method(#setBitrateKbps, [bitrate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setEnableCustomTabs(bool? enableCustomTabs) => (super.noSuchMethod( - Invocation.method( - #setEnableCustomTabs, - [enableCustomTabs], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setEnableCustomTabs, [enableCustomTabs]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setEnablePreloading(bool? enablePreloading) => (super.noSuchMethod( - Invocation.method( - #setEnablePreloading, - [enablePreloading], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setEnablePreloading, [enablePreloading]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setFocusSkipButtonWhenAvailable( - bool? enableFocusSkipButton) => + bool? enableFocusSkipButton, + ) => (super.noSuchMethod( - Invocation.method( - #setFocusSkipButtonWhenAvailable, - [enableFocusSkipButton], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setFocusSkipButtonWhenAvailable, [ + enableFocusSkipButton, + ]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setLoadVideoTimeout(int? loadVideoTimeout) => (super.noSuchMethod( - Invocation.method( - #setLoadVideoTimeout, - [loadVideoTimeout], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setLoadVideoTimeout, [loadVideoTimeout]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future setMimeTypes(List? mimeTypes) => (super.noSuchMethod( - Invocation.method( - #setMimeTypes, - [mimeTypes], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setMimeTypes(List? mimeTypes) => + (super.noSuchMethod( + Invocation.method(#setMimeTypes, [mimeTypes]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future setPlayAdsAfterTime(double? time) => (super.noSuchMethod( - Invocation.method( - #setPlayAdsAfterTime, - [time], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setPlayAdsAfterTime(double? time) => + (super.noSuchMethod( + Invocation.method(#setPlayAdsAfterTime, [time]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setUiElements(List<_i2.UiElement>? uiElements) => (super.noSuchMethod( - Invocation.method( - #setUiElements, - [uiElements], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.AdsRenderingSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeAdsRenderingSettings_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeAdsRenderingSettings_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.AdsRenderingSettings); + Invocation.method(#setUiElements, [uiElements]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.AdsRenderingSettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsRenderingSettings_7( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAdsRenderingSettings_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.AdsRenderingSettings); } /// A class which mocks [ImaSdkFactory]. @@ -830,65 +699,57 @@ class MockAdsRenderingSettings extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i4.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( - Invocation.method( - #createCompanionAdSlot, - [], - ), - returnValue: - _i4.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_8( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - returnValueForMissingStub: - _i4.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_8( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - ) as _i4.Future<_i2.CompanionAdSlot>); - - @override - _i4.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( - Invocation.method( - #createImaSdkSettings, - [], - ), - returnValue: _i4.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_9( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - returnValueForMissingStub: - _i4.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_9( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - ) as _i4.Future<_i2.ImaSdkSettings>); + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i4.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_8( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_8( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + ) + as _i4.Future<_i2.CompanionAdSlot>); + + @override + _i4.Future<_i2.ImaSdkSettings> createImaSdkSettings() => + (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i4.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_9( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_9( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + ) + as _i4.Future<_i2.ImaSdkSettings>); @override _i4.Future<_i2.AdsLoader> createAdsLoader( @@ -896,103 +757,73 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { _i2.AdDisplayContainer? container, ) => (super.noSuchMethod( - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - returnValue: _i4.Future<_i2.AdsLoader>.value(_FakeAdsLoader_10( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - returnValueForMissingStub: - _i4.Future<_i2.AdsLoader>.value(_FakeAdsLoader_10( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - ) as _i4.Future<_i2.AdsLoader>); - - @override - _i4.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( - Invocation.method( - #createAdsRequest, - [], - ), - returnValue: _i4.Future<_i2.AdsRequest>.value(_FakeAdsRequest_11( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - returnValueForMissingStub: - _i4.Future<_i2.AdsRequest>.value(_FakeAdsRequest_11( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - ) as _i4.Future<_i2.AdsRequest>); + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i4.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_10( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_10( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + ) + as _i4.Future<_i2.AdsLoader>); + + @override + _i4.Future<_i2.AdsRequest> createAdsRequest() => + (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i4.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_11( + this, + Invocation.method(#createAdsRequest, []), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_11( + this, + Invocation.method(#createAdsRequest, []), + ), + ), + ) + as _i4.Future<_i2.AdsRequest>); @override _i4.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( - Invocation.method( - #createAdsRenderingSettings, - [], - ), - returnValue: _i4.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_7( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - returnValueForMissingStub: _i4.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_7( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - ) as _i4.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkFactory_12( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkFactory_12( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkFactory); + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i4.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_7( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + returnValueForMissingStub: + _i4.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_7( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + ) + as _i4.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_12( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkFactory_12( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkFactory); } diff --git a/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart b/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart index 950fdee9d8f..4c0e269d9d0 100644 --- a/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart +++ b/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart @@ -27,20 +27,20 @@ void main() { final MockCompanionAdSlot mockCompanionAdSlot = MockCompanionAdSlot(); final AndroidCompanionAdSlotCreationParams params = AndroidCompanionAdSlotCreationParams( - size: CompanionAdSlotSize.fixed(width: 300, height: 400), - proxy: InteractiveMediaAdsProxy( - newFrameLayout: () { - return frameLayout; - }, - instanceImaSdkFactory: () { - final MockImaSdkFactory mockFactory = MockImaSdkFactory(); - when(mockFactory.createCompanionAdSlot()).thenAnswer( - (_) async => mockCompanionAdSlot, - ); - return mockFactory; - }, - ), - ); + size: CompanionAdSlotSize.fixed(width: 300, height: 400), + proxy: InteractiveMediaAdsProxy( + newFrameLayout: () { + return frameLayout; + }, + instanceImaSdkFactory: () { + final MockImaSdkFactory mockFactory = MockImaSdkFactory(); + when( + mockFactory.createCompanionAdSlot(), + ).thenAnswer((_) async => mockCompanionAdSlot); + return mockFactory; + }, + ), + ); final AndroidCompanionAdSlot adSlot = AndroidCompanionAdSlot(params); await adSlot.getNativeCompanionAdSlot(); @@ -53,41 +53,41 @@ void main() { final MockCompanionAdSlot mockCompanionAdSlot = MockCompanionAdSlot(); final AndroidCompanionAdSlotCreationParams params = AndroidCompanionAdSlotCreationParams( - size: CompanionAdSlotSize.fixed(width: 300, height: 400), - onClicked: expectAsync0(() {}), - proxy: InteractiveMediaAdsProxy( - newFrameLayout: () { - return ima.FrameLayout.pigeon_detached( - pigeon_instanceManager: _TestInstanceManager(), - ); - }, - instanceImaSdkFactory: () { - final MockImaSdkFactory mockFactory = MockImaSdkFactory(); - when(mockFactory.createCompanionAdSlot()).thenAnswer( - (_) async => mockCompanionAdSlot, - ); - return mockFactory; - }, - newCompanionAdSlotClickListener: ({ - required void Function( - ima.CompanionAdSlotClickListener, - ) onCompanionAdClick, - }) { - return ima.CompanionAdSlotClickListener.pigeon_detached( - onCompanionAdClick: onCompanionAdClick, - pigeon_instanceManager: _TestInstanceManager(), - ); - }, - ), - ); + size: CompanionAdSlotSize.fixed(width: 300, height: 400), + onClicked: expectAsync0(() {}), + proxy: InteractiveMediaAdsProxy( + newFrameLayout: () { + return ima.FrameLayout.pigeon_detached( + pigeon_instanceManager: _TestInstanceManager(), + ); + }, + instanceImaSdkFactory: () { + final MockImaSdkFactory mockFactory = MockImaSdkFactory(); + when( + mockFactory.createCompanionAdSlot(), + ).thenAnswer((_) async => mockCompanionAdSlot); + return mockFactory; + }, + newCompanionAdSlotClickListener: ({ + required void Function(ima.CompanionAdSlotClickListener) + onCompanionAdClick, + }) { + return ima.CompanionAdSlotClickListener.pigeon_detached( + onCompanionAdClick: onCompanionAdClick, + pigeon_instanceManager: _TestInstanceManager(), + ); + }, + ), + ); final AndroidCompanionAdSlot adSlot = AndroidCompanionAdSlot(params); await adSlot.getNativeCompanionAdSlot(); final ima.CompanionAdSlotClickListener clickListener = - verify(mockCompanionAdSlot.addClickListener(captureAny)) - .captured - .single as ima.CompanionAdSlotClickListener; + verify( + mockCompanionAdSlot.addClickListener(captureAny), + ).captured.single + as ima.CompanionAdSlotClickListener; clickListener.onCompanionAdClick(clickListener); }); diff --git a/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart b/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart index 4a905596e1a..b2d843060d4 100644 --- a/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart @@ -25,96 +25,51 @@ import 'package:mockito/mockito.dart' as _i1; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeViewGroup_1 extends _i1.SmartFake implements _i2.ViewGroup { - _FakeViewGroup_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeViewGroup_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCompanionAdSlot_2 extends _i1.SmartFake implements _i2.CompanionAdSlot { - _FakeCompanionAdSlot_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCompanionAdSlot_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFrameLayout_3 extends _i1.SmartFake implements _i2.FrameLayout { - _FakeFrameLayout_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFrameLayout_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkSettings_4 extends _i1.SmartFake implements _i2.ImaSdkSettings { - _FakeImaSdkSettings_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkSettings_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsLoader_5 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsLoader_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRequest_6 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRequest_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRenderingSettings_7 extends _i1.SmartFake implements _i2.AdsRenderingSettings { - _FakeAdsRenderingSettings_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRenderingSettings_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkFactory_8 extends _i1.SmartFake implements _i2.ImaSdkFactory { - _FakeImaSdkFactory_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkFactory_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [CompanionAdSlot]. @@ -122,154 +77,123 @@ class _FakeImaSdkFactory_8 extends _i1.SmartFake implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future addClickListener( - _i2.CompanionAdSlotClickListener? clickListener) => + _i2.CompanionAdSlotClickListener? clickListener, + ) => (super.noSuchMethod( - Invocation.method( - #addClickListener, - [clickListener], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#addClickListener, [clickListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future<_i2.ViewGroup> getContainer() => (super.noSuchMethod( - Invocation.method( - #getContainer, - [], - ), - returnValue: _i3.Future<_i2.ViewGroup>.value(_FakeViewGroup_1( - this, - Invocation.method( - #getContainer, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.ViewGroup>.value(_FakeViewGroup_1( - this, - Invocation.method( - #getContainer, - [], - ), - )), - ) as _i3.Future<_i2.ViewGroup>); + _i3.Future<_i2.ViewGroup> getContainer() => + (super.noSuchMethod( + Invocation.method(#getContainer, []), + returnValue: _i3.Future<_i2.ViewGroup>.value( + _FakeViewGroup_1(this, Invocation.method(#getContainer, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.ViewGroup>.value( + _FakeViewGroup_1(this, Invocation.method(#getContainer, [])), + ), + ) + as _i3.Future<_i2.ViewGroup>); @override - _i3.Future getHeight() => (super.noSuchMethod( - Invocation.method( - #getHeight, - [], - ), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) as _i3.Future); + _i3.Future getHeight() => + (super.noSuchMethod( + Invocation.method(#getHeight, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) + as _i3.Future); @override - _i3.Future getWidth() => (super.noSuchMethod( - Invocation.method( - #getWidth, - [], - ), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) as _i3.Future); + _i3.Future getWidth() => + (super.noSuchMethod( + Invocation.method(#getWidth, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) + as _i3.Future); @override - _i3.Future isFilled() => (super.noSuchMethod( - Invocation.method( - #isFilled, - [], - ), - returnValue: _i3.Future.value(false), - returnValueForMissingStub: _i3.Future.value(false), - ) as _i3.Future); + _i3.Future isFilled() => + (super.noSuchMethod( + Invocation.method(#isFilled, []), + returnValue: _i3.Future.value(false), + returnValueForMissingStub: _i3.Future.value(false), + ) + as _i3.Future); @override _i3.Future removeClickListener( - _i2.CompanionAdSlotClickListener? clickListener) => + _i2.CompanionAdSlotClickListener? clickListener, + ) => (super.noSuchMethod( - Invocation.method( - #removeClickListener, - [clickListener], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#removeClickListener, [clickListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setContainer(_i2.ViewGroup? container) => (super.noSuchMethod( - Invocation.method( - #setContainer, - [container], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setContainer, [container]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setSize( - int? width, - int? height, - ) => + _i3.Future setSize(int? width, int? height) => (super.noSuchMethod( - Invocation.method( - #setSize, - [ - width, - height, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setSize, [width, height]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setFluidSize() => (super.noSuchMethod( - Invocation.method( - #setFluidSize, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setFluidSize() => + (super.noSuchMethod( + Invocation.method(#setFluidSize, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.CompanionAdSlot pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeCompanionAdSlot_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeCompanionAdSlot_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.CompanionAdSlot); + _i2.CompanionAdSlot pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCompanionAdSlot_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCompanionAdSlot_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.CompanionAdSlot); } /// A class which mocks [FrameLayout]. @@ -277,59 +201,52 @@ class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { /// See the documentation for Mockito's code generation for more information. class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i2.FrameLayout pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeFrameLayout_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeFrameLayout_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.FrameLayout); + _i2.FrameLayout pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFrameLayout_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeFrameLayout_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.FrameLayout); @override - _i3.Future addView(_i2.View? view) => (super.noSuchMethod( - Invocation.method( - #addView, - [view], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future addView(_i2.View? view) => + (super.noSuchMethod( + Invocation.method(#addView, [view]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future removeView(_i2.View? view) => (super.noSuchMethod( - Invocation.method( - #removeView, - [view], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future removeView(_i2.View? view) => + (super.noSuchMethod( + Invocation.method(#removeView, [view]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } /// A class which mocks [ImaSdkFactory]. @@ -337,65 +254,57 @@ class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( - Invocation.method( - #createCompanionAdSlot, - [], - ), - returnValue: - _i3.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_2( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_2( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - ) as _i3.Future<_i2.CompanionAdSlot>); + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_2( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + returnValueForMissingStub: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_2( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + ) + as _i3.Future<_i2.CompanionAdSlot>); @override - _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( - Invocation.method( - #createImaSdkSettings, - [], - ), - returnValue: _i3.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_4( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_4( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - ) as _i3.Future<_i2.ImaSdkSettings>); + _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => + (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_4( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + returnValueForMissingStub: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_4( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + ) + as _i3.Future<_i2.ImaSdkSettings>); @override _i3.Future<_i2.AdsLoader> createAdsLoader( @@ -403,103 +312,67 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { _i2.AdDisplayContainer? container, ) => (super.noSuchMethod( - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - returnValue: _i3.Future<_i2.AdsLoader>.value(_FakeAdsLoader_5( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.AdsLoader>.value(_FakeAdsLoader_5( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - ) as _i3.Future<_i2.AdsLoader>); + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_5( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_5( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + ) + as _i3.Future<_i2.AdsLoader>); @override - _i3.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( - Invocation.method( - #createAdsRequest, - [], - ), - returnValue: _i3.Future<_i2.AdsRequest>.value(_FakeAdsRequest_6( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.AdsRequest>.value(_FakeAdsRequest_6( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - ) as _i3.Future<_i2.AdsRequest>); + _i3.Future<_i2.AdsRequest> createAdsRequest() => + (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_6(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_6(this, Invocation.method(#createAdsRequest, [])), + ), + ) + as _i3.Future<_i2.AdsRequest>); @override _i3.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( - Invocation.method( - #createAdsRenderingSettings, - [], - ), - returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_7( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - returnValueForMissingStub: _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_7( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - ) as _i3.Future<_i2.AdsRenderingSettings>); + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_7( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + returnValueForMissingStub: + _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_7( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + ) + as _i3.Future<_i2.AdsRenderingSettings>); @override - _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkFactory_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkFactory_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkFactory); + _i2.ImaSdkFactory pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_8( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkFactory_8( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkFactory); } diff --git a/packages/interactive_media_ads/test/android/content_progress_provider_test.dart b/packages/interactive_media_ads/test/android/content_progress_provider_test.dart index 9566988bf52..fbf7318e134 100644 --- a/packages/interactive_media_ads/test/android/content_progress_provider_test.dart +++ b/packages/interactive_media_ads/test/android/content_progress_provider_test.dart @@ -12,9 +12,7 @@ import 'package:mockito/mockito.dart'; import 'content_progress_provider_test.mocks.dart'; -@GenerateNiceMocks(>[ - MockSpec(), -]) +@GenerateNiceMocks(>[MockSpec()]) void main() { group('AndroidContentProgressProvider', () { test('setProgress', () async { @@ -23,24 +21,24 @@ void main() { final AndroidContentProgressProvider provider = AndroidContentProgressProvider( - AndroidContentProgressProviderCreationParams( - proxy: InteractiveMediaAdsProxy( - newContentProgressProvider: () => mockContentProgressProvider, - newVideoProgressUpdate: ({ - required int currentTimeMs, - required int durationMs, - }) { - expect(currentTimeMs, 1000); - expect(durationMs, 10000); - return ima.VideoProgressUpdate.pigeon_detached( - pigeon_instanceManager: ima.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); - }, - ), - ), - ); + AndroidContentProgressProviderCreationParams( + proxy: InteractiveMediaAdsProxy( + newContentProgressProvider: () => mockContentProgressProvider, + newVideoProgressUpdate: ({ + required int currentTimeMs, + required int durationMs, + }) { + expect(currentTimeMs, 1000); + expect(durationMs, 10000); + return ima.VideoProgressUpdate.pigeon_detached( + pigeon_instanceManager: ima.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ), + ), + ); await provider.setProgress( progress: const Duration(seconds: 1), diff --git a/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart b/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart index c37290e27f3..46bb33b330e 100644 --- a/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart @@ -25,24 +25,14 @@ import 'package:mockito/mockito.dart' as _i1; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeContentProgressProvider_1 extends _i1.SmartFake implements _i2.ContentProgressProvider { - _FakeContentProgressProvider_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeContentProgressProvider_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [ContentProgressProvider]. @@ -51,48 +41,41 @@ class _FakeContentProgressProvider_1 extends _i1.SmartFake class MockContentProgressProvider extends _i1.Mock implements _i2.ContentProgressProvider { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setContentProgress(_i2.VideoProgressUpdate? update) => (super.noSuchMethod( - Invocation.method( - #setContentProgress, - [update], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setContentProgress, [update]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.ContentProgressProvider pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeContentProgressProvider_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeContentProgressProvider_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ContentProgressProvider); + _i2.ContentProgressProvider pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeContentProgressProvider_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeContentProgressProvider_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ContentProgressProvider); } diff --git a/packages/interactive_media_ads/test/android/ima_settings_test.dart b/packages/interactive_media_ads/test/android/ima_settings_test.dart index e1286b51743..51425febedc 100644 --- a/packages/interactive_media_ads/test/android/ima_settings_test.dart +++ b/packages/interactive_media_ads/test/android/ima_settings_test.dart @@ -135,9 +135,9 @@ void main() { MockImaSdkSettings _mockImaSdkSettings() { final MockImaSdkFactory mockImaSdkFactory = MockImaSdkFactory(); final MockImaSdkSettings mockImaSdkSettings = MockImaSdkSettings(); - when(mockImaSdkFactory.createImaSdkSettings()).thenAnswer( - (_) async => mockImaSdkSettings, - ); + when( + mockImaSdkFactory.createImaSdkSettings(), + ).thenAnswer((_) async => mockImaSdkSettings); ima.PigeonOverrides.imaSdkFactory_instance = mockImaSdkFactory; return mockImaSdkSettings; diff --git a/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart b/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart index 31b3e692934..193494b308c 100644 --- a/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart @@ -25,76 +25,41 @@ import 'package:mockito/mockito.dart' as _i1; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCompanionAdSlot_1 extends _i1.SmartFake implements _i2.CompanionAdSlot { - _FakeCompanionAdSlot_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCompanionAdSlot_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkSettings_2 extends _i1.SmartFake implements _i2.ImaSdkSettings { - _FakeImaSdkSettings_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkSettings_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsLoader_3 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsLoader_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRequest_4 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRequest_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAdsRenderingSettings_5 extends _i1.SmartFake implements _i2.AdsRenderingSettings { - _FakeAdsRenderingSettings_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAdsRenderingSettings_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeImaSdkFactory_6 extends _i1.SmartFake implements _i2.ImaSdkFactory { - _FakeImaSdkFactory_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeImaSdkFactory_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [ImaSdkFactory]. @@ -102,65 +67,57 @@ class _FakeImaSdkFactory_6 extends _i1.SmartFake implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( - Invocation.method( - #createCompanionAdSlot, - [], - ), - returnValue: - _i3.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_1( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.CompanionAdSlot>.value(_FakeCompanionAdSlot_1( - this, - Invocation.method( - #createCompanionAdSlot, - [], - ), - )), - ) as _i3.Future<_i2.CompanionAdSlot>); + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_1( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + returnValueForMissingStub: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_1( + this, + Invocation.method(#createCompanionAdSlot, []), + ), + ), + ) + as _i3.Future<_i2.CompanionAdSlot>); @override - _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( - Invocation.method( - #createImaSdkSettings, - [], - ), - returnValue: _i3.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_2( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.ImaSdkSettings>.value(_FakeImaSdkSettings_2( - this, - Invocation.method( - #createImaSdkSettings, - [], - ), - )), - ) as _i3.Future<_i2.ImaSdkSettings>); + _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => + (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_2( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + returnValueForMissingStub: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_2( + this, + Invocation.method(#createImaSdkSettings, []), + ), + ), + ) + as _i3.Future<_i2.ImaSdkSettings>); @override _i3.Future<_i2.AdsLoader> createAdsLoader( @@ -168,105 +125,69 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { _i2.AdDisplayContainer? container, ) => (super.noSuchMethod( - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - returnValue: _i3.Future<_i2.AdsLoader>.value(_FakeAdsLoader_3( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.AdsLoader>.value(_FakeAdsLoader_3( - this, - Invocation.method( - #createAdsLoader, - [ - settings, - container, - ], - ), - )), - ) as _i3.Future<_i2.AdsLoader>); + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_3( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_3( + this, + Invocation.method(#createAdsLoader, [settings, container]), + ), + ), + ) + as _i3.Future<_i2.AdsLoader>); @override - _i3.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( - Invocation.method( - #createAdsRequest, - [], - ), - returnValue: _i3.Future<_i2.AdsRequest>.value(_FakeAdsRequest_4( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - returnValueForMissingStub: - _i3.Future<_i2.AdsRequest>.value(_FakeAdsRequest_4( - this, - Invocation.method( - #createAdsRequest, - [], - ), - )), - ) as _i3.Future<_i2.AdsRequest>); + _i3.Future<_i2.AdsRequest> createAdsRequest() => + (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_4(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_4(this, Invocation.method(#createAdsRequest, [])), + ), + ) + as _i3.Future<_i2.AdsRequest>); @override _i3.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( - Invocation.method( - #createAdsRenderingSettings, - [], - ), - returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_5( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - returnValueForMissingStub: _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_5( - this, - Invocation.method( - #createAdsRenderingSettings, - [], - ), - )), - ) as _i3.Future<_i2.AdsRenderingSettings>); + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_5( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + returnValueForMissingStub: + _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_5( + this, + Invocation.method(#createAdsRenderingSettings, []), + ), + ), + ) + as _i3.Future<_i2.AdsRenderingSettings>); @override - _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkFactory_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkFactory_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkFactory); + _i2.ImaSdkFactory pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_6( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkFactory_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkFactory); } /// A class which mocks [ImaSdkSettings]. @@ -274,130 +195,113 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockImaSdkSettings extends _i1.Mock implements _i2.ImaSdkSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setAutoPlayAdBreaks(bool? autoPlayAdBreaks) => (super.noSuchMethod( - Invocation.method( - #setAutoPlayAdBreaks, - [autoPlayAdBreaks], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setAutoPlayAdBreaks, [autoPlayAdBreaks]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setDebugMode(bool? debugMode) => (super.noSuchMethod( - Invocation.method( - #setDebugMode, - [debugMode], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setDebugMode(bool? debugMode) => + (super.noSuchMethod( + Invocation.method(#setDebugMode, [debugMode]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setFeatureFlags(Map? featureFlags) => (super.noSuchMethod( - Invocation.method( - #setFeatureFlags, - [featureFlags], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setFeatureFlags, [featureFlags]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setLanguage(String? language) => (super.noSuchMethod( - Invocation.method( - #setLanguage, - [language], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setLanguage(String? language) => + (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setMaxRedirects(int? maxRedirects) => (super.noSuchMethod( - Invocation.method( - #setMaxRedirects, - [maxRedirects], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setMaxRedirects(int? maxRedirects) => + (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [maxRedirects]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setPlayerType(String? playerType) => (super.noSuchMethod( - Invocation.method( - #setPlayerType, - [playerType], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setPlayerType(String? playerType) => + (super.noSuchMethod( + Invocation.method(#setPlayerType, [playerType]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setPlayerVersion(String? playerVersion) => (super.noSuchMethod( - Invocation.method( - #setPlayerVersion, - [playerVersion], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setPlayerVersion, [playerVersion]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setPpid(String? ppid) => (super.noSuchMethod( - Invocation.method( - #setPpid, - [ppid], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setPpid(String? ppid) => + (super.noSuchMethod( + Invocation.method(#setPpid, [ppid]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setSessionId(String? sessionId) => (super.noSuchMethod( - Invocation.method( - #setSessionId, - [sessionId], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setSessionId(String? sessionId) => + (super.noSuchMethod( + Invocation.method(#setSessionId, [sessionId]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.ImaSdkSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeImaSdkSettings_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeImaSdkSettings_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.ImaSdkSettings); + _i2.ImaSdkSettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkSettings_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImaSdkSettings_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.ImaSdkSettings); } diff --git a/packages/interactive_media_ads/test/content_progress_provider_test.dart b/packages/interactive_media_ads/test/content_progress_provider_test.dart index 180d9ce0d01..2eedd25b3a3 100644 --- a/packages/interactive_media_ads/test/content_progress_provider_test.dart +++ b/packages/interactive_media_ads/test/content_progress_provider_test.dart @@ -15,20 +15,18 @@ void main() { final TestContentProgressProvider platformProvider = TestContentProgressProvider( - const PlatformContentProgressProviderCreationParams(), - onSetProgress: ({ - required Duration progress, - required Duration duration, - }) async { - callbackProgress = progress; - callbackDuration = duration; - }, - ); + const PlatformContentProgressProviderCreationParams(), + onSetProgress: ({ + required Duration progress, + required Duration duration, + }) async { + callbackProgress = progress; + callbackDuration = duration; + }, + ); final ContentProgressProvider provider = - ContentProgressProvider.fromPlatform( - platformProvider, - ); + ContentProgressProvider.fromPlatform(platformProvider); await provider.setProgress( progress: const Duration(seconds: 1), diff --git a/packages/interactive_media_ads/test/ios/ad_display_container_test.dart b/packages/interactive_media_ads/test/ios/ad_display_container_test.dart index eb481968620..77cf4a0bbee 100644 --- a/packages/interactive_media_ads/test/ios/ad_display_container_test.dart +++ b/packages/interactive_media_ads/test/ios/ad_display_container_test.dart @@ -34,9 +34,9 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); expect(find.byType(UiKitView), findsOneWidget); expect(find.byKey(const Key('testKey')), findsOneWidget); @@ -53,20 +53,21 @@ void main() { final PigeonInstanceManager instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final UIView view = - UIView.pigeon_detached(pigeon_instanceManager: instanceManager); + final UIView view = UIView.pigeon_detached( + pigeon_instanceManager: instanceManager, + ); instanceManager.addDartCreatedInstance(view); final MockUIViewController mockController = MockUIViewController(); when(mockController.view).thenReturn(view); return mockController; }, - newIMAAdDisplayContainer: ({ - required UIView adContainer, - UIViewController? adContainerViewController, - List? companionSlots, - }) => - MockIMAAdDisplayContainer(), + newIMAAdDisplayContainer: + ({ + required UIView adContainer, + UIViewController? adContainerViewController, + List? companionSlots, + }) => MockIMAAdDisplayContainer(), ); final Completer onContainerAddedCompleter = Completer(); @@ -78,9 +79,9 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); final UiKitView view = find.byType(UiKitView).evaluate().single.widget as UiKitView; @@ -95,8 +96,9 @@ void main() { expect(onContainerAddedCompleter.isCompleted, isTrue); }); - testWidgets('AdDisplayContainer ads CompanionAdSlots', - (WidgetTester tester) async { + testWidgets('AdDisplayContainer ads CompanionAdSlots', ( + WidgetTester tester, + ) async { final PigeonInstanceManager instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); @@ -112,8 +114,9 @@ void main() { }) { viewDidAppearCallback = viewDidAppear!; - final UIView view = - UIView.pigeon_detached(pigeon_instanceManager: instanceManager); + final UIView view = UIView.pigeon_detached( + pigeon_instanceManager: instanceManager, + ); instanceManager.addDartCreatedInstance(view); final MockUIViewController mockController = MockUIViewController(); @@ -155,15 +158,15 @@ void main() { size: CompanionAdSlotSize.fixed(width: 300, height: 400), proxy: imaProxy, ), - ) + ), ], imaProxy: imaProxy, ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); final UiKitView view = find.byType(UiKitView).evaluate().single.widget as UiKitView; @@ -174,10 +177,9 @@ void main() { await onContainerAddedCompleter.future; - expect( - await addedAdSlotsCompleter.future, - [mockCompanionAdSlot], - ); + expect(await addedAdSlotsCompleter.future, [ + mockCompanionAdSlot, + ]); }); }); } diff --git a/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart b/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart index 1bfa309a9e0..b7b26314b54 100644 --- a/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart @@ -24,57 +24,32 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class class _FakeUIView_0 extends _i1.SmartFake implements _i2.UIView { - _FakeUIView_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUIView_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePigeonInstanceManager_1 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdDisplayContainer_2 extends _i1.SmartFake implements _i2.IMAAdDisplayContainer { - _FakeIMAAdDisplayContainer_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdDisplayContainer_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMACompanionAdSlot_3 extends _i1.SmartFake implements _i2.IMACompanionAdSlot { - _FakeIMACompanionAdSlot_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMACompanionAdSlot_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUIViewController_4 extends _i1.SmartFake implements _i2.UIViewController { - _FakeUIViewController_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUIViewController_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [IMAAdDisplayContainer]. @@ -83,97 +58,89 @@ class _FakeUIViewController_4 extends _i1.SmartFake class MockIMAAdDisplayContainer extends _i1.Mock implements _i2.IMAAdDisplayContainer { @override - _i2.UIView get adContainer => (super.noSuchMethod( - Invocation.getter(#adContainer), - returnValue: _FakeUIView_0( - this, - Invocation.getter(#adContainer), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#adContainer), - ), - ) as _i2.UIView); + _i2.UIView get adContainer => + (super.noSuchMethod( + Invocation.getter(#adContainer), + returnValue: _FakeUIView_0(this, Invocation.getter(#adContainer)), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.getter(#adContainer), + ), + ) + as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setAdContainerViewController( - _i2.UIViewController? controller) => + _i2.UIViewController? controller, + ) => (super.noSuchMethod( - Invocation.method( - #setAdContainerViewController, - [controller], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setAdContainerViewController, [controller]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future<_i2.UIViewController?> getAdContainerViewController() => (super.noSuchMethod( - Invocation.method( - #getAdContainerViewController, - [], - ), - returnValue: _i3.Future<_i2.UIViewController?>.value(), - returnValueForMissingStub: _i3.Future<_i2.UIViewController?>.value(), - ) as _i3.Future<_i2.UIViewController?>); + Invocation.method(#getAdContainerViewController, []), + returnValue: _i3.Future<_i2.UIViewController?>.value(), + returnValueForMissingStub: + _i3.Future<_i2.UIViewController?>.value(), + ) + as _i3.Future<_i2.UIViewController?>); @override _i3.Future registerFriendlyObstruction( - _i2.IMAFriendlyObstruction? friendlyObstruction) => + _i2.IMAFriendlyObstruction? friendlyObstruction, + ) => (super.noSuchMethod( - Invocation.method( - #registerFriendlyObstruction, - [friendlyObstruction], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#registerFriendlyObstruction, [ + friendlyObstruction, + ]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future unregisterAllFriendlyObstructions() => (super.noSuchMethod( - Invocation.method( - #unregisterAllFriendlyObstructions, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future unregisterAllFriendlyObstructions() => + (super.noSuchMethod( + Invocation.method(#unregisterAllFriendlyObstructions, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.IMAAdDisplayContainer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdDisplayContainer); + _i2.IMAAdDisplayContainer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdDisplayContainer); } /// A class which mocks [IMACompanionAdSlot]. @@ -182,83 +149,73 @@ class MockIMAAdDisplayContainer extends _i1.Mock class MockIMACompanionAdSlot extends _i1.Mock implements _i2.IMACompanionAdSlot { @override - _i2.UIView get view => (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) as _i2.UIView); + _i2.UIView get view => + (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.getter(#view), + ), + ) + as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setDelegate(_i2.IMACompanionDelegate? delegate) => (super.noSuchMethod( - Invocation.method( - #setDelegate, - [delegate], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future width() => (super.noSuchMethod( - Invocation.method( - #width, - [], - ), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) as _i3.Future); + _i3.Future width() => + (super.noSuchMethod( + Invocation.method(#width, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) + as _i3.Future); @override - _i3.Future height() => (super.noSuchMethod( - Invocation.method( - #height, - [], - ), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) as _i3.Future); + _i3.Future height() => + (super.noSuchMethod( + Invocation.method(#height, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) + as _i3.Future); @override - _i2.IMACompanionAdSlot pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMACompanionAdSlot_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMACompanionAdSlot_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMACompanionAdSlot); + _i2.IMACompanionAdSlot pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMACompanionAdSlot_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMACompanionAdSlot_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMACompanionAdSlot); } /// A class which mocks [UIView]. @@ -266,39 +223,34 @@ class MockIMACompanionAdSlot extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockUIView extends _i1.Mock implements _i2.UIView { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i2.UIView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeUIView_0( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.UIView); + _i2.UIView pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIView_0( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.UIView); } /// A class which mocks [UIViewController]. @@ -306,72 +258,59 @@ class MockUIView extends _i1.Mock implements _i2.UIView { /// See the documentation for Mockito's code generation for more information. class MockUIViewController extends _i1.Mock implements _i2.UIViewController { @override - _i2.UIView get view => (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) as _i2.UIView); + _i2.UIView get view => + (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.getter(#view), + ), + ) + as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i2.UIView pigeonVar_view() => (super.noSuchMethod( - Invocation.method( - #pigeonVar_view, - [], - ), - returnValue: _FakeUIView_0( - this, - Invocation.method( - #pigeonVar_view, - [], - ), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method( - #pigeonVar_view, - [], - ), - ), - ) as _i2.UIView); + _i2.UIView pigeonVar_view() => + (super.noSuchMethod( + Invocation.method(#pigeonVar_view, []), + returnValue: _FakeUIView_0( + this, + Invocation.method(#pigeonVar_view, []), + ), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.method(#pigeonVar_view, []), + ), + ) + as _i2.UIView); @override - _i2.UIViewController pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeUIViewController_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeUIViewController_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.UIViewController); + _i2.UIViewController pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIViewController_4( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeUIViewController_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.UIViewController); } diff --git a/packages/interactive_media_ads/test/ios/ads_loader_test.dart b/packages/interactive_media_ads/test/ios/ads_loader_test.dart index ae96c774539..d832a4298a2 100644 --- a/packages/interactive_media_ads/test/ios/ads_loader_test.dart +++ b/packages/interactive_media_ads/test/ios/ads_loader_test.dart @@ -34,8 +34,9 @@ void main() { }); testWidgets('instantiate IOSAdsLoader', (WidgetTester tester) async { - final IOSAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); IOSAdsLoader( IOSAdsLoaderCreationParams( @@ -116,18 +117,20 @@ void main() { IOSContentProgressProviderCreationParams(proxy: imaProxy), ); - await loader.requestAds(PlatformAdsRequest.withAdTagUrl( - adTagUrl: adTag, - adWillAutoPlay: true, - adWillPlayMuted: false, - continuousPlayback: true, - contentDuration: const Duration(seconds: 2), - contentKeywords: ['keyword1', 'keyword2'], - contentTitle: 'contentTitle', - liveStreamPrefetchMaxWaitTime: const Duration(seconds: 3), - vastLoadTimeout: const Duration(milliseconds: 5000), - contentProgressProvider: provider, - )); + await loader.requestAds( + PlatformAdsRequest.withAdTagUrl( + adTagUrl: adTag, + adWillAutoPlay: true, + adWillPlayMuted: false, + continuousPlayback: true, + contentDuration: const Duration(seconds: 2), + contentKeywords: ['keyword1', 'keyword2'], + contentTitle: 'contentTitle', + liveStreamPrefetchMaxWaitTime: const Duration(seconds: 3), + vastLoadTimeout: const Duration(milliseconds: 5000), + contentProgressProvider: provider, + ), + ); verify(mockRequest.setAdWillAutoPlay(true)); verify(mockRequest.setAdWillPlayMuted(false)); @@ -142,8 +145,9 @@ void main() { }); testWidgets('onAdsLoaded', (WidgetTester tester) async { - final IOSAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); ima.PigeonOverrides.iMASettings_new = () => MockIMASettings(); @@ -151,7 +155,8 @@ void main() { ima.IMAAdsLoaderDelegate, ima.IMAAdsLoader, ima.IMAAdsLoadedData, - ) adLoaderLoadedWithCallback; + ) + adLoaderLoadedWithCallback; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newIMAAdsLoader: ({ima.IMASettings? settings}) => MockIMAAdsLoader(), @@ -160,7 +165,8 @@ void main() { ima.IMAAdsLoaderDelegate, ima.IMAAdsLoader, ima.IMAAdsLoadedData, - ) adLoaderLoadedWith, + ) + adLoaderLoadedWith, required dynamic adsLoaderFailedWithErrorData, }) { adLoaderLoadedWithCallback = adLoaderLoadedWith; @@ -193,8 +199,9 @@ void main() { }); testWidgets('onAdsLoadError', (WidgetTester tester) async { - final IOSAdDisplayContainer container = - await _pumpAdDisplayContainer(tester); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( + tester, + ); ima.PigeonOverrides.iMASettings_new = () => MockIMASettings(); @@ -202,7 +209,8 @@ void main() { ima.IMAAdsLoaderDelegate, ima.IMAAdsLoader, ima.IMAAdLoadingErrorData, - ) adsLoaderFailedWithErrorDataCallback; + ) + adsLoaderFailedWithErrorDataCallback; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newIMAAdsLoader: ({ima.IMASettings? settings}) => MockIMAAdsLoader(), @@ -212,7 +220,8 @@ void main() { ima.IMAAdsLoaderDelegate, ima.IMAAdsLoader, ima.IMAAdLoadingErrorData, - ) adsLoaderFailedWithErrorData, + ) + adsLoaderFailedWithErrorData, }) { adsLoaderFailedWithErrorDataCallback = adsLoaderFailedWithErrorData; return MockIMAAdsLoaderDelegate(); @@ -235,9 +244,7 @@ void main() { await adsLoader.contentComplete(); final ima.PigeonInstanceManager instanceManager = - ima.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + ima.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); adsLoaderFailedWithErrorDataCallback( MockIMAAdsLoaderDelegate(), @@ -256,17 +263,17 @@ void main() { } Future _pumpAdDisplayContainer( - WidgetTester tester) async { + WidgetTester tester, +) async { final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( newUIViewController: ({ void Function(ima.UIViewController, bool)? viewDidAppear, }) { final ima.PigeonInstanceManager instanceManager = - ima.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, + ima.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final ima.UIView view = ima.UIView.pigeon_detached( + pigeon_instanceManager: instanceManager, ); - final ima.UIView view = - ima.UIView.pigeon_detached(pigeon_instanceManager: instanceManager); instanceManager.addDartCreatedInstance(view); final MockUIViewController mockController = MockUIViewController(); @@ -274,12 +281,12 @@ Future _pumpAdDisplayContainer( when(mockController.view).thenReturn(view); return mockController; }, - newIMAAdDisplayContainer: ({ - required ima.UIView adContainer, - ima.UIViewController? adContainerViewController, - List? companionSlots, - }) => - MockIMAAdDisplayContainer(), + newIMAAdDisplayContainer: + ({ + required ima.UIView adContainer, + ima.UIViewController? adContainerViewController, + List? companionSlots, + }) => MockIMAAdDisplayContainer(), ); final IOSAdDisplayContainer container = IOSAdDisplayContainer( @@ -289,9 +296,9 @@ Future _pumpAdDisplayContainer( ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => container.build(context), - )); + await tester.pumpWidget( + Builder(builder: (BuildContext context) => container.build(context)), + ); final UiKitView view = find.byType(UiKitView).evaluate().single.widget as UiKitView; diff --git a/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart b/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart index f847c4e50f4..a7d336d0a86 100644 --- a/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart @@ -24,97 +24,52 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class class _FakeUIView_0 extends _i1.SmartFake implements _i2.UIView { - _FakeUIView_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUIView_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePigeonInstanceManager_1 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdDisplayContainer_2 extends _i1.SmartFake implements _i2.IMAAdDisplayContainer { - _FakeIMAAdDisplayContainer_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdDisplayContainer_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdsLoader_3 extends _i1.SmartFake implements _i2.IMAAdsLoader { - _FakeIMAAdsLoader_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdsLoader_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdsLoaderDelegate_4 extends _i1.SmartFake implements _i2.IMAAdsLoaderDelegate { - _FakeIMAAdsLoaderDelegate_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdsLoaderDelegate_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdsManager_5 extends _i1.SmartFake implements _i2.IMAAdsManager { - _FakeIMAAdsManager_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdsManager_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdsRequest_6 extends _i1.SmartFake implements _i2.IMAAdsRequest { - _FakeIMAAdsRequest_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdsRequest_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMASettings_7 extends _i1.SmartFake implements _i2.IMASettings { - _FakeIMASettings_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMASettings_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUIViewController_8 extends _i1.SmartFake implements _i2.UIViewController { - _FakeUIViewController_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUIViewController_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [IMAAdDisplayContainer]. @@ -123,97 +78,89 @@ class _FakeUIViewController_8 extends _i1.SmartFake class MockIMAAdDisplayContainer extends _i1.Mock implements _i2.IMAAdDisplayContainer { @override - _i2.UIView get adContainer => (super.noSuchMethod( - Invocation.getter(#adContainer), - returnValue: _FakeUIView_0( - this, - Invocation.getter(#adContainer), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#adContainer), - ), - ) as _i2.UIView); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.UIView get adContainer => + (super.noSuchMethod( + Invocation.getter(#adContainer), + returnValue: _FakeUIView_0(this, Invocation.getter(#adContainer)), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.getter(#adContainer), + ), + ) + as _i2.UIView); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setAdContainerViewController( - _i2.UIViewController? controller) => + _i2.UIViewController? controller, + ) => (super.noSuchMethod( - Invocation.method( - #setAdContainerViewController, - [controller], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setAdContainerViewController, [controller]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future<_i2.UIViewController?> getAdContainerViewController() => (super.noSuchMethod( - Invocation.method( - #getAdContainerViewController, - [], - ), - returnValue: _i3.Future<_i2.UIViewController?>.value(), - returnValueForMissingStub: _i3.Future<_i2.UIViewController?>.value(), - ) as _i3.Future<_i2.UIViewController?>); + Invocation.method(#getAdContainerViewController, []), + returnValue: _i3.Future<_i2.UIViewController?>.value(), + returnValueForMissingStub: + _i3.Future<_i2.UIViewController?>.value(), + ) + as _i3.Future<_i2.UIViewController?>); @override _i3.Future registerFriendlyObstruction( - _i2.IMAFriendlyObstruction? friendlyObstruction) => - (super.noSuchMethod( - Invocation.method( - #registerFriendlyObstruction, - [friendlyObstruction], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future unregisterAllFriendlyObstructions() => (super.noSuchMethod( - Invocation.method( - #unregisterAllFriendlyObstructions, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i2.IMAAdDisplayContainer pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdDisplayContainer); + _i2.IMAFriendlyObstruction? friendlyObstruction, + ) => + (super.noSuchMethod( + Invocation.method(#registerFriendlyObstruction, [ + friendlyObstruction, + ]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future unregisterAllFriendlyObstructions() => + (super.noSuchMethod( + Invocation.method(#unregisterAllFriendlyObstructions, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i2.IMAAdDisplayContainer pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdDisplayContainer); } /// A class which mocks [IMAAdsLoader]. @@ -221,71 +168,61 @@ class MockIMAAdDisplayContainer extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockIMAAdsLoader extends _i1.Mock implements _i2.IMAAdsLoader { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i3.Future contentComplete() => (super.noSuchMethod( - Invocation.method( - #contentComplete, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i3.Future contentComplete() => + (super.noSuchMethod( + Invocation.method(#contentComplete, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future requestAds(_i2.IMAAdsRequest? request) => (super.noSuchMethod( - Invocation.method( - #requestAds, - [request], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#requestAds, [request]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setDelegate(_i2.IMAAdsLoaderDelegate? delegate) => (super.noSuchMethod( - Invocation.method( - #setDelegate, - [delegate], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i2.IMAAdsLoader pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdsLoader_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdsLoader_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdsLoader); + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i2.IMAAdsLoader pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsLoader_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdsLoader_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdsLoader); } /// A class which mocks [IMAAdsLoaderDelegate]. @@ -298,81 +235,86 @@ class MockIMAAdsLoaderDelegate extends _i1.Mock _i2.IMAAdsLoaderDelegate, _i2.IMAAdsLoader, _i2.IMAAdsLoadedData, - ) get adLoaderLoadedWith => (super.noSuchMethod( - Invocation.getter(#adLoaderLoadedWith), - returnValue: ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdsLoadedData adsLoadedData, - ) {}, - returnValueForMissingStub: ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdsLoadedData adsLoadedData, - ) {}, - ) as void Function( - _i2.IMAAdsLoaderDelegate, - _i2.IMAAdsLoader, - _i2.IMAAdsLoadedData, - )); + ) + get adLoaderLoadedWith => + (super.noSuchMethod( + Invocation.getter(#adLoaderLoadedWith), + returnValue: + ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdsLoadedData adsLoadedData, + ) {}, + returnValueForMissingStub: + ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdsLoadedData adsLoadedData, + ) {}, + ) + as void Function( + _i2.IMAAdsLoaderDelegate, + _i2.IMAAdsLoader, + _i2.IMAAdsLoadedData, + )); @override void Function( _i2.IMAAdsLoaderDelegate, _i2.IMAAdsLoader, _i2.IMAAdLoadingErrorData, - ) get adsLoaderFailedWithErrorData => (super.noSuchMethod( - Invocation.getter(#adsLoaderFailedWithErrorData), - returnValue: ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdLoadingErrorData adErrorData, - ) {}, - returnValueForMissingStub: ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdLoadingErrorData adErrorData, - ) {}, - ) as void Function( - _i2.IMAAdsLoaderDelegate, - _i2.IMAAdsLoader, - _i2.IMAAdLoadingErrorData, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.IMAAdsLoaderDelegate pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdsLoaderDelegate_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdsLoaderDelegate_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdsLoaderDelegate); + ) + get adsLoaderFailedWithErrorData => + (super.noSuchMethod( + Invocation.getter(#adsLoaderFailedWithErrorData), + returnValue: + ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdLoadingErrorData adErrorData, + ) {}, + returnValueForMissingStub: + ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdLoadingErrorData adErrorData, + ) {}, + ) + as void Function( + _i2.IMAAdsLoaderDelegate, + _i2.IMAAdsLoader, + _i2.IMAAdLoadingErrorData, + )); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.IMAAdsLoaderDelegate pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsLoaderDelegate_4( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdsLoaderDelegate_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdsLoaderDelegate); } /// A class which mocks [IMAAdsManager]. @@ -380,122 +322,108 @@ class MockIMAAdsLoaderDelegate extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setDelegate(_i2.IMAAdsManagerDelegate? delegate) => (super.noSuchMethod( - Invocation.method( - #setDelegate, - [delegate], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future initialize( - _i2.IMAAdsRenderingSettings? adsRenderingSettings) => - (super.noSuchMethod( - Invocation.method( - #initialize, - [adsRenderingSettings], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future start() => (super.noSuchMethod( - Invocation.method( - #start, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future resume() => (super.noSuchMethod( - Invocation.method( - #resume, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future skip() => (super.noSuchMethod( - Invocation.method( - #skip, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future discardAdBreak() => (super.noSuchMethod( - Invocation.method( - #discardAdBreak, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i2.IMAAdsManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdsManager_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdsManager_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdsManager); + _i2.IMAAdsRenderingSettings? adsRenderingSettings, + ) => + (super.noSuchMethod( + Invocation.method(#initialize, [adsRenderingSettings]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future start() => + (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future pause() => + (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future resume() => + (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future skip() => + (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future discardAdBreak() => + (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future destroy() => + (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i2.IMAAdsManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsManager_5( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdsManager_5( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdsManager); } /// A class which mocks [IMAAdsRequest]. @@ -503,179 +431,153 @@ class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { /// See the documentation for Mockito's code generation for more information. class MockIMAAdsRequest extends _i1.Mock implements _i2.IMAAdsRequest { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i3.Future getAdTagUrl() => (super.noSuchMethod( - Invocation.method( - #getAdTagUrl, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future getAdsResponse() => (super.noSuchMethod( - Invocation.method( - #getAdsResponse, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i3.Future getAdTagUrl() => + (super.noSuchMethod( + Invocation.method(#getAdTagUrl, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future getAdsResponse() => + (super.noSuchMethod( + Invocation.method(#getAdsResponse, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future<_i2.IMAAdDisplayContainer> getAdDisplayContainer() => (super.noSuchMethod( - Invocation.method( - #getAdDisplayContainer, - [], - ), - returnValue: _i3.Future<_i2.IMAAdDisplayContainer>.value( - _FakeIMAAdDisplayContainer_2( - this, - Invocation.method( - #getAdDisplayContainer, - [], - ), - )), - returnValueForMissingStub: _i3.Future<_i2.IMAAdDisplayContainer>.value( - _FakeIMAAdDisplayContainer_2( - this, - Invocation.method( - #getAdDisplayContainer, - [], - ), - )), - ) as _i3.Future<_i2.IMAAdDisplayContainer>); + Invocation.method(#getAdDisplayContainer, []), + returnValue: _i3.Future<_i2.IMAAdDisplayContainer>.value( + _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#getAdDisplayContainer, []), + ), + ), + returnValueForMissingStub: + _i3.Future<_i2.IMAAdDisplayContainer>.value( + _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#getAdDisplayContainer, []), + ), + ), + ) + as _i3.Future<_i2.IMAAdDisplayContainer>); @override _i3.Future setAdWillAutoPlay(bool? adWillAutoPlay) => (super.noSuchMethod( - Invocation.method( - #setAdWillAutoPlay, - [adWillAutoPlay], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setAdWillAutoPlay, [adWillAutoPlay]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setAdWillPlayMuted(bool? adWillPlayMuted) => (super.noSuchMethod( - Invocation.method( - #setAdWillPlayMuted, - [adWillPlayMuted], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setAdWillPlayMuted, [adWillPlayMuted]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setContinuousPlayback(bool? continuousPlayback) => (super.noSuchMethod( - Invocation.method( - #setContinuousPlayback, - [continuousPlayback], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setContinuousPlayback, [continuousPlayback]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setContentDuration(double? duration) => (super.noSuchMethod( - Invocation.method( - #setContentDuration, - [duration], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setContentDuration(double? duration) => + (super.noSuchMethod( + Invocation.method(#setContentDuration, [duration]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setContentKeywords(List? keywords) => (super.noSuchMethod( - Invocation.method( - #setContentKeywords, - [keywords], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setContentTitle(String? title) => (super.noSuchMethod( - Invocation.method( - #setContentTitle, - [title], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setContentURL(String? contentURL) => (super.noSuchMethod( - Invocation.method( - #setContentURL, - [contentURL], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setVastLoadTimeout(double? timeout) => (super.noSuchMethod( - Invocation.method( - #setVastLoadTimeout, - [timeout], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setContentKeywords, [keywords]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setContentTitle(String? title) => + (super.noSuchMethod( + Invocation.method(#setContentTitle, [title]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setContentURL(String? contentURL) => + (super.noSuchMethod( + Invocation.method(#setContentURL, [contentURL]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setVastLoadTimeout(double? timeout) => + (super.noSuchMethod( + Invocation.method(#setVastLoadTimeout, [timeout]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setLiveStreamPrefetchSeconds(double? seconds) => (super.noSuchMethod( - Invocation.method( - #setLiveStreamPrefetchSeconds, - [seconds], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i2.IMAAdsRequest pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdsRequest_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdsRequest_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdsRequest); + Invocation.method(#setLiveStreamPrefetchSeconds, [seconds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i2.IMAAdsRequest pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsRequest_6( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdsRequest_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdsRequest); } /// A class which mocks [IMASettings]. @@ -683,162 +585,142 @@ class MockIMAAdsRequest extends _i1.Mock implements _i2.IMAAdsRequest { /// See the documentation for Mockito's code generation for more information. class MockIMASettings extends _i1.Mock implements _i2.IMASettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i3.Future setPPID(String? ppid) => (super.noSuchMethod( - Invocation.method( - #setPPID, - [ppid], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setLanguage(String? language) => (super.noSuchMethod( - Invocation.method( - #setLanguage, - [language], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setMaxRedirects(int? max) => (super.noSuchMethod( - Invocation.method( - #setMaxRedirects, - [max], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i3.Future setPPID(String? ppid) => + (super.noSuchMethod( + Invocation.method(#setPPID, [ppid]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setLanguage(String? language) => + (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setMaxRedirects(int? max) => + (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [max]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setFeatureFlags(Map? flags) => (super.noSuchMethod( - Invocation.method( - #setFeatureFlags, - [flags], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setFeatureFlags, [flags]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setEnableBackgroundPlayback(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setEnableBackgroundPlayback, - [enabled], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setEnableBackgroundPlayback, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => (super.noSuchMethod( - Invocation.method( - #setAutoPlayAdBreaks, - [autoPlay], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => + (super.noSuchMethod( + Invocation.method(#setAutoPlayAdBreaks, [autoPlay]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setDisableNowPlayingInfo(bool? disable) => (super.noSuchMethod( - Invocation.method( - #setDisableNowPlayingInfo, - [disable], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setPlayerType(String? type) => (super.noSuchMethod( - Invocation.method( - #setPlayerType, - [type], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setPlayerVersion(String? version) => (super.noSuchMethod( - Invocation.method( - #setPlayerVersion, - [version], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setSessionID(String? sessionID) => (super.noSuchMethod( - Invocation.method( - #setSessionID, - [sessionID], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setSameAppKeyEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setSameAppKeyEnabled, - [enabled], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setEnableDebugMode(bool? enable) => (super.noSuchMethod( - Invocation.method( - #setEnableDebugMode, - [enable], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i2.IMASettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMASettings_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMASettings_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMASettings); + Invocation.method(#setDisableNowPlayingInfo, [disable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setPlayerType(String? type) => + (super.noSuchMethod( + Invocation.method(#setPlayerType, [type]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setPlayerVersion(String? version) => + (super.noSuchMethod( + Invocation.method(#setPlayerVersion, [version]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setSessionID(String? sessionID) => + (super.noSuchMethod( + Invocation.method(#setSessionID, [sessionID]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setSameAppKeyEnabled(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setSameAppKeyEnabled, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future setEnableDebugMode(bool? enable) => + (super.noSuchMethod( + Invocation.method(#setEnableDebugMode, [enable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i2.IMASettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMASettings_7( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMASettings_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMASettings); } /// A class which mocks [UIView]. @@ -846,39 +728,34 @@ class MockIMASettings extends _i1.Mock implements _i2.IMASettings { /// See the documentation for Mockito's code generation for more information. class MockUIView extends _i1.Mock implements _i2.UIView { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.UIView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeUIView_0( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.UIView); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.UIView pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIView_0( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.UIView); } /// A class which mocks [UIViewController]. @@ -886,72 +763,59 @@ class MockUIView extends _i1.Mock implements _i2.UIView { /// See the documentation for Mockito's code generation for more information. class MockUIViewController extends _i1.Mock implements _i2.UIViewController { @override - _i2.UIView get view => (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) as _i2.UIView); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.UIView pigeonVar_view() => (super.noSuchMethod( - Invocation.method( - #pigeonVar_view, - [], - ), - returnValue: _FakeUIView_0( - this, - Invocation.method( - #pigeonVar_view, - [], - ), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method( - #pigeonVar_view, - [], - ), - ), - ) as _i2.UIView); - - @override - _i2.UIViewController pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeUIViewController_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeUIViewController_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.UIViewController); + _i2.UIView get view => + (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.getter(#view), + ), + ) + as _i2.UIView); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.UIView pigeonVar_view() => + (super.noSuchMethod( + Invocation.method(#pigeonVar_view, []), + returnValue: _FakeUIView_0( + this, + Invocation.method(#pigeonVar_view, []), + ), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.method(#pigeonVar_view, []), + ), + ) + as _i2.UIView); + + @override + _i2.UIViewController pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIViewController_8( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeUIViewController_8( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.UIViewController); } diff --git a/packages/interactive_media_ads/test/ios/ads_manager_delegate_tests.dart b/packages/interactive_media_ads/test/ios/ads_manager_delegate_tests.dart index 62174b25d87..d2df945123e 100644 --- a/packages/interactive_media_ads/test/ios/ads_manager_delegate_tests.dart +++ b/packages/interactive_media_ads/test/ios/ads_manager_delegate_tests.dart @@ -19,7 +19,8 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent, - ) didReceiveAdEventCallback; + ) + didReceiveAdEventCallback; late final ima.IMAAdsManagerDelegate delegate; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( @@ -28,16 +29,18 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentPause, + didRequestContentPause, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentResume, + didRequestContentResume, }) { didReceiveAdEventCallback = didReceiveAdEvent; delegate = ima.IMAAdsManagerDelegate.pigeon_detached( @@ -84,7 +87,7 @@ void main() { ima.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); late final void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentPauseCallback; + didRequestContentPauseCallback; late final ima.IMAAdsManagerDelegate delegate; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( @@ -93,16 +96,18 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentPause, + didRequestContentPause, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentResume, + didRequestContentResume, }) { didRequestContentPauseCallback = didRequestContentPause; delegate = ima.IMAAdsManagerDelegate.pigeon_detached( @@ -142,7 +147,7 @@ void main() { ima.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); late final void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentResumeCallback; + didRequestContentResumeCallback; late final ima.IMAAdsManagerDelegate delegate; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( @@ -151,16 +156,18 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentPause, + didRequestContentPause, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentResume, + didRequestContentResume, }) { didRequestContentResumeCallback = didRequestContentResume; delegate = ima.IMAAdsManagerDelegate.pigeon_detached( @@ -203,7 +210,8 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError, - ) didReceiveAdErrorCallback; + ) + didReceiveAdErrorCallback; late final ima.IMAAdsManagerDelegate delegate; final InteractiveMediaAdsProxy imaProxy = InteractiveMediaAdsProxy( @@ -212,16 +220,18 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentPause, + didRequestContentPause, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentResume, + didRequestContentResume, }) { didReceiveAdErrorCallback = didReceiveAdError; delegate = ima.IMAAdsManagerDelegate.pigeon_detached( diff --git a/packages/interactive_media_ads/test/ios/ads_manager_test.dart b/packages/interactive_media_ads/test/ios/ads_manager_test.dart index ff4094bc804..1d2c9f83759 100644 --- a/packages/interactive_media_ads/test/ios/ads_manager_test.dart +++ b/packages/interactive_media_ads/test/ios/ads_manager_test.dart @@ -58,9 +58,9 @@ void main() { mockAdsRenderingSettings.setLoadVideoTimeout(9.0), mockAdsRenderingSettings.setMimeTypes(['value']), mockAdsRenderingSettings.setPlayAdsAfterTime(5.0), - mockAdsRenderingSettings.setUIElements( - [ima.UIElementType.countdown], - ), + mockAdsRenderingSettings.setUIElements([ + ima.UIElementType.countdown, + ]), mockAdsManager.initialize(mockAdsRenderingSettings), ]); }); @@ -116,16 +116,18 @@ void main() { ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent, - ) didReceiveAdEvent, + ) + didReceiveAdEvent, required void Function( ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError, - ) didReceiveAdError, + ) + didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentPause, + didRequestContentPause, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) - didRequestContentResume, + didRequestContentResume, }) { delegate = ima.IMAAdsManagerDelegate.pigeon_detached( didReceiveAdEvent: didReceiveAdEvent, @@ -140,9 +142,11 @@ void main() { }, ); - adsManager.setAdsManagerDelegate(IOSAdsManagerDelegate( - IOSAdsManagerDelegateCreationParams(proxy: imaProxy), - )); + adsManager.setAdsManagerDelegate( + IOSAdsManagerDelegate( + IOSAdsManagerDelegateCreationParams(proxy: imaProxy), + ), + ); verify(mockAdsManager.setDelegate(delegate)); }); diff --git a/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart b/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart index 6b6b945c09c..6d1b4b9a03e 100644 --- a/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart @@ -25,34 +25,19 @@ import 'package:mockito/mockito.dart' as _i1; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdsManager_1 extends _i1.SmartFake implements _i2.IMAAdsManager { - _FakeIMAAdsManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdsManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAAdsRenderingSettings_2 extends _i1.SmartFake implements _i2.IMAAdsRenderingSettings { - _FakeIMAAdsRenderingSettings_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAAdsRenderingSettings_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [IMAAdsManager]. @@ -60,122 +45,108 @@ class _FakeIMAAdsRenderingSettings_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setDelegate(_i2.IMAAdsManagerDelegate? delegate) => (super.noSuchMethod( - Invocation.method( - #setDelegate, - [delegate], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future initialize( - _i2.IMAAdsRenderingSettings? adsRenderingSettings) => + _i2.IMAAdsRenderingSettings? adsRenderingSettings, + ) => (super.noSuchMethod( - Invocation.method( - #initialize, - [adsRenderingSettings], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#initialize, [adsRenderingSettings]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future start() => (super.noSuchMethod( - Invocation.method( - #start, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future start() => + (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future pause() => + (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future resume() => (super.noSuchMethod( - Invocation.method( - #resume, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future resume() => + (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future skip() => (super.noSuchMethod( - Invocation.method( - #skip, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future skip() => + (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future discardAdBreak() => (super.noSuchMethod( - Invocation.method( - #discardAdBreak, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future discardAdBreak() => + (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future destroy() => + (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.IMAAdsManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdsManager_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdsManager_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdsManager); + _i2.IMAAdsManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsManager_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdsManager_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdsManager); } /// A class which mocks [IMAAdsRenderingSettings]. @@ -184,110 +155,97 @@ class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { class MockIMAAdsRenderingSettings extends _i1.Mock implements _i2.IMAAdsRenderingSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i3.Future setMimeTypes(List? types) => (super.noSuchMethod( - Invocation.method( - #setMimeTypes, - [types], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i3.Future setMimeTypes(List? types) => + (super.noSuchMethod( + Invocation.method(#setMimeTypes, [types]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setBitrate(int? bitrate) => (super.noSuchMethod( - Invocation.method( - #setBitrate, - [bitrate], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setBitrate(int? bitrate) => + (super.noSuchMethod( + Invocation.method(#setBitrate, [bitrate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setLoadVideoTimeout(double? seconds) => (super.noSuchMethod( - Invocation.method( - #setLoadVideoTimeout, - [seconds], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setLoadVideoTimeout(double? seconds) => + (super.noSuchMethod( + Invocation.method(#setLoadVideoTimeout, [seconds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setPlayAdsAfterTime(double? seconds) => (super.noSuchMethod( - Invocation.method( - #setPlayAdsAfterTime, - [seconds], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setPlayAdsAfterTime(double? seconds) => + (super.noSuchMethod( + Invocation.method(#setPlayAdsAfterTime, [seconds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setUIElements(List<_i2.UIElementType>? types) => (super.noSuchMethod( - Invocation.method( - #setUIElements, - [types], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setUIElements, [types]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setEnablePreloading(bool? enable) => (super.noSuchMethod( - Invocation.method( - #setEnablePreloading, - [enable], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setEnablePreloading(bool? enable) => + (super.noSuchMethod( + Invocation.method(#setEnablePreloading, [enable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setLinkOpenerPresentingController( - _i2.UIViewController? controller) => + _i2.UIViewController? controller, + ) => (super.noSuchMethod( - Invocation.method( - #setLinkOpenerPresentingController, - [controller], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setLinkOpenerPresentingController, [controller]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.IMAAdsRenderingSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAAdsRenderingSettings_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAAdsRenderingSettings_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAAdsRenderingSettings); + _i2.IMAAdsRenderingSettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsRenderingSettings_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAAdsRenderingSettings_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAAdsRenderingSettings); } diff --git a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart index 750001baa68..1c428058161 100644 --- a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart +++ b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart @@ -12,9 +12,7 @@ import 'package:mockito/mockito.dart'; import 'companion_ad_slot_test.mocks.dart'; -@GenerateNiceMocks(>[ - MockSpec(), -]) +@GenerateNiceMocks(>[MockSpec()]) void main() { group('IOSCompanionAdSlot', () { test('instantiate CompanionAdSlot with size', () async { @@ -22,24 +20,24 @@ void main() { MockIMACompanionAdSlot(); final IOSCompanionAdSlotCreationParams params = IOSCompanionAdSlotCreationParams( - size: CompanionAdSlotSize.fixed(width: 300, height: 400), - proxy: InteractiveMediaAdsProxy( - sizeIMACompanionAdSlot: ({ - required int width, - required int height, - required UIView view, - }) { - expect(width, 300); - expect(height, 400); - return mockCompanionAdSlot; - }, - newUIView: () { - return UIView.pigeon_detached( - pigeon_instanceManager: _TestInstanceManager(), - ); - }, - ), - ); + size: CompanionAdSlotSize.fixed(width: 300, height: 400), + proxy: InteractiveMediaAdsProxy( + sizeIMACompanionAdSlot: ({ + required int width, + required int height, + required UIView view, + }) { + expect(width, 300); + expect(height, 400); + return mockCompanionAdSlot; + }, + newUIView: () { + return UIView.pigeon_detached( + pigeon_instanceManager: _TestInstanceManager(), + ); + }, + ), + ); final IOSCompanionAdSlot adSlot = IOSCompanionAdSlot(params); expect(adSlot.nativeCompanionAdSlot, mockCompanionAdSlot); @@ -50,40 +48,35 @@ void main() { MockIMACompanionAdSlot(); final IOSCompanionAdSlotCreationParams params = IOSCompanionAdSlotCreationParams( - size: CompanionAdSlotSize.fixed(width: 300, height: 400), - onClicked: expectAsync0(() {}), - proxy: InteractiveMediaAdsProxy( - sizeIMACompanionAdSlot: ({ - required int width, - required int height, - required UIView view, - }) { - return mockCompanionAdSlot; - }, - newUIView: () { - return UIView.pigeon_detached( - pigeon_instanceManager: _TestInstanceManager(), - ); - }, - newIMACompanionDelegate: ({ - void Function( - IMACompanionDelegate, - IMACompanionAdSlot, - bool, - )? companionAdSlotFilled, - void Function( - IMACompanionDelegate, - IMACompanionAdSlot, - )? companionSlotWasClicked, - }) { - return IMACompanionDelegate.pigeon_detached( - companionAdSlotFilled: companionAdSlotFilled, - companionSlotWasClicked: companionSlotWasClicked, - pigeon_instanceManager: _TestInstanceManager(), - ); - }, - ), - ); + size: CompanionAdSlotSize.fixed(width: 300, height: 400), + onClicked: expectAsync0(() {}), + proxy: InteractiveMediaAdsProxy( + sizeIMACompanionAdSlot: ({ + required int width, + required int height, + required UIView view, + }) { + return mockCompanionAdSlot; + }, + newUIView: () { + return UIView.pigeon_detached( + pigeon_instanceManager: _TestInstanceManager(), + ); + }, + newIMACompanionDelegate: ({ + void Function(IMACompanionDelegate, IMACompanionAdSlot, bool)? + companionAdSlotFilled, + void Function(IMACompanionDelegate, IMACompanionAdSlot)? + companionSlotWasClicked, + }) { + return IMACompanionDelegate.pigeon_detached( + companionAdSlotFilled: companionAdSlotFilled, + companionSlotWasClicked: companionSlotWasClicked, + pigeon_instanceManager: _TestInstanceManager(), + ); + }, + ), + ); final IOSCompanionAdSlot adSlot = IOSCompanionAdSlot(params); expect(adSlot.nativeCompanionAdSlot, mockCompanionAdSlot); diff --git a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart index ba82b9c8de8..569dbce1384 100644 --- a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart @@ -24,35 +24,20 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class class _FakeUIView_0 extends _i1.SmartFake implements _i2.UIView { - _FakeUIView_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUIView_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePigeonInstanceManager_1 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMACompanionAdSlot_2 extends _i1.SmartFake implements _i2.IMACompanionAdSlot { - _FakeIMACompanionAdSlot_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMACompanionAdSlot_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [IMACompanionAdSlot]. @@ -61,81 +46,71 @@ class _FakeIMACompanionAdSlot_2 extends _i1.SmartFake class MockIMACompanionAdSlot extends _i1.Mock implements _i2.IMACompanionAdSlot { @override - _i2.UIView get view => (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) as _i2.UIView); + _i2.UIView get view => + (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0( + this, + Invocation.getter(#view), + ), + ) + as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i3.Future setDelegate(_i2.IMACompanionDelegate? delegate) => (super.noSuchMethod( - Invocation.method( - #setDelegate, - [delegate], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future width() => (super.noSuchMethod( - Invocation.method( - #width, - [], - ), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) as _i3.Future); + _i3.Future width() => + (super.noSuchMethod( + Invocation.method(#width, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) + as _i3.Future); @override - _i3.Future height() => (super.noSuchMethod( - Invocation.method( - #height, - [], - ), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) as _i3.Future); + _i3.Future height() => + (super.noSuchMethod( + Invocation.method(#height, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) + as _i3.Future); @override - _i2.IMACompanionAdSlot pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMACompanionAdSlot_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMACompanionAdSlot_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMACompanionAdSlot); + _i2.IMACompanionAdSlot pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMACompanionAdSlot_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMACompanionAdSlot_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMACompanionAdSlot); } diff --git a/packages/interactive_media_ads/test/ios/content_progress_provider_test.dart b/packages/interactive_media_ads/test/ios/content_progress_provider_test.dart index 80975174d3a..d508feee474 100644 --- a/packages/interactive_media_ads/test/ios/content_progress_provider_test.dart +++ b/packages/interactive_media_ads/test/ios/content_progress_provider_test.dart @@ -11,9 +11,7 @@ import 'package:mockito/mockito.dart'; import 'content_progress_provider_test.mocks.dart'; -@GenerateNiceMocks(>[ - MockSpec(), -]) +@GenerateNiceMocks(>[MockSpec()]) void main() { group('IOSContentProgressProvider', () { test('setProgress', () async { diff --git a/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart b/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart index cdb10245a4f..5e7fdf48b49 100644 --- a/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart @@ -25,24 +25,14 @@ import 'package:mockito/mockito.dart' as _i1; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMAContentPlayhead_1 extends _i1.SmartFake implements _i2.IMAContentPlayhead { - _FakeIMAContentPlayhead_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMAContentPlayhead_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [IMAContentPlayhead]. @@ -51,47 +41,41 @@ class _FakeIMAContentPlayhead_1 extends _i1.SmartFake class MockIMAContentPlayhead extends _i1.Mock implements _i2.IMAContentPlayhead { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future setCurrentTime(double? timeInterval) => (super.noSuchMethod( - Invocation.method( - #setCurrentTime, - [timeInterval], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setCurrentTime(double? timeInterval) => + (super.noSuchMethod( + Invocation.method(#setCurrentTime, [timeInterval]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.IMAContentPlayhead pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMAContentPlayhead_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMAContentPlayhead_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMAContentPlayhead); + _i2.IMAContentPlayhead pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAContentPlayhead_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMAContentPlayhead_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMAContentPlayhead); } diff --git a/packages/interactive_media_ads/test/ios/ima_settings_test.dart b/packages/interactive_media_ads/test/ios/ima_settings_test.dart index 5f97779268a..ef00b9b5b3d 100644 --- a/packages/interactive_media_ads/test/ios/ima_settings_test.dart +++ b/packages/interactive_media_ads/test/ios/ima_settings_test.dart @@ -11,9 +11,7 @@ import 'package:mockito/mockito.dart'; import 'ima_settings_test.mocks.dart'; -@GenerateNiceMocks(>[ - MockSpec(), -]) +@GenerateNiceMocks(>[MockSpec()]) void main() { group('IOSImaSettings', () { setUp(() { diff --git a/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart b/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart index e62fe39d833..7531eeeb520 100644 --- a/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart @@ -25,23 +25,13 @@ import 'package:mockito/mockito.dart' as _i1; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIMASettings_1 extends _i1.SmartFake implements _i2.IMASettings { - _FakeIMASettings_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIMASettings_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [IMASettings]. @@ -49,160 +39,140 @@ class _FakeIMASettings_1 extends _i1.SmartFake implements _i2.IMASettings { /// See the documentation for Mockito's code generation for more information. class MockIMASettings extends _i1.Mock implements _i2.IMASettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future setPPID(String? ppid) => (super.noSuchMethod( - Invocation.method( - #setPPID, - [ppid], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setPPID(String? ppid) => + (super.noSuchMethod( + Invocation.method(#setPPID, [ppid]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setLanguage(String? language) => (super.noSuchMethod( - Invocation.method( - #setLanguage, - [language], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setLanguage(String? language) => + (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setMaxRedirects(int? max) => (super.noSuchMethod( - Invocation.method( - #setMaxRedirects, - [max], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setMaxRedirects(int? max) => + (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [max]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setFeatureFlags(Map? flags) => (super.noSuchMethod( - Invocation.method( - #setFeatureFlags, - [flags], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setFeatureFlags, [flags]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setEnableBackgroundPlayback(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setEnableBackgroundPlayback, - [enabled], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setEnableBackgroundPlayback, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => (super.noSuchMethod( - Invocation.method( - #setAutoPlayAdBreaks, - [autoPlay], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => + (super.noSuchMethod( + Invocation.method(#setAutoPlayAdBreaks, [autoPlay]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override _i3.Future setDisableNowPlayingInfo(bool? disable) => (super.noSuchMethod( - Invocation.method( - #setDisableNowPlayingInfo, - [disable], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setDisableNowPlayingInfo, [disable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setPlayerType(String? type) => (super.noSuchMethod( - Invocation.method( - #setPlayerType, - [type], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setPlayerType(String? type) => + (super.noSuchMethod( + Invocation.method(#setPlayerType, [type]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setPlayerVersion(String? version) => (super.noSuchMethod( - Invocation.method( - #setPlayerVersion, - [version], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setPlayerVersion(String? version) => + (super.noSuchMethod( + Invocation.method(#setPlayerVersion, [version]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setSessionID(String? sessionID) => (super.noSuchMethod( - Invocation.method( - #setSessionID, - [sessionID], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setSessionID(String? sessionID) => + (super.noSuchMethod( + Invocation.method(#setSessionID, [sessionID]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setSameAppKeyEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setSameAppKeyEnabled, - [enabled], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setSameAppKeyEnabled(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setSameAppKeyEnabled, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future setEnableDebugMode(bool? enable) => (super.noSuchMethod( - Invocation.method( - #setEnableDebugMode, - [enable], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future setEnableDebugMode(bool? enable) => + (super.noSuchMethod( + Invocation.method(#setEnableDebugMode, [enable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.IMASettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeIMASettings_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeIMASettings_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.IMASettings); + _i2.IMASettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMASettings_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeIMASettings_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.IMASettings); } diff --git a/packages/interactive_media_ads/test/test_stubs.dart b/packages/interactive_media_ads/test/test_stubs.dart index b2359e33ee9..9ec7eecdd6b 100644 --- a/packages/interactive_media_ads/test/test_stubs.dart +++ b/packages/interactive_media_ads/test/test_stubs.dart @@ -17,31 +17,35 @@ final class TestInteractiveMediaAdsPlatform }); PlatformAdsLoader Function(PlatformAdsLoaderCreationParams params) - onCreatePlatformAdsLoader; + onCreatePlatformAdsLoader; PlatformAdsManagerDelegate Function( PlatformAdsManagerDelegateCreationParams params, - ) onCreatePlatformAdsManagerDelegate; + ) + onCreatePlatformAdsManagerDelegate; PlatformAdDisplayContainer Function( PlatformAdDisplayContainerCreationParams params, - ) onCreatePlatformAdDisplayContainer; + ) + onCreatePlatformAdDisplayContainer; PlatformContentProgressProvider Function( PlatformContentProgressProviderCreationParams params, - ) onCreatePlatformContentProgressProvider; + ) + onCreatePlatformContentProgressProvider; PlatformAdsRenderingSettings Function( PlatformAdsRenderingSettingsCreationParams params, - )? onCreatePlatformAdsRenderingSettings; + )? + onCreatePlatformAdsRenderingSettings; PlatformCompanionAdSlot Function( PlatformCompanionAdSlotCreationParams params, - )? onCreatePlatformCompanionAdSlot; + )? + onCreatePlatformCompanionAdSlot; - PlatformImaSettings Function( - PlatformImaSettingsCreationParams params, - )? onCreatePlatformImaSettings; + PlatformImaSettings Function(PlatformImaSettingsCreationParams params)? + onCreatePlatformImaSettings; @override PlatformAdsLoader createPlatformAdsLoader( @@ -84,10 +88,7 @@ final class TestInteractiveMediaAdsPlatform PlatformCompanionAdSlotCreationParams params, ) { return onCreatePlatformCompanionAdSlot?.call(params) ?? - TestCompanionAdSlot( - params, - onBuildWidget: (_) => Container(), - ); + TestCompanionAdSlot(params, onBuildWidget: (_) => Container()); } @override @@ -99,10 +100,8 @@ final class TestInteractiveMediaAdsPlatform } final class TestPlatformAdDisplayContainer extends PlatformAdDisplayContainer { - TestPlatformAdDisplayContainer( - super.params, { - required this.onBuild, - }) : super.implementation(); + TestPlatformAdDisplayContainer(super.params, {required this.onBuild}) + : super.implementation(); Widget Function(BuildContext context) onBuild; @@ -153,7 +152,7 @@ class TestAdsManager extends PlatformAdsManager { Future Function({PlatformAdsRenderingSettings? settings})? onInit; Future Function(PlatformAdsManagerDelegate delegate)? - onSetAdsManagerDelegate; + onSetAdsManagerDelegate; Future Function(AdsManagerStartParams params)? onStart; @@ -211,15 +210,14 @@ class TestAdsManager extends PlatformAdsManager { } class TestContentProgressProvider extends PlatformContentProgressProvider { - TestContentProgressProvider( - super.params, { - this.onSetProgress, - }) : super.implementation(); + TestContentProgressProvider(super.params, {this.onSetProgress}) + : super.implementation(); Future Function({ required Duration progress, required Duration duration, - })? onSetProgress; + })? + onSetProgress; @override Future setProgress({ @@ -235,10 +233,8 @@ final class TestAdsRenderingSettings extends PlatformAdsRenderingSettings { } final class TestCompanionAdSlot extends PlatformCompanionAdSlot { - TestCompanionAdSlot( - super.params, { - required this.onBuildWidget, - }) : super.implementation(); + TestCompanionAdSlot(super.params, {required this.onBuildWidget}) + : super.implementation(); Widget Function(BuildWidgetCreationParams params) onBuildWidget; diff --git a/packages/local_auth/local_auth/CHANGELOG.md b/packages/local_auth/local_auth/CHANGELOG.md index 8c2ed857a88..9dd19517d5c 100644 --- a/packages/local_auth/local_auth/CHANGELOG.md +++ b/packages/local_auth/local_auth/CHANGELOG.md @@ -1,7 +1,7 @@ ## NEXT +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. * Updates README to indicate that Andoid SDK <21 is no longer supported. -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. ## 2.3.0 diff --git a/packages/local_auth/local_auth/README.md b/packages/local_auth/local_auth/README.md index 17c71a7aaf0..2a7e4c043a8 100644 --- a/packages/local_auth/local_auth/README.md +++ b/packages/local_auth/local_auth/README.md @@ -73,7 +73,8 @@ also allows fallback to pin, pattern, or passcode. ```dart try { final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance'); + localizedReason: 'Please authenticate to show account balance', + ); // ··· } on PlatformException { // ... @@ -86,8 +87,9 @@ To require biometric authentication, pass `AuthenticationOptions` with ```dart final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - options: const AuthenticationOptions(biometricOnly: true)); + localizedReason: 'Please authenticate to show account balance', + options: const AuthenticationOptions(biometricOnly: true), +); ``` *Note*: `biometricOnly` is not supported on Windows since the Windows implementation's underlying API (Windows Hello) doesn't support selecting the authentication method. @@ -114,8 +116,9 @@ import 'package:local_auth/error_codes.dart' as auth_error; // ··· try { final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - options: const AuthenticationOptions(useErrorDialogs: false)); + localizedReason: 'Please authenticate to show account balance', + options: const AuthenticationOptions(useErrorDialogs: false), + ); // ··· } on PlatformException catch (e) { if (e.code == auth_error.notAvailable) { @@ -139,16 +142,15 @@ import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_darwin/local_auth_darwin.dart'; // ··· final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - authMessages: const [ - AndroidAuthMessages( - signInTitle: 'Oops! Biometric authentication required!', - cancelButton: 'No thanks', - ), - IOSAuthMessages( - cancelButton: 'No thanks', - ), - ]); + localizedReason: 'Please authenticate to show account balance', + authMessages: const [ + AndroidAuthMessages( + signInTitle: 'Oops! Biometric authentication required!', + cancelButton: 'No thanks', + ), + IOSAuthMessages(cancelButton: 'No thanks'), + ], + ); ``` See the platform-specific classes for details about what can be customized on @@ -170,8 +172,9 @@ import 'package:local_auth/local_auth.dart'; // ··· try { final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - options: const AuthenticationOptions(useErrorDialogs: false)); + localizedReason: 'Please authenticate to show account balance', + options: const AuthenticationOptions(useErrorDialogs: false), + ); // ··· } on PlatformException catch (e) { if (e.code == auth_error.notEnrolled) { diff --git a/packages/local_auth/local_auth/example/integration_test/local_auth_test.dart b/packages/local_auth/local_auth/example/integration_test/local_auth_test.dart index 5e8577f2b4d..c1689e2ff86 100644 --- a/packages/local_auth/local_auth/example/integration_test/local_auth_test.dart +++ b/packages/local_auth/local_auth/example/integration_test/local_auth_test.dart @@ -11,9 +11,6 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canCheckBiometrics', (WidgetTester tester) async { - expect( - LocalAuthentication().getAvailableBiometrics(), - completion(isList), - ); + expect(LocalAuthentication().getAvailableBiometrics(), completion(isList)); }); } diff --git a/packages/local_auth/local_auth/example/lib/main.dart b/packages/local_auth/local_auth/example/lib/main.dart index f8e08863b56..9f7b5cbaac5 100644 --- a/packages/local_auth/local_auth/example/lib/main.dart +++ b/packages/local_auth/local_auth/example/lib/main.dart @@ -33,10 +33,14 @@ class _MyAppState extends State { void initState() { super.initState(); auth.isDeviceSupported().then( - (bool isSupported) => setState(() => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported), - ); + (bool isSupported) => setState( + () => + _supportState = + isSupported + ? _SupportState.supported + : _SupportState.unsupported, + ), + ); } Future _checkBiometrics() async { @@ -82,9 +86,7 @@ class _MyAppState extends State { }); authenticated = await auth.authenticate( localizedReason: 'Let OS determine authentication method', - options: const AuthenticationOptions( - stickyAuth: true, - ), + options: const AuthenticationOptions(stickyAuth: true), ); setState(() { _isAuthenticating = false; @@ -102,7 +104,8 @@ class _MyAppState extends State { } setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); + () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', + ); } Future _authenticateWithBiometrics() async { @@ -151,9 +154,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), + appBar: AppBar(title: const Text('Plugin example app')), body: ListView( padding: const EdgeInsets.only(top: 30), children: [ @@ -209,9 +210,11 @@ class _MyAppState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text(_isAuthenticating - ? 'Cancel' - : 'Authenticate: biometrics only'), + Text( + _isAuthenticating + ? 'Cancel' + : 'Authenticate: biometrics only', + ), const Icon(Icons.fingerprint), ], ), @@ -227,8 +230,4 @@ class _MyAppState extends State { } } -enum _SupportState { - unknown, - supported, - unsupported, -} +enum _SupportState { unknown, supported, unsupported } diff --git a/packages/local_auth/local_auth/example/lib/readme_excerpts.dart b/packages/local_auth/local_auth/example/lib/readme_excerpts.dart index b0ee0e9daf0..f48d21b95bd 100644 --- a/packages/local_auth/local_auth/example/lib/readme_excerpts.dart +++ b/packages/local_auth/local_auth/example/lib/readme_excerpts.dart @@ -45,9 +45,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('README example app'), - ), + appBar: AppBar(title: const Text('README example app')), body: const Text('See example in main.dart'), ), ); @@ -85,7 +83,8 @@ class _MyAppState extends State { // #docregion AuthAny try { final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance'); + localizedReason: 'Please authenticate to show account balance', + ); // #enddocregion AuthAny print(didAuthenticate); // #docregion AuthAny @@ -98,8 +97,9 @@ class _MyAppState extends State { Future authenticateWithBiometrics() async { // #docregion AuthBioOnly final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - options: const AuthenticationOptions(biometricOnly: true)); + localizedReason: 'Please authenticate to show account balance', + options: const AuthenticationOptions(biometricOnly: true), + ); // #enddocregion AuthBioOnly print(didAuthenticate); } @@ -108,8 +108,9 @@ class _MyAppState extends State { // #docregion NoErrorDialogs try { final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - options: const AuthenticationOptions(useErrorDialogs: false)); + localizedReason: 'Please authenticate to show account balance', + options: const AuthenticationOptions(useErrorDialogs: false), + ); // #enddocregion NoErrorDialogs print(didAuthenticate ? 'Success!' : 'Failure'); // #docregion NoErrorDialogs @@ -129,8 +130,9 @@ class _MyAppState extends State { // #docregion ErrorHandling try { final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - options: const AuthenticationOptions(useErrorDialogs: false)); + localizedReason: 'Please authenticate to show account balance', + options: const AuthenticationOptions(useErrorDialogs: false), + ); // #enddocregion ErrorHandling print(didAuthenticate ? 'Success!' : 'Failure'); // #docregion ErrorHandling @@ -150,16 +152,15 @@ class _MyAppState extends State { Future authenticateWithCustomDialogMessages() async { // #docregion CustomMessages final bool didAuthenticate = await auth.authenticate( - localizedReason: 'Please authenticate to show account balance', - authMessages: const [ - AndroidAuthMessages( - signInTitle: 'Oops! Biometric authentication required!', - cancelButton: 'No thanks', - ), - IOSAuthMessages( - cancelButton: 'No thanks', - ), - ]); + localizedReason: 'Please authenticate to show account balance', + authMessages: const [ + AndroidAuthMessages( + signInTitle: 'Oops! Biometric authentication required!', + cancelButton: 'No thanks', + ), + IOSAuthMessages(cancelButton: 'No thanks'), + ], + ); // #enddocregion CustomMessages print(didAuthenticate ? 'Success!' : 'Failure'); } diff --git a/packages/local_auth/local_auth/example/pubspec.yaml b/packages/local_auth/local_auth/example/pubspec.yaml index 24e636b82a4..48d1809f2e9 100644 --- a/packages/local_auth/local_auth/example/pubspec.yaml +++ b/packages/local_auth/local_auth/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the local_auth plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth/lib/src/local_auth.dart b/packages/local_auth/local_auth/lib/src/local_auth.dart index 9046743dd5d..6d56548d018 100644 --- a/packages/local_auth/local_auth/lib/src/local_auth.dart +++ b/packages/local_auth/local_auth/lib/src/local_auth.dart @@ -36,14 +36,15 @@ class LocalAuthentication { /// authentication (e.g. lack of relevant hardware). This might throw /// [PlatformException] with error code [otherOperatingSystem] on the iOS /// simulator. - Future authenticate( - {required String localizedReason, - Iterable authMessages = const [ - IOSAuthMessages(), - AndroidAuthMessages(), - WindowsAuthMessages() - ], - AuthenticationOptions options = const AuthenticationOptions()}) { + Future authenticate({ + required String localizedReason, + Iterable authMessages = const [ + IOSAuthMessages(), + AndroidAuthMessages(), + WindowsAuthMessages(), + ], + AuthenticationOptions options = const AuthenticationOptions(), + }) { return LocalAuthPlatform.instance.authenticate( localizedReason: localizedReason, authMessages: authMessages, diff --git a/packages/local_auth/local_auth/pubspec.yaml b/packages/local_auth/local_auth/pubspec.yaml index bf4cd12bc98..eda0fdd07a8 100644 --- a/packages/local_auth/local_auth/pubspec.yaml +++ b/packages/local_auth/local_auth/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.3.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/local_auth/local_auth/test/local_auth_test.dart b/packages/local_auth/local_auth/test/local_auth_test.dart index aa9c5cf5e6b..df81bab2151 100644 --- a/packages/local_auth/local_auth/test/local_auth_test.dart +++ b/packages/local_auth/local_auth/test/local_auth_test.dart @@ -24,51 +24,60 @@ void main() { }); test('authenticate calls platform implementation', () { - when(mockLocalAuthPlatform.authenticate( - localizedReason: anyNamed('localizedReason'), - authMessages: anyNamed('authMessages'), - options: anyNamed('options'), - )).thenAnswer((_) async => true); + when( + mockLocalAuthPlatform.authenticate( + localizedReason: anyNamed('localizedReason'), + authMessages: anyNamed('authMessages'), + options: anyNamed('options'), + ), + ).thenAnswer((_) async => true); localAuthentication.authenticate(localizedReason: 'Test Reason'); - verify(mockLocalAuthPlatform.authenticate( - localizedReason: 'Test Reason', - authMessages: [ - const IOSAuthMessages(), - const AndroidAuthMessages(), - const WindowsAuthMessages(), - ], - )).called(1); + verify( + mockLocalAuthPlatform.authenticate( + localizedReason: 'Test Reason', + authMessages: [ + const IOSAuthMessages(), + const AndroidAuthMessages(), + const WindowsAuthMessages(), + ], + ), + ).called(1); }); test('isDeviceSupported calls platform implementation', () { - when(mockLocalAuthPlatform.isDeviceSupported()) - .thenAnswer((_) async => true); + when( + mockLocalAuthPlatform.isDeviceSupported(), + ).thenAnswer((_) async => true); localAuthentication.isDeviceSupported(); verify(mockLocalAuthPlatform.isDeviceSupported()).called(1); }); test('getEnrolledBiometrics calls platform implementation', () { - when(mockLocalAuthPlatform.getEnrolledBiometrics()) - .thenAnswer((_) async => []); + when( + mockLocalAuthPlatform.getEnrolledBiometrics(), + ).thenAnswer((_) async => []); localAuthentication.getAvailableBiometrics(); verify(mockLocalAuthPlatform.getEnrolledBiometrics()).called(1); }); test('stopAuthentication calls platform implementation', () { - when(mockLocalAuthPlatform.stopAuthentication()) - .thenAnswer((_) async => true); + when( + mockLocalAuthPlatform.stopAuthentication(), + ).thenAnswer((_) async => true); localAuthentication.stopAuthentication(); verify(mockLocalAuthPlatform.stopAuthentication()).called(1); }); test('canCheckBiometrics returns correct result', () async { - when(mockLocalAuthPlatform.deviceSupportsBiometrics()) - .thenAnswer((_) async => false); + when( + mockLocalAuthPlatform.deviceSupportsBiometrics(), + ).thenAnswer((_) async => false); bool? result; result = await localAuthentication.canCheckBiometrics; expect(result, false); - when(mockLocalAuthPlatform.deviceSupportsBiometrics()) - .thenAnswer((_) async => true); + when( + mockLocalAuthPlatform.deviceSupportsBiometrics(), + ).thenAnswer((_) async => true); result = await localAuthentication.canCheckBiometrics; expect(result, true); verify(mockLocalAuthPlatform.deviceSupportsBiometrics()).called(2); @@ -89,31 +98,44 @@ class MockLocalAuthPlatform extends Mock AuthenticationOptions? options = const AuthenticationOptions(), }) => super.noSuchMethod( - Invocation.method(#authenticate, [], { - #localizedReason: localizedReason, - #authMessages: authMessages, - #options: options, - }), - returnValue: Future.value(false)) as Future; + Invocation.method(#authenticate, [], { + #localizedReason: localizedReason, + #authMessages: authMessages, + #options: options, + }), + returnValue: Future.value(false), + ) + as Future; @override Future> getEnrolledBiometrics() => - super.noSuchMethod(Invocation.method(#getEnrolledBiometrics, []), - returnValue: Future>.value([])) + super.noSuchMethod( + Invocation.method(#getEnrolledBiometrics, []), + returnValue: Future>.value([]), + ) as Future>; @override Future isDeviceSupported() => - super.noSuchMethod(Invocation.method(#isDeviceSupported, []), - returnValue: Future.value(false)) as Future; + super.noSuchMethod( + Invocation.method(#isDeviceSupported, []), + returnValue: Future.value(false), + ) + as Future; @override Future stopAuthentication() => - super.noSuchMethod(Invocation.method(#stopAuthentication, []), - returnValue: Future.value(false)) as Future; + super.noSuchMethod( + Invocation.method(#stopAuthentication, []), + returnValue: Future.value(false), + ) + as Future; @override - Future deviceSupportsBiometrics() => super.noSuchMethod( - Invocation.method(#deviceSupportsBiometrics, []), - returnValue: Future.value(false)) as Future; + Future deviceSupportsBiometrics() => + super.noSuchMethod( + Invocation.method(#deviceSupportsBiometrics, []), + returnValue: Future.value(false), + ) + as Future; } diff --git a/packages/local_auth/local_auth_android/CHANGELOG.md b/packages/local_auth/local_auth_android/CHANGELOG.md index 69ec3474ea6..29be4e8936e 100644 --- a/packages/local_auth/local_auth_android/CHANGELOG.md +++ b/packages/local_auth/local_auth_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 1.0.51 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/local_auth/local_auth_android/example/integration_test/local_auth_test.dart b/packages/local_auth/local_auth_android/example/integration_test/local_auth_test.dart index 1dfc0ae7a6d..6010c6964b5 100644 --- a/packages/local_auth/local_auth_android/example/integration_test/local_auth_test.dart +++ b/packages/local_auth/local_auth_android/example/integration_test/local_auth_test.dart @@ -11,9 +11,6 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canCheckBiometrics', (WidgetTester tester) async { - expect( - LocalAuthAndroid().getEnrolledBiometrics(), - completion(isList), - ); + expect(LocalAuthAndroid().getEnrolledBiometrics(), completion(isList)); }); } diff --git a/packages/local_auth/local_auth_android/example/lib/main.dart b/packages/local_auth/local_auth_android/example/lib/main.dart index 378ada594aa..16790279b75 100644 --- a/packages/local_auth/local_auth_android/example/lib/main.dart +++ b/packages/local_auth/local_auth_android/example/lib/main.dart @@ -33,10 +33,14 @@ class _MyAppState extends State { void initState() { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( - (bool isSupported) => setState(() => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported), - ); + (bool isSupported) => setState( + () => + _supportState = + isSupported + ? _SupportState.supported + : _SupportState.unsupported, + ), + ); } Future _checkBiometrics() async { @@ -85,9 +89,7 @@ class _MyAppState extends State { authenticated = await LocalAuthPlatform.instance.authenticate( localizedReason: 'Let OS determine authentication method', authMessages: [const AndroidAuthMessages()], - options: const AuthenticationOptions( - stickyAuth: true, - ), + options: const AuthenticationOptions(stickyAuth: true), ); setState(() { _isAuthenticating = false; @@ -105,7 +107,8 @@ class _MyAppState extends State { } setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); + () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', + ); } Future _authenticateWithBiometrics() async { @@ -155,9 +158,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), + appBar: AppBar(title: const Text('Plugin example app')), body: ListView( padding: const EdgeInsets.only(top: 30), children: [ @@ -172,7 +173,8 @@ class _MyAppState extends State { const Text('This device is not supported'), const Divider(height: 100), Text( - 'Device supports biometrics: $_deviceSupportsBiometrics\n'), + 'Device supports biometrics: $_deviceSupportsBiometrics\n', + ), ElevatedButton( onPressed: _checkBiometrics, child: const Text('Check biometrics'), @@ -214,9 +216,11 @@ class _MyAppState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text(_isAuthenticating - ? 'Cancel' - : 'Authenticate: biometrics only'), + Text( + _isAuthenticating + ? 'Cancel' + : 'Authenticate: biometrics only', + ), const Icon(Icons.fingerprint), ], ), @@ -232,8 +236,4 @@ class _MyAppState extends State { } } -enum _SupportState { - unknown, - supported, - unsupported, -} +enum _SupportState { unknown, supported, unsupported } diff --git a/packages/local_auth/local_auth_android/example/pubspec.yaml b/packages/local_auth/local_auth_android/example/pubspec.yaml index 5d15fccff2d..3a10bee4329 100644 --- a/packages/local_auth/local_auth_android/example/pubspec.yaml +++ b/packages/local_auth/local_auth_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the local_auth_android plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth_android/lib/local_auth_android.dart b/packages/local_auth/local_auth_android/lib/local_auth_android.dart index 3b1fd96059e..3c81c90297d 100644 --- a/packages/local_auth/local_auth_android/lib/local_auth_android.dart +++ b/packages/local_auth/local_auth_android/lib/local_auth_android.dart @@ -17,9 +17,8 @@ export 'package:local_auth_platform_interface/types/biometric_type.dart'; /// The implementation of [LocalAuthPlatform] for Android. class LocalAuthAndroid extends LocalAuthPlatform { /// Creates a new plugin implementation instance. - LocalAuthAndroid({ - @visibleForTesting LocalAuthApi? api, - }) : _api = api ?? LocalAuthApi(); + LocalAuthAndroid({@visibleForTesting LocalAuthApi? api}) + : _api = api ?? LocalAuthApi(); /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { @@ -36,12 +35,14 @@ class LocalAuthAndroid extends LocalAuthPlatform { }) async { assert(localizedReason.isNotEmpty); final AuthResult result = await _api.authenticate( - AuthOptions( - biometricOnly: options.biometricOnly, - sensitiveTransaction: options.sensitiveTransaction, - sticky: options.stickyAuth, - useErrorDialgs: options.useErrorDialogs), - _pigeonStringsFromAuthMessages(localizedReason, authMessages)); + AuthOptions( + biometricOnly: options.biometricOnly, + sensitiveTransaction: options.sensitiveTransaction, + sticky: options.stickyAuth, + useErrorDialgs: options.useErrorDialogs, + ), + _pigeonStringsFromAuthMessages(localizedReason, authMessages), + ); // TODO(stuartmorgan): Replace this with structured errors, coordinated // across all platform implementations, per // https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#platform-exception-handling @@ -54,37 +55,47 @@ class LocalAuthAndroid extends LocalAuthPlatform { return false; case AuthResult.errorAlreadyInProgress: throw PlatformException( - code: 'auth_in_progress', message: 'Authentication in progress'); + code: 'auth_in_progress', + message: 'Authentication in progress', + ); case AuthResult.errorNoActivity: throw PlatformException( - code: 'no_activity', - message: 'local_auth plugin requires a foreground activity'); + code: 'no_activity', + message: 'local_auth plugin requires a foreground activity', + ); case AuthResult.errorNotFragmentActivity: throw PlatformException( - code: 'no_fragment_activity', - message: - 'local_auth plugin requires activity to be a FragmentActivity.'); + code: 'no_fragment_activity', + message: + 'local_auth plugin requires activity to be a FragmentActivity.', + ); case AuthResult.errorNotAvailable: throw PlatformException( - code: 'NotAvailable', - message: 'Security credentials not available.'); + code: 'NotAvailable', + message: 'Security credentials not available.', + ); case AuthResult.errorNotEnrolled: throw PlatformException( - code: 'NotEnrolled', - message: 'No Biometrics enrolled on this device.'); + code: 'NotEnrolled', + message: 'No Biometrics enrolled on this device.', + ); case AuthResult.errorLockedOutTemporarily: throw PlatformException( - code: 'LockedOut', - message: 'The operation was canceled because the API is locked out ' - 'due to too many attempts. This occurs after 5 failed ' - 'attempts, and lasts for 30 seconds.'); + code: 'LockedOut', + message: + 'The operation was canceled because the API is locked out ' + 'due to too many attempts. This occurs after 5 failed ' + 'attempts, and lasts for 30 seconds.', + ); case AuthResult.errorLockedOutPermanently: throw PlatformException( - code: 'PermanentlyLockedOut', - message: 'The operation was canceled because ERROR_LOCKOUT ' - 'occurred too many times. Biometric authentication is disabled ' - 'until the user unlocks with strong authentication ' - '(PIN/Pattern/Password)'); + code: 'PermanentlyLockedOut', + message: + 'The operation was canceled because ERROR_LOCKOUT ' + 'occurred too many times. Biometric authentication is disabled ' + 'until the user unlocks with strong authentication ' + '(PIN/Pattern/Password)', + ); } } @@ -113,7 +124,9 @@ class LocalAuthAndroid extends LocalAuthPlatform { Future stopAuthentication() async => _api.stopAuthentication(); AuthStrings _pigeonStringsFromAuthMessages( - String localizedReason, Iterable messagesList) { + String localizedReason, + Iterable messagesList, + ) { AndroidAuthMessages? messages; for (final AuthMessages entry in messagesList) { if (entry is AndroidAuthMessages) { @@ -121,22 +134,23 @@ class LocalAuthAndroid extends LocalAuthPlatform { } } return AuthStrings( - reason: localizedReason, - biometricHint: messages?.biometricHint ?? androidBiometricHint, - biometricNotRecognized: - messages?.biometricNotRecognized ?? androidBiometricNotRecognized, - biometricRequiredTitle: - messages?.biometricRequiredTitle ?? androidBiometricRequiredTitle, - cancelButton: messages?.cancelButton ?? androidCancelButton, - deviceCredentialsRequiredTitle: - messages?.deviceCredentialsRequiredTitle ?? - androidDeviceCredentialsRequiredTitle, - deviceCredentialsSetupDescription: - messages?.deviceCredentialsSetupDescription ?? - androidDeviceCredentialsSetupDescription, - goToSettingsButton: messages?.goToSettingsButton ?? goToSettings, - goToSettingsDescription: - messages?.goToSettingsDescription ?? androidGoToSettingsDescription, - signInTitle: messages?.signInTitle ?? androidSignInTitle); + reason: localizedReason, + biometricHint: messages?.biometricHint ?? androidBiometricHint, + biometricNotRecognized: + messages?.biometricNotRecognized ?? androidBiometricNotRecognized, + biometricRequiredTitle: + messages?.biometricRequiredTitle ?? androidBiometricRequiredTitle, + cancelButton: messages?.cancelButton ?? androidCancelButton, + deviceCredentialsRequiredTitle: + messages?.deviceCredentialsRequiredTitle ?? + androidDeviceCredentialsRequiredTitle, + deviceCredentialsSetupDescription: + messages?.deviceCredentialsSetupDescription ?? + androidDeviceCredentialsSetupDescription, + goToSettingsButton: messages?.goToSettingsButton ?? goToSettings, + goToSettingsDescription: + messages?.goToSettingsDescription ?? androidGoToSettingsDescription, + signInTitle: messages?.signInTitle ?? androidSignInTitle, + ); } } diff --git a/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart b/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart index c82f6820055..e9918e6c573 100644 --- a/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart +++ b/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart @@ -80,9 +80,11 @@ class AndroidAuthMessages extends AuthMessages { 'biometricRequired': biometricRequiredTitle ?? androidBiometricRequiredTitle, 'cancelButton': cancelButton ?? androidCancelButton, - 'deviceCredentialsRequired': deviceCredentialsRequiredTitle ?? + 'deviceCredentialsRequired': + deviceCredentialsRequiredTitle ?? androidDeviceCredentialsRequiredTitle, - 'deviceCredentialsSetupDescription': deviceCredentialsSetupDescription ?? + 'deviceCredentialsSetupDescription': + deviceCredentialsSetupDescription ?? androidDeviceCredentialsSetupDescription, 'goToSetting': goToSettingsButton ?? goToSettings, 'goToSettingDescription': @@ -111,17 +113,18 @@ class AndroidAuthMessages extends AuthMessages { @override int get hashCode => Object.hash( - super.hashCode, - biometricHint, - biometricNotRecognized, - biometricRequiredTitle, - biometricSuccess, - cancelButton, - deviceCredentialsRequiredTitle, - deviceCredentialsSetupDescription, - goToSettingsButton, - goToSettingsDescription, - signInTitle); + super.hashCode, + biometricHint, + biometricNotRecognized, + biometricRequiredTitle, + biometricSuccess, + cancelButton, + deviceCredentialsRequiredTitle, + deviceCredentialsSetupDescription, + goToSettingsButton, + goToSettingsDescription, + signInTitle, + ); } // Default strings for AndroidAuthMessages. Currently supports English. @@ -129,64 +132,90 @@ class AndroidAuthMessages extends AuthMessages { /// Message shown on a button that the user can click to go to settings pages /// from the current dialog. -String get goToSettings => Intl.message('Go to settings', - desc: 'Message shown on a button that the user can click to go to ' - 'settings pages from the current dialog. Maximum 30 characters.'); +String get goToSettings => Intl.message( + 'Go to settings', + desc: + 'Message shown on a button that the user can click to go to ' + 'settings pages from the current dialog. Maximum 30 characters.', +); /// Hint message advising the user how to authenticate with biometrics. -String get androidBiometricHint => Intl.message('Verify identity', - desc: 'Hint message advising the user how to authenticate with biometrics. ' - 'Maximum 60 characters.'); +String get androidBiometricHint => Intl.message( + 'Verify identity', + desc: + 'Hint message advising the user how to authenticate with biometrics. ' + 'Maximum 60 characters.', +); /// Message to let the user know that authentication was failed. -String get androidBiometricNotRecognized => - Intl.message('Not recognized. Try again.', - desc: 'Message to let the user know that authentication was failed. ' - 'Maximum 60 characters.'); +String get androidBiometricNotRecognized => Intl.message( + 'Not recognized. Try again.', + desc: + 'Message to let the user know that authentication was failed. ' + 'Maximum 60 characters.', +); /// Message to let the user know that authentication was successful. It -String get androidBiometricSuccess => Intl.message('Success', - desc: 'Message to let the user know that authentication was successful. ' - 'Maximum 60 characters.'); +String get androidBiometricSuccess => Intl.message( + 'Success', + desc: + 'Message to let the user know that authentication was successful. ' + 'Maximum 60 characters.', +); /// Message shown on a button that the user can click to leave the /// current dialog. -String get androidCancelButton => Intl.message('Cancel', - desc: 'Message shown on a button that the user can click to leave the ' - 'current dialog. Maximum 30 characters.'); +String get androidCancelButton => Intl.message( + 'Cancel', + desc: + 'Message shown on a button that the user can click to leave the ' + 'current dialog. Maximum 30 characters.', +); /// Message shown as a title in a dialog which indicates the user /// that they need to scan biometric to continue. -String get androidSignInTitle => Intl.message('Authentication required', - desc: 'Message shown as a title in a dialog which indicates the user ' - 'that they need to scan biometric to continue. Maximum 60 characters.'); +String get androidSignInTitle => Intl.message( + 'Authentication required', + desc: + 'Message shown as a title in a dialog which indicates the user ' + 'that they need to scan biometric to continue. Maximum 60 characters.', +); /// Message shown as a title in a dialog which indicates the user /// has not set up biometric authentication on their device. -String get androidBiometricRequiredTitle => Intl.message('Biometric required', - desc: 'Message shown as a title in a dialog which indicates the user ' - 'has not set up biometric authentication on their device. ' - 'Maximum 60 characters.'); +String get androidBiometricRequiredTitle => Intl.message( + 'Biometric required', + desc: + 'Message shown as a title in a dialog which indicates the user ' + 'has not set up biometric authentication on their device. ' + 'Maximum 60 characters.', +); /// Message shown as a title in a dialog which indicates the user /// has not set up credentials authentication on their device. -String get androidDeviceCredentialsRequiredTitle => - Intl.message('Device credentials required', - desc: 'Message shown as a title in a dialog which indicates the user ' - 'has not set up credentials authentication on their device. ' - 'Maximum 60 characters.'); +String get androidDeviceCredentialsRequiredTitle => Intl.message( + 'Device credentials required', + desc: + 'Message shown as a title in a dialog which indicates the user ' + 'has not set up credentials authentication on their device. ' + 'Maximum 60 characters.', +); /// Message advising the user to go to the settings and configure /// device credentials on their device. -String get androidDeviceCredentialsSetupDescription => - Intl.message('Device credentials required', - desc: 'Message advising the user to go to the settings and configure ' - 'device credentials on their device.'); +String get androidDeviceCredentialsSetupDescription => Intl.message( + 'Device credentials required', + desc: + 'Message advising the user to go to the settings and configure ' + 'device credentials on their device.', +); /// Message advising the user to go to the settings and configure /// biometric on their device. String get androidGoToSettingsDescription => Intl.message( - 'Biometric authentication is not set up on your device. Go to ' - "'Settings > Security' to add biometric authentication.", - desc: 'Message advising the user to go to the settings and configure ' - 'biometric on their device.'); + 'Biometric authentication is not set up on your device. Go to ' + "'Settings > Security' to add biometric authentication.", + desc: + 'Message advising the user to go to the settings and configure ' + 'biometric on their device.', +); diff --git a/packages/local_auth/local_auth_android/lib/src/messages.g.dart b/packages/local_auth/local_auth_android/lib/src/messages.g.dart index 590562c0370..ad0c2be01ef 100644 --- a/packages/local_auth/local_auth_android/lib/src/messages.g.dart +++ b/packages/local_auth/local_auth_android/lib/src/messages.g.dart @@ -50,10 +50,7 @@ enum AuthResult { } /// Pigeon equivalent of the subset of BiometricType used by Android. -enum AuthClassification { - weak, - strong, -} +enum AuthClassification { weak, strong } /// Pigeon version of AndroidAuthStrings, plus the authorization reason. /// @@ -207,11 +204,12 @@ class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LocalAuthApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + LocalAuthApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -224,10 +222,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.isDeviceSupported$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -255,10 +253,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.deviceCanSupportBiometrics$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -288,10 +286,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.stopAuthentication$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -319,10 +317,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.getEnrolledBiometrics$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -347,17 +345,20 @@ class LocalAuthApi { /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. Future authenticate( - AuthOptions options, AuthStrings strings) async { + AuthOptions options, + AuthStrings strings, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.authenticate$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([options, strings]) as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([options, strings]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/local_auth/local_auth_android/pigeons/messages.dart b/packages/local_auth/local_auth_android/pigeons/messages.dart index b08936637e2..f78ddb1a57c 100644 --- a/packages/local_auth/local_auth_android/pigeons/messages.dart +++ b/packages/local_auth/local_auth_android/pigeons/messages.dart @@ -4,13 +4,14 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - javaOut: 'android/src/main/java/io/flutter/plugins/localauth/Messages.java', - javaOptions: JavaOptions(package: 'io.flutter.plugins.localauth'), - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + javaOut: 'android/src/main/java/io/flutter/plugins/localauth/Messages.java', + javaOptions: JavaOptions(package: 'io.flutter.plugins.localauth'), + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Pigeon version of AndroidAuthStrings, plus the authorization reason. /// /// See auth_messages_android.dart for details. @@ -73,11 +74,12 @@ enum AuthResult { } class AuthOptions { - AuthOptions( - {required this.biometricOnly, - required this.sensitiveTransaction, - required this.sticky, - required this.useErrorDialgs}); + AuthOptions({ + required this.biometricOnly, + required this.sensitiveTransaction, + required this.sticky, + required this.useErrorDialgs, + }); final bool biometricOnly; final bool sensitiveTransaction; final bool sticky; diff --git a/packages/local_auth/local_auth_android/pubspec.yaml b/packages/local_auth/local_auth_android/pubspec.yaml index d835fc5d639..2a1565e61c0 100644 --- a/packages/local_auth/local_auth_android/pubspec.yaml +++ b/packages/local_auth/local_auth_android/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.0.51 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/local_auth/local_auth_android/test/local_auth_test.dart b/packages/local_auth/local_auth_android/test/local_auth_test.dart index 4c3785c9672..1342b388bfa 100644 --- a/packages/local_auth/local_auth_android/test/local_auth_test.dart +++ b/packages/local_auth/local_auth_android/test/local_auth_test.dart @@ -65,23 +65,22 @@ void main() { group('getEnrolledBiometrics', () { test('translates values', () async { - when(api.getEnrolledBiometrics()) - .thenAnswer((_) async => [ - AuthClassification.weak, - AuthClassification.strong, - ]); + when(api.getEnrolledBiometrics()).thenAnswer( + (_) async => [ + AuthClassification.weak, + AuthClassification.strong, + ], + ); final List result = await plugin.getEnrolledBiometrics(); - expect(result, [ - BiometricType.weak, - BiometricType.strong, - ]); + expect(result, [BiometricType.weak, BiometricType.strong]); }); test('handles empty', () async { - when(api.getEnrolledBiometrics()) - .thenAnswer((_) async => []); + when( + api.getEnrolledBiometrics(), + ).thenAnswer((_) async => []); final List result = await plugin.getEnrolledBiometrics(); @@ -92,15 +91,19 @@ void main() { group('authenticate', () { group('strings', () { test('passes default values when nothing is provided', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); const String reason = 'test reason'; await plugin.authenticate( - localizedReason: reason, authMessages: []); + localizedReason: reason, + authMessages: [], + ); - final VerificationResult result = - verify(api.authenticate(any, captureAny)); + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from @@ -109,47 +112,64 @@ void main() { expect(strings.biometricNotRecognized, androidBiometricNotRecognized); expect(strings.biometricRequiredTitle, androidBiometricRequiredTitle); expect(strings.cancelButton, androidCancelButton); - expect(strings.deviceCredentialsRequiredTitle, - androidDeviceCredentialsRequiredTitle); - expect(strings.deviceCredentialsSetupDescription, - androidDeviceCredentialsSetupDescription); + expect( + strings.deviceCredentialsRequiredTitle, + androidDeviceCredentialsRequiredTitle, + ); + expect( + strings.deviceCredentialsSetupDescription, + androidDeviceCredentialsSetupDescription, + ); expect(strings.goToSettingsButton, goToSettings); expect(strings.goToSettingsDescription, androidGoToSettingsDescription); expect(strings.signInTitle, androidSignInTitle); }); - test('passes default values when only other platform values are provided', - () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + test( + 'passes default values when only other platform values are provided', + () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); - const String reason = 'test reason'; - await plugin.authenticate( + const String reason = 'test reason'; + await plugin.authenticate( localizedReason: reason, - authMessages: [AnotherPlatformAuthMessages()]); - - final VerificationResult result = - verify(api.authenticate(any, captureAny)); - final AuthStrings strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - // These should all be the default values from - // auth_messages_android.dart - expect(strings.biometricHint, androidBiometricHint); - expect(strings.biometricNotRecognized, androidBiometricNotRecognized); - expect(strings.biometricRequiredTitle, androidBiometricRequiredTitle); - expect(strings.cancelButton, androidCancelButton); - expect(strings.deviceCredentialsRequiredTitle, - androidDeviceCredentialsRequiredTitle); - expect(strings.deviceCredentialsSetupDescription, - androidDeviceCredentialsSetupDescription); - expect(strings.goToSettingsButton, goToSettings); - expect(strings.goToSettingsDescription, androidGoToSettingsDescription); - expect(strings.signInTitle, androidSignInTitle); - }); + authMessages: [AnotherPlatformAuthMessages()], + ); + + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); + final AuthStrings strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + // These should all be the default values from + // auth_messages_android.dart + expect(strings.biometricHint, androidBiometricHint); + expect(strings.biometricNotRecognized, androidBiometricNotRecognized); + expect(strings.biometricRequiredTitle, androidBiometricRequiredTitle); + expect(strings.cancelButton, androidCancelButton); + expect( + strings.deviceCredentialsRequiredTitle, + androidDeviceCredentialsRequiredTitle, + ); + expect( + strings.deviceCredentialsSetupDescription, + androidDeviceCredentialsSetupDescription, + ); + expect(strings.goToSettingsButton, goToSettings); + expect( + strings.goToSettingsDescription, + androidGoToSettingsDescription, + ); + expect(strings.signInTitle, androidSignInTitle); + }, + ); test('passes all non-default values correctly', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and @@ -164,24 +184,27 @@ void main() { const String goButton = 'H'; const String goDescription = 'I'; const String signInTitle = 'J'; - await plugin - .authenticate(localizedReason: reason, authMessages: [ - const AndroidAuthMessages( - biometricHint: hint, - biometricNotRecognized: bioNotRecognized, - biometricRequiredTitle: bioRequired, - cancelButton: cancel, - deviceCredentialsRequiredTitle: credentialsRequired, - deviceCredentialsSetupDescription: credentialsSetup, - goToSettingsButton: goButton, - goToSettingsDescription: goDescription, - signInTitle: signInTitle, - ), - AnotherPlatformAuthMessages(), - ]); - - final VerificationResult result = - verify(api.authenticate(any, captureAny)); + await plugin.authenticate( + localizedReason: reason, + authMessages: [ + const AndroidAuthMessages( + biometricHint: hint, + biometricNotRecognized: bioNotRecognized, + biometricRequiredTitle: bioRequired, + cancelButton: cancel, + deviceCredentialsRequiredTitle: credentialsRequired, + deviceCredentialsSetupDescription: credentialsSetup, + goToSettingsButton: goButton, + goToSettingsDescription: goDescription, + signInTitle: signInTitle, + ), + AnotherPlatformAuthMessages(), + ], + ); + + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.biometricHint, hint); @@ -196,8 +219,9 @@ void main() { }); test('passes provided messages with default fallbacks', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and @@ -207,18 +231,21 @@ void main() { const String bioNotRecognized = 'C'; const String bioRequired = 'D'; const String cancel = 'E'; - await plugin - .authenticate(localizedReason: reason, authMessages: [ - const AndroidAuthMessages( - biometricHint: hint, - biometricNotRecognized: bioNotRecognized, - biometricRequiredTitle: bioRequired, - cancelButton: cancel, - ), - ]); - - final VerificationResult result = - verify(api.authenticate(any, captureAny)); + await plugin.authenticate( + localizedReason: reason, + authMessages: [ + const AndroidAuthMessages( + biometricHint: hint, + biometricNotRecognized: bioNotRecognized, + biometricRequiredTitle: bioRequired, + cancelButton: cancel, + ), + ], + ); + + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the provided values. @@ -228,10 +255,14 @@ void main() { expect(strings.cancelButton, cancel); // These were non set, so should all be the default values from // auth_messages_android.dart - expect(strings.deviceCredentialsRequiredTitle, - androidDeviceCredentialsRequiredTitle); - expect(strings.deviceCredentialsSetupDescription, - androidDeviceCredentialsSetupDescription); + expect( + strings.deviceCredentialsRequiredTitle, + androidDeviceCredentialsRequiredTitle, + ); + expect( + strings.deviceCredentialsSetupDescription, + androidDeviceCredentialsSetupDescription, + ); expect(strings.goToSettingsButton, goToSettings); expect(strings.goToSettingsDescription, androidGoToSettingsDescription); expect(strings.signInTitle, androidSignInTitle); @@ -240,14 +271,18 @@ void main() { group('options', () { test('passes default values', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); await plugin.authenticate( - localizedReason: 'reason', authMessages: []); + localizedReason: 'reason', + authMessages: [], + ); - final VerificationResult result = - verify(api.authenticate(captureAny, any)); + final VerificationResult result = verify( + api.authenticate(captureAny, any), + ); final AuthOptions options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sensitiveTransaction, true); @@ -256,21 +291,24 @@ void main() { }); test('passes provided non-default values', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); await plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - options: const AuthenticationOptions( - biometricOnly: true, - sensitiveTransaction: false, - stickyAuth: true, - useErrorDialogs: false, - )); - - final VerificationResult result = - verify(api.authenticate(captureAny, any)); + localizedReason: 'reason', + authMessages: [], + options: const AuthenticationOptions( + biometricOnly: true, + sensitiveTransaction: false, + stickyAuth: true, + useErrorDialogs: false, + ), + ); + + final VerificationResult result = verify( + api.authenticate(captureAny, any), + ); final AuthOptions options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sensitiveTransaction, false); @@ -281,131 +319,213 @@ void main() { group('return values', () { test('handles success', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.success); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.success); final bool result = await plugin.authenticate( - localizedReason: 'reason', authMessages: []); + localizedReason: 'reason', + authMessages: [], + ); expect(result, true); }); test('handles failure', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.failure); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.failure); final bool result = await plugin.authenticate( - localizedReason: 'reason', authMessages: []); + localizedReason: 'reason', + authMessages: [], + ); expect(result, false); }); - test('converts errorAlreadyInProgress to legacy PlatformException', - () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorAlreadyInProgress); + test( + 'converts errorAlreadyInProgress to legacy PlatformException', + () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorAlreadyInProgress); - expect( + expect( () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() - .having( - (PlatformException e) => e.code, 'code', 'auth_in_progress') - .having((PlatformException e) => e.message, 'message', - 'Authentication in progress'))); - }); + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() + .having( + (PlatformException e) => e.code, + 'code', + 'auth_in_progress', + ) + .having( + (PlatformException e) => e.message, + 'message', + 'Authentication in progress', + ), + ), + ); + }, + ); test('converts errorNoActivity to legacy PlatformException', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorNoActivity); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorNoActivity); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'no_activity') - .having((PlatformException e) => e.message, 'message', - 'local_auth plugin requires a foreground activity'))); + .having( + (PlatformException e) => e.message, + 'message', + 'local_auth plugin requires a foreground activity', + ), + ), + ); }); - test('converts errorNotFragmentActivity to legacy PlatformException', - () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorNotFragmentActivity); + test( + 'converts errorNotFragmentActivity to legacy PlatformException', + () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorNotFragmentActivity); - expect( + expect( () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() - .having((PlatformException e) => e.code, 'code', - 'no_fragment_activity') - .having((PlatformException e) => e.message, 'message', - 'local_auth plugin requires activity to be a FragmentActivity.'))); - }); + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() + .having( + (PlatformException e) => e.code, + 'code', + 'no_fragment_activity', + ) + .having( + (PlatformException e) => e.message, + 'message', + 'local_auth plugin requires activity to be a FragmentActivity.', + ), + ), + ); + }, + ); test('converts errorNotAvailable to legacy PlatformException', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorNotAvailable); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorNotAvailable); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'NotAvailable') - .having((PlatformException e) => e.message, 'message', - 'Security credentials not available.'))); + .having( + (PlatformException e) => e.message, + 'message', + 'Security credentials not available.', + ), + ), + ); }); test('converts errorNotEnrolled to legacy PlatformException', () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorNotEnrolled); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorNotEnrolled); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'NotEnrolled') - .having((PlatformException e) => e.message, 'message', - 'No Biometrics enrolled on this device.'))); + .having( + (PlatformException e) => e.message, + 'message', + 'No Biometrics enrolled on this device.', + ), + ), + ); }); - test('converts errorLockedOutTemporarily to legacy PlatformException', - () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorLockedOutTemporarily); + test( + 'converts errorLockedOutTemporarily to legacy PlatformException', + () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorLockedOutTemporarily); - expect( + expect( () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() - .having((PlatformException e) => e.code, 'code', 'LockedOut') - .having( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() + .having((PlatformException e) => e.code, 'code', 'LockedOut') + .having( (PlatformException e) => e.message, 'message', 'The operation was canceled because the API is locked out ' 'due to too many attempts. This occurs after 5 failed ' - 'attempts, and lasts for 30 seconds.'))); - }); - - test('converts errorLockedOutPermanently to legacy PlatformException', - () async { - when(api.authenticate(any, any)) - .thenAnswer((_) async => AuthResult.errorLockedOutPermanently); - - expect( + 'attempts, and lasts for 30 seconds.', + ), + ), + ); + }, + ); + + test( + 'converts errorLockedOutPermanently to legacy PlatformException', + () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult.errorLockedOutPermanently); + + expect( () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() - .having((PlatformException e) => e.code, 'code', - 'PermanentlyLockedOut') - .having( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() + .having( + (PlatformException e) => e.code, + 'code', + 'PermanentlyLockedOut', + ) + .having( (PlatformException e) => e.message, 'message', 'The operation was canceled because ERROR_LOCKOUT occurred ' 'too many times. Biometric authentication is disabled ' 'until the user unlocks with strong ' - 'authentication (PIN/Pattern/Password)'))); - }); + 'authentication (PIN/Pattern/Password)', + ), + ), + ); + }, + ); }); }); } diff --git a/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart b/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart index e09d0bda114..549cb242bcd 100644 --- a/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart +++ b/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart @@ -31,51 +31,49 @@ class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { } @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override - _i4.Future isDeviceSupported() => (super.noSuchMethod( - Invocation.method( - #isDeviceSupported, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); + _i4.Future isDeviceSupported() => + (super.noSuchMethod( + Invocation.method(#isDeviceSupported, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); @override - _i4.Future deviceCanSupportBiometrics() => (super.noSuchMethod( - Invocation.method( - #deviceCanSupportBiometrics, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); + _i4.Future deviceCanSupportBiometrics() => + (super.noSuchMethod( + Invocation.method(#deviceCanSupportBiometrics, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); @override - _i4.Future stopAuthentication() => (super.noSuchMethod( - Invocation.method( - #stopAuthentication, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); + _i4.Future stopAuthentication() => + (super.noSuchMethod( + Invocation.method(#stopAuthentication, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); @override _i4.Future> getEnrolledBiometrics() => (super.noSuchMethod( - Invocation.method( - #getEnrolledBiometrics, - [], - ), - returnValue: _i4.Future>.value( - <_i2.AuthClassification>[]), - ) as _i4.Future>); + Invocation.method(#getEnrolledBiometrics, []), + returnValue: _i4.Future>.value( + <_i2.AuthClassification>[], + ), + ) + as _i4.Future>); @override _i4.Future<_i2.AuthResult> authenticate( @@ -83,13 +81,10 @@ class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { _i2.AuthStrings? strings, ) => (super.noSuchMethod( - Invocation.method( - #authenticate, - [ - options, - strings, - ], - ), - returnValue: _i4.Future<_i2.AuthResult>.value(_i2.AuthResult.success), - ) as _i4.Future<_i2.AuthResult>); + Invocation.method(#authenticate, [options, strings]), + returnValue: _i4.Future<_i2.AuthResult>.value( + _i2.AuthResult.success, + ), + ) + as _i4.Future<_i2.AuthResult>); } diff --git a/packages/local_auth/local_auth_darwin/CHANGELOG.md b/packages/local_auth/local_auth_darwin/CHANGELOG.md index a98cdea5b17..382bd8e75f5 100644 --- a/packages/local_auth/local_auth_darwin/CHANGELOG.md +++ b/packages/local_auth/local_auth_darwin/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 1.6.0 * Provides more specific error codes on iOS for authentication failures. diff --git a/packages/local_auth/local_auth_darwin/example/integration_test/local_auth_test.dart b/packages/local_auth/local_auth_darwin/example/integration_test/local_auth_test.dart index ac9ba69bff7..a5496522da1 100644 --- a/packages/local_auth/local_auth_darwin/example/integration_test/local_auth_test.dart +++ b/packages/local_auth/local_auth_darwin/example/integration_test/local_auth_test.dart @@ -11,9 +11,6 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canCheckBiometrics', (WidgetTester tester) async { - expect( - LocalAuthDarwin().getEnrolledBiometrics(), - completion(isList), - ); + expect(LocalAuthDarwin().getEnrolledBiometrics(), completion(isList)); }); } diff --git a/packages/local_auth/local_auth_darwin/example/lib/main.dart b/packages/local_auth/local_auth_darwin/example/lib/main.dart index 9cb85a6984f..3ec0b5a604f 100644 --- a/packages/local_auth/local_auth_darwin/example/lib/main.dart +++ b/packages/local_auth/local_auth_darwin/example/lib/main.dart @@ -33,10 +33,14 @@ class _MyAppState extends State { void initState() { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( - (bool isSupported) => setState(() => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported), - ); + (bool isSupported) => setState( + () => + _supportState = + isSupported + ? _SupportState.supported + : _SupportState.unsupported, + ), + ); } Future _checkBiometrics() async { @@ -85,9 +89,7 @@ class _MyAppState extends State { authenticated = await LocalAuthPlatform.instance.authenticate( localizedReason: 'Let OS determine authentication method', authMessages: [const IOSAuthMessages()], - options: const AuthenticationOptions( - stickyAuth: true, - ), + options: const AuthenticationOptions(stickyAuth: true), ); setState(() { _isAuthenticating = false; @@ -105,7 +107,8 @@ class _MyAppState extends State { } setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); + () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', + ); } Future _authenticateWithBiometrics() async { @@ -155,9 +158,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), + appBar: AppBar(title: const Text('Plugin example app')), body: ListView( padding: const EdgeInsets.only(top: 30), children: [ @@ -213,9 +214,11 @@ class _MyAppState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text(_isAuthenticating - ? 'Cancel' - : 'Authenticate: biometrics only'), + Text( + _isAuthenticating + ? 'Cancel' + : 'Authenticate: biometrics only', + ), const Icon(Icons.fingerprint), ], ), @@ -231,8 +234,4 @@ class _MyAppState extends State { } } -enum _SupportState { - unknown, - supported, - unsupported, -} +enum _SupportState { unknown, supported, unsupported } diff --git a/packages/local_auth/local_auth_darwin/example/pubspec.yaml b/packages/local_auth/local_auth_darwin/example/pubspec.yaml index 82d04218afe..95c7f923b6b 100644 --- a/packages/local_auth/local_auth_darwin/example/pubspec.yaml +++ b/packages/local_auth/local_auth_darwin/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the local_auth_darwin plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart b/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart index a3be6ab5e26..a9c4e223b17 100644 --- a/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart +++ b/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart @@ -23,9 +23,8 @@ class LocalAuthDarwin extends LocalAuthPlatform { LocalAuthDarwin({ @visibleForTesting LocalAuthApi? api, @visibleForTesting bool? overrideUseMacOSAuthMessages, - }) : _api = api ?? LocalAuthApi(), - _useMacOSAuthMessages = - overrideUseMacOSAuthMessages ?? Platform.isMacOS; + }) : _api = api ?? LocalAuthApi(), + _useMacOSAuthMessages = overrideUseMacOSAuthMessages ?? Platform.isMacOS; /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { @@ -43,13 +42,15 @@ class LocalAuthDarwin extends LocalAuthPlatform { }) async { assert(localizedReason.isNotEmpty); final AuthResultDetails resultDetails = await _api.authenticate( - AuthOptions( - biometricOnly: options.biometricOnly, - sticky: options.stickyAuth, - useErrorDialogs: options.useErrorDialogs), - _useMacOSAuthMessages - ? _pigeonStringsFromMacOSAuthMessages(localizedReason, authMessages) - : _pigeonStringsFromiOSAuthMessages(localizedReason, authMessages)); + AuthOptions( + biometricOnly: options.biometricOnly, + sticky: options.stickyAuth, + useErrorDialogs: options.useErrorDialogs, + ), + _useMacOSAuthMessages + ? _pigeonStringsFromMacOSAuthMessages(localizedReason, authMessages) + : _pigeonStringsFromiOSAuthMessages(localizedReason, authMessages), + ); // TODO(stuartmorgan): Replace this with structured errors, coordinated // across all platform implementations, per // https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#platform-exception-handling @@ -62,34 +63,40 @@ class LocalAuthDarwin extends LocalAuthPlatform { return false; case AuthResult.errorNotAvailable: throw PlatformException( - code: 'NotAvailable', - message: resultDetails.errorMessage, - details: resultDetails.errorDetails); + code: 'NotAvailable', + message: resultDetails.errorMessage, + details: resultDetails.errorDetails, + ); case AuthResult.errorNotEnrolled: throw PlatformException( - code: 'NotEnrolled', - message: resultDetails.errorMessage, - details: resultDetails.errorDetails); + code: 'NotEnrolled', + message: resultDetails.errorMessage, + details: resultDetails.errorDetails, + ); case AuthResult.errorPasscodeNotSet: throw PlatformException( - code: 'PasscodeNotSet', - message: resultDetails.errorMessage, - details: resultDetails.errorDetails); + code: 'PasscodeNotSet', + message: resultDetails.errorMessage, + details: resultDetails.errorDetails, + ); case AuthResult.errorUserCancelled: throw PlatformException( - code: 'UserCancelled', - message: resultDetails.errorMessage, - details: resultDetails.errorDetails); + code: 'UserCancelled', + message: resultDetails.errorMessage, + details: resultDetails.errorDetails, + ); case AuthResult.errorBiometricNotAvailable: throw PlatformException( - code: 'BiometricNotAvailable', - message: resultDetails.errorMessage, - details: resultDetails.errorDetails); + code: 'BiometricNotAvailable', + message: resultDetails.errorMessage, + details: resultDetails.errorDetails, + ); case AuthResult.errorUserFallback: throw PlatformException( - code: 'UserFallback', - message: resultDetails.errorMessage, - details: resultDetails.errorDetails); + code: 'UserFallback', + message: resultDetails.errorMessage, + details: resultDetails.errorDetails, + ); } } @@ -119,7 +126,9 @@ class LocalAuthDarwin extends LocalAuthPlatform { Future stopAuthentication() async => false; AuthStrings _pigeonStringsFromiOSAuthMessages( - String localizedReason, Iterable messagesList) { + String localizedReason, + Iterable messagesList, + ) { IOSAuthMessages? messages; for (final AuthMessages entry in messagesList) { if (entry is IOSAuthMessages) { @@ -141,7 +150,9 @@ class LocalAuthDarwin extends LocalAuthPlatform { } AuthStrings _pigeonStringsFromMacOSAuthMessages( - String localizedReason, Iterable messagesList) { + String localizedReason, + Iterable messagesList, + ) { MacOSAuthMessages? messages; for (final AuthMessages entry in messagesList) { if (entry is MacOSAuthMessages) { diff --git a/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart b/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart index fa3a4987aeb..8b829b5e7bd 100644 --- a/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart +++ b/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart @@ -21,14 +21,17 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -61,10 +64,7 @@ enum AuthResult { } /// Pigeon equivalent of the subset of BiometricType used by iOS. -enum AuthBiometric { - face, - fingerprint, -} +enum AuthBiometric { face, fingerprint } /// Pigeon version of IOSAuthMessages, plus the authorization reason. /// @@ -149,11 +149,7 @@ class AuthOptions { bool useErrorDialogs; List _toList() { - return [ - biometricOnly, - sticky, - useErrorDialogs, - ]; + return [biometricOnly, sticky, useErrorDialogs]; } Object encode() { @@ -203,11 +199,7 @@ class AuthResultDetails { String? errorDetails; List _toList() { - return [ - result, - errorMessage, - errorDetails, - ]; + return [result, errorMessage, errorDetails]; } Object encode() { @@ -292,11 +284,12 @@ class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LocalAuthApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + LocalAuthApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -309,10 +302,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.isDeviceSupported$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -341,10 +334,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.deviceCanSupportBiometrics$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -373,10 +366,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.getEnrolledBiometrics$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -401,17 +394,20 @@ class LocalAuthApi { /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. Future authenticate( - AuthOptions options, AuthStrings strings) async { + AuthOptions options, + AuthStrings strings, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.authenticate$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [options, strings], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([options, strings]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart index e5173fc4ab4..2650d78713a 100644 --- a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart +++ b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart @@ -66,13 +66,13 @@ class IOSAuthMessages extends AuthMessages { @override int get hashCode => Object.hash( - super.hashCode, - lockOut, - goToSettingsButton, - goToSettingsDescription, - cancelButton, - localizedFallbackTitle, - ); + super.hashCode, + lockOut, + goToSettingsButton, + goToSettingsDescription, + cancelButton, + localizedFallbackTitle, + ); } // Default Strings for IOSAuthMessages plugin. Currently supports English. @@ -80,28 +80,36 @@ class IOSAuthMessages extends AuthMessages { /// Message shown on a button that the user can click to go to settings pages /// from the current dialog. -String get goToSettings => Intl.message('Go to settings', - desc: 'Message shown on a button that the user can click to go to ' - 'settings pages from the current dialog. Maximum 30 characters.'); +String get goToSettings => Intl.message( + 'Go to settings', + desc: + 'Message shown on a button that the user can click to go to ' + 'settings pages from the current dialog. Maximum 30 characters.', +); /// Message advising the user to re-enable biometrics on their device. /// It shows in a dialog on iOS. String get iOSLockOut => Intl.message( - 'Biometric authentication is disabled. Please lock and unlock your screen to ' - 'enable it.', - desc: 'Message advising the user to re-enable biometrics on their device.'); + 'Biometric authentication is disabled. Please lock and unlock your screen to ' + 'enable it.', + desc: 'Message advising the user to re-enable biometrics on their device.', +); /// Message advising the user to go to the settings and configure Biometrics /// for their device. String get iOSGoToSettingsDescription => Intl.message( - 'Biometric authentication is not set up on your device. Please either enable ' - 'Touch ID or Face ID on your phone.', - desc: - 'Message advising the user to go to the settings and configure Biometrics ' - 'for their device.'); + 'Biometric authentication is not set up on your device. Please either enable ' + 'Touch ID or Face ID on your phone.', + desc: + 'Message advising the user to go to the settings and configure Biometrics ' + 'for their device.', +); /// Message shown on a button that the user can click to leave the current /// dialog. -String get iOSOkButton => Intl.message('OK', - desc: 'Message showed on a button that the user can click to leave the ' - 'current dialog. Maximum 30 characters.'); +String get iOSOkButton => Intl.message( + 'OK', + desc: + 'Message showed on a button that the user can click to leave the ' + 'current dialog. Maximum 30 characters.', +); diff --git a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart index 16ce91a15bb..c4d6860cf5c 100644 --- a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart +++ b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart @@ -55,11 +55,11 @@ class MacOSAuthMessages extends AuthMessages { @override int get hashCode => Object.hash( - super.hashCode, - lockOut, - cancelButton, - localizedFallbackTitle, - ); + super.hashCode, + lockOut, + cancelButton, + localizedFallbackTitle, + ); } // Default Strings for MacOSAuthMessages plugin. Currently supports English. @@ -68,20 +68,25 @@ class MacOSAuthMessages extends AuthMessages { /// Message advising the user to re-enable biometrics on their device. /// It shows in a dialog on macOS. String get macOSLockOut => Intl.message( - 'Biometric authentication is disabled. Please restart your computer and try again.', - desc: 'Message advising the user to re-enable biometrics on their device.'); + 'Biometric authentication is disabled. Please restart your computer and try again.', + desc: 'Message advising the user to re-enable biometrics on their device.', +); /// Message advising the user to go to the settings and configure Biometrics /// for their device. String get macOSGoToSettingsDescription => Intl.message( - 'Biometric authentication is not set up on your device. Please enable ' - 'Touch ID on your computer in the Settings app.', - desc: - 'Message advising the user to go to the settings and configure Biometrics ' - 'for their device.'); + 'Biometric authentication is not set up on your device. Please enable ' + 'Touch ID on your computer in the Settings app.', + desc: + 'Message advising the user to go to the settings and configure Biometrics ' + 'for their device.', +); /// Message shown on a button that the user can click to leave the current /// dialog. -String get macOSCancelButton => Intl.message('OK', - desc: 'Message showed on a button that the user can click to leave the ' - 'current dialog. Maximum 30 characters.'); +String get macOSCancelButton => Intl.message( + 'OK', + desc: + 'Message showed on a button that the user can click to leave the ' + 'current dialog. Maximum 30 characters.', +); diff --git a/packages/local_auth/local_auth_darwin/pigeons/messages.dart b/packages/local_auth/local_auth_darwin/pigeons/messages.dart index 9c89bfd3682..5216c1dbe4d 100644 --- a/packages/local_auth/local_auth_darwin/pigeons/messages.dart +++ b/packages/local_auth/local_auth_darwin/pigeons/messages.dart @@ -4,13 +4,14 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - swiftOut: - 'darwin/local_auth_darwin/Sources/local_auth_darwin/messages.g.swift', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + swiftOut: + 'darwin/local_auth_darwin/Sources/local_auth_darwin/messages.g.swift', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Pigeon version of IOSAuthMessages, plus the authorization reason. /// /// See auth_messages_ios.dart for details. @@ -61,18 +62,22 @@ enum AuthResult { } class AuthOptions { - AuthOptions( - {required this.biometricOnly, - required this.sticky, - required this.useErrorDialogs}); + AuthOptions({ + required this.biometricOnly, + required this.sticky, + required this.useErrorDialogs, + }); final bool biometricOnly; final bool sticky; final bool useErrorDialogs; } class AuthResultDetails { - AuthResultDetails( - {required this.result, this.errorMessage, this.errorDetails}); + AuthResultDetails({ + required this.result, + this.errorMessage, + this.errorDetails, + }); /// The result of authenticating. final AuthResult result; diff --git a/packages/local_auth/local_auth_darwin/pubspec.yaml b/packages/local_auth/local_auth_darwin/pubspec.yaml index 3c00fc879ab..a0596f945cd 100644 --- a/packages/local_auth/local_auth_darwin/pubspec.yaml +++ b/packages/local_auth/local_auth_darwin/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.6.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart index 5ab2dac7aad..344de548922 100644 --- a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart +++ b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart @@ -60,10 +60,12 @@ void main() { group('getEnrolledBiometrics', () { test('translates values', () async { - when(api.getEnrolledBiometrics()).thenAnswer((_) async => [ - AuthBiometric.face, - AuthBiometric.fingerprint, - ]); + when(api.getEnrolledBiometrics()).thenAnswer( + (_) async => [ + AuthBiometric.face, + AuthBiometric.fingerprint, + ], + ); final List result = await plugin.getEnrolledBiometrics(); @@ -74,8 +76,9 @@ void main() { }); test('handles empty', () async { - when(api.getEnrolledBiometrics()) - .thenAnswer((_) async => []); + when( + api.getEnrolledBiometrics(), + ).thenAnswer((_) async => []); final List result = await plugin.getEnrolledBiometrics(); @@ -89,14 +92,18 @@ void main() { plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + (_) async => AuthResultDetails(result: AuthResult.success), + ); const String reason = 'test reason'; await plugin.authenticate( - localizedReason: reason, authMessages: []); + localizedReason: reason, + authMessages: [], + ); - final VerificationResult result = - verify(api.authenticate(any, captureAny)); + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from @@ -108,64 +115,82 @@ void main() { expect(strings.localizedFallbackTitle, null); }); - test('passes default values when only other platform values are provided', - () async { - plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); + test( + 'passes default values when only other platform values are provided', + () async { + plugin = LocalAuthDarwin( + api: api, + overrideUseMacOSAuthMessages: false, + ); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails(result: AuthResult.success), + ); - const String reason = 'test reason'; - await plugin.authenticate( + const String reason = 'test reason'; + await plugin.authenticate( localizedReason: reason, - authMessages: [AnotherPlatformAuthMessages()]); + authMessages: [AnotherPlatformAuthMessages()], + ); - final VerificationResult result = - verify(api.authenticate(any, captureAny)); - final AuthStrings strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - // These should all be the default values from - // auth_messages_ios.dart - expect(strings.lockOut, iOSLockOut); - expect(strings.goToSettingsButton, goToSettings); - expect(strings.goToSettingsDescription, iOSGoToSettingsDescription); - expect(strings.cancelButton, iOSOkButton); - expect(strings.localizedFallbackTitle, null); - }); + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); + final AuthStrings strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + // These should all be the default values from + // auth_messages_ios.dart + expect(strings.lockOut, iOSLockOut); + expect(strings.goToSettingsButton, goToSettings); + expect(strings.goToSettingsDescription, iOSGoToSettingsDescription); + expect(strings.cancelButton, iOSOkButton); + expect(strings.localizedFallbackTitle, null); + }, + ); test( - 'passes default values when only MacOSAuthMessages platform values are provided', - () async { - plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: true); + 'passes default values when only MacOSAuthMessages platform values are provided', + () async { + plugin = LocalAuthDarwin( + api: api, + overrideUseMacOSAuthMessages: true, + ); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails(result: AuthResult.success), + ); - const String reason = 'test reason'; - await plugin.authenticate( + const String reason = 'test reason'; + await plugin.authenticate( localizedReason: reason, - authMessages: [const MacOSAuthMessages()]); + authMessages: [const MacOSAuthMessages()], + ); - final VerificationResult result = - verify(api.authenticate(any, captureAny)); - final AuthStrings strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - // These should all be the default values from - // auth_messages_ios.dart - expect(strings.lockOut, macOSLockOut); - expect(strings.goToSettingsDescription, macOSGoToSettingsDescription); - expect(strings.cancelButton, macOSCancelButton); - expect(strings.localizedFallbackTitle, null); - }); + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); + final AuthStrings strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + // These should all be the default values from + // auth_messages_ios.dart + expect(strings.lockOut, macOSLockOut); + expect(strings.goToSettingsDescription, macOSGoToSettingsDescription); + expect(strings.cancelButton, macOSCancelButton); + expect(strings.localizedFallbackTitle, null); + }, + ); test( 'passes all non-default values correctly with IOSAuthMessages', () async { - plugin = - LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); + plugin = LocalAuthDarwin( + api: api, + overrideUseMacOSAuthMessages: false, + ); when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + (_) async => AuthResultDetails(result: AuthResult.success), + ); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and @@ -178,20 +203,22 @@ void main() { const String localizedFallbackTitle = 'F'; await plugin.authenticate( - localizedReason: reason, - authMessages: [ - const IOSAuthMessages( - lockOut: lockOut, - goToSettingsButton: goToSettingsButton, - goToSettingsDescription: gotToSettingsDescription, - cancelButton: cancel, - localizedFallbackTitle: localizedFallbackTitle, - ), - AnotherPlatformAuthMessages(), - ]); - - final VerificationResult result = - verify(api.authenticate(any, captureAny)); + localizedReason: reason, + authMessages: [ + const IOSAuthMessages( + lockOut: lockOut, + goToSettingsButton: goToSettingsButton, + goToSettingsDescription: gotToSettingsDescription, + cancelButton: cancel, + localizedFallbackTitle: localizedFallbackTitle, + ), + AnotherPlatformAuthMessages(), + ], + ); + + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.lockOut, lockOut); @@ -202,43 +229,53 @@ void main() { }, ); - test('passes all non-default values correctly with MacOSAuthMessages', - () async { - plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: true); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); - - // These are arbitrary values; all that matters is that: - // - they are different from the defaults, and - // - they are different from each other. - const String reason = 'A'; - const String lockOut = 'B'; - const String cancel = 'E'; - const String localizedFallbackTitle = 'F'; - await plugin - .authenticate(localizedReason: reason, authMessages: [ - const MacOSAuthMessages( - lockOut: lockOut, - cancelButton: cancel, - localizedFallbackTitle: localizedFallbackTitle, - ), - AnotherPlatformAuthMessages(), - ]); + test( + 'passes all non-default values correctly with MacOSAuthMessages', + () async { + plugin = LocalAuthDarwin( + api: api, + overrideUseMacOSAuthMessages: true, + ); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails(result: AuthResult.success), + ); - final VerificationResult result = - verify(api.authenticate(any, captureAny)); - final AuthStrings strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - expect(strings.lockOut, lockOut); - expect(strings.cancelButton, cancel); - expect(strings.localizedFallbackTitle, localizedFallbackTitle); - }); + // These are arbitrary values; all that matters is that: + // - they are different from the defaults, and + // - they are different from each other. + const String reason = 'A'; + const String lockOut = 'B'; + const String cancel = 'E'; + const String localizedFallbackTitle = 'F'; + await plugin.authenticate( + localizedReason: reason, + authMessages: [ + const MacOSAuthMessages( + lockOut: lockOut, + cancelButton: cancel, + localizedFallbackTitle: localizedFallbackTitle, + ), + AnotherPlatformAuthMessages(), + ], + ); + + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); + final AuthStrings strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + expect(strings.lockOut, lockOut); + expect(strings.cancelButton, cancel); + expect(strings.localizedFallbackTitle, localizedFallbackTitle); + }, + ); test('passes provided messages with default fallbacks', () async { plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + (_) async => AuthResultDetails(result: AuthResult.success), + ); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and @@ -247,17 +284,20 @@ void main() { const String lockOut = 'B'; const String localizedFallbackTitle = 'C'; const String cancel = 'D'; - await plugin - .authenticate(localizedReason: reason, authMessages: [ - const IOSAuthMessages( - lockOut: lockOut, - localizedFallbackTitle: localizedFallbackTitle, - cancelButton: cancel, - ), - ]); - - final VerificationResult result = - verify(api.authenticate(any, captureAny)); + await plugin.authenticate( + localizedReason: reason, + authMessages: [ + const IOSAuthMessages( + lockOut: lockOut, + localizedFallbackTitle: localizedFallbackTitle, + cancelButton: cancel, + ), + ], + ); + + final VerificationResult result = verify( + api.authenticate(any, captureAny), + ); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the provided values. @@ -276,13 +316,17 @@ void main() { plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + (_) async => AuthResultDetails(result: AuthResult.success), + ); await plugin.authenticate( - localizedReason: 'reason', authMessages: []); + localizedReason: 'reason', + authMessages: [], + ); - final VerificationResult result = - verify(api.authenticate(captureAny, any)); + final VerificationResult result = verify( + api.authenticate(captureAny, any), + ); final AuthOptions options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sticky, false); @@ -291,19 +335,22 @@ void main() { test('passes provided non-default values', () async { when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + (_) async => AuthResultDetails(result: AuthResult.success), + ); await plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - options: const AuthenticationOptions( - biometricOnly: true, - stickyAuth: true, - useErrorDialogs: false, - )); - - final VerificationResult result = - verify(api.authenticate(captureAny, any)); + localizedReason: 'reason', + authMessages: [], + options: const AuthenticationOptions( + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: false, + ), + ); + + final VerificationResult result = verify( + api.authenticate(captureAny, any), + ); final AuthOptions options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sticky, true); @@ -314,20 +361,26 @@ void main() { group('return values', () { test('handles success', () async { when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success)); + (_) async => AuthResultDetails(result: AuthResult.success), + ); final bool result = await plugin.authenticate( - localizedReason: 'reason', authMessages: []); + localizedReason: 'reason', + authMessages: [], + ); expect(result, true); }); test('handles failure', () async { when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.failure)); + (_) async => AuthResultDetails(result: AuthResult.failure), + ); final bool result = await plugin.authenticate( - localizedReason: 'reason', authMessages: []); + localizedReason: 'reason', + authMessages: [], + ); expect(result, false); }); @@ -335,129 +388,217 @@ void main() { test('converts errorNotAvailable to legacy PlatformException', () async { const String errorMessage = 'a message'; const String errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer((_) async => - AuthResultDetails( - result: AuthResult.errorNotAvailable, - errorMessage: errorMessage, - errorDetails: errorDetails)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.errorNotAvailable, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'NotAvailable') .having( - (PlatformException e) => e.message, 'message', errorMessage) - .having((PlatformException e) => e.details, 'details', - errorDetails))); + (PlatformException e) => e.message, + 'message', + errorMessage, + ) + .having( + (PlatformException e) => e.details, + 'details', + errorDetails, + ), + ), + ); }); test('converts errorNotEnrolled to legacy PlatformException', () async { const String errorMessage = 'a message'; const String errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer((_) async => - AuthResultDetails( - result: AuthResult.errorNotEnrolled, - errorMessage: errorMessage, - errorDetails: errorDetails)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.errorNotEnrolled, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'NotEnrolled') .having( - (PlatformException e) => e.message, 'message', errorMessage) - .having((PlatformException e) => e.details, 'details', - errorDetails))); + (PlatformException e) => e.message, + 'message', + errorMessage, + ) + .having( + (PlatformException e) => e.details, + 'details', + errorDetails, + ), + ), + ); }); test('converts errorUserCancelled to PlatformException', () async { const String errorMessage = 'The user cancelled authentication.'; const String errorDetails = 'com.apple.LocalAuthentication'; - when(api.authenticate(any, any)).thenAnswer((_) async => - AuthResultDetails( - result: AuthResult.errorUserCancelled, - errorMessage: errorMessage, - errorDetails: errorDetails)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.errorUserCancelled, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() + .having( + (PlatformException e) => e.code, + 'code', + 'UserCancelled', + ) .having( - (PlatformException e) => e.code, 'code', 'UserCancelled') + (PlatformException e) => e.message, + 'message', + errorMessage, + ) .having( - (PlatformException e) => e.message, 'message', errorMessage) - .having((PlatformException e) => e.details, 'details', - errorDetails))); + (PlatformException e) => e.details, + 'details', + errorDetails, + ), + ), + ); }); test('converts errorUserFallback to PlatformException', () async { const String errorMessage = 'The user chose to use the fallback.'; const String errorDetails = 'com.apple.LocalAuthentication'; - when(api.authenticate(any, any)).thenAnswer((_) async => - AuthResultDetails( - result: AuthResult.errorUserFallback, - errorMessage: errorMessage, - errorDetails: errorDetails)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.errorUserFallback, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'UserFallback') .having( - (PlatformException e) => e.message, 'message', errorMessage) - .having((PlatformException e) => e.details, 'details', - errorDetails))); + (PlatformException e) => e.message, + 'message', + errorMessage, + ) + .having( + (PlatformException e) => e.details, + 'details', + errorDetails, + ), + ), + ); }); - test('converts errorBiometricNotAvailable to PlatformException', - () async { + test('converts errorBiometricNotAvailable to PlatformException', () async { const String errorMessage = 'Biometrics are not available on this device.'; const String errorDetails = 'com.apple.LocalAuthentication'; - when(api.authenticate(any, any)).thenAnswer((_) async => - AuthResultDetails( - result: AuthResult.errorBiometricNotAvailable, - errorMessage: errorMessage, - errorDetails: errorDetails)); + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.errorBiometricNotAvailable, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() // The code here should match what you defined in your Dart switch statement. - .having((PlatformException e) => e.code, 'code', - 'BiometricNotAvailable') .having( - (PlatformException e) => e.message, 'message', errorMessage) - .having((PlatformException e) => e.details, 'details', - errorDetails))); - }); - - test('converts errorPasscodeNotSet to legacy PlatformException', - () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer((_) async => - AuthResultDetails( - result: AuthResult.errorPasscodeNotSet, - errorMessage: errorMessage, - errorDetails: errorDetails)); - - expect( - () async => plugin.authenticate( - localizedReason: 'reason', authMessages: []), - throwsA(isA() + (PlatformException e) => e.code, + 'code', + 'BiometricNotAvailable', + ) .having( - (PlatformException e) => e.code, 'code', 'PasscodeNotSet') + (PlatformException e) => e.message, + 'message', + errorMessage, + ) .having( - (PlatformException e) => e.message, 'message', errorMessage) - .having((PlatformException e) => e.details, 'details', - errorDetails))); + (PlatformException e) => e.details, + 'details', + errorDetails, + ), + ), + ); }); + + test( + 'converts errorPasscodeNotSet to legacy PlatformException', + () async { + const String errorMessage = 'a message'; + const String errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.errorPasscodeNotSet, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); + + expect( + () async => plugin.authenticate( + localizedReason: 'reason', + authMessages: [], + ), + throwsA( + isA() + .having( + (PlatformException e) => e.code, + 'code', + 'PasscodeNotSet', + ) + .having( + (PlatformException e) => e.message, + 'message', + errorMessage, + ) + .having( + (PlatformException e) => e.details, + 'details', + errorDetails, + ), + ), + ); + }, + ); }); }); } diff --git a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart index befeb1bbbfc..ffa5c074a44 100644 --- a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart +++ b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart @@ -24,13 +24,8 @@ import 'package:mockito/src/dummies.dart' as _i3; class _FakeAuthResultDetails_0 extends _i1.SmartFake implements _i2.AuthResultDetails { - _FakeAuthResultDetails_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthResultDetails_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [LocalAuthApi]. @@ -42,42 +37,41 @@ class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { } @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override - _i4.Future isDeviceSupported() => (super.noSuchMethod( - Invocation.method( - #isDeviceSupported, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); + _i4.Future isDeviceSupported() => + (super.noSuchMethod( + Invocation.method(#isDeviceSupported, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); @override - _i4.Future deviceCanSupportBiometrics() => (super.noSuchMethod( - Invocation.method( - #deviceCanSupportBiometrics, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); + _i4.Future deviceCanSupportBiometrics() => + (super.noSuchMethod( + Invocation.method(#deviceCanSupportBiometrics, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); @override _i4.Future> getEnrolledBiometrics() => (super.noSuchMethod( - Invocation.method( - #getEnrolledBiometrics, - [], - ), - returnValue: - _i4.Future>.value(<_i2.AuthBiometric>[]), - ) as _i4.Future>); + Invocation.method(#getEnrolledBiometrics, []), + returnValue: _i4.Future>.value( + <_i2.AuthBiometric>[], + ), + ) + as _i4.Future>); @override _i4.Future<_i2.AuthResultDetails> authenticate( @@ -85,23 +79,13 @@ class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { _i2.AuthStrings? strings, ) => (super.noSuchMethod( - Invocation.method( - #authenticate, - [ - options, - strings, - ], - ), - returnValue: - _i4.Future<_i2.AuthResultDetails>.value(_FakeAuthResultDetails_0( - this, - Invocation.method( - #authenticate, - [ - options, - strings, - ], - ), - )), - ) as _i4.Future<_i2.AuthResultDetails>); + Invocation.method(#authenticate, [options, strings]), + returnValue: _i4.Future<_i2.AuthResultDetails>.value( + _FakeAuthResultDetails_0( + this, + Invocation.method(#authenticate, [options, strings]), + ), + ), + ) + as _i4.Future<_i2.AuthResultDetails>); } diff --git a/packages/local_auth/local_auth_platform_interface/CHANGELOG.md b/packages/local_auth/local_auth_platform_interface/CHANGELOG.md index 028f3fd4520..9391da4be9f 100644 --- a/packages/local_auth/local_auth_platform_interface/CHANGELOG.md +++ b/packages/local_auth/local_auth_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 1.0.10 diff --git a/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart b/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart index f40bc7914ba..67f3f2e040e 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart @@ -37,9 +37,8 @@ class DefaultLocalAuthPlatform extends LocalAuthPlatform { @override Future> getEnrolledBiometrics() async { - final List result = (await _channel.invokeListMethod( - 'getAvailableBiometrics', - )) ?? + final List result = + (await _channel.invokeListMethod('getAvailableBiometrics')) ?? []; final List biometrics = []; for (final String value in result) { @@ -62,10 +61,8 @@ class DefaultLocalAuthPlatform extends LocalAuthPlatform { @override Future deviceSupportsBiometrics() async { final List availableBiometrics = - (await _channel.invokeListMethod( - 'getAvailableBiometrics', - )) ?? - []; + (await _channel.invokeListMethod('getAvailableBiometrics')) ?? + []; // If anything, including the 'undefined' sentinel, is returned, then there // is device support for biometrics. return availableBiometrics.isNotEmpty; diff --git a/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart b/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart index 4c6d58238ed..ec400ddafa3 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart @@ -80,7 +80,8 @@ abstract class LocalAuthPlatform extends PlatformInterface { /// - BiometricType.weak Future> getEnrolledBiometrics() async { throw UnimplementedError( - 'getAvailableBiometrics() has not been implemented.'); + 'getAvailableBiometrics() has not been implemented.', + ); } /// Returns true if device is capable of checking biometrics or is able to diff --git a/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart b/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart index a5af8e73a64..b2cc9c13a69 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart @@ -53,9 +53,9 @@ class AuthenticationOptions { @override int get hashCode => Object.hash( - useErrorDialogs, - stickyAuth, - sensitiveTransaction, - biometricOnly, - ); + useErrorDialogs, + stickyAuth, + sensitiveTransaction, + biometricOnly, + ); } diff --git a/packages/local_auth/local_auth_platform_interface/pubspec.yaml b/packages/local_auth/local_auth_platform_interface/pubspec.yaml index cbe54da5f98..4b19c7d05e0 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.0.10 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 f8c96adc370..af249ce151d 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 @@ -10,9 +10,7 @@ import 'package:local_auth_platform_interface/local_auth_platform_interface.dart void main() { TestWidgetsFlutterBinding.ensureInitialized(); - const MethodChannel channel = MethodChannel( - 'plugins.flutter.io/local_auth', - ); + const MethodChannel channel = MethodChannel('plugins.flutter.io/local_auth'); late List log; late LocalAuthPlatform localAuthentication; @@ -22,26 +20,26 @@ void main() { }); test( - 'DefaultLocalAuthPlatform is registered as the default platform implementation', - () async { - expect(LocalAuthPlatform.instance, - const TypeMatcher()); - }); + 'DefaultLocalAuthPlatform is registered as the default platform implementation', + () async { + expect( + LocalAuthPlatform.instance, + const TypeMatcher(), + ); + }, + ); test('getAvailableBiometrics', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall); - return Future.value([]); - }); + log.add(methodCall); + return Future.value([]); + }); localAuthentication = DefaultLocalAuthPlatform(); await localAuthentication.getEnrolledBiometrics(); - expect( - log, - [ - isMethodCall('getAvailableBiometrics', arguments: null), - ], - ); + expect(log, [ + isMethodCall('getAvailableBiometrics', arguments: null), + ]); }); test('deviceSupportsBiometrics handles special sentinal value', () async { @@ -52,50 +50,41 @@ void main() { // enrolled, but that the hardware does support biometrics. TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall); - return Future.value(['undefined']); - }); + log.add(methodCall); + return Future.value(['undefined']); + }); localAuthentication = DefaultLocalAuthPlatform(); final bool supportsBiometrics = await localAuthentication.deviceSupportsBiometrics(); expect(supportsBiometrics, true); - expect( - log, - [ - isMethodCall('getAvailableBiometrics', arguments: null), - ], - ); + expect(log, [ + isMethodCall('getAvailableBiometrics', arguments: null), + ]); }); group('Boolean returning methods', () { setUp(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall); - return Future.value(true); - }); + log.add(methodCall); + return Future.value(true); + }); localAuthentication = DefaultLocalAuthPlatform(); }); test('isDeviceSupported', () async { await localAuthentication.isDeviceSupported(); - expect( - log, - [ - isMethodCall('isDeviceSupported', arguments: null), - ], - ); + expect(log, [ + isMethodCall('isDeviceSupported', arguments: null), + ]); }); test('stopAuthentication', () async { await localAuthentication.stopAuthentication(); - expect( - log, - [ - isMethodCall('stopAuthentication', arguments: null), - ], - ); + expect(log, [ + isMethodCall('stopAuthentication', arguments: null), + ]); }); group('authenticate with device auth fail over', () { @@ -105,21 +94,18 @@ void main() { localizedReason: 'Needs secure', options: const AuthenticationOptions(biometricOnly: true), ); - expect( - log, - [ - isMethodCall( - 'authenticate', - arguments: { - 'localizedReason': 'Needs secure', - 'useErrorDialogs': true, - 'stickyAuth': false, - 'sensitiveTransaction': true, - 'biometricOnly': true, - }, - ), - ], - ); + expect(log, [ + isMethodCall( + 'authenticate', + arguments: { + 'localizedReason': 'Needs secure', + 'useErrorDialogs': true, + 'stickyAuth': false, + 'sensitiveTransaction': true, + 'biometricOnly': true, + }, + ), + ]); }); test('authenticate with no sensitive transaction.', () async { @@ -132,21 +118,18 @@ void main() { biometricOnly: true, ), ); - expect( - log, - [ - isMethodCall( - 'authenticate', - arguments: { - 'localizedReason': 'Insecure', - 'useErrorDialogs': false, - 'stickyAuth': false, - 'sensitiveTransaction': false, - 'biometricOnly': true, - }, - ), - ], - ); + expect(log, [ + isMethodCall( + 'authenticate', + arguments: { + 'localizedReason': 'Insecure', + 'useErrorDialogs': false, + 'stickyAuth': false, + 'sensitiveTransaction': false, + 'biometricOnly': true, + }, + ), + ]); }); }); @@ -156,21 +139,18 @@ void main() { authMessages: [], localizedReason: 'Needs secure', ); - expect( - log, - [ - isMethodCall( - 'authenticate', - arguments: { - 'localizedReason': 'Needs secure', - 'useErrorDialogs': true, - 'stickyAuth': false, - 'sensitiveTransaction': true, - 'biometricOnly': false, - }, - ), - ], - ); + expect(log, [ + isMethodCall( + 'authenticate', + arguments: { + 'localizedReason': 'Needs secure', + 'useErrorDialogs': true, + 'stickyAuth': false, + 'sensitiveTransaction': true, + 'biometricOnly': false, + }, + ), + ]); }); test('authenticate with no sensitive transaction.', () async { @@ -182,21 +162,18 @@ void main() { useErrorDialogs: false, ), ); - expect( - log, - [ - isMethodCall( - 'authenticate', - arguments: { - 'localizedReason': 'Insecure', - 'useErrorDialogs': false, - 'stickyAuth': false, - 'sensitiveTransaction': false, - 'biometricOnly': false, - }, - ), - ], - ); + expect(log, [ + isMethodCall( + 'authenticate', + arguments: { + 'localizedReason': 'Insecure', + 'useErrorDialogs': false, + 'stickyAuth': false, + 'sensitiveTransaction': false, + 'biometricOnly': false, + }, + ), + ]); }); }); }); diff --git a/packages/local_auth/local_auth_windows/CHANGELOG.md b/packages/local_auth/local_auth_windows/CHANGELOG.md index cd007ecc686..cab0a630bc7 100644 --- a/packages/local_auth/local_auth_windows/CHANGELOG.md +++ b/packages/local_auth/local_auth_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 1.0.11 diff --git a/packages/local_auth/local_auth_windows/example/integration_test/local_auth_test.dart b/packages/local_auth/local_auth_windows/example/integration_test/local_auth_test.dart index cedaaf28ff2..67a213b5111 100644 --- a/packages/local_auth/local_auth_windows/example/integration_test/local_auth_test.dart +++ b/packages/local_auth/local_auth_windows/example/integration_test/local_auth_test.dart @@ -11,9 +11,6 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canCheckBiometrics', (WidgetTester tester) async { - expect( - LocalAuthWindows().getEnrolledBiometrics(), - completion(isList), - ); + expect(LocalAuthWindows().getEnrolledBiometrics(), completion(isList)); }); } 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 3f4ee19d686..b8f9e119e02 100644 --- a/packages/local_auth/local_auth_windows/example/lib/main.dart +++ b/packages/local_auth/local_auth_windows/example/lib/main.dart @@ -33,10 +33,14 @@ class _MyAppState extends State { void initState() { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( - (bool isSupported) => setState(() => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported), - ); + (bool isSupported) => setState( + () => + _supportState = + isSupported + ? _SupportState.supported + : _SupportState.unsupported, + ), + ); } Future _checkBiometrics() async { @@ -85,9 +89,7 @@ class _MyAppState extends State { authenticated = await LocalAuthPlatform.instance.authenticate( localizedReason: 'Let OS determine authentication method', authMessages: [const WindowsAuthMessages()], - options: const AuthenticationOptions( - stickyAuth: true, - ), + options: const AuthenticationOptions(stickyAuth: true), ); setState(() { _isAuthenticating = false; @@ -105,7 +107,8 @@ class _MyAppState extends State { } setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); + () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', + ); } Future _cancelAuthentication() async { @@ -117,9 +120,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), + appBar: AppBar(title: const Text('Plugin example app')), body: ListView( padding: const EdgeInsets.only(top: 30), children: [ @@ -134,7 +135,8 @@ class _MyAppState extends State { const Text('This device is not supported'), const Divider(height: 100), Text( - 'Device supports biometrics: $_deviceSupportsBiometrics\n'), + 'Device supports biometrics: $_deviceSupportsBiometrics\n', + ), ElevatedButton( onPressed: _checkBiometrics, child: const Text('Check biometrics'), @@ -182,8 +184,4 @@ class _MyAppState extends State { } } -enum _SupportState { - unknown, - supported, - unsupported, -} +enum _SupportState { unknown, supported, unsupported } diff --git a/packages/local_auth/local_auth_windows/example/pubspec.yaml b/packages/local_auth/local_auth_windows/example/pubspec.yaml index ac702b8a0d1..bef084fb595 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 9f918aab058..de19b1548c4 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 @@ -15,9 +15,8 @@ export 'package:local_auth_windows/types/auth_messages_windows.dart'; /// The implementation of [LocalAuthPlatform] for Windows. class LocalAuthWindows extends LocalAuthPlatform { /// Creates a new plugin implementation instance. - LocalAuthWindows({ - @visibleForTesting LocalAuthApi? api, - }) : _api = api ?? LocalAuthApi(); + LocalAuthWindows({@visibleForTesting LocalAuthApi? api}) + : _api = api ?? LocalAuthApi(); final LocalAuthApi _api; @@ -36,7 +35,8 @@ class LocalAuthWindows extends LocalAuthPlatform { if (options.biometricOnly) { throw UnsupportedError( - "Windows doesn't support the biometricOnly parameter."); + "Windows doesn't support the biometricOnly parameter.", + ); } return _api.authenticate(localizedReason); 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 e1c45ef20c5..1b511f686fb 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 @@ -26,11 +26,12 @@ class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LocalAuthApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : __pigeon_binaryMessenger = binaryMessenger, - __pigeon_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + LocalAuthApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : __pigeon_binaryMessenger = binaryMessenger, + __pigeon_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -43,10 +44,10 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_windows.LocalAuthApi.isDeviceSupported$__pigeon_messageChannelSuffix'; final BasicMessageChannel __pigeon_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); + __pigeon_channelName, + pigeonChannelCodec, + binaryMessenger: __pigeon_binaryMessenger, + ); final List? __pigeon_replyList = await __pigeon_channel.send(null) as List?; if (__pigeon_replyList == null) { @@ -77,12 +78,13 @@ class LocalAuthApi { 'dev.flutter.pigeon.local_auth_windows.LocalAuthApi.authenticate$__pigeon_messageChannelSuffix'; final BasicMessageChannel __pigeon_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); - final List? __pigeon_replyList = await __pigeon_channel - .send([localizedReason]) as List?; + __pigeon_channelName, + pigeonChannelCodec, + binaryMessenger: __pigeon_binaryMessenger, + ); + final List? __pigeon_replyList = + await __pigeon_channel.send([localizedReason]) + as List?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { diff --git a/packages/local_auth/local_auth_windows/pigeons/messages.dart b/packages/local_auth/local_auth_windows/pigeons/messages.dart index 683becdd61f..d3ac41192dc 100644 --- a/packages/local_auth/local_auth_windows/pigeons/messages.dart +++ b/packages/local_auth/local_auth_windows/pigeons/messages.dart @@ -4,13 +4,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - cppOptions: CppOptions(namespace: 'local_auth_windows'), - cppHeaderOut: 'windows/messages.g.h', - cppSourceOut: 'windows/messages.g.cpp', - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + cppOptions: CppOptions(namespace: 'local_auth_windows'), + cppHeaderOut: 'windows/messages.g.h', + cppSourceOut: 'windows/messages.g.cpp', + copyrightHeader: 'pigeons/copyright.txt', + ), +) @HostApi() abstract class LocalAuthApi { /// Returns true if this device supports authentication. diff --git a/packages/local_auth/local_auth_windows/pubspec.yaml b/packages/local_auth/local_auth_windows/pubspec.yaml index 2abac37a7e2..6401846b5b0 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: 1.0.11 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/local_auth/local_auth_windows/test/local_auth_test.dart b/packages/local_auth/local_auth_windows/test/local_auth_test.dart index 917e7b1784b..80bc78576c7 100644 --- a/packages/local_auth/local_auth_windows/test/local_auth_test.dart +++ b/packages/local_auth/local_auth_windows/test/local_auth_test.dart @@ -20,8 +20,9 @@ void main() { api.returnValue = true; final bool result = await plugin.authenticate( - authMessages: [const WindowsAuthMessages()], - localizedReason: 'My localized reason'); + authMessages: [const WindowsAuthMessages()], + localizedReason: 'My localized reason', + ); expect(result, true); expect(api.passedReason, 'My localized reason'); @@ -31,8 +32,9 @@ void main() { api.returnValue = false; final bool result = await plugin.authenticate( - authMessages: [const WindowsAuthMessages()], - localizedReason: 'My localized reason'); + authMessages: [const WindowsAuthMessages()], + localizedReason: 'My localized reason', + ); expect(result, false); expect(api.passedReason, 'My localized reason'); @@ -40,11 +42,13 @@ void main() { test('authenticate throws for biometricOnly', () async { expect( - plugin.authenticate( - authMessages: [const WindowsAuthMessages()], - localizedReason: 'My localized reason', - options: const AuthenticationOptions(biometricOnly: true)), - throwsA(isUnsupportedError)); + plugin.authenticate( + authMessages: [const WindowsAuthMessages()], + localizedReason: 'My localized reason', + options: const AuthenticationOptions(biometricOnly: true), + ), + throwsA(isUnsupportedError), + ); }); test('isDeviceSupported handles supported', () async { @@ -79,14 +83,19 @@ void main() { expect(result, false); }); - test('getEnrolledBiometrics returns expected values when supported', - () async { - api.returnValue = true; + test( + 'getEnrolledBiometrics returns expected values when supported', + () async { + api.returnValue = true; - final List result = await plugin.getEnrolledBiometrics(); + final List result = await plugin.getEnrolledBiometrics(); - expect(result, [BiometricType.weak, BiometricType.strong]); - }); + expect(result, [ + BiometricType.weak, + BiometricType.strong, + ]); + }, + ); test('getEnrolledBiometrics returns nothing when unsupported', () async { api.returnValue = false; diff --git a/packages/metrics_center/CHANGELOG.md b/packages/metrics_center/CHANGELOG.md index cc10e733dad..a06e9300afa 100644 --- a/packages/metrics_center/CHANGELOG.md +++ b/packages/metrics_center/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 1.0.14 * Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. diff --git a/packages/metrics_center/lib/src/common.dart b/packages/metrics_center/lib/src/common.dart index 249c57f1fb5..114dfa72e5d 100644 --- a/packages/metrics_center/lib/src/common.dart +++ b/packages/metrics_center/lib/src/common.dart @@ -12,10 +12,8 @@ import 'package:http/http.dart'; /// Common format of a metric data point. class MetricPoint { /// Creates a new data point. - MetricPoint( - this.value, - Map tags, - ) : _tags = SplayTreeMap.from(tags); + MetricPoint(this.value, Map tags) + : _tags = SplayTreeMap.from(tags); /// Can store integer values. final double? value; @@ -44,16 +42,25 @@ class MetricPoint { abstract class MetricDestination { /// Insert new data points or modify old ones with matching id. Future update( - List points, DateTime commitTime, String taskName); + List points, + DateTime commitTime, + String taskName, + ); } /// Create `AuthClient` in case we only have an access token without the full /// credentials json. It's currently the case for Chrmoium LUCI bots. AuthClient authClientFromAccessToken(String token, List scopes) { final DateTime anHourLater = DateTime.now().add(const Duration(hours: 1)); - final AccessToken accessToken = - AccessToken('Bearer', token, anHourLater.toUtc()); - final AccessCredentials accessCredentials = - AccessCredentials(accessToken, null, scopes); + final AccessToken accessToken = AccessToken( + 'Bearer', + token, + anHourLater.toUtc(), + ); + final AccessCredentials accessCredentials = AccessCredentials( + accessToken, + null, + scopes, + ); return authenticatedClient(Client(), accessCredentials); } diff --git a/packages/metrics_center/lib/src/flutter.dart b/packages/metrics_center/lib/src/flutter.dart index acdac08b95d..d9d9e213ef9 100644 --- a/packages/metrics_center/lib/src/flutter.dart +++ b/packages/metrics_center/lib/src/flutter.dart @@ -17,13 +17,13 @@ class FlutterEngineMetricPoint extends MetricPoint { String gitRevision, { Map moreTags = const {}, }) : super( - value, - { - kNameKey: name, - kGithubRepoKey: kFlutterEngineRepo, - kGitRevisionKey: gitRevision, - }..addAll(moreTags), - ); + value, + { + kNameKey: name, + kGithubRepoKey: kFlutterEngineRepo, + kGitRevisionKey: gitRevision, + }..addAll(moreTags), + ); } /// All Flutter performance metrics (framework, engine, ...) should be written @@ -33,27 +33,38 @@ class FlutterDestination extends MetricDestination { /// Creates a [FlutterDestination] from service account JSON. static Future makeFromCredentialsJson( - Map json, - {bool isTesting = false}) async { + Map json, { + bool isTesting = false, + }) async { final SkiaPerfDestination skiaPerfDestination = - await SkiaPerfDestination.makeFromGcpCredentials(json, - isTesting: isTesting); + await SkiaPerfDestination.makeFromGcpCredentials( + json, + isTesting: isTesting, + ); return FlutterDestination._(skiaPerfDestination); } /// Creates a [FlutterDestination] from an OAuth access token. static Future makeFromAccessToken( - String accessToken, String projectId, - {bool isTesting = false}) async { + String accessToken, + String projectId, { + bool isTesting = false, + }) async { final SkiaPerfDestination skiaPerfDestination = - await SkiaPerfDestination.makeFromAccessToken(accessToken, projectId, - isTesting: isTesting); + await SkiaPerfDestination.makeFromAccessToken( + accessToken, + projectId, + isTesting: isTesting, + ); return FlutterDestination._(skiaPerfDestination); } @override Future update( - List points, DateTime commitTime, String taskName) async { + List points, + DateTime commitTime, + String taskName, + ) async { await _skiaPerfDestination.update(points, commitTime, taskName); } diff --git a/packages/metrics_center/lib/src/gcs_lock.dart b/packages/metrics_center/lib/src/gcs_lock.dart index 7c22c862627..463ee10f15b 100644 --- a/packages/metrics_center/lib/src/gcs_lock.dart +++ b/packages/metrics_center/lib/src/gcs_lock.dart @@ -28,7 +28,9 @@ class GcsLock { /// one may need to manually delete the lock file from GCS to unblock any /// [protectedRun] that may depend on it. Future protectedRun( - String lockFileName, Future Function() f) async { + String lockFileName, + Future Function() f, + ) async { await _lock(lockFileName); try { await f(); @@ -50,8 +52,12 @@ class GcsLock { bool locked = false; while (!locked) { try { - await _api.objects.insert(object, _bucketName, - ifGenerationMatch: '0', uploadMedia: content); + await _api.objects.insert( + object, + _bucketName, + ifGenerationMatch: '0', + uploadMedia: content, + ); locked = true; } on DetailedApiRequestError catch (e) { if (e.status == 412) { diff --git a/packages/metrics_center/lib/src/google_benchmark.dart b/packages/metrics_center/lib/src/google_benchmark.dart index b3133a8a7d6..cf9567d798f 100644 --- a/packages/metrics_center/lib/src/google_benchmark.dart +++ b/packages/metrics_center/lib/src/google_benchmark.dart @@ -66,7 +66,8 @@ void _parseAnItem( ) { final String name = item[kNameKey] as String; final Map timeUnitMap = { - if (item.containsKey(_kTimeUnitKey)) kUnitKey: item[_kTimeUnitKey] as String + if (item.containsKey(_kTimeUnitKey)) + kUnitKey: item[_kTimeUnitKey] as String, }; for (final String subResult in item.keys) { if (!_kNonNumericalValueSubResults.contains(subResult)) { @@ -76,7 +77,8 @@ void _parseAnItem( } catch (e) { // ignore: avoid_print print( - '$subResult: ${item[subResult]} (${(item[subResult] as Object?).runtimeType}) is not a number'); + '$subResult: ${item[subResult]} (${(item[subResult] as Object?).runtimeType}) is not a number', + ); rethrow; } @@ -88,7 +90,8 @@ void _parseAnItem( {kNameKey: name, kSubResultKey: subResult} ..addAll(context) ..addAll( - subResult.endsWith('time') ? timeUnitMap : {}), + subResult.endsWith('time') ? timeUnitMap : {}, + ), ), ); } diff --git a/packages/metrics_center/lib/src/skiaperf.dart b/packages/metrics_center/lib/src/skiaperf.dart index c389f62b96e..4ff9643d10a 100644 --- a/packages/metrics_center/lib/src/skiaperf.dart +++ b/packages/metrics_center/lib/src/skiaperf.dart @@ -49,22 +49,28 @@ import 'gcs_lock.dart'; /// } /// ``` class SkiaPerfPoint extends MetricPoint { - SkiaPerfPoint._(this.githubRepo, this.gitHash, this.testName, this.subResult, - double? value, this._options, this.jsonUrl) - : assert(_options[kGithubRepoKey] == null), - assert(_options[kGitRevisionKey] == null), - assert(_options[kNameKey] == null), - super( - value, - {} - ..addAll(_options) - ..addAll({ - kGithubRepoKey: githubRepo, - kGitRevisionKey: gitHash, - kNameKey: testName, - kSubResultKey: subResult, - }), - ) { + SkiaPerfPoint._( + this.githubRepo, + this.gitHash, + this.testName, + this.subResult, + double? value, + this._options, + this.jsonUrl, + ) : assert(_options[kGithubRepoKey] == null), + assert(_options[kGitRevisionKey] == null), + assert(_options[kNameKey] == null), + super( + value, + {} + ..addAll(_options) + ..addAll({ + kGithubRepoKey: githubRepo, + kGitRevisionKey: gitHash, + kNameKey: testName, + kSubResultKey: subResult, + }), + ) { assert(tags[kGithubRepoKey] != null); assert(tags[kGitRevisionKey] != null); assert(tags[kNameKey] != null); @@ -86,29 +92,38 @@ class SkiaPerfPoint extends MetricPoint { if (githubRepo == null || gitHash == null || name == null) { throw StateError( - '$kGithubRepoKey, $kGitRevisionKey, $kNameKey must be set in' - ' the tags of $p.'); + '$kGithubRepoKey, $kGitRevisionKey, $kNameKey must be set in' + ' the tags of $p.', + ); } 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, gitHash, name, subResult, p.value, options, null); + githubRepo, + gitHash, + name, + subResult, + p.value, + options, + null, + ); } /// In the format of '/' such as 'flutter/flutter' or @@ -144,10 +159,7 @@ class SkiaPerfPoint extends MetricPoint { final String? jsonUrl; Map _toSubResultJson() { - return { - subResult: value, - kSkiaPerfOptionsKey: _options, - }; + return {subResult: value, kSkiaPerfOptionsKey: _options}; } /// Convert a list of SkiaPoints with the same git repo and git revision into @@ -178,11 +190,14 @@ class SkiaPerfPoint extends MetricPoint { // options/configurations. If this actually happens in the future, we // probably can use different values of config (currently there's only // one kSkiaPerfDefaultConfig) to resolve the conflict. - assert(results[p.testName][kSkiaPerfDefaultConfig][kSkiaPerfOptionsKey] - .toString() == - subResultJson[kSkiaPerfOptionsKey].toString()); assert( - results[p.testName][kSkiaPerfDefaultConfig][p.subResult] == null); + results[p.testName][kSkiaPerfDefaultConfig][kSkiaPerfOptionsKey] + .toString() == + subResultJson[kSkiaPerfOptionsKey].toString(), + ); + assert( + results[p.testName][kSkiaPerfDefaultConfig][p.subResult] == null, + ); results[p.testName][kSkiaPerfDefaultConfig][p.subResult] = p.value; } } @@ -216,7 +231,9 @@ class SkiaPerfGcsAdaptor { /// The read may retry multiple times if transient network errors with code /// 504 happens. Future writePoints( - String objectName, List points) async { + String objectName, + List points, + ) async { final String jsonString = jsonEncode(SkiaPerfPoint.toSkiaPerfJson(points)); final List content = utf8.encode(jsonString); @@ -293,18 +310,21 @@ class SkiaPerfGcsAdaptor { for (final String name in results.keys) { final Map subResultMap = results[name][kSkiaPerfDefaultConfig] as Map; - for (final String subResult - in subResultMap.keys.where((String s) => s != kSkiaPerfOptionsKey)) { - points.add(SkiaPerfPoint._( - githubRepo, - gitHash, - name, - subResult, - subResultMap[subResult] as double?, - (subResultMap[kSkiaPerfOptionsKey] as Map) - .cast(), - info.downloadLink.toString(), - )); + for (final String subResult in subResultMap.keys.where( + (String s) => s != kSkiaPerfOptionsKey, + )) { + points.add( + SkiaPerfPoint._( + githubRepo, + gitHash, + name, + subResult, + subResultMap[subResult] as double?, + (subResultMap[kSkiaPerfOptionsKey] as Map) + .cast(), + info.downloadLink.toString(), + ), + ); } } return points; @@ -318,8 +338,12 @@ class SkiaPerfGcsAdaptor { /// in that leaf directory. We are using multiple json files divided by test /// names to scale up the system to avoid too many writes competing for /// the same json file. - static Future computeObjectName(String githubRepo, String? revision, - DateTime commitTime, String taskName) async { + static Future computeObjectName( + String githubRepo, + String? revision, + DateTime commitTime, + String taskName, + ) async { assert(_githubRepoToGcsName[githubRepo] != null); final String? topComponent = _githubRepoToGcsName[githubRepo]; // [commitTime] is not guranteed to be UTC. Ensure it is so all results @@ -358,10 +382,13 @@ class SkiaPerfDestination extends MetricDestination { /// Create from a full credentials json (of a service account). static Future makeFromGcpCredentials( - Map credentialsJson, - {bool isTesting = false}) async { + Map credentialsJson, { + bool isTesting = false, + }) async { final AutoRefreshingAuthClient client = await clientViaServiceAccount( - ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES); + ServiceAccountCredentials.fromJson(credentialsJson), + Storage.SCOPES, + ); return make( client, credentialsJson[kProjectId] as String, @@ -371,8 +398,10 @@ class SkiaPerfDestination extends MetricDestination { /// Create from an access token and its project id. static Future makeFromAccessToken( - String token, String projectId, - {bool isTesting = false}) async { + String token, + String projectId, { + bool isTesting = false, + }) async { final AuthClient client = authClientFromAccessToken(token, Storage.SCOPES); return make(client, projectId, isTesting: isTesting); } @@ -380,29 +409,37 @@ class SkiaPerfDestination extends MetricDestination { /// Create from an [AuthClient] and a GCP project id. /// /// [AuthClient] can be obtained from functions like `clientViaUserConsent`. - static Future make(AuthClient client, String projectId, - {bool isTesting = false}) async { + static Future make( + AuthClient client, + String projectId, { + bool isTesting = false, + }) async { final Storage storage = Storage(client, projectId); final String bucketName = isTesting ? kTestBucketName : kBucketName; if (!await storage.bucketExists(bucketName)) { throw StateError('Bucket $bucketName does not exist.'); } - final SkiaPerfGcsAdaptor adaptor = - SkiaPerfGcsAdaptor(storage.bucket(bucketName)); + final SkiaPerfGcsAdaptor adaptor = SkiaPerfGcsAdaptor( + storage.bucket(bucketName), + ); final GcsLock lock = GcsLock(StorageApi(client), bucketName); return SkiaPerfDestination(adaptor, lock); } @override Future update( - List points, DateTime commitTime, String taskName) async { + List points, + DateTime commitTime, + String taskName, + ) async { // 1st, create a map based on git repo, git revision, and point id. Git repo // and git revision are the top level components of the Skia perf GCS object // name. final Map>> pointMap = >>{}; - for (final SkiaPerfPoint p - in points.map((MetricPoint x) => SkiaPerfPoint.fromPoint(x))) { + for (final SkiaPerfPoint p in points.map( + (MetricPoint x) => SkiaPerfPoint.fromPoint(x), + )) { pointMap[p.githubRepo] ??= >{}; pointMap[p.githubRepo]![p.gitHash] ??= {}; pointMap[p.githubRepo]![p.gitHash]![p.id] = p; @@ -415,7 +452,11 @@ class SkiaPerfDestination extends MetricDestination { for (final String repo in pointMap.keys) { for (final String? revision in pointMap[repo]!.keys) { final String objectName = await SkiaPerfGcsAdaptor.computeObjectName( - repo, revision, commitTime, taskName); + repo, + revision, + commitTime, + taskName, + ); final Map? newPoints = pointMap[repo]![revision]; // Too many bots writing the metrics of a git revision into a single json // file will cause high contention on the lock. We use multiple @@ -424,8 +465,9 @@ class SkiaPerfDestination extends MetricDestination { // file names. lockFutures.add( _lock!.protectedRun('$objectName.lock', () async { - final List oldPoints = - await _gcs.readPoints(objectName); + final List oldPoints = await _gcs.readPoints( + objectName, + ); for (final SkiaPerfPoint p in oldPoints) { if (newPoints![p.id] == null) { newPoints[p.id] = p; diff --git a/packages/metrics_center/pubspec.yaml b/packages/metrics_center/pubspec.yaml index ebb77f98c31..ae8e079401b 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.6.0 + sdk: ^3.7.0 dependencies: _discoveryapis_commons: ^1.0.0 diff --git a/packages/metrics_center/test/flutter_test.dart b/packages/metrics_center/test/flutter_test.dart index 05dee1b7abc..25d8d3249ed 100644 --- a/packages/metrics_center/test/flutter_test.dart +++ b/packages/metrics_center/test/flutter_test.dart @@ -40,11 +40,20 @@ void main() { final Map? credentialsJson = getTestGcpCredentialsJson(); - test('FlutterDestination integration test with update.', () async { - final FlutterDestination dst = - await FlutterDestination.makeFromCredentialsJson(credentialsJson!, - isTesting: true); - await dst.update([simplePoint], - DateTime.fromMillisecondsSinceEpoch(123), 'test'); - }, skip: credentialsJson == null); + test( + 'FlutterDestination integration test with update.', + () async { + final FlutterDestination dst = + await FlutterDestination.makeFromCredentialsJson( + credentialsJson!, + isTesting: true, + ); + await dst.update( + [simplePoint], + DateTime.fromMillisecondsSinceEpoch(123), + 'test', + ); + }, + skip: credentialsJson == null, + ); } diff --git a/packages/metrics_center/test/gcs_lock_test.dart b/packages/metrics_center/test/gcs_lock_test.dart index 8222db4928e..c87248e01e8 100644 --- a/packages/metrics_center/test/gcs_lock_test.dart +++ b/packages/metrics_center/test/gcs_lock_test.dart @@ -17,17 +17,14 @@ import 'common.dart'; import 'gcs_lock_test.mocks.dart'; import 'utility.dart'; -enum TestPhase { - run1, - run2, -} - -@GenerateMocks([ - AuthClient, - StorageApi -], customMocks: >[ - MockSpec(onMissingStub: OnMissingStub.returnDefault) -]) +enum TestPhase { run1, run2 } + +@GenerateMocks( + [AuthClient, StorageApi], + customMocks: >[ + MockSpec(onMissingStub: OnMissingStub.returnDefault), + ], +) void main() { const Duration kDelayStep = Duration(milliseconds: 10); final Map? credentialsJson = getTestGcpCredentialsJson(); @@ -35,16 +32,19 @@ void main() { test('GcsLock prints warnings for long waits', () { // Capture print to verify error messages. final List prints = []; - final ZoneSpecification spec = - ZoneSpecification(print: (_, __, ___, String msg) => prints.add(msg)); + final ZoneSpecification spec = ZoneSpecification( + print: (_, __, ___, String msg) => prints.add(msg), + ); Zone.current.fork(specification: spec).run(() { fakeAsync((FakeAsync fakeAsync) { final MockAuthClient mockClient = MockAuthClient(); final GcsLock lock = GcsLock(StorageApi(mockClient), 'mockBucket'); when(mockClient.send(any)).thenThrow(DetailedApiRequestError(412, '')); - final Future runFinished = - lock.protectedRun('mock.lock', () async {}); + final Future runFinished = lock.protectedRun( + 'mock.lock', + () async {}, + ); fakeAsync.elapse(const Duration(seconds: 10)); when(mockClient.send(any)).thenThrow(AssertionError('Stop!')); runFinished.catchError((dynamic e) { @@ -58,61 +58,73 @@ void main() { }); }); - const String kExpectedErrorMessage = 'The lock is waiting for a long time: ' + const String kExpectedErrorMessage = + 'The lock is waiting for a long time: ' '0:00:10.240000. If the lock file mock.lock in bucket mockBucket ' 'seems to be stuck (i.e., it was created a long time ago and no one ' 'seems to be owning it currently), delete it manually to unblock this.'; expect(prints, equals([kExpectedErrorMessage, 'Stop!'])); }); - test('GcsLock integration test: single protectedRun is successful', () async { - final AutoRefreshingAuthClient client = await clientViaServiceAccount( - ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES); - final GcsLock lock = GcsLock(StorageApi(client), kTestBucketName); - int testValue = 0; - await lock.protectedRun('test.lock', () async { - testValue = 1; - }); - expect(testValue, 1); - }, skip: credentialsJson == null); - - test('GcsLock integration test: protectedRun is exclusive', () async { - final AutoRefreshingAuthClient client = await clientViaServiceAccount( - ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES); - final GcsLock lock1 = GcsLock(StorageApi(client), kTestBucketName); - final GcsLock lock2 = GcsLock(StorageApi(client), kTestBucketName); - - TestPhase phase = TestPhase.run1; - final Completer started1 = Completer(); - final Future finished1 = lock1.protectedRun('test.lock', () async { - started1.complete(); - while (phase == TestPhase.run1) { - await Future.delayed(kDelayStep); - } - }); + test( + 'GcsLock integration test: single protectedRun is successful', + () async { + final AutoRefreshingAuthClient client = await clientViaServiceAccount( + ServiceAccountCredentials.fromJson(credentialsJson), + Storage.SCOPES, + ); + final GcsLock lock = GcsLock(StorageApi(client), kTestBucketName); + int testValue = 0; + await lock.protectedRun('test.lock', () async { + testValue = 1; + }); + expect(testValue, 1); + }, + skip: credentialsJson == null, + ); + + test( + 'GcsLock integration test: protectedRun is exclusive', + () async { + final AutoRefreshingAuthClient client = await clientViaServiceAccount( + ServiceAccountCredentials.fromJson(credentialsJson), + Storage.SCOPES, + ); + final GcsLock lock1 = GcsLock(StorageApi(client), kTestBucketName); + final GcsLock lock2 = GcsLock(StorageApi(client), kTestBucketName); + + TestPhase phase = TestPhase.run1; + final Completer started1 = Completer(); + final Future finished1 = lock1.protectedRun('test.lock', () async { + started1.complete(); + while (phase == TestPhase.run1) { + await Future.delayed(kDelayStep); + } + }); - await started1.future; + await started1.future; - final Completer started2 = Completer(); - final Future finished2 = lock2.protectedRun('test.lock', () async { - started2.complete(); - }); + final Completer started2 = Completer(); + final Future finished2 = lock2.protectedRun('test.lock', () async { + started2.complete(); + }); - // started2 should not be set even after a long wait because lock1 is - // holding the GCS lock file. - await Future.delayed(kDelayStep * 10); - expect(started2.isCompleted, false); - - // When phase is switched to run2, lock1 should be released soon and - // lock2 should soon be able to proceed its protectedRun. - phase = TestPhase.run2; - await started2.future; - await finished1; - await finished2; - }, skip: credentialsJson == null); - - test('GcsLock attempts to unlock again on a DetailedApiRequestError', - () async { + // started2 should not be set even after a long wait because lock1 is + // holding the GCS lock file. + await Future.delayed(kDelayStep * 10); + expect(started2.isCompleted, false); + + // When phase is switched to run2, lock1 should be released soon and + // lock2 should soon be able to proceed its protectedRun. + phase = TestPhase.run2; + await started2.future; + await finished1; + await finished2; + }, + skip: credentialsJson == null, + ); + + test('GcsLock attempts to unlock again on a DetailedApiRequestError', () async { fakeAsync((FakeAsync fakeAsync) { final StorageApi mockStorageApi = MockStorageApi(); final ObjectsResource mockObjectsResource = MockObjectsResource(); @@ -121,28 +133,32 @@ void main() { when(mockStorageApi.objects).thenReturn(mockObjectsResource); // Simulate a failure to delete a lock file. - when(mockObjectsResource.delete(kTestBucketName, lockFileName)) - .thenThrow(DetailedApiRequestError(504, '')); + when( + mockObjectsResource.delete(kTestBucketName, lockFileName), + ).thenThrow(DetailedApiRequestError(504, '')); gcsLock.protectedRun(lockFileName, () async {}); // Allow time to pass by to ensure deleting the lock file is retried multiple times. fakeAsync.elapse(const Duration(milliseconds: 30)); - verify(mockObjectsResource.delete(kTestBucketName, lockFileName)) - .called(3); + verify( + mockObjectsResource.delete(kTestBucketName, lockFileName), + ).called(3); // Simulate a successful deletion of the lock file. - when(mockObjectsResource.delete(kTestBucketName, lockFileName)) - .thenAnswer((_) => Future( - () { - return; - }, - )); + when( + mockObjectsResource.delete(kTestBucketName, lockFileName), + ).thenAnswer( + (_) => Future(() { + return; + }), + ); // At this point, there should only be one more (successful) attempt to delete the lock file. fakeAsync.elapse(const Duration(minutes: 2)); - verify(mockObjectsResource.delete(kTestBucketName, lockFileName)) - .called(1); + verify( + mockObjectsResource.delete(kTestBucketName, lockFileName), + ).called(1); }); }); } diff --git a/packages/metrics_center/test/gcs_lock_test.mocks.dart b/packages/metrics_center/test/gcs_lock_test.mocks.dart index 54800d07f30..7edc4181206 100644 --- a/packages/metrics_center/test/gcs_lock_test.mocks.dart +++ b/packages/metrics_center/test/gcs_lock_test.mocks.dart @@ -31,45 +31,25 @@ import 'package:mockito/src/dummies.dart' as _i8; class _FakeAccessCredentials_0 extends _i1.SmartFake implements _i2.AccessCredentials { - _FakeAccessCredentials_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAccessCredentials_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_1 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeStreamedResponse_2 extends _i1.SmartFake implements _i3.StreamedResponse { - _FakeStreamedResponse_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeStreamedResponse_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAnywhereCachesResource_3 extends _i1.SmartFake implements _i4.AnywhereCachesResource { - _FakeAnywhereCachesResource_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAnywhereCachesResource_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeBucketAccessControlsResource_4 extends _i1.SmartFake @@ -77,32 +57,19 @@ class _FakeBucketAccessControlsResource_4 extends _i1.SmartFake _FakeBucketAccessControlsResource_4( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeBucketsResource_5 extends _i1.SmartFake implements _i4.BucketsResource { - _FakeBucketsResource_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeBucketsResource_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeChannelsResource_6 extends _i1.SmartFake implements _i4.ChannelsResource { - _FakeChannelsResource_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeChannelsResource_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDefaultObjectAccessControlsResource_7 extends _i1.SmartFake @@ -110,43 +77,25 @@ class _FakeDefaultObjectAccessControlsResource_7 extends _i1.SmartFake _FakeDefaultObjectAccessControlsResource_7( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeFoldersResource_8 extends _i1.SmartFake implements _i4.FoldersResource { - _FakeFoldersResource_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFoldersResource_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeManagedFoldersResource_9 extends _i1.SmartFake implements _i4.ManagedFoldersResource { - _FakeManagedFoldersResource_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeManagedFoldersResource_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeNotificationsResource_10 extends _i1.SmartFake implements _i4.NotificationsResource { - _FakeNotificationsResource_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeNotificationsResource_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObjectAccessControlsResource_11 extends _i1.SmartFake @@ -154,126 +103,68 @@ class _FakeObjectAccessControlsResource_11 extends _i1.SmartFake _FakeObjectAccessControlsResource_11( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeObjectsResource_12 extends _i1.SmartFake implements _i4.ObjectsResource { - _FakeObjectsResource_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObjectsResource_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOperationsResource_13 extends _i1.SmartFake implements _i4.OperationsResource { - _FakeOperationsResource_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOperationsResource_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeProjectsResource_14 extends _i1.SmartFake implements _i4.ProjectsResource { - _FakeProjectsResource_14( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeProjectsResource_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeGoogleLongrunningOperation_15 extends _i1.SmartFake implements _i4.GoogleLongrunningOperation { - _FakeGoogleLongrunningOperation_15( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeGoogleLongrunningOperation_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObject_16 extends _i1.SmartFake implements _i4.Object { - _FakeObject_16( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_16(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObject_17 extends _i1.SmartFake implements Object { - _FakeObject_17( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePolicy_18 extends _i1.SmartFake implements _i4.Policy { - _FakePolicy_18( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePolicy_18(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObjects_19 extends _i1.SmartFake implements _i4.Objects { - _FakeObjects_19( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObjects_19(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeRewriteResponse_20 extends _i1.SmartFake implements _i4.RewriteResponse { - _FakeRewriteResponse_20( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeRewriteResponse_20(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeTestIamPermissionsResponse_21 extends _i1.SmartFake implements _i4.TestIamPermissionsResponse { - _FakeTestIamPermissionsResponse_21( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeTestIamPermissionsResponse_21(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeChannel_22 extends _i1.SmartFake implements _i4.Channel { - _FakeChannel_22( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeChannel_22(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AuthClient]. @@ -285,55 +176,41 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { } @override - _i2.AccessCredentials get credentials => (super.noSuchMethod( - Invocation.getter(#credentials), - returnValue: _FakeAccessCredentials_0( - this, - Invocation.getter(#credentials), - ), - ) as _i2.AccessCredentials); + _i2.AccessCredentials get credentials => + (super.noSuchMethod( + Invocation.getter(#credentials), + returnValue: _FakeAccessCredentials_0( + this, + Invocation.getter(#credentials), + ), + ) + as _i2.AccessCredentials); @override - _i6.Future<_i3.Response> head( - Uri? url, { - Map? headers, - }) => + _i6.Future<_i3.Response> head(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #head, - [url], - {#headers: headers}, - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( - this, - Invocation.method( - #head, - [url], - {#headers: headers}, - ), - )), - ) as _i6.Future<_i3.Response>); + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method(#head, [url], {#headers: headers}), + ), + ), + ) + as _i6.Future<_i3.Response>); @override - _i6.Future<_i3.Response> get( - Uri? url, { - Map? headers, - }) => + _i6.Future<_i3.Response> get(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #get, - [url], - {#headers: headers}, - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( - this, - Invocation.method( - #get, - [url], - {#headers: headers}, - ), - )), - ) as _i6.Future<_i3.Response>); + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method(#get, [url], {#headers: headers}), + ), + ), + ) + as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> post( @@ -343,28 +220,23 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { _i7.Encoding? encoding, }) => (super.noSuchMethod( - Invocation.method( - #post, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( - this, - Invocation.method( - #post, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - )), - ) as _i6.Future<_i3.Response>); + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> put( @@ -374,28 +246,23 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { _i7.Encoding? encoding, }) => (super.noSuchMethod( - Invocation.method( - #put, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( - this, - Invocation.method( - #put, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - )), - ) as _i6.Future<_i3.Response>); + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> patch( @@ -405,28 +272,23 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { _i7.Encoding? encoding, }) => (super.noSuchMethod( - Invocation.method( - #patch, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( - this, - Invocation.method( - #patch, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - )), - ) as _i6.Future<_i3.Response>); + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> delete( @@ -436,49 +298,36 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { _i7.Encoding? encoding, }) => (super.noSuchMethod( - Invocation.method( - #delete, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( - this, - Invocation.method( - #delete, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - )), - ) as _i6.Future<_i3.Response>); + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i6.Future<_i3.Response>); @override - _i6.Future read( - Uri? url, { - Map? headers, - }) => + _i6.Future read(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #read, - [url], - {#headers: headers}, - ), - returnValue: _i6.Future.value(_i8.dummyValue( - this, - Invocation.method( - #read, - [url], - {#headers: headers}, - ), - )), - ) as _i6.Future); + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i6.Future.value( + _i8.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), + ), + ), + ) + as _i6.Future); @override _i6.Future<_i9.Uint8List> readBytes( @@ -486,39 +335,29 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { Map? headers, }) => (super.noSuchMethod( - Invocation.method( - #readBytes, - [url], - {#headers: headers}, - ), - returnValue: _i6.Future<_i9.Uint8List>.value(_i9.Uint8List(0)), - ) as _i6.Future<_i9.Uint8List>); + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: _i6.Future<_i9.Uint8List>.value(_i9.Uint8List(0)), + ) + as _i6.Future<_i9.Uint8List>); @override _i6.Future<_i3.StreamedResponse> send(_i3.BaseRequest? request) => (super.noSuchMethod( - Invocation.method( - #send, - [request], - ), - returnValue: - _i6.Future<_i3.StreamedResponse>.value(_FakeStreamedResponse_2( - this, - Invocation.method( - #send, - [request], - ), - )), - ) as _i6.Future<_i3.StreamedResponse>); + Invocation.method(#send, [request]), + returnValue: _i6.Future<_i3.StreamedResponse>.value( + _FakeStreamedResponse_2( + this, + Invocation.method(#send, [request]), + ), + ), + ) + as _i6.Future<_i3.StreamedResponse>); @override void close() => super.noSuchMethod( - Invocation.method( - #close, - [], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#close, []), + returnValueForMissingStub: null, + ); } /// A class which mocks [StorageApi]. @@ -530,115 +369,136 @@ class MockStorageApi extends _i1.Mock implements _i4.StorageApi { } @override - _i4.AnywhereCachesResource get anywhereCaches => (super.noSuchMethod( - Invocation.getter(#anywhereCaches), - returnValue: _FakeAnywhereCachesResource_3( - this, - Invocation.getter(#anywhereCaches), - ), - ) as _i4.AnywhereCachesResource); + _i4.AnywhereCachesResource get anywhereCaches => + (super.noSuchMethod( + Invocation.getter(#anywhereCaches), + returnValue: _FakeAnywhereCachesResource_3( + this, + Invocation.getter(#anywhereCaches), + ), + ) + as _i4.AnywhereCachesResource); @override _i4.BucketAccessControlsResource get bucketAccessControls => (super.noSuchMethod( - Invocation.getter(#bucketAccessControls), - returnValue: _FakeBucketAccessControlsResource_4( - this, - Invocation.getter(#bucketAccessControls), - ), - ) as _i4.BucketAccessControlsResource); + Invocation.getter(#bucketAccessControls), + returnValue: _FakeBucketAccessControlsResource_4( + this, + Invocation.getter(#bucketAccessControls), + ), + ) + as _i4.BucketAccessControlsResource); @override - _i4.BucketsResource get buckets => (super.noSuchMethod( - Invocation.getter(#buckets), - returnValue: _FakeBucketsResource_5( - this, - Invocation.getter(#buckets), - ), - ) as _i4.BucketsResource); + _i4.BucketsResource get buckets => + (super.noSuchMethod( + Invocation.getter(#buckets), + returnValue: _FakeBucketsResource_5( + this, + Invocation.getter(#buckets), + ), + ) + as _i4.BucketsResource); @override - _i4.ChannelsResource get channels => (super.noSuchMethod( - Invocation.getter(#channels), - returnValue: _FakeChannelsResource_6( - this, - Invocation.getter(#channels), - ), - ) as _i4.ChannelsResource); + _i4.ChannelsResource get channels => + (super.noSuchMethod( + Invocation.getter(#channels), + returnValue: _FakeChannelsResource_6( + this, + Invocation.getter(#channels), + ), + ) + as _i4.ChannelsResource); @override _i4.DefaultObjectAccessControlsResource get defaultObjectAccessControls => (super.noSuchMethod( - Invocation.getter(#defaultObjectAccessControls), - returnValue: _FakeDefaultObjectAccessControlsResource_7( - this, - Invocation.getter(#defaultObjectAccessControls), - ), - ) as _i4.DefaultObjectAccessControlsResource); + Invocation.getter(#defaultObjectAccessControls), + returnValue: _FakeDefaultObjectAccessControlsResource_7( + this, + Invocation.getter(#defaultObjectAccessControls), + ), + ) + as _i4.DefaultObjectAccessControlsResource); @override - _i4.FoldersResource get folders => (super.noSuchMethod( - Invocation.getter(#folders), - returnValue: _FakeFoldersResource_8( - this, - Invocation.getter(#folders), - ), - ) as _i4.FoldersResource); + _i4.FoldersResource get folders => + (super.noSuchMethod( + Invocation.getter(#folders), + returnValue: _FakeFoldersResource_8( + this, + Invocation.getter(#folders), + ), + ) + as _i4.FoldersResource); @override - _i4.ManagedFoldersResource get managedFolders => (super.noSuchMethod( - Invocation.getter(#managedFolders), - returnValue: _FakeManagedFoldersResource_9( - this, - Invocation.getter(#managedFolders), - ), - ) as _i4.ManagedFoldersResource); + _i4.ManagedFoldersResource get managedFolders => + (super.noSuchMethod( + Invocation.getter(#managedFolders), + returnValue: _FakeManagedFoldersResource_9( + this, + Invocation.getter(#managedFolders), + ), + ) + as _i4.ManagedFoldersResource); @override - _i4.NotificationsResource get notifications => (super.noSuchMethod( - Invocation.getter(#notifications), - returnValue: _FakeNotificationsResource_10( - this, - Invocation.getter(#notifications), - ), - ) as _i4.NotificationsResource); + _i4.NotificationsResource get notifications => + (super.noSuchMethod( + Invocation.getter(#notifications), + returnValue: _FakeNotificationsResource_10( + this, + Invocation.getter(#notifications), + ), + ) + as _i4.NotificationsResource); @override _i4.ObjectAccessControlsResource get objectAccessControls => (super.noSuchMethod( - Invocation.getter(#objectAccessControls), - returnValue: _FakeObjectAccessControlsResource_11( - this, - Invocation.getter(#objectAccessControls), - ), - ) as _i4.ObjectAccessControlsResource); + Invocation.getter(#objectAccessControls), + returnValue: _FakeObjectAccessControlsResource_11( + this, + Invocation.getter(#objectAccessControls), + ), + ) + as _i4.ObjectAccessControlsResource); @override - _i4.ObjectsResource get objects => (super.noSuchMethod( - Invocation.getter(#objects), - returnValue: _FakeObjectsResource_12( - this, - Invocation.getter(#objects), - ), - ) as _i4.ObjectsResource); + _i4.ObjectsResource get objects => + (super.noSuchMethod( + Invocation.getter(#objects), + returnValue: _FakeObjectsResource_12( + this, + Invocation.getter(#objects), + ), + ) + as _i4.ObjectsResource); @override - _i4.OperationsResource get operations => (super.noSuchMethod( - Invocation.getter(#operations), - returnValue: _FakeOperationsResource_13( - this, - Invocation.getter(#operations), - ), - ) as _i4.OperationsResource); + _i4.OperationsResource get operations => + (super.noSuchMethod( + Invocation.getter(#operations), + returnValue: _FakeOperationsResource_13( + this, + Invocation.getter(#operations), + ), + ) + as _i4.OperationsResource); @override - _i4.ProjectsResource get projects => (super.noSuchMethod( - Invocation.getter(#projects), - returnValue: _FakeProjectsResource_14( - this, - Invocation.getter(#projects), - ), - ) as _i4.ProjectsResource); + _i4.ProjectsResource get projects => + (super.noSuchMethod( + Invocation.getter(#projects), + returnValue: _FakeProjectsResource_14( + this, + Invocation.getter(#projects), + ), + ) + as _i4.ProjectsResource); } /// A class which mocks [ObjectsResource]. @@ -652,40 +512,34 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #bulkRestore, - [ - request, - bucket, - ], - {#$fields: $fields}, - ), - returnValue: _i6.Future<_i4.GoogleLongrunningOperation>.value( - _FakeGoogleLongrunningOperation_15( - this, - Invocation.method( - #bulkRestore, - [ - request, - bucket, - ], - {#$fields: $fields}, - ), - )), - returnValueForMissingStub: - _i6.Future<_i4.GoogleLongrunningOperation>.value( - _FakeGoogleLongrunningOperation_15( - this, - Invocation.method( - #bulkRestore, - [ - request, - bucket, - ], - {#$fields: $fields}, - ), - )), - ) as _i6.Future<_i4.GoogleLongrunningOperation>); + Invocation.method( + #bulkRestore, + [request, bucket], + {#$fields: $fields}, + ), + returnValue: _i6.Future<_i4.GoogleLongrunningOperation>.value( + _FakeGoogleLongrunningOperation_15( + this, + Invocation.method( + #bulkRestore, + [request, bucket], + {#$fields: $fields}, + ), + ), + ), + returnValueForMissingStub: + _i6.Future<_i4.GoogleLongrunningOperation>.value( + _FakeGoogleLongrunningOperation_15( + this, + Invocation.method( + #bulkRestore, + [request, bucket], + {#$fields: $fields}, + ), + ), + ), + ) + as _i6.Future<_i4.GoogleLongrunningOperation>); @override _i6.Future<_i4.Object> compose( @@ -700,61 +554,54 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #compose, - [ - request, - destinationBucket, - destinationObject, - ], - { - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #kmsKeyName: kmsKeyName, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #compose, - [ - request, - destinationBucket, - destinationObject, - ], - { - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #kmsKeyName: kmsKeyName, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #compose, - [ - request, - destinationBucket, - destinationObject, - ], - { - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #kmsKeyName: kmsKeyName, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #compose, + [request, destinationBucket, destinationObject], + { + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #kmsKeyName: kmsKeyName, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #compose, + [request, destinationBucket, destinationObject], + { + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #kmsKeyName: kmsKeyName, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #compose, + [request, destinationBucket, destinationObject], + { + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #kmsKeyName: kmsKeyName, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> copy( @@ -779,91 +626,98 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #copy, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #projection: projection, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #copy, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #projection: projection, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #copy, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #projection: projection, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #copy, + [ + request, + sourceBucket, + sourceObject, + destinationBucket, + destinationObject, + ], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #projection: projection, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #copy, + [ + request, + sourceBucket, + sourceObject, + destinationBucket, + destinationObject, + ], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: + ifSourceMetagenerationNotMatch, + #projection: projection, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #copy, + [ + request, + sourceBucket, + sourceObject, + destinationBucket, + destinationObject, + ], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: + ifSourceMetagenerationNotMatch, + #projection: projection, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future delete( @@ -878,25 +732,23 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #delete, - [ - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future.value(), - returnValueForMissingStub: _i6.Future.value(), - ) as _i6.Future); + Invocation.method( + #delete, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); @override _i6.Future get( @@ -915,73 +767,69 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { _i10.DownloadOptions? downloadOptions = _i10.DownloadOptions.metadata, }) => (super.noSuchMethod( - Invocation.method( - #get, - [ - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #softDeleted: softDeleted, - #userProject: userProject, - #$fields: $fields, - #downloadOptions: downloadOptions, - }, - ), - returnValue: _i6.Future.value(_FakeObject_17( - this, - Invocation.method( - #get, - [ - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #softDeleted: softDeleted, - #userProject: userProject, - #$fields: $fields, - #downloadOptions: downloadOptions, - }, - ), - )), - returnValueForMissingStub: _i6.Future.value(_FakeObject_17( - this, - Invocation.method( - #get, - [ - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #softDeleted: softDeleted, - #userProject: userProject, - #$fields: $fields, - #downloadOptions: downloadOptions, - }, - ), - )), - ) as _i6.Future); + Invocation.method( + #get, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #softDeleted: softDeleted, + #userProject: userProject, + #$fields: $fields, + #downloadOptions: downloadOptions, + }, + ), + returnValue: _i6.Future.value( + _FakeObject_17( + this, + Invocation.method( + #get, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #softDeleted: softDeleted, + #userProject: userProject, + #$fields: $fields, + #downloadOptions: downloadOptions, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future.value( + _FakeObject_17( + this, + Invocation.method( + #get, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #softDeleted: softDeleted, + #userProject: userProject, + #$fields: $fields, + #downloadOptions: downloadOptions, + }, + ), + ), + ), + ) + as _i6.Future); @override _i6.Future<_i4.Policy> getIamPolicy( @@ -992,49 +840,45 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #getIamPolicy, - [ - bucket, - object, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Policy>.value(_FakePolicy_18( - this, - Invocation.method( - #getIamPolicy, - [ - bucket, - object, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Policy>.value(_FakePolicy_18( - this, - Invocation.method( - #getIamPolicy, - [ - bucket, - object, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Policy>); + Invocation.method( + #getIamPolicy, + [bucket, object], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #getIamPolicy, + [bucket, object], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #getIamPolicy, + [bucket, object], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Policy>); @override _i6.Future<_i4.Object> insert( @@ -1055,79 +899,75 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { _i10.Media? uploadMedia, }) => (super.noSuchMethod( - Invocation.method( - #insert, - [ - request, - bucket, - ], - { - #contentEncoding: contentEncoding, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #kmsKeyName: kmsKeyName, - #name: name, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - #uploadOptions: uploadOptions, - #uploadMedia: uploadMedia, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #insert, - [ - request, - bucket, - ], - { - #contentEncoding: contentEncoding, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #kmsKeyName: kmsKeyName, - #name: name, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - #uploadOptions: uploadOptions, - #uploadMedia: uploadMedia, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #insert, - [ - request, - bucket, - ], - { - #contentEncoding: contentEncoding, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #kmsKeyName: kmsKeyName, - #name: name, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - #uploadOptions: uploadOptions, - #uploadMedia: uploadMedia, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #insert, + [request, bucket], + { + #contentEncoding: contentEncoding, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #kmsKeyName: kmsKeyName, + #name: name, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + #uploadOptions: uploadOptions, + #uploadMedia: uploadMedia, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #insert, + [request, bucket], + { + #contentEncoding: contentEncoding, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #kmsKeyName: kmsKeyName, + #name: name, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + #uploadOptions: uploadOptions, + #uploadMedia: uploadMedia, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #insert, + [request, bucket], + { + #contentEncoding: contentEncoding, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #kmsKeyName: kmsKeyName, + #name: name, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + #uploadOptions: uploadOptions, + #uploadMedia: uploadMedia, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Objects> list( @@ -1148,74 +988,78 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #list, - [bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeFoldersAsPrefixes: includeFoldersAsPrefixes, - #includeTrailingDelimiter: includeTrailingDelimiter, - #matchGlob: matchGlob, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #softDeleted: softDeleted, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Objects>.value(_FakeObjects_19( - this, - Invocation.method( - #list, - [bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeFoldersAsPrefixes: includeFoldersAsPrefixes, - #includeTrailingDelimiter: includeTrailingDelimiter, - #matchGlob: matchGlob, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #softDeleted: softDeleted, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: - _i6.Future<_i4.Objects>.value(_FakeObjects_19( - this, - Invocation.method( - #list, - [bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeFoldersAsPrefixes: includeFoldersAsPrefixes, - #includeTrailingDelimiter: includeTrailingDelimiter, - #matchGlob: matchGlob, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #softDeleted: softDeleted, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Objects>); + Invocation.method( + #list, + [bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeFoldersAsPrefixes: includeFoldersAsPrefixes, + #includeTrailingDelimiter: includeTrailingDelimiter, + #matchGlob: matchGlob, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #softDeleted: softDeleted, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Objects>.value( + _FakeObjects_19( + this, + Invocation.method( + #list, + [bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeFoldersAsPrefixes: includeFoldersAsPrefixes, + #includeTrailingDelimiter: includeTrailingDelimiter, + #matchGlob: matchGlob, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #softDeleted: softDeleted, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Objects>.value( + _FakeObjects_19( + this, + Invocation.method( + #list, + [bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeFoldersAsPrefixes: includeFoldersAsPrefixes, + #includeTrailingDelimiter: includeTrailingDelimiter, + #matchGlob: matchGlob, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #softDeleted: softDeleted, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Objects>); @override _i6.Future<_i4.Object> move( @@ -1234,73 +1078,68 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #move, - [ - bucket, - sourceObject, - destinationObject, - ], - { - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #move, - [ - bucket, - sourceObject, - destinationObject, - ], - { - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #move, - [ - bucket, - sourceObject, - destinationObject, - ], - { - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #move, + [bucket, sourceObject, destinationObject], + { + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #move, + [bucket, sourceObject, destinationObject], + { + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: + ifSourceMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #move, + [bucket, sourceObject, destinationObject], + { + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: + ifSourceMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> patch( @@ -1319,73 +1158,66 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #patch, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #patch, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #patch, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #patch, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #patch, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> restore( @@ -1403,70 +1235,63 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #restore, - [ - bucket, - object, - generation, - ], - { - #copySourceAcl: copySourceAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #restore, - [ - bucket, - object, - generation, - ], - { - #copySourceAcl: copySourceAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #restore, - [ - bucket, - object, - generation, - ], - { - #copySourceAcl: copySourceAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #restore, + [bucket, object, generation], + { + #copySourceAcl: copySourceAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #restore, + [bucket, object, generation], + { + #copySourceAcl: copySourceAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #restore, + [bucket, object, generation], + { + #copySourceAcl: copySourceAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future<_i4.RewriteResponse> rewrite( @@ -1493,99 +1318,104 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #rewrite, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, - #projection: projection, - #rewriteToken: rewriteToken, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: - _i6.Future<_i4.RewriteResponse>.value(_FakeRewriteResponse_20( - this, - Invocation.method( - #rewrite, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, - #projection: projection, - #rewriteToken: rewriteToken, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: - _i6.Future<_i4.RewriteResponse>.value(_FakeRewriteResponse_20( - this, - Invocation.method( - #rewrite, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, - #projection: projection, - #rewriteToken: rewriteToken, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.RewriteResponse>); + Invocation.method( + #rewrite, + [ + request, + sourceBucket, + sourceObject, + destinationBucket, + destinationObject, + ], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, + #projection: projection, + #rewriteToken: rewriteToken, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.RewriteResponse>.value( + _FakeRewriteResponse_20( + this, + Invocation.method( + #rewrite, + [ + request, + sourceBucket, + sourceObject, + destinationBucket, + destinationObject, + ], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: + ifSourceMetagenerationNotMatch, + #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, + #projection: projection, + #rewriteToken: rewriteToken, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.RewriteResponse>.value( + _FakeRewriteResponse_20( + this, + Invocation.method( + #rewrite, + [ + request, + sourceBucket, + sourceObject, + destinationBucket, + destinationObject, + ], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: + ifSourceMetagenerationNotMatch, + #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, + #projection: projection, + #rewriteToken: rewriteToken, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.RewriteResponse>); @override _i6.Future<_i4.Policy> setIamPolicy( @@ -1597,52 +1427,45 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #setIamPolicy, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Policy>.value(_FakePolicy_18( - this, - Invocation.method( - #setIamPolicy, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Policy>.value(_FakePolicy_18( - this, - Invocation.method( - #setIamPolicy, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Policy>); + Invocation.method( + #setIamPolicy, + [request, bucket, object], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #setIamPolicy, + [request, bucket, object], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #setIamPolicy, + [request, bucket, object], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Policy>); @override _i6.Future<_i4.TestIamPermissionsResponse> testIamPermissions( @@ -1654,55 +1477,46 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #testIamPermissions, - [ - bucket, - object, - permissions, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.TestIamPermissionsResponse>.value( - _FakeTestIamPermissionsResponse_21( - this, - Invocation.method( - #testIamPermissions, - [ - bucket, - object, - permissions, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: - _i6.Future<_i4.TestIamPermissionsResponse>.value( - _FakeTestIamPermissionsResponse_21( - this, - Invocation.method( - #testIamPermissions, - [ - bucket, - object, - permissions, - ], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.TestIamPermissionsResponse>); + Invocation.method( + #testIamPermissions, + [bucket, object, permissions], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.TestIamPermissionsResponse>.value( + _FakeTestIamPermissionsResponse_21( + this, + Invocation.method( + #testIamPermissions, + [bucket, object, permissions], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: + _i6.Future<_i4.TestIamPermissionsResponse>.value( + _FakeTestIamPermissionsResponse_21( + this, + Invocation.method( + #testIamPermissions, + [bucket, object, permissions], + { + #generation: generation, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.TestIamPermissionsResponse>); @override _i6.Future<_i4.Object> update( @@ -1721,73 +1535,66 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #update, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #update, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_16( - this, - Invocation.method( - #update, - [ - request, - bucket, - object, - ], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Object>); + Invocation.method( + #update, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #update, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #update, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Channel> watchAll( @@ -1806,72 +1613,67 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, }) => (super.noSuchMethod( - Invocation.method( - #watchAll, - [ - request, - bucket, - ], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeTrailingDelimiter: includeTrailingDelimiter, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Channel>.value(_FakeChannel_22( - this, - Invocation.method( - #watchAll, - [ - request, - bucket, - ], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeTrailingDelimiter: includeTrailingDelimiter, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - )), - returnValueForMissingStub: - _i6.Future<_i4.Channel>.value(_FakeChannel_22( - this, - Invocation.method( - #watchAll, - [ - request, - bucket, - ], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeTrailingDelimiter: includeTrailingDelimiter, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - )), - ) as _i6.Future<_i4.Channel>); + Invocation.method( + #watchAll, + [request, bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeTrailingDelimiter: includeTrailingDelimiter, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Channel>.value( + _FakeChannel_22( + this, + Invocation.method( + #watchAll, + [request, bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeTrailingDelimiter: includeTrailingDelimiter, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Channel>.value( + _FakeChannel_22( + this, + Invocation.method( + #watchAll, + [request, bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeTrailingDelimiter: includeTrailingDelimiter, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + ) + as _i6.Future<_i4.Channel>); } diff --git a/packages/metrics_center/test/google_benchmark_test.dart b/packages/metrics_center/test/google_benchmark_test.dart index 5bb02cce4d5..5150003f25c 100644 --- a/packages/metrics_center/test/google_benchmark_test.dart +++ b/packages/metrics_center/test/google_benchmark_test.dart @@ -11,13 +11,21 @@ import 'utility.dart'; void main() { test('GoogleBenchmarkParser parses example json.', () async { - final List points = - await GoogleBenchmarkParser.parse('test/example_google_benchmark.json'); - expect(points.length, 9); - expectSetMatch( - points.map((MetricPoint p) => p.value), - [101, 101, 4460, 4460, 6548, 6548, 3.8, 3.89, 4.89], + final List points = await GoogleBenchmarkParser.parse( + 'test/example_google_benchmark.json', ); + expect(points.length, 9); + expectSetMatch(points.map((MetricPoint p) => p.value), [ + 101, + 101, + 4460, + 4460, + 6548, + 6548, + 3.8, + 3.89, + 4.89, + ]); expectSetMatch( points.map((MetricPoint p) => p.tags[kSubResultKey]), [ @@ -28,16 +36,13 @@ void main() { 'rms', ], ); - expectSetMatch( - points.map((MetricPoint p) => p.tags[kNameKey]), - [ - 'BM_PaintRecordInit', - 'SkParagraphFixture/ShortLayout', - 'SkParagraphFixture/TextBigO_BigO', - 'ParagraphFixture/TextBigO_BigO', - 'ParagraphFixture/TextBigO_RMS', - ], - ); + expectSetMatch(points.map((MetricPoint p) => p.tags[kNameKey]), [ + 'BM_PaintRecordInit', + 'SkParagraphFixture/ShortLayout', + 'SkParagraphFixture/TextBigO_BigO', + 'ParagraphFixture/TextBigO_BigO', + 'ParagraphFixture/TextBigO_RMS', + ]); for (final MetricPoint p in points) { expect(p.tags.containsKey('host_name'), false); expect(p.tags.containsKey('load_avg'), false); diff --git a/packages/metrics_center/test/skiaperf_test.dart b/packages/metrics_center/test/skiaperf_test.dart index 8a015cbd83e..b5799f21fef 100644 --- a/packages/metrics_center/test/skiaperf_test.dart +++ b/packages/metrics_center/test/skiaperf_test.dart @@ -24,15 +24,15 @@ import 'utility.dart'; class MockGcsLock implements GcsLock { @override Future protectedRun( - String exclusiveObjectName, Future Function() f) async { + String exclusiveObjectName, + Future Function() f, + ) async { await f(); } } class MockSkiaPerfGcsAdaptor implements SkiaPerfGcsAdaptor { - MockSkiaPerfGcsAdaptor({ - this.writePointsOverride, - }); + MockSkiaPerfGcsAdaptor({this.writePointsOverride}); final Future Function()? writePointsOverride; @@ -43,7 +43,9 @@ class MockSkiaPerfGcsAdaptor implements SkiaPerfGcsAdaptor { @override Future writePoints( - String objectName, List points) async { + String objectName, + List points, + ) async { if (writePointsOverride != null) { return writePointsOverride!(); } @@ -69,67 +71,60 @@ Future main() async { const String kMetric1 = 'flutter_repo_batch_maximum'; const String kMetric2 = 'flutter_repo_watch_maximum'; - final MetricPoint cocoonPointRev1Metric1 = MetricPoint( - kValue1, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: kTaskName, - kSubResultKey: kMetric1, - kUnitKey: 's', - }, - ); - - final MetricPoint cocoonPointRev1Metric2 = MetricPoint( - kValue2, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: kTaskName, - kSubResultKey: kMetric2, - kUnitKey: 's', - }, - ); + final MetricPoint cocoonPointRev1Metric1 = + MetricPoint(kValue1, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: kTaskName, + kSubResultKey: kMetric1, + kUnitKey: 's', + }); - final MetricPoint cocoonPointRev2Metric1 = MetricPoint( - kValue3, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision2, - kNameKey: kTaskName, - kSubResultKey: kMetric1, - kUnitKey: 's', - }, - ); + final MetricPoint cocoonPointRev1Metric2 = + MetricPoint(kValue2, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: kTaskName, + kSubResultKey: kMetric2, + kUnitKey: 's', + }); - final MetricPoint cocoonPointBetaRev1Metric1 = MetricPoint( - kValue1, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: 'beta/$kTaskName', - kSubResultKey: kMetric1, - kUnitKey: 's', - 'branch': 'beta', - }, - ); + final MetricPoint cocoonPointRev2Metric1 = + MetricPoint(kValue3, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision2, + kNameKey: kTaskName, + kSubResultKey: kMetric1, + kUnitKey: 's', + }); - final MetricPoint cocoonPointBetaRev1Metric1BadBranch = MetricPoint( - kValue1, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: kTaskName, - kSubResultKey: kMetric1, - kUnitKey: 's', - - // If we only add this 'branch' tag without changing the test or sub-result name, an exception - // would be thrown as Skia Perf currently only supports the same set of tags for a pair of - // kNameKey and kSubResultKey values. So to support branches, one also has to add the branch - // name to the test name. - 'branch': 'beta', - }, - ); + final MetricPoint cocoonPointBetaRev1Metric1 = + MetricPoint(kValue1, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: 'beta/$kTaskName', + kSubResultKey: kMetric1, + kUnitKey: 's', + 'branch': 'beta', + }); + + final MetricPoint + cocoonPointBetaRev1Metric1BadBranch = MetricPoint(kValue1, const < + String, + String + >{ + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: kTaskName, + kSubResultKey: kMetric1, + kUnitKey: 's', + + // If we only add this 'branch' tag without changing the test or sub-result name, an exception + // would be thrown as Skia Perf currently only supports the same set of tags for a pair of + // kNameKey and kSubResultKey values. So to support branches, one also has to add the branch + // name to the test name. + 'branch': 'beta', + }); const String engineMetricName = 'BM_PaintRecordInit'; const String engineRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; @@ -193,13 +188,16 @@ Future main() async { expect(() => SkiaPerfPoint.fromPoint(noGithubRepoPoint), throwsA(anything)); expect( - () => SkiaPerfPoint.fromPoint(noGitRevisionPoint), throwsA(anything)); + () => SkiaPerfPoint.fromPoint(noGitRevisionPoint), + throwsA(anything), + ); expect(() => SkiaPerfPoint.fromPoint(noTestNamePoint), throwsA(anything)); }); test('Correctly convert a metric point from cocoon to SkiaPoint', () { - final SkiaPerfPoint skiaPoint1 = - SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); + final SkiaPerfPoint skiaPoint1 = SkiaPerfPoint.fromPoint( + cocoonPointRev1Metric1, + ); expect(skiaPoint1, isNotNull); expect(skiaPoint1.testName, equals(kTaskName)); expect(skiaPoint1.subResult, equals(kMetric1)); @@ -210,15 +208,17 @@ Future main() async { test('Cocoon points correctly encode into Skia perf json format', () { final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); final SkiaPerfPoint p2 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2); - final SkiaPerfPoint p3 = - SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1); + final SkiaPerfPoint p3 = SkiaPerfPoint.fromPoint( + cocoonPointBetaRev1Metric1, + ); const JsonEncoder encoder = JsonEncoder.withIndent(' '); expect( - encoder - .convert(SkiaPerfPoint.toSkiaPerfJson([p1, p2, p3])), - equals(''' + encoder.convert( + SkiaPerfPoint.toSkiaPerfJson([p1, p2, p3]), + ), + equals(''' { "gitHash": "9011cece2595447eea5dd91adaa241c1c9ef9a33", "results": { @@ -241,18 +241,20 @@ Future main() async { } } } -}''')); +}'''), + ); }); test('Engine metric points correctly encode into Skia perf json format', () { const JsonEncoder encoder = JsonEncoder.withIndent(' '); expect( - encoder.convert(SkiaPerfPoint.toSkiaPerfJson([ - SkiaPerfPoint.fromPoint(enginePoint1), - SkiaPerfPoint.fromPoint(enginePoint2), - ])), - equals( - ''' + encoder.convert( + SkiaPerfPoint.toSkiaPerfJson([ + SkiaPerfPoint.fromPoint(enginePoint1), + SkiaPerfPoint.fromPoint(enginePoint2), + ]), + ), + equals(''' { "gitHash": "ca799fa8b2254d09664b78ee80c43b434788d112", "results": { @@ -270,57 +272,63 @@ Future main() async { } } } -}''', - ), +}'''), ); }); test( - 'Throw if engine points with the same test name but different options are converted to ' - 'Skia perf points', () { - final FlutterEngineMetricPoint enginePoint1 = FlutterEngineMetricPoint( - 'BM_PaintRecordInit', - 101, - 'ca799fa8b2254d09664b78ee80c43b434788d112', - moreTags: const { - kSubResultKey: 'cpu_time', - kUnitKey: 'ns', - 'cpu_scaling_enabled': 'true', - }, - ); - final FlutterEngineMetricPoint enginePoint2 = FlutterEngineMetricPoint( - 'BM_PaintRecordInit', - 102, - 'ca799fa8b2254d09664b78ee80c43b434788d112', - moreTags: const { - kSubResultKey: 'real_time', - kUnitKey: 'ns', - 'cpu_scaling_enabled': 'false', - }, - ); + 'Throw if engine points with the same test name but different options are converted to ' + 'Skia perf points', + () { + final FlutterEngineMetricPoint enginePoint1 = FlutterEngineMetricPoint( + 'BM_PaintRecordInit', + 101, + 'ca799fa8b2254d09664b78ee80c43b434788d112', + moreTags: const { + kSubResultKey: 'cpu_time', + kUnitKey: 'ns', + 'cpu_scaling_enabled': 'true', + }, + ); + final FlutterEngineMetricPoint enginePoint2 = FlutterEngineMetricPoint( + 'BM_PaintRecordInit', + 102, + 'ca799fa8b2254d09664b78ee80c43b434788d112', + moreTags: const { + kSubResultKey: 'real_time', + kUnitKey: 'ns', + 'cpu_scaling_enabled': 'false', + }, + ); - const JsonEncoder encoder = JsonEncoder.withIndent(' '); - expect( - () => encoder.convert(SkiaPerfPoint.toSkiaPerfJson([ - SkiaPerfPoint.fromPoint(enginePoint1), - SkiaPerfPoint.fromPoint(enginePoint2), - ])), - throwsA(anything), - ); - }); + const JsonEncoder encoder = JsonEncoder.withIndent(' '); + expect( + () => encoder.convert( + SkiaPerfPoint.toSkiaPerfJson([ + SkiaPerfPoint.fromPoint(enginePoint1), + SkiaPerfPoint.fromPoint(enginePoint2), + ]), + ), + throwsA(anything), + ); + }, + ); test( - 'Throw if two Cocoon metric points with the same name and subResult keys ' - 'but different options are converted to Skia perf points', () { - final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); - final SkiaPerfPoint p2 = - SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1BadBranch); + 'Throw if two Cocoon metric points with the same name and subResult keys ' + 'but different options are converted to Skia perf points', + () { + final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); + final SkiaPerfPoint p2 = SkiaPerfPoint.fromPoint( + cocoonPointBetaRev1Metric1BadBranch, + ); - expect( - () => SkiaPerfPoint.toSkiaPerfJson([p1, p2]), - throwsA(anything), - ); - }); + expect( + () => SkiaPerfPoint.toSkiaPerfJson([p1, p2]), + throwsA(anything), + ); + }, + ); test('SkiaPerfGcsAdaptor computes name correctly', () async { expect( @@ -331,7 +339,8 @@ Future main() async { 'test', ), equals( - 'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json'), + 'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json', + ), ); expect( await SkiaPerfGcsAdaptor.computeObjectName( @@ -367,27 +376,34 @@ Future main() async { final List writePoints = [ SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1), ]; - final String skiaPerfJson = - jsonEncode(SkiaPerfPoint.toSkiaPerfJson(writePoints)); - when(testBucket.writeBytes(testObjectName, utf8.encode(skiaPerfJson))) - .thenAnswer((_) async => FakeObjectInfo()); + final String skiaPerfJson = jsonEncode( + SkiaPerfPoint.toSkiaPerfJson(writePoints), + ); + when( + testBucket.writeBytes(testObjectName, utf8.encode(skiaPerfJson)), + ).thenAnswer((_) async => FakeObjectInfo()); await skiaPerfGcs.writePoints(testObjectName, writePoints); verify(testBucket.writeBytes(testObjectName, utf8.encode(skiaPerfJson))); // Emulate the first network request to fail with 504. - when(testBucket.info(testObjectName)) - .thenThrow(DetailedApiRequestError(504, 'Test Failure')); + when( + testBucket.info(testObjectName), + ).thenThrow(DetailedApiRequestError(504, 'Test Failure')); final MockObjectInfo mockObjectInfo = MockObjectInfo(); - when(mockObjectInfo.downloadLink) - .thenReturn(Uri.https('test.com', 'mock.json')); - when(testBucket.info(testObjectName)) - .thenAnswer((_) => Future.value(mockObjectInfo)); - when(testBucket.read(testObjectName)) - .thenAnswer((_) => Stream>.value(utf8.encode(skiaPerfJson))); - - final List readPoints = - await skiaPerfGcs.readPoints(testObjectName); + when( + mockObjectInfo.downloadLink, + ).thenReturn(Uri.https('test.com', 'mock.json')); + when( + testBucket.info(testObjectName), + ).thenAnswer((_) => Future.value(mockObjectInfo)); + when( + testBucket.read(testObjectName), + ).thenAnswer((_) => Stream>.value(utf8.encode(skiaPerfJson))); + + final List readPoints = await skiaPerfGcs.readPoints( + testObjectName, + ); expect(readPoints.length, equals(1)); expect(readPoints[0].testName, kTaskName); expect(readPoints[0].subResult, kMetric1); @@ -406,8 +422,9 @@ Future main() async { DateTime.fromMillisecondsSinceEpoch(123), 'test', ); - when(testBucket.info(testObjectName)) - .thenThrow(Exception('No such object')); + when( + testBucket.info(testObjectName), + ).thenThrow(Exception('No such object')); expect((await skiaPerfGcs.readPoints(testObjectName)).length, 0); }); @@ -419,10 +436,14 @@ Future main() async { final ServiceAccountCredentials credentials = ServiceAccountCredentials.fromJson(credentialsJson); - final AutoRefreshingAuthClient client = - await clientViaServiceAccount(credentials, Storage.SCOPES); - final Storage storage = - Storage(client, credentialsJson['project_id'] as String); + final AutoRefreshingAuthClient client = await clientViaServiceAccount( + credentials, + Storage.SCOPES, + ); + final Storage storage = Storage( + client, + credentialsJson['project_id'] as String, + ); const String kTestBucketName = 'flutter-skia-perf-test'; @@ -446,19 +467,27 @@ Future main() async { SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2), ]); - final List points = - await skiaPerfGcs.readPoints(testObjectName); + final List points = await skiaPerfGcs.readPoints( + testObjectName, + ); expect(points.length, equals(2)); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.testName), [kTaskName]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), - [kMetric1, kMetric2]); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.value), [kValue1, kValue2]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), - [kFlutterFrameworkRepo]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), - [kFrameworkRevision1]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [ + kTaskName, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), [ + kMetric1, + kMetric2, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ + kValue1, + kValue2, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), [ + kFlutterFrameworkRepo, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [ + kFrameworkRevision1, + ]); for (int i = 0; i < 2; i += 1) { expect(points[0].jsonUrl, startsWith('https://')); } @@ -479,23 +508,24 @@ Future main() async { SkiaPerfPoint.fromPoint(enginePoint2), ]); - final List points = - await skiaPerfGcs.readPoints(testObjectName); - expect(points.length, equals(2)); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.testName), - [engineMetricName, engineMetricName], - ); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.value), - [engineValue1, engineValue2], - ); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.githubRepo), - [kFlutterEngineRepo], + final List points = await skiaPerfGcs.readPoints( + testObjectName, ); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.gitHash), [engineRevision]); + expect(points.length, equals(2)); + expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [ + engineMetricName, + engineMetricName, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ + engineValue1, + engineValue2, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), [ + kFlutterEngineRepo, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [ + engineRevision, + ]); for (int i = 0; i < 2; i += 1) { expect(points[0].jsonUrl, startsWith('https://')); } @@ -531,7 +561,8 @@ Future main() async { 'test', ), equals( - 'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json'), + 'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json', + ), ); expect( await SkiaPerfGcsAdaptor.computeObjectName( @@ -541,7 +572,8 @@ Future main() async { 'test', ), equals( - 'flutter-engine/2019/12/03/20/$kEngineRevision1/test_values.json'), + 'flutter-engine/2019/12/03/20/$kEngineRevision1/test_values.json', + ), ); expect( await SkiaPerfGcsAdaptor.computeObjectName( @@ -551,7 +583,8 @@ Future main() async { 'test', ), equals( - 'flutter-engine/2020/01/03/15/$kEngineRevision2/test_values.json'), + 'flutter-engine/2020/01/03/15/$kEngineRevision2/test_values.json', + ), ); }, skip: testBucket == null, @@ -598,23 +631,31 @@ Future main() async { DateTime.fromMillisecondsSinceEpoch(123), 'test', ); - List points = - await mockGcs.readPoints(await SkiaPerfGcsAdaptor.computeObjectName( - kFlutterFrameworkRepo, - kFrameworkRevision1, - DateTime.fromMillisecondsSinceEpoch(123), - 'test', - )); + List points = await mockGcs.readPoints( + await SkiaPerfGcsAdaptor.computeObjectName( + kFlutterFrameworkRepo, + kFrameworkRevision1, + DateTime.fromMillisecondsSinceEpoch(123), + 'test', + ), + ); expect(points.length, equals(2)); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.testName), [kTaskName]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), - [kMetric1, kMetric2]); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.value), [kValue1, kValue2]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [ + kTaskName, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), [ + kMetric1, + kMetric2, + ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ + kValue1, + kValue2, + ]); - final MetricPoint updated = - MetricPoint(kValue3, cocoonPointRev1Metric1.tags); + final MetricPoint updated = MetricPoint( + kValue3, + cocoonPointRev1Metric1.tags, + ); await dst.update( [updated, cocoonPointRev2Metric1], @@ -622,31 +663,37 @@ Future main() async { 'test', ); - points = - await mockGcs.readPoints(await SkiaPerfGcsAdaptor.computeObjectName( - kFlutterFrameworkRepo, - kFrameworkRevision2, - DateTime.fromMillisecondsSinceEpoch(123), - 'test', - )); + points = await mockGcs.readPoints( + await SkiaPerfGcsAdaptor.computeObjectName( + kFlutterFrameworkRepo, + kFrameworkRevision2, + DateTime.fromMillisecondsSinceEpoch(123), + 'test', + ), + ); expect(points.length, equals(1)); expect(points[0].gitHash, equals(kFrameworkRevision2)); expect(points[0].value, equals(kValue3)); - points = - await mockGcs.readPoints(await SkiaPerfGcsAdaptor.computeObjectName( - kFlutterFrameworkRepo, - kFrameworkRevision1, - DateTime.fromMillisecondsSinceEpoch(123), - 'test', - )); - expectSetMatch( - points.map((SkiaPerfPoint p) => p.value), [kValue2, kValue3]); + points = await mockGcs.readPoints( + await SkiaPerfGcsAdaptor.computeObjectName( + kFlutterFrameworkRepo, + kFrameworkRevision1, + DateTime.fromMillisecondsSinceEpoch(123), + 'test', + ), + ); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ + kValue2, + kValue3, + ]); }); Future skiaPerfDestinationIntegrationTest() async { - final SkiaPerfDestination destination = - SkiaPerfDestination(SkiaPerfGcsAdaptor(testBucket!), testLock); + final SkiaPerfDestination destination = SkiaPerfDestination( + SkiaPerfGcsAdaptor(testBucket!), + testLock, + ); await destination.update( [cocoonPointRev1Metric1], DateTime.fromMillisecondsSinceEpoch(123), diff --git a/packages/metrics_center/test/skiaperf_test.mocks.dart b/packages/metrics_center/test/skiaperf_test.mocks.dart index 8142809b76a..6e4793b601f 100644 --- a/packages/metrics_center/test/skiaperf_test.mocks.dart +++ b/packages/metrics_center/test/skiaperf_test.mocks.dart @@ -25,75 +25,40 @@ import 'package:mockito/src/dummies.dart' as _i5; // ignore_for_file: subtype_of_sealed_class class _FakeStreamSink_0 extends _i1.SmartFake implements _i2.StreamSink { - _FakeStreamSink_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeStreamSink_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObjectInfo_1 extends _i1.SmartFake implements _i3.ObjectInfo { - _FakeObjectInfo_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObjectInfo_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePage_2 extends _i1.SmartFake implements _i4.Page { - _FakePage_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePage_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDateTime_3 extends _i1.SmartFake implements DateTime { - _FakeDateTime_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDateTime_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_4 extends _i1.SmartFake implements Uri { - _FakeUri_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObjectGeneration_5 extends _i1.SmartFake implements _i3.ObjectGeneration { - _FakeObjectGeneration_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObjectGeneration_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeObjectMetadata_6 extends _i1.SmartFake implements _i3.ObjectMetadata { - _FakeObjectMetadata_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObjectMetadata_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [Bucket]. @@ -105,28 +70,26 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { } @override - String get bucketName => (super.noSuchMethod( - Invocation.getter(#bucketName), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#bucketName), - ), - ) as String); + String get bucketName => + (super.noSuchMethod( + Invocation.getter(#bucketName), + returnValue: _i5.dummyValue( + this, + Invocation.getter(#bucketName), + ), + ) + as String); @override - String absoluteObjectName(String? objectName) => (super.noSuchMethod( - Invocation.method( - #absoluteObjectName, - [objectName], - ), - returnValue: _i5.dummyValue( - this, - Invocation.method( - #absoluteObjectName, - [objectName], - ), - ), - ) as String); + String absoluteObjectName(String? objectName) => + (super.noSuchMethod( + Invocation.method(#absoluteObjectName, [objectName]), + returnValue: _i5.dummyValue( + this, + Invocation.method(#absoluteObjectName, [objectName]), + ), + ) + as String); @override _i2.StreamSink> write( @@ -138,32 +101,33 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { String? contentType, }) => (super.noSuchMethod( - Invocation.method( - #write, - [objectName], - { - #length: length, - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - returnValue: _FakeStreamSink_0>( - this, - Invocation.method( - #write, - [objectName], - { - #length: length, - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - ), - ) as _i2.StreamSink>); + Invocation.method( + #write, + [objectName], + { + #length: length, + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + returnValue: _FakeStreamSink_0>( + this, + Invocation.method( + #write, + [objectName], + { + #length: length, + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + ), + ) + as _i2.StreamSink>); @override _i2.Future<_i3.ObjectInfo> writeBytes( @@ -175,78 +139,63 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { String? contentType, }) => (super.noSuchMethod( - Invocation.method( - #writeBytes, - [ - name, - bytes, - ], - { - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - returnValue: _i2.Future<_i3.ObjectInfo>.value(_FakeObjectInfo_1( - this, - Invocation.method( - #writeBytes, - [ - name, - bytes, - ], - { - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - )), - ) as _i2.Future<_i3.ObjectInfo>); + Invocation.method( + #writeBytes, + [name, bytes], + { + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + returnValue: _i2.Future<_i3.ObjectInfo>.value( + _FakeObjectInfo_1( + this, + Invocation.method( + #writeBytes, + [name, bytes], + { + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + ), + ), + ) + as _i2.Future<_i3.ObjectInfo>); @override - _i2.Stream> read( - String? objectName, { - int? offset, - int? length, - }) => + _i2.Stream> read(String? objectName, {int? offset, int? length}) => (super.noSuchMethod( - Invocation.method( - #read, - [objectName], - { - #offset: offset, - #length: length, - }, - ), - returnValue: _i2.Stream>.empty(), - ) as _i2.Stream>); + Invocation.method( + #read, + [objectName], + {#offset: offset, #length: length}, + ), + returnValue: _i2.Stream>.empty(), + ) + as _i2.Stream>); @override - _i2.Future<_i3.ObjectInfo> info(String? name) => (super.noSuchMethod( - Invocation.method( - #info, - [name], - ), - returnValue: _i2.Future<_i3.ObjectInfo>.value(_FakeObjectInfo_1( - this, - Invocation.method( - #info, - [name], - ), - )), - ) as _i2.Future<_i3.ObjectInfo>); + _i2.Future<_i3.ObjectInfo> info(String? name) => + (super.noSuchMethod( + Invocation.method(#info, [name]), + returnValue: _i2.Future<_i3.ObjectInfo>.value( + _FakeObjectInfo_1(this, Invocation.method(#info, [name])), + ), + ) + as _i2.Future<_i3.ObjectInfo>); @override - _i2.Future delete(String? name) => (super.noSuchMethod( - Invocation.method( - #delete, - [name], - ), - returnValue: _i2.Future.value(), - ) as _i2.Future); + _i2.Future delete(String? name) => + (super.noSuchMethod( + Invocation.method(#delete, [name]), + returnValue: _i2.Future.value(), + ) + as _i2.Future); @override _i2.Future updateMetadata( @@ -254,32 +203,21 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { _i3.ObjectMetadata? metadata, ) => (super.noSuchMethod( - Invocation.method( - #updateMetadata, - [ - objectName, - metadata, - ], - ), - returnValue: _i2.Future.value(), - ) as _i2.Future); + Invocation.method(#updateMetadata, [objectName, metadata]), + returnValue: _i2.Future.value(), + ) + as _i2.Future); @override - _i2.Stream<_i3.BucketEntry> list({ - String? prefix, - String? delimiter, - }) => + _i2.Stream<_i3.BucketEntry> list({String? prefix, String? delimiter}) => (super.noSuchMethod( - Invocation.method( - #list, - [], - { - #prefix: prefix, - #delimiter: delimiter, - }, - ), - returnValue: _i2.Stream<_i3.BucketEntry>.empty(), - ) as _i2.Stream<_i3.BucketEntry>); + Invocation.method(#list, [], { + #prefix: prefix, + #delimiter: delimiter, + }), + returnValue: _i2.Stream<_i3.BucketEntry>.empty(), + ) + as _i2.Stream<_i3.BucketEntry>); @override _i2.Future<_i4.Page<_i3.BucketEntry>> page({ @@ -288,29 +226,23 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { int? pageSize = 50, }) => (super.noSuchMethod( - Invocation.method( - #page, - [], - { - #prefix: prefix, - #delimiter: delimiter, - #pageSize: pageSize, - }, - ), - returnValue: _i2.Future<_i4.Page<_i3.BucketEntry>>.value( - _FakePage_2<_i3.BucketEntry>( - this, - Invocation.method( - #page, - [], - { + Invocation.method(#page, [], { #prefix: prefix, #delimiter: delimiter, #pageSize: pageSize, - }, - ), - )), - ) as _i2.Future<_i4.Page<_i3.BucketEntry>>); + }), + returnValue: _i2.Future<_i4.Page<_i3.BucketEntry>>.value( + _FakePage_2<_i3.BucketEntry>( + this, + Invocation.method(#page, [], { + #prefix: prefix, + #delimiter: delimiter, + #pageSize: pageSize, + }), + ), + ), + ) + as _i2.Future<_i4.Page<_i3.BucketEntry>>); } /// A class which mocks [ObjectInfo]. @@ -322,74 +254,70 @@ class MockObjectInfo extends _i1.Mock implements _i3.ObjectInfo { } @override - String get name => (super.noSuchMethod( - Invocation.getter(#name), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#name), - ), - ) as String); + String get name => + (super.noSuchMethod( + Invocation.getter(#name), + returnValue: _i5.dummyValue(this, Invocation.getter(#name)), + ) + as String); @override - int get length => (super.noSuchMethod( - Invocation.getter(#length), - returnValue: 0, - ) as int); + int get length => + (super.noSuchMethod(Invocation.getter(#length), returnValue: 0) as int); @override - DateTime get updated => (super.noSuchMethod( - Invocation.getter(#updated), - returnValue: _FakeDateTime_3( - this, - Invocation.getter(#updated), - ), - ) as DateTime); + DateTime get updated => + (super.noSuchMethod( + Invocation.getter(#updated), + returnValue: _FakeDateTime_3(this, Invocation.getter(#updated)), + ) + as DateTime); @override - String get etag => (super.noSuchMethod( - Invocation.getter(#etag), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#etag), - ), - ) as String); + String get etag => + (super.noSuchMethod( + Invocation.getter(#etag), + returnValue: _i5.dummyValue(this, Invocation.getter(#etag)), + ) + as String); @override - List get md5Hash => (super.noSuchMethod( - Invocation.getter(#md5Hash), - returnValue: [], - ) as List); + List get md5Hash => + (super.noSuchMethod(Invocation.getter(#md5Hash), returnValue: []) + as List); @override - int get crc32CChecksum => (super.noSuchMethod( - Invocation.getter(#crc32CChecksum), - returnValue: 0, - ) as int); + int get crc32CChecksum => + (super.noSuchMethod(Invocation.getter(#crc32CChecksum), returnValue: 0) + as int); @override - Uri get downloadLink => (super.noSuchMethod( - Invocation.getter(#downloadLink), - returnValue: _FakeUri_4( - this, - Invocation.getter(#downloadLink), - ), - ) as Uri); + Uri get downloadLink => + (super.noSuchMethod( + Invocation.getter(#downloadLink), + returnValue: _FakeUri_4(this, Invocation.getter(#downloadLink)), + ) + as Uri); @override - _i3.ObjectGeneration get generation => (super.noSuchMethod( - Invocation.getter(#generation), - returnValue: _FakeObjectGeneration_5( - this, - Invocation.getter(#generation), - ), - ) as _i3.ObjectGeneration); + _i3.ObjectGeneration get generation => + (super.noSuchMethod( + Invocation.getter(#generation), + returnValue: _FakeObjectGeneration_5( + this, + Invocation.getter(#generation), + ), + ) + as _i3.ObjectGeneration); @override - _i3.ObjectMetadata get metadata => (super.noSuchMethod( - Invocation.getter(#metadata), - returnValue: _FakeObjectMetadata_6( - this, - Invocation.getter(#metadata), - ), - ) as _i3.ObjectMetadata); + _i3.ObjectMetadata get metadata => + (super.noSuchMethod( + Invocation.getter(#metadata), + returnValue: _FakeObjectMetadata_6( + this, + Invocation.getter(#metadata), + ), + ) + as _i3.ObjectMetadata); } diff --git a/packages/multicast_dns/CHANGELOG.md b/packages/multicast_dns/CHANGELOG.md index 495b69af786..6c4cbfa7262 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.3.3 diff --git a/packages/multicast_dns/example/main.dart b/packages/multicast_dns/example/main.dart index 2fdb57a6ec2..81c7697cab3 100644 --- a/packages/multicast_dns/example/main.dart +++ b/packages/multicast_dns/example/main.dart @@ -18,19 +18,23 @@ Future main() async { await client.start(); // Get the PTR record for the service. - await for (final PtrResourceRecord ptr in client - .lookup(ResourceRecordQuery.serverPointer(name))) { + await for (final PtrResourceRecord ptr in client.lookup( + ResourceRecordQuery.serverPointer(name), + )) { // Use the domainName from the PTR record to get the SRV record, // which will have the port and local hostname. // Note that duplicate messages may come through, especially if any // other mDNS queries are running elsewhere on the machine. await for (final SrvResourceRecord srv in client.lookup( - ResourceRecordQuery.service(ptr.domainName))) { + ResourceRecordQuery.service(ptr.domainName), + )) { // Domain name will be something like "io.flutter.example@some-iphone.local._dartobservatory._tcp.local" final String bundleId = ptr.domainName; //.substring(0, ptr.domainName.indexOf('@')); - print('Dart observatory instance found at ' - '${srv.target}:${srv.port} for "$bundleId".'); + print( + 'Dart observatory instance found at ' + '${srv.target}:${srv.port} for "$bundleId".', + ); } } client.stop(); diff --git a/packages/multicast_dns/example/mdns_sd.dart b/packages/multicast_dns/example/mdns_sd.dart index 50b46ebf91b..b728b612d9f 100644 --- a/packages/multicast_dns/example/mdns_sd.dart +++ b/packages/multicast_dns/example/mdns_sd.dart @@ -24,13 +24,15 @@ For example: final MDnsClient client = MDnsClient(); await client.start(); - await for (final PtrResourceRecord ptr in client - .lookup(ResourceRecordQuery.serverPointer(name))) { + await for (final PtrResourceRecord ptr in client.lookup( + ResourceRecordQuery.serverPointer(name), + )) { if (verbose) { print(ptr); } await for (final SrvResourceRecord srv in client.lookup( - ResourceRecordQuery.service(ptr.domainName))) { + ResourceRecordQuery.service(ptr.domainName), + )) { if (verbose) { print(srv); } @@ -39,23 +41,29 @@ For example: .lookup(ResourceRecordQuery.text(ptr.domainName)) .forEach(print); } - await for (final IPAddressResourceRecord ip - in client.lookup( - ResourceRecordQuery.addressIPv4(srv.target))) { + await for (final IPAddressResourceRecord ip in client + .lookup( + ResourceRecordQuery.addressIPv4(srv.target), + )) { if (verbose) { print(ip); } - print('Service instance found at ' - '${srv.target}:${srv.port} with ${ip.address}.'); + print( + 'Service instance found at ' + '${srv.target}:${srv.port} with ${ip.address}.', + ); } - await for (final IPAddressResourceRecord ip - in client.lookup( - ResourceRecordQuery.addressIPv6(srv.target))) { + await for (final IPAddressResourceRecord ip in client + .lookup( + ResourceRecordQuery.addressIPv6(srv.target), + )) { if (verbose) { print(ip); } - print('Service instance found at ' - '${srv.target}:${srv.port} with ${ip.address}.'); + print( + 'Service instance found at ' + '${srv.target}:${srv.port} with ${ip.address}.', + ); } } } diff --git a/packages/multicast_dns/lib/multicast_dns.dart b/packages/multicast_dns/lib/multicast_dns.dart index 9efd54ae5e3..18674fb25fc 100644 --- a/packages/multicast_dns/lib/multicast_dns.dart +++ b/packages/multicast_dns/lib/multicast_dns.dart @@ -21,16 +21,21 @@ export 'package:multicast_dns/src/resource_record.dart'; /// /// See also: /// * [MDnsQuerier.allInterfacesFactory] -typedef NetworkInterfacesFactory = Future> Function( - InternetAddressType type); +typedef NetworkInterfacesFactory = + Future> Function(InternetAddressType type); /// A factory for construction of datagram sockets. /// /// This can be injected into the [MDnsClient] to provide alternative /// implementations of [RawDatagramSocket.bind]. -typedef RawDatagramSocketFactory = Future Function( - dynamic host, int port, - {bool reuseAddress, bool reusePort, int ttl}); +typedef RawDatagramSocketFactory = + Future Function( + dynamic host, + int port, { + bool reuseAddress, + bool reusePort, + int ttl, + }); /// Client for DNS lookup and publishing using the mDNS protocol. /// @@ -59,7 +64,8 @@ class MDnsClient { /// Find all network interfaces with an the [InternetAddressType] specified. Future> allInterfacesFactory( - InternetAddressType type) { + InternetAddressType type, + ) { return NetworkInterface.list( includeLinkLocal: true, type: type, @@ -100,8 +106,10 @@ class MDnsClient { listenAddress ??= InternetAddress.anyIPv4; interfacesFactory ??= allInterfacesFactory; - assert(listenAddress.address == InternetAddress.anyIPv4.address || - listenAddress.address == InternetAddress.anyIPv6.address); + assert( + listenAddress.address == InternetAddress.anyIPv4.address || + listenAddress.address == InternetAddress.anyIPv6.address, + ); if (_started || _starting) { return; @@ -127,9 +135,10 @@ 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(); @@ -147,11 +156,13 @@ class MDnsClient { ttl: 255, ); _ipv6InterfaceSockets.add(socket); - socket.setRawOption(RawSocketOption.fromInt( - RawSocketOption.levelIPv6, - RawSocketOption.IPv6MulticastInterface, - interface.index, - )); + socket.setRawOption( + RawSocketOption.fromInt( + RawSocketOption.levelIPv6, + RawSocketOption.IPv6MulticastInterface, + interface.index, + ), + ); } // Join multicast on this interface. @@ -208,7 +219,10 @@ class MDnsClient { // Look for entries in the cache. final List cached = []; _cache.lookup( - query.fullyQualifiedName, query.resourceRecordType, cached); + query.fullyQualifiedName, + query.resourceRecordType, + cached, + ); if (cached.isNotEmpty) { final StreamController controller = StreamController(); cached.forEach(controller.add); @@ -218,7 +232,10 @@ class MDnsClient { // Add the pending request before sending the query. final Stream results = _resolver.addPendingRequest( - query.resourceRecordType, query.fullyQualifiedName, timeout); + query.resourceRecordType, + query.fullyQualifiedName, + timeout, + ); final List packet = query.encode(); diff --git a/packages/multicast_dns/lib/src/lookup_resolver.dart b/packages/multicast_dns/lib/src/lookup_resolver.dart index ceaa13a7262..a12c3e10baf 100644 --- a/packages/multicast_dns/lib/src/lookup_resolver.dart +++ b/packages/multicast_dns/lib/src/lookup_resolver.dart @@ -36,7 +36,10 @@ class LookupResolver { /// Adds a request and returns a [Stream] of [ResourceRecord] responses. Stream addPendingRequest( - int type, String name, Duration timeout) { + int type, + String name, + Duration timeout, + ) { final StreamController controller = StreamController(); final PendingRequest request = PendingRequest(type, name, controller); final Timer timer = Timer(timeout, () { diff --git a/packages/multicast_dns/lib/src/native_protocol_client.dart b/packages/multicast_dns/lib/src/native_protocol_client.dart index b7545190660..fb94343e0d5 100644 --- a/packages/multicast_dns/lib/src/native_protocol_client.dart +++ b/packages/multicast_dns/lib/src/native_protocol_client.dart @@ -50,7 +50,7 @@ class ResourceRecordCache { SplayTreeMap>(); _cache[record.resourceRecordType]![record.name] = [ - record + record, ]; } else { _cache[record.resourceRecordType]![record.name]!.add(record); @@ -60,7 +60,10 @@ class ResourceRecordCache { /// Get a record from this cache. void lookup( - String name, int type, List results) { + String name, + int type, + List results, + ) { assert(ResourceRecordType.debugAssertValid(type)); final int time = DateTime.now().millisecondsSinceEpoch; final SplayTreeMap>? candidates = _cache[type]; @@ -72,8 +75,9 @@ class ResourceRecordCache { if (candidateRecords == null) { return; } - candidateRecords - .removeWhere((ResourceRecord candidate) => candidate.validUntil < time); + candidateRecords.removeWhere( + (ResourceRecord candidate) => candidate.validUntil < time, + ); results.addAll(candidateRecords.cast()); } } diff --git a/packages/multicast_dns/lib/src/packet.dart b/packages/multicast_dns/lib/src/packet.dart index 330397deaa8..aa41cefd9a9 100644 --- a/packages/multicast_dns/lib/src/packet.dart +++ b/packages/multicast_dns/lib/src/packet.dart @@ -87,9 +87,10 @@ List encodeMDnsQuery( packetByteData.setUint16(offset, type); // QTYPE. offset += 2; packetByteData.setUint16( - offset, - ResourceRecordClass.internet | - (multicast ? QuestionType.multicast : QuestionType.unicast)); + offset, + ResourceRecordClass.internet | + (multicast ? QuestionType.multicast : QuestionType.unicast), + ); return data; } @@ -126,7 +127,11 @@ String readFQDN(List packet, [int offset = 0]) { // // If decoding fails (e.g. due to an invalid packet) `null` is returned. _FQDNReadResult _readFQDN( - Uint8List data, ByteData byteData, int offset, int length) { + Uint8List data, + ByteData byteData, + int offset, + int length, +) { void checkLength(int required) { if (length < required) { throw MDnsDecodeException(required); @@ -168,8 +173,11 @@ _FQDNReadResult _readFQDN( offset++; if (partLength > 0) { checkLength(offset + partLength); - final Uint8List partBytes = - Uint8List.view(data.buffer, offset, partLength); + final Uint8List partBytes = Uint8List.view( + data.buffer, + offset, + partLength, + ); offset += partLength; // According to the RFC, this is supposed to be utf-8 encoded, but // we should continue decoding even if it isn't to avoid dropping the @@ -258,8 +266,11 @@ List? decodeMDnsResponse(List packet) { addr.write('.'); addr.write(packetBytes.getUint8(offset)); } - return IPAddressResourceRecord(fqdn, validUntil, - address: InternetAddress(addr.toString())); + return IPAddressResourceRecord( + fqdn, + validUntil, + address: InternetAddress(addr.toString()), + ); case ResourceRecordType.addressIPv6: checkLength(offset + readDataLength); final StringBuffer addr = StringBuffer(); @@ -285,8 +296,12 @@ List? decodeMDnsResponse(List packet) { checkLength(offset + 2); final int port = packetBytes.getUint16(offset); offset += 2; - final _FQDNReadResult result = - _readFQDN(data, packetBytes, offset, length); + final _FQDNReadResult result = _readFQDN( + data, + packetBytes, + offset, + length, + ); offset += result.bytesRead; return SrvResourceRecord( fqdn, @@ -298,14 +313,14 @@ List? decodeMDnsResponse(List packet) { ); case ResourceRecordType.serverPointer: checkLength(offset + readDataLength); - final _FQDNReadResult result = - _readFQDN(data, packetBytes, offset, length); - offset += readDataLength; - return PtrResourceRecord( - fqdn, - validUntil, - domainName: result.fqdn, + final _FQDNReadResult result = _readFQDN( + data, + packetBytes, + offset, + length, ); + offset += readDataLength; + return PtrResourceRecord(fqdn, validUntil, domainName: result.fqdn); case ResourceRecordType.text: checkLength(offset + readDataLength); // The first byte of the buffer is the length of the first string of @@ -342,8 +357,12 @@ List? decodeMDnsResponse(List packet) { try { for (int i = 0; i < questionCount; i++) { - final _FQDNReadResult result = - _readFQDN(data, packetBytes, offset, length); + final _FQDNReadResult result = _readFQDN( + data, + packetBytes, + offset, + length, + ); offset += result.bytesRead; checkLength(offset + 4); offset += 4; diff --git a/packages/multicast_dns/lib/src/resource_record.dart b/packages/multicast_dns/lib/src/resource_record.dart index d58da791dd9..8c59ab2c3ec 100644 --- a/packages/multicast_dns/lib/src/resource_record.dart +++ b/packages/multicast_dns/lib/src/resource_record.dart @@ -80,54 +80,44 @@ class ResourceRecordQuery { ) : assert(ResourceRecordType.debugAssertValid(resourceRecordType)); /// An A (IPv4) query. - ResourceRecordQuery.addressIPv4( - String name, { - bool isMulticast = true, - }) : this( - ResourceRecordType.addressIPv4, - name, - isMulticast ? QuestionType.multicast : QuestionType.unicast, - ); + ResourceRecordQuery.addressIPv4(String name, {bool isMulticast = true}) + : this( + ResourceRecordType.addressIPv4, + name, + isMulticast ? QuestionType.multicast : QuestionType.unicast, + ); /// An AAAA (IPv6) query. - ResourceRecordQuery.addressIPv6( - String name, { - bool isMulticast = true, - }) : this( - ResourceRecordType.addressIPv6, - name, - isMulticast ? QuestionType.multicast : QuestionType.unicast, - ); + ResourceRecordQuery.addressIPv6(String name, {bool isMulticast = true}) + : this( + ResourceRecordType.addressIPv6, + name, + isMulticast ? QuestionType.multicast : QuestionType.unicast, + ); /// A PTR (Server pointer) query. - ResourceRecordQuery.serverPointer( - String name, { - bool isMulticast = true, - }) : this( - ResourceRecordType.serverPointer, - name, - isMulticast ? QuestionType.multicast : QuestionType.unicast, - ); + ResourceRecordQuery.serverPointer(String name, {bool isMulticast = true}) + : this( + ResourceRecordType.serverPointer, + name, + isMulticast ? QuestionType.multicast : QuestionType.unicast, + ); /// An SRV (Service) query. - ResourceRecordQuery.service( - String name, { - bool isMulticast = true, - }) : this( - ResourceRecordType.service, - name, - isMulticast ? QuestionType.multicast : QuestionType.unicast, - ); + ResourceRecordQuery.service(String name, {bool isMulticast = true}) + : this( + ResourceRecordType.service, + name, + isMulticast ? QuestionType.multicast : QuestionType.unicast, + ); /// A TXT (Text record) query. - ResourceRecordQuery.text( - String name, { - bool isMulticast = true, - }) : this( - ResourceRecordType.text, - name, - isMulticast ? QuestionType.multicast : QuestionType.unicast, - ); + ResourceRecordQuery.text(String name, {bool isMulticast = true}) + : this( + ResourceRecordType.text, + name, + isMulticast ? QuestionType.multicast : QuestionType.unicast, + ); /// Tye type of resource record - one of [ResourceRecordType]'s values. final int resourceRecordType; @@ -244,16 +234,14 @@ class PtrResourceRecord extends ResourceRecord { /// An IP Address record for IPv4 (DNS "A") or IPv6 (DNS "AAAA") records. class IPAddressResourceRecord extends ResourceRecord { /// Creates a new IPAddressResourceRecord. - IPAddressResourceRecord( - String name, - int validUntil, { - required this.address, - }) : super( - address.type == InternetAddressType.IPv4 - ? ResourceRecordType.addressIPv4 - : ResourceRecordType.addressIPv6, - name, - validUntil); + IPAddressResourceRecord(String name, int validUntil, {required this.address}) + : super( + address.type == InternetAddressType.IPv4 + ? ResourceRecordType.addressIPv4 + : ResourceRecordType.addressIPv6, + name, + validUntil, + ); /// The [InternetAddress] for this record. final InternetAddress address; @@ -335,11 +323,8 @@ class SrvResourceRecord extends ResourceRecord { /// A Text record, contianing additional textual data (DNS "TXT"). class TxtResourceRecord extends ResourceRecord { /// Creates a new text record. - const TxtResourceRecord( - String name, - int validUntil, { - required this.text, - }) : super(ResourceRecordType.text, name, validUntil); + const TxtResourceRecord(String name, int validUntil, {required this.text}) + : super(ResourceRecordType.text, name, validUntil); /// The raw text from this record. final String text; diff --git a/packages/multicast_dns/pubspec.yaml b/packages/multicast_dns/pubspec.yaml index 15fbae4dffb..38de03aacee 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.6.0 + sdk: ^3.7.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 706e2f1aa8e..b5fef509002 100644 --- a/packages/multicast_dns/test/client_test.dart +++ b/packages/multicast_dns/test/client_test.dart @@ -13,37 +13,47 @@ void main() { test('Can inject datagram socket factory and configure mdns port', () async { 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; - }); + final MDnsClient client = MDnsClient( + 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 => - []); + mDnsPort: 1234, + interfacesFactory: + (InternetAddressType type) async => [], + ); expect(lastPort, 1234); }); 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; - }); + final MDnsClient client = MDnsClient( + 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 => - []); + mDnsPort: 1234, + interfacesFactory: + (InternetAddressType type) async => [], + ); expect(datagramSocket.closed, false); client.stop(); expect(datagramSocket.closed, true); @@ -52,18 +62,23 @@ void main() { test('Closes IPv6 sockets', () async { 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; - }); + final MDnsClient client = MDnsClient( + 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 => - []); + mDnsPort: 1234, + interfacesFactory: + (InternetAddressType type) async => [], + ); expect(datagramSocket.closed, false); client.stop(); expect(datagramSocket.closed, true); @@ -72,17 +87,22 @@ void main() { test('start() is idempotent', () async { 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; - }); + final MDnsClient client = MDnsClient( + 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(); }); @@ -92,13 +112,13 @@ void main() { { 'name': 'IPv4', 'datagramSocketType': InternetAddress.anyIPv4, - 'interfacePrefix': '192.168.2.' + 'interfacePrefix': '192.168.2.', }, { 'name': 'IPv6', 'datagramSocketType': InternetAddress.anyIPv6, - 'interfacePrefix': '2001:0db8:85a3:0000:0000:8a2e:7335:030' - } + 'interfacePrefix': '2001:0db8:85a3:0000:0000:8a2e:7335:030', + }, ]; for (final Map testCase in testCases) { @@ -109,29 +129,32 @@ void main() { testCase['datagramSocketType']! as InternetAddress; 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; - }); + final MDnsClient client = MDnsClient( + rawDatagramSocketFactory: ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + selectedInterfacesForSendingPackets.add(host); + return datagramSocket; + }, + ); const int numberOfFakeInterfaces = 10; Future> fakeNetworkInterfacesFactory( - InternetAddressType type) async { + InternetAddressType type, + ) async { final List fakeInterfaces = []; // Generate "fake" interfaces for (int i = 0; i < numberOfFakeInterfaces; i++) { - fakeInterfaces.add(FakeNetworkInterface( - 'inetfake$i', - [ - InternetAddress("${testCase['interfacePrefix']! as String}$i") - ], - 0, - )); + fakeInterfaces.add( + FakeNetworkInterface('inetfake$i', [ + InternetAddress("${testCase['interfacePrefix']! as String}$i"), + ], 0), + ); } // ignore: always_specify_types @@ -142,17 +165,20 @@ void main() { testCase['datagramSocketType']! as InternetAddress; await client.start( - listenAddress: listenAddress, - mDnsPort: 1234, - interfacesFactory: fakeNetworkInterfacesFactory); + listenAddress: listenAddress, + mDnsPort: 1234, + interfacesFactory: fakeNetworkInterfacesFactory, + ); client.stop(); if (testCase['datagramSocketType'] == InternetAddress.anyIPv4) { expect(selectedInterfacesForSendingPackets.length, 1); } else { // + 1 because of unspecified address (::) - expect(selectedInterfacesForSendingPackets.length, - numberOfFakeInterfaces + 1); + expect( + selectedInterfacesForSendingPackets.length, + numberOfFakeInterfaces + 1, + ); } expect(selectedInterfacesForSendingPackets[0], listenAddress.address); }); @@ -177,8 +203,8 @@ void main() { 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(); @@ -195,12 +221,17 @@ class FakeRawDatagramSocket extends Fake implements RawDatagramSocket { @override StreamSubscription listen( - void Function(RawSocketEvent event)? onData, - {Function? onError, - void Function()? onDone, - bool? cancelOnError}) { - return const Stream.empty().listen(onData, - onError: onError, cancelOnError: cancelOnError, onDone: onDone); + void Function(RawSocketEvent event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { + return const Stream.empty().listen( + onData, + onError: onError, + cancelOnError: cancelOnError, + onDone: onDone, + ); } bool closed = false; diff --git a/packages/multicast_dns/test/decode_test.dart b/packages/multicast_dns/test/decode_test.dart index 358f764eba9..7d5d16b821b 100644 --- a/packages/multicast_dns/test/decode_test.dart +++ b/packages/multicast_dns/test/decode_test.dart @@ -63,8 +63,11 @@ void testValidPackages() { result[3].validUntil, text: '', ), - PtrResourceRecord('_services._dns-sd._udp.local', result[4].validUntil, - domainName: '_udisks-ssh._tcp.local'), + PtrResourceRecord( + '_services._dns-sd._udp.local', + result[4].validUntil, + domainName: '_udisks-ssh._tcp.local', + ), PtrResourceRecord( '_workstation._tcp.local', result[5].validUntil, @@ -145,25 +148,27 @@ void testValidPackages() { }); // Fixes https://github.com/flutter/flutter/issues/31854 - test('Can decode packages without question and with answer and additional', - () { - final List result = - decodeMDnsResponse(packetWithoutQuestionWithAnArCount)!; - expect(result, isNotNull); - expect(result.length, 2); - expect(result, [ - PtrResourceRecord( - '_______________.____._____', - result[0].validUntil, - domainName: '______________________._______________.____._____', - ), - TxtResourceRecord( - '______________________.____________.____._____', - result[1].validUntil, - text: 'model=MacBookPro14,3\nosxvers=18\necolor=225,225,223\n', - ), - ]); - }); + test( + 'Can decode packages without question and with answer and additional', + () { + final List result = + decodeMDnsResponse(packetWithoutQuestionWithAnArCount)!; + expect(result, isNotNull); + expect(result.length, 2); + expect(result, [ + PtrResourceRecord( + '_______________.____._____', + result[0].validUntil, + domainName: '______________________._______________.____._____', + ), + TxtResourceRecord( + '______________________.____________.____._____', + result[1].validUntil, + text: 'model=MacBookPro14,3\nosxvers=18\necolor=225,225,223\n', + ), + ]); + }, + ); test('Can decode packages with a long text resource', () { final List result = decodeMDnsResponse(packetWithLongTxt)!; @@ -200,8 +205,10 @@ void testBadPackages() { void testPTRRData() { test('Can read FQDN from PTR data', () { - expect('sgjesse-macbookpro2 [78:31:c1:b8:55:38]._workstation._tcp.local', - readFQDN(ptrRData)); + expect( + 'sgjesse-macbookpro2 [78:31:c1:b8:55:38]._workstation._tcp.local', + readFQDN(ptrRData), + ); expect('fletch-agent._fletch_agent._tcp.local', readFQDN(ptrRData2)); }); } @@ -268,7 +275,7 @@ const List package1 = [ 0xc0, 0xa8, 0x01, - 0xbf + 0xbf, ]; // Two addresses. @@ -333,7 +340,7 @@ const List package2 = [ 0xa9, 0xfe, 0x5f, - 0x53 + 0x53, ]; // Eight mixed answers. @@ -585,7 +592,7 @@ const List package3 = [ 0x00, 0x02, 0xc0, - 0x2c + 0x2c, ]; /// Contains compressed domain names where a there is a cycle amongst the @@ -621,7 +628,7 @@ const List cycle = [ 0xc0, 0xa8, 0x01, - 0xbf + 0xbf, ]; const List packagePtrResponse = [ @@ -807,7 +814,7 @@ const List packagePtrResponse = [ 0xa9, 0xfe, 0xa7, - 0xac + 0xac, ]; const List ptrRData = [ @@ -875,7 +882,7 @@ const List ptrRData = [ 0x63, 0x61, 0x6c, - 0x00 + 0x00, ]; const List ptrRData2 = [ @@ -917,7 +924,7 @@ const List ptrRData2 = [ 0x63, 0x61, 0x6c, - 0x00 + 0x00, ]; const List srvRData = [ @@ -940,7 +947,7 @@ const List srvRData = [ 0x63, 0x61, 0x6c, - 0x00 + 0x00, ]; const List packetWithQuestionAnArCount = [ @@ -1637,5 +1644,5 @@ const List nonUtf8Package = [ 0x00, 0x02, 0xc0, - 0x2c + 0x2c, ]; diff --git a/packages/multicast_dns/test/lookup_resolver_test.dart b/packages/multicast_dns/test/lookup_resolver_test.dart index db3e3a3abdc..1188ec26ba8 100644 --- a/packages/multicast_dns/test/lookup_resolver_test.dart +++ b/packages/multicast_dns/test/lookup_resolver_test.dart @@ -25,7 +25,10 @@ void testTimeout() { const Duration shortTimeout = Duration(milliseconds: 1); final LookupResolver resolver = LookupResolver(); final Stream result = resolver.addPendingRequest( - ResourceRecordType.addressIPv4, 'xxx', shortTimeout); + ResourceRecordType.addressIPv4, + 'xxx', + shortTimeout, + ); expect(await result.isEmpty, isTrue); }); } @@ -36,9 +39,14 @@ void testResult() { const Duration noTimeout = Duration(days: 1); final LookupResolver resolver = LookupResolver(); final Stream futureResult = resolver.addPendingRequest( - ResourceRecordType.addressIPv4, 'xxx.local', noTimeout); - final ResourceRecord response = - ip4Result('xxx.local', InternetAddress('1.2.3.4')); + ResourceRecordType.addressIPv4, + 'xxx.local', + noTimeout, + ); + final ResourceRecord response = ip4Result( + 'xxx.local', + InternetAddress('1.2.3.4'), + ); resolver.handleResponse([response]); final IPAddressResourceRecord result = await futureResult.first as IPAddressResourceRecord; @@ -52,13 +60,23 @@ void testResult2() { const Duration noTimeout = Duration(days: 1); final LookupResolver resolver = LookupResolver(); final Stream futureResult1 = resolver.addPendingRequest( - ResourceRecordType.addressIPv4, 'xxx.local', noTimeout); + ResourceRecordType.addressIPv4, + 'xxx.local', + noTimeout, + ); final Stream futureResult2 = resolver.addPendingRequest( - ResourceRecordType.addressIPv4, 'yyy.local', noTimeout); - final ResourceRecord response1 = - ip4Result('xxx.local', InternetAddress('1.2.3.4')); - final ResourceRecord response2 = - ip4Result('yyy.local', InternetAddress('2.3.4.5')); + ResourceRecordType.addressIPv4, + 'yyy.local', + noTimeout, + ); + final ResourceRecord response1 = ip4Result( + 'xxx.local', + InternetAddress('1.2.3.4'), + ); + final ResourceRecord response2 = ip4Result( + 'yyy.local', + InternetAddress('2.3.4.5'), + ); resolver.handleResponse([response2, response1]); final IPAddressResourceRecord result1 = await futureResult1.first as IPAddressResourceRecord; @@ -74,20 +92,32 @@ void testResult3() { test('Multiple requests', () async { const Duration noTimeout = Duration(days: 1); final LookupResolver resolver = LookupResolver(); - final ResourceRecord response0 = - ip4Result('zzz.local', InternetAddress('2.3.4.5')); + final ResourceRecord response0 = ip4Result( + 'zzz.local', + InternetAddress('2.3.4.5'), + ); resolver.handleResponse([response0]); final Stream futureResult1 = resolver.addPendingRequest( - ResourceRecordType.addressIPv4, 'xxx.local', noTimeout); + ResourceRecordType.addressIPv4, + 'xxx.local', + noTimeout, + ); resolver.handleResponse([response0]); final Stream futureResult2 = resolver.addPendingRequest( - ResourceRecordType.addressIPv4, 'yyy.local', noTimeout); + ResourceRecordType.addressIPv4, + 'yyy.local', + noTimeout, + ); resolver.handleResponse([response0]); - final ResourceRecord response1 = - ip4Result('xxx.local', InternetAddress('1.2.3.4')); + final ResourceRecord response1 = ip4Result( + 'xxx.local', + InternetAddress('1.2.3.4'), + ); resolver.handleResponse([response0]); - final ResourceRecord response2 = - ip4Result('yyy.local', InternetAddress('2.3.4.5')); + final ResourceRecord response2 = ip4Result( + 'yyy.local', + InternetAddress('2.3.4.5'), + ); resolver.handleResponse([response0]); resolver.handleResponse([response2, response1]); resolver.handleResponse([response0]); diff --git a/packages/multicast_dns/test/resource_record_cache_test.dart b/packages/multicast_dns/test/resource_record_cache_test.dart index 21aed34ecd9..11be62768e7 100644 --- a/packages/multicast_dns/test/resource_record_cache_test.dart +++ b/packages/multicast_dns/test/resource_record_cache_test.dart @@ -29,14 +29,14 @@ void testOverwrite() { // Add two different records. cache.updateRecords([ IPAddressResourceRecord('hest', valid, address: ip1), - IPAddressResourceRecord('fisk', valid, address: ip2) + IPAddressResourceRecord('fisk', valid, address: ip2), ]); expect(cache.entryCount, 2); // Update these records. cache.updateRecords([ IPAddressResourceRecord('hest', valid, address: ip1), - IPAddressResourceRecord('fisk', valid, address: ip2) + IPAddressResourceRecord('fisk', valid, address: ip2), ]); expect(cache.entryCount, 2); @@ -44,7 +44,7 @@ void testOverwrite() { // with that name only.) cache.updateRecords([ IPAddressResourceRecord('hest', valid, address: ip1), - IPAddressResourceRecord('hest', valid, address: ip2) + IPAddressResourceRecord('hest', valid, address: ip2), ]); expect(cache.entryCount, 3); @@ -64,12 +64,13 @@ void testTimeout() { final ResourceRecordCache cache = ResourceRecordCache(); - cache.updateRecords( - [IPAddressResourceRecord('hest', valid, address: ip1)]); + cache.updateRecords([ + IPAddressResourceRecord('hest', valid, address: ip1), + ]); expect(cache.entryCount, 1); cache.updateRecords([ - IPAddressResourceRecord('fisk', notValid, address: ip1) + IPAddressResourceRecord('fisk', notValid, address: ip1), ]); List results = []; diff --git a/packages/path_provider/path_provider/CHANGELOG.md b/packages/path_provider/path_provider/CHANGELOG.md index d8d5821f008..c01c866836d 100644 --- a/packages/path_provider/path_provider/CHANGELOG.md +++ b/packages/path_provider/path_provider/CHANGELOG.md @@ -1,7 +1,7 @@ ## NEXT +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. * Updates README to indicate that Andoid SDK <21 is no longer supported. -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. ## 2.1.5 diff --git a/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart index 846d87df399..89b88eb4a9b 100644 --- a/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart @@ -83,8 +83,9 @@ void main() { ]; for (final StorageDirectory? type in allDirs) { - testWidgets('getExternalStorageDirectories (type: $type)', - (WidgetTester tester) async { + testWidgets('getExternalStorageDirectories (type: $type)', ( + WidgetTester tester, + ) async { if (Platform.isIOS) { final Future?> result = getExternalStorageDirectories(); await expectLater(result, throwsA(isInstanceOf())); @@ -129,7 +130,9 @@ void _verifySampleFile(Directory? directory, String name) { // https://github.com/dart-lang/sdk/issues/54287. if (Platform.isAndroid) { expect( - Process.runSync('ls', [directory.path]).stdout, contains(name)); + Process.runSync('ls', [directory.path]).stdout, + contains(name), + ); } else { expect(directory.listSync(), isNotEmpty); } diff --git a/packages/path_provider/path_provider/example/lib/main.dart b/packages/path_provider/path_provider/example/lib/main.dart index fcf0e138a65..f19098aa4a3 100644 --- a/packages/path_provider/path_provider/example/lib/main.dart +++ b/packages/path_provider/path_provider/example/lib/main.dart @@ -20,9 +20,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Path Provider', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'Path Provider'), ); } @@ -54,7 +52,9 @@ class _MyHomePageState extends State { } Widget _buildDirectory( - BuildContext context, AsyncSnapshot snapshot) { + BuildContext context, + AsyncSnapshot snapshot, + ) { Text text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -69,14 +69,17 @@ class _MyHomePageState extends State { } Widget _buildDirectories( - BuildContext context, AsyncSnapshot?> snapshot) { + BuildContext context, + AsyncSnapshot?> snapshot, + ) { Text text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); } else if (snapshot.hasData) { - final String combined = - snapshot.data!.map((Directory d) => d.path).join(', '); + final String combined = snapshot.data! + .map((Directory d) => d.path) + .join(', '); text = Text('paths: $combined'); } else { text = const Text('path unavailable'); @@ -136,9 +139,7 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: Center( child: ListView( children: [ @@ -148,9 +149,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: ElevatedButton( onPressed: _requestTempDirectory, - child: const Text( - 'Get Temporary Directory', - ), + child: const Text('Get Temporary Directory'), ), ), FutureBuilder( @@ -165,9 +164,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: ElevatedButton( onPressed: _requestAppDocumentsDirectory, - child: const Text( - 'Get Application Documents Directory', - ), + child: const Text('Get Application Documents Directory'), ), ), FutureBuilder( @@ -182,9 +179,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: ElevatedButton( onPressed: _requestAppSupportDirectory, - child: const Text( - 'Get Application Support Directory', - ), + child: const Text('Get Application Support Directory'), ), ), FutureBuilder( @@ -219,9 +214,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: ElevatedButton( onPressed: _requestAppCacheDirectory, - child: const Text( - 'Get Application Cache Directory', - ), + child: const Text('Get Application Cache Directory'), ), ), FutureBuilder( @@ -235,9 +228,10 @@ 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' @@ -256,13 +250,14 @@ 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' @@ -281,9 +276,10 @@ 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' @@ -302,9 +298,10 @@ 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 bc9eb561eb8..8892a58ac7a 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider/lib/path_provider.dart b/packages/path_provider/path_provider/lib/path_provider.dart index e7ab24fbe49..5776e7722b2 100644 --- a/packages/path_provider/path_provider/lib/path_provider.dart +++ b/packages/path_provider/path_provider/lib/path_provider.dart @@ -55,7 +55,8 @@ Future getTemporaryDirectory() async { final String? path = await _platform.getTemporaryPath(); if (path == null) { throw MissingPlatformDirectoryException( - 'Unable to get temporary directory'); + 'Unable to get temporary directory', + ); } return Directory(path); } @@ -78,7 +79,8 @@ Future getApplicationSupportDirectory() async { final String? path = await _platform.getApplicationSupportPath(); if (path == null) { throw MissingPlatformDirectoryException( - 'Unable to get application support directory'); + 'Unable to get application support directory', + ); } return Directory(path); @@ -121,7 +123,8 @@ Future getApplicationDocumentsDirectory() async { final String? path = await _platform.getApplicationDocumentsPath(); if (path == null) { throw MissingPlatformDirectoryException( - 'Unable to get application documents directory'); + 'Unable to get application documents directory', + ); } return Directory(path); } @@ -137,7 +140,8 @@ Future getApplicationCacheDirectory() async { final String? path = await _platform.getApplicationCachePath(); if (path == null) { throw MissingPlatformDirectoryException( - 'Unable to get application cache directory'); + 'Unable to get application cache directory', + ); } return Directory(path); } @@ -198,8 +202,9 @@ Future?> getExternalStorageDirectories({ /// how this type translates to Android storage directories. StorageDirectory? type, }) async { - final List? paths = - await _platform.getExternalStoragePaths(type: type); + final List? paths = await _platform.getExternalStoragePaths( + type: type, + ); if (paths == null) { return null; } diff --git a/packages/path_provider/path_provider/pubspec.yaml b/packages/path_provider/path_provider/pubspec.yaml index cafee8e3c21..77ac63fb6dd 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/path_provider/path_provider/test/path_provider_test.dart b/packages/path_provider/path_provider/test/path_provider_test.dart index aa6d325574d..5a90bf614f4 100644 --- a/packages/path_provider/path_provider/test/path_provider_test.dart +++ b/packages/path_provider/path_provider/test/path_provider_test.dart @@ -73,23 +73,31 @@ void main() { }); test('getTemporaryDirectory throws on null', () async { - expect(getTemporaryDirectory(), - throwsA(isA())); + expect( + getTemporaryDirectory(), + throwsA(isA()), + ); }); test('getApplicationSupportDirectory throws on null', () async { - expect(getApplicationSupportDirectory(), - throwsA(isA())); + expect( + getApplicationSupportDirectory(), + throwsA(isA()), + ); }); test('getLibraryDirectory throws on null', () async { - expect(getLibraryDirectory(), - throwsA(isA())); + expect( + getLibraryDirectory(), + throwsA(isA()), + ); }); test('getApplicationDocumentsDirectory throws on null', () async { - expect(getApplicationDocumentsDirectory(), - throwsA(isA())); + expect( + getApplicationDocumentsDirectory(), + throwsA(isA()), + ); }); test('getExternalStorageDirectory passes null through', () async { diff --git a/packages/path_provider/path_provider_android/CHANGELOG.md b/packages/path_provider/path_provider_android/CHANGELOG.md index 91d224331a2..7708990dbd5 100644 --- a/packages/path_provider/path_provider_android/CHANGELOG.md +++ b/packages/path_provider/path_provider_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 2.2.17 * Removes obsolete code related to supporting SDK <21. diff --git a/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart index 8f4422613c2..3f0723f51c8 100644 --- a/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart @@ -36,8 +36,10 @@ void main() { testWidgets('getLibraryDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; - expect(() => provider.getLibraryPath(), - throwsA(isInstanceOf())); + expect( + () => provider.getLibraryPath(), + throwsA(isInstanceOf()), + ); }); testWidgets('getExternalStorageDirectory', (WidgetTester tester) async { @@ -67,12 +69,14 @@ void main() { ]; for (final StorageDirectory? type in allDirs) { - testWidgets('getExternalStorageDirectories (type: $type)', - (WidgetTester tester) async { + testWidgets('getExternalStorageDirectories (type: $type)', ( + WidgetTester tester, + ) async { final PathProviderPlatform provider = PathProviderPlatform.instance; - final List? directories = - await provider.getExternalStoragePaths(type: type); + final List? directories = await provider.getExternalStoragePaths( + type: type, + ); expect(directories, isNotNull); expect(directories, isNotEmpty); for (final String result in directories!) { @@ -102,6 +106,8 @@ void _verifySampleFile(String? directoryPath, String name) { // This check intentionally avoids using Directory.listSync due to // https://github.com/dart-lang/sdk/issues/54287. expect( - Process.runSync('ls', [directory.path]).stdout, contains(name)); + Process.runSync('ls', [directory.path]).stdout, + contains(name), + ); file.deleteSync(); } diff --git a/packages/path_provider/path_provider_android/example/lib/main.dart b/packages/path_provider/path_provider_android/example/lib/main.dart index 29ce6f19155..34c667c55b2 100644 --- a/packages/path_provider/path_provider_android/example/lib/main.dart +++ b/packages/path_provider/path_provider_android/example/lib/main.dart @@ -18,9 +18,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Path Provider', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'Path Provider'), ); } @@ -52,7 +50,9 @@ class _MyHomePageState extends State { } Widget _buildDirectory( - BuildContext context, AsyncSnapshot snapshot) { + BuildContext context, + AsyncSnapshot snapshot, + ) { Text text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -67,7 +67,9 @@ class _MyHomePageState extends State { } Widget _buildDirectories( - BuildContext context, AsyncSnapshot?> snapshot) { + BuildContext context, + AsyncSnapshot?> snapshot, + ) { Text text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -108,8 +110,9 @@ class _MyHomePageState extends State { void _requestExternalStorageDirectories(StorageDirectory type) { setState(() { - _externalStorageDirectories = - provider.getExternalStoragePaths(type: type); + _externalStorageDirectories = provider.getExternalStoragePaths( + type: type, + ); }); } @@ -128,9 +131,7 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: Center( child: ListView( children: [ @@ -142,7 +143,9 @@ class _MyHomePageState extends State { ), ), FutureBuilder( - future: _tempDirectory, builder: _buildDirectory), + future: _tempDirectory, + builder: _buildDirectory, + ), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -151,7 +154,9 @@ class _MyHomePageState extends State { ), ), FutureBuilder( - future: _appDocumentsDirectory, builder: _buildDirectory), + future: _appDocumentsDirectory, + builder: _buildDirectory, + ), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -160,7 +165,9 @@ class _MyHomePageState extends State { ), ), FutureBuilder( - future: _appSupportDirectory, builder: _buildDirectory), + future: _appSupportDirectory, + builder: _buildDirectory, + ), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -169,7 +176,9 @@ class _MyHomePageState extends State { ), ), FutureBuilder( - future: _appCacheDirectory, builder: _buildDirectory), + future: _appCacheDirectory, + builder: _buildDirectory, + ), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -178,34 +187,43 @@ class _MyHomePageState extends State { ), ), FutureBuilder( - future: _externalDocumentsDirectory, builder: _buildDirectory), - Column(children: [ - Padding( - padding: const EdgeInsets.all(16.0), - child: ElevatedButton( - child: const Text('Get External Storage Directories'), - onPressed: () { - _requestExternalStorageDirectories( - StorageDirectory.music, - ); - }, + future: _externalDocumentsDirectory, + builder: _buildDirectory, + ), + Column( + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: ElevatedButton( + child: const Text('Get External Storage Directories'), + onPressed: () { + _requestExternalStorageDirectories( + StorageDirectory.music, + ); + }, + ), ), - ), - ]), + ], + ), FutureBuilder?>( - future: _externalStorageDirectories, - builder: _buildDirectories), - Column(children: [ - Padding( - padding: const EdgeInsets.all(16.0), - child: ElevatedButton( - onPressed: _requestExternalCacheDirectories, - child: const Text('Get External Cache Directories'), + future: _externalStorageDirectories, + builder: _buildDirectories, + ), + Column( + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: ElevatedButton( + onPressed: _requestExternalCacheDirectories, + child: const Text('Get External Cache Directories'), + ), ), - ), - ]), + ], + ), FutureBuilder?>( - future: _externalCacheDirectories, builder: _buildDirectories), + future: _externalCacheDirectories, + builder: _buildDirectories, + ), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -214,7 +232,9 @@ class _MyHomePageState extends State { ), ), FutureBuilder( - future: _externalDownloadsDirectory, builder: _buildDirectory), + future: _externalDownloadsDirectory, + builder: _buildDirectory, + ), ], ), ), diff --git a/packages/path_provider/path_provider_android/example/pubspec.yaml b/packages/path_provider/path_provider_android/example/pubspec.yaml index c862b55a7c5..686559935fc 100644 --- a/packages/path_provider/path_provider_android/example/pubspec.yaml +++ b/packages/path_provider/path_provider_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_android/lib/messages.g.dart b/packages/path_provider/path_provider_android/lib/messages.g.dart index 20c0e9c2399..c7e9b2f8d4c 100644 --- a/packages/path_provider/path_provider_android/lib/messages.g.dart +++ b/packages/path_provider/path_provider_android/lib/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -74,11 +77,12 @@ class PathProviderApi { /// Constructor for [PathProviderApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - PathProviderApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + PathProviderApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -90,10 +94,10 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getTemporaryPath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -114,10 +118,10 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationSupportPath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -138,10 +142,10 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationDocumentsPath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -162,10 +166,10 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationCachePath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -186,10 +190,10 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -210,10 +214,10 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalCachePaths$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -235,15 +239,16 @@ class PathProviderApi { } Future> getExternalStoragePaths( - StorageDirectory directory) async { + StorageDirectory directory, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([directory]) as List?; if (pigeonVar_replyList == null) { diff --git a/packages/path_provider/path_provider_android/lib/path_provider_android.dart b/packages/path_provider/path_provider_android/lib/path_provider_android.dart index 2698e10ab63..5cc191e6e91 100644 --- a/packages/path_provider/path_provider_android/lib/path_provider_android.dart +++ b/packages/path_provider/path_provider_android/lib/path_provider_android.dart @@ -6,7 +6,8 @@ import 'package:path_provider_platform_interface/path_provider_platform_interfac import 'messages.g.dart' as messages; messages.StorageDirectory _convertStorageDirectory( - StorageDirectory? directory) { + StorageDirectory? directory, +) { switch (directory) { case null: return messages.StorageDirectory.root; @@ -86,8 +87,9 @@ class PathProviderAndroid extends PathProviderPlatform { @override Future getDownloadsPath() async { - final List paths = - await _getExternalStoragePaths(type: StorageDirectory.downloads); + final List paths = await _getExternalStoragePaths( + type: StorageDirectory.downloads, + ); return paths.isEmpty ? null : paths.first; } diff --git a/packages/path_provider/path_provider_android/pigeons/messages.dart b/packages/path_provider/path_provider_android/pigeons/messages.dart index c8db7ec55e1..30c43ea04b2 100644 --- a/packages/path_provider/path_provider_android/pigeons/messages.dart +++ b/packages/path_provider/path_provider_android/pigeons/messages.dart @@ -3,16 +3,20 @@ // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - input: 'pigeons/messages.dart', - javaOut: - 'android/src/main/java/io/flutter/plugins/pathprovider/Messages.java', - javaOptions: JavaOptions( - className: 'Messages', package: 'io.flutter.plugins.pathprovider'), - dartOut: 'lib/messages.g.dart', - dartTestOut: 'test/messages_test.g.dart', - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + input: 'pigeons/messages.dart', + javaOut: + 'android/src/main/java/io/flutter/plugins/pathprovider/Messages.java', + javaOptions: JavaOptions( + className: 'Messages', + package: 'io.flutter.plugins.pathprovider', + ), + dartOut: 'lib/messages.g.dart', + dartTestOut: 'test/messages_test.g.dart', + copyrightHeader: 'pigeons/copyright.txt', + ), +) enum StorageDirectory { root, music, diff --git a/packages/path_provider/path_provider_android/pubspec.yaml b/packages/path_provider/path_provider_android/pubspec.yaml index fe5ccc56f41..3fa880c1f97 100644 --- a/packages/path_provider/path_provider_android/pubspec.yaml +++ b/packages/path_provider/path_provider_android/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.2.17 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_android/test/messages_test.g.dart b/packages/path_provider/path_provider_android/test/messages_test.g.dart index 48b8e023862..f83da3ba092 100644 --- a/packages/path_provider/path_provider_android/test/messages_test.g.dart +++ b/packages/path_provider/path_provider_android/test/messages_test.g.dart @@ -67,193 +67,233 @@ abstract class TestPathProviderApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getTemporaryPath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getTemporaryPath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - final String? output = api.getTemporaryPath(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final String? output = api.getTemporaryPath(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationSupportPath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationSupportPath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - final String? output = api.getApplicationSupportPath(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final String? output = api.getApplicationSupportPath(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationDocumentsPath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationDocumentsPath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - final String? output = api.getApplicationDocumentsPath(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final String? output = api.getApplicationDocumentsPath(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationCachePath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getApplicationCachePath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - final String? output = api.getApplicationCachePath(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final String? output = api.getApplicationCachePath(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - final String? output = api.getExternalStoragePath(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final String? output = api.getExternalStoragePath(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalCachePaths$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalCachePaths$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - final List output = api.getExternalCachePaths(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final List output = api.getExternalCachePaths(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths was null.'); - final List args = (message as List?)!; - final StorageDirectory? arg_directory = - (args[0] as StorageDirectory?); - assert(arg_directory != null, - 'Argument for dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths was null, expected non-null StorageDirectory.'); - try { - final List output = - api.getExternalStoragePaths(arg_directory!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths was null.', + ); + final List args = (message as List?)!; + final StorageDirectory? arg_directory = + (args[0] as StorageDirectory?); + assert( + arg_directory != null, + 'Argument for dev.flutter.pigeon.path_provider_android.PathProviderApi.getExternalStoragePaths was null, expected non-null StorageDirectory.', + ); + try { + final List output = api.getExternalStoragePaths( + arg_directory!, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/packages/path_provider/path_provider_android/test/path_provider_android_test.dart b/packages/path_provider/path_provider_android/test/path_provider_android_test.dart index 440c5275a71..75149bc8b02 100644 --- a/packages/path_provider/path_provider_android/test/path_provider_android_test.dart +++ b/packages/path_provider/path_provider_android/test/path_provider_android_test.dart @@ -91,11 +91,12 @@ void main() { }); for (final StorageDirectory? type in [ - ...StorageDirectory.values + ...StorageDirectory.values, ]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { - final List? result = - await pathProvider.getExternalStoragePaths(type: type); + final List? result = await pathProvider.getExternalStoragePaths( + type: type, + ); expect(result!.length, 1); expect(result.first, kExternalStoragePaths); }); @@ -106,8 +107,7 @@ void main() { expect(path, kExternalStoragePaths); }); - test( - 'getDownloadsPath returns null, when getExternalStoragePaths returns ' + test('getDownloadsPath returns null, when getExternalStoragePaths returns ' 'an empty list', () async { final PathProviderAndroid pathProvider = PathProviderAndroid(); TestPathProviderApi.setUp(_Api(returnsExternalStoragePaths: false)); diff --git a/packages/path_provider/path_provider_foundation/CHANGELOG.md b/packages/path_provider/path_provider_foundation/CHANGELOG.md index 095dfc8da72..69433e8b306 100644 --- a/packages/path_provider/path_provider_foundation/CHANGELOG.md +++ b/packages/path_provider/path_provider_foundation/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 2.4.2 * Updates to Pigeon 25.5.0. diff --git a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart index 4436dc55f8f..711334b3cde 100644 --- a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart @@ -61,7 +61,8 @@ void main() { if (Platform.isIOS) { final PathProviderFoundation provider = PathProviderFoundation(); final String? result = await provider.getContainerPath( - appGroupIdentifier: 'group.flutter.appGroupTest'); + appGroupIdentifier: 'group.flutter.appGroupTest', + ); _verifySampleFile(result, 'appGroup'); } }); diff --git a/packages/path_provider/path_provider_foundation/example/lib/main.dart b/packages/path_provider/path_provider_foundation/example/lib/main.dart index c766ccf96e9..de0a510e800 100644 --- a/packages/path_provider/path_provider_foundation/example/lib/main.dart +++ b/packages/path_provider/path_provider_foundation/example/lib/main.dart @@ -78,7 +78,8 @@ class _MyAppState extends State { try { containerDirectory = await providerFoundation.getContainerPath( - appGroupIdentifier: 'group.flutter.appGroupTest'); + appGroupIdentifier: 'group.flutter.appGroupTest', + ); } catch (exception) { containerDirectory = 'Failed to get app group container directory: $exception'; @@ -105,9 +106,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Path Provider example app'), - ), + appBar: AppBar(title: const Text('Path Provider example app')), body: Center( child: Column( children: [ diff --git a/packages/path_provider/path_provider_foundation/example/pubspec.yaml b/packages/path_provider/path_provider_foundation/example/pubspec.yaml index 91c791764bf..6c2ff307a92 100644 --- a/packages/path_provider/path_provider_foundation/example/pubspec.yaml +++ b/packages/path_provider/path_provider_foundation/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_foundation/lib/messages.g.dart b/packages/path_provider/path_provider_foundation/lib/messages.g.dart index 2f994237733..892b73bd1fe 100644 --- a/packages/path_provider/path_provider_foundation/lib/messages.g.dart +++ b/packages/path_provider/path_provider_foundation/lib/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -69,11 +72,12 @@ class PathProviderApi { /// Constructor for [PathProviderApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - PathProviderApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + PathProviderApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -85,12 +89,13 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([type]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -111,12 +116,13 @@ class PathProviderApi { 'dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [appGroupIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([appGroupIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/path_provider/path_provider_foundation/lib/path_provider_foundation.dart b/packages/path_provider/path_provider_foundation/lib/path_provider_foundation.dart index 55e24c4f259..d769c09f3de 100644 --- a/packages/path_provider/path_provider_foundation/lib/path_provider_foundation.dart +++ b/packages/path_provider/path_provider_foundation/lib/path_provider_foundation.dart @@ -31,8 +31,9 @@ class PathProviderFoundation extends PathProviderPlatform { @override Future getApplicationSupportPath() async { - final String? path = - await _pathProvider.getDirectoryPath(DirectoryType.applicationSupport); + final String? path = await _pathProvider.getDirectoryPath( + DirectoryType.applicationSupport, + ); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. @@ -53,8 +54,9 @@ class PathProviderFoundation extends PathProviderPlatform { @override Future getApplicationCachePath() async { - final String? path = - await _pathProvider.getDirectoryPath(DirectoryType.applicationCache); + final String? path = await _pathProvider.getDirectoryPath( + DirectoryType.applicationCache, + ); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. @@ -66,13 +68,15 @@ class PathProviderFoundation extends PathProviderPlatform { @override Future getExternalStoragePath() async { throw UnsupportedError( - 'getExternalStoragePath is not supported on this platform'); + 'getExternalStoragePath is not supported on this platform', + ); } @override Future?> getExternalCachePaths() async { throw UnsupportedError( - 'getExternalCachePaths is not supported on this platform'); + 'getExternalCachePaths is not supported on this platform', + ); } @override @@ -80,7 +84,8 @@ class PathProviderFoundation extends PathProviderPlatform { StorageDirectory? type, }) async { throw UnsupportedError( - 'getExternalStoragePaths is not supported on this platform'); + 'getExternalStoragePaths is not supported on this platform', + ); } @override @@ -93,7 +98,8 @@ class PathProviderFoundation extends PathProviderPlatform { Future getContainerPath({required String appGroupIdentifier}) async { if (!_platformProvider.isIOS) { throw UnsupportedError( - 'getContainerPath is not supported on this platform'); + 'getContainerPath is not supported on this platform', + ); } return _pathProvider.getContainerPath(appGroupIdentifier); } diff --git a/packages/path_provider/path_provider_foundation/pigeons/messages.dart b/packages/path_provider/path_provider_foundation/pigeons/messages.dart index c7d5fdb834f..c1028d06df0 100644 --- a/packages/path_provider/path_provider_foundation/pigeons/messages.dart +++ b/packages/path_provider/path_provider_foundation/pigeons/messages.dart @@ -3,14 +3,16 @@ // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - input: 'pigeons/messages.dart', - swiftOut: - 'darwin/path_provider_foundation/Sources/path_provider_foundation/messages.g.swift', - dartOut: 'lib/messages.g.dart', - dartTestOut: 'test/messages_test.g.dart', - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + input: 'pigeons/messages.dart', + swiftOut: + 'darwin/path_provider_foundation/Sources/path_provider_foundation/messages.g.swift', + dartOut: 'lib/messages.g.dart', + dartTestOut: 'test/messages_test.g.dart', + copyrightHeader: 'pigeons/copyright.txt', + ), +) enum DirectoryType { applicationDocuments, applicationSupport, diff --git a/packages/path_provider/path_provider_foundation/pubspec.yaml b/packages/path_provider/path_provider_foundation/pubspec.yaml index f9232c8b5d6..d7ff1920389 100644 --- a/packages/path_provider/path_provider_foundation/pubspec.yaml +++ b/packages/path_provider/path_provider_foundation/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.2 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_foundation/test/messages_test.g.dart b/packages/path_provider/path_provider_foundation/test/messages_test.g.dart index 29ad5a4eacd..c5ae64af05d 100644 --- a/packages/path_provider/path_provider_foundation/test/messages_test.g.dart +++ b/packages/path_provider/path_provider_foundation/test/messages_test.g.dart @@ -57,68 +57,87 @@ abstract class TestPathProviderApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath was null.'); - final List args = (message as List?)!; - final DirectoryType? arg_type = (args[0] as DirectoryType?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath was null, expected non-null DirectoryType.'); - try { - final String? output = api.getDirectoryPath(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath was null.', + ); + final List args = (message as List?)!; + final DirectoryType? arg_type = (args[0] as DirectoryType?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getDirectoryPath was null, expected non-null DirectoryType.', + ); + try { + final String? output = api.getDirectoryPath(arg_type!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath was null.'); - final List args = (message as List?)!; - final String? arg_appGroupIdentifier = (args[0] as String?); - assert(arg_appGroupIdentifier != null, - 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath was null, expected non-null String.'); - try { - final String? output = - api.getContainerPath(arg_appGroupIdentifier!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath was null.', + ); + final List args = (message as List?)!; + final String? arg_appGroupIdentifier = (args[0] as String?); + assert( + arg_appGroupIdentifier != null, + 'Argument for dev.flutter.pigeon.path_provider_foundation.PathProviderApi.getContainerPath was null, expected non-null String.', + ); + try { + final String? output = api.getContainerPath( + arg_appGroupIdentifier!, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart index 4006af774f5..bc181296c9c 100644 --- a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart +++ b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart @@ -38,8 +38,9 @@ void main() { test('getTemporaryPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String temporaryPath = p.join(testRoot.path, 'temporary', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.temp)) - .thenReturn(temporaryPath); + when( + mockApi.getDirectoryPath(DirectoryType.temp), + ).thenReturn(temporaryPath); final String? path = await pathProvider.getTemporaryPath(); @@ -49,10 +50,15 @@ void main() { test('getApplicationSupportPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); - final String applicationSupportPath = - p.join(testRoot.path, 'application', 'support', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.applicationSupport)) - .thenReturn(applicationSupportPath); + final String applicationSupportPath = p.join( + testRoot.path, + 'application', + 'support', + 'path', + ); + when( + mockApi.getDirectoryPath(DirectoryType.applicationSupport), + ).thenReturn(applicationSupportPath); final String? path = await pathProvider.getApplicationSupportPath(); @@ -60,24 +66,32 @@ void main() { expect(path, applicationSupportPath); }); - test('getApplicationSupportPath creates the directory if necessary', - () async { - final PathProviderFoundation pathProvider = PathProviderFoundation(); - final String applicationSupportPath = - p.join(testRoot.path, 'application', 'support', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.applicationSupport)) - .thenReturn(applicationSupportPath); - - final String? path = await pathProvider.getApplicationSupportPath(); - - expect(Directory(path!).existsSync(), isTrue); - }); + test( + 'getApplicationSupportPath creates the directory if necessary', + () async { + final PathProviderFoundation pathProvider = PathProviderFoundation(); + final String applicationSupportPath = p.join( + testRoot.path, + 'application', + 'support', + 'path', + ); + when( + mockApi.getDirectoryPath(DirectoryType.applicationSupport), + ).thenReturn(applicationSupportPath); + + final String? path = await pathProvider.getApplicationSupportPath(); + + expect(Directory(path!).existsSync(), isTrue); + }, + ); test('getLibraryPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String libraryPath = p.join(testRoot.path, 'library', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.library)) - .thenReturn(libraryPath); + when( + mockApi.getDirectoryPath(DirectoryType.library), + ).thenReturn(libraryPath); final String? path = await pathProvider.getLibraryPath(); @@ -87,10 +101,15 @@ void main() { test('getApplicationDocumentsPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); - final String applicationDocumentsPath = - p.join(testRoot.path, 'application', 'documents', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.applicationDocuments)) - .thenReturn(applicationDocumentsPath); + final String applicationDocumentsPath = p.join( + testRoot.path, + 'application', + 'documents', + 'path', + ); + when( + mockApi.getDirectoryPath(DirectoryType.applicationDocuments), + ).thenReturn(applicationDocumentsPath); final String? path = await pathProvider.getApplicationDocumentsPath(); @@ -100,10 +119,15 @@ void main() { test('getApplicationCachePath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); - final String applicationCachePath = - p.join(testRoot.path, 'application', 'cache', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.applicationCache)) - .thenReturn(applicationCachePath); + final String applicationCachePath = p.join( + testRoot.path, + 'application', + 'cache', + 'path', + ); + when( + mockApi.getDirectoryPath(DirectoryType.applicationCache), + ).thenReturn(applicationCachePath); final String? path = await pathProvider.getApplicationCachePath(); @@ -111,24 +135,32 @@ void main() { expect(path, applicationCachePath); }); - test('getApplicationCachePath creates the directory if necessary', - () async { - final PathProviderFoundation pathProvider = PathProviderFoundation(); - final String applicationCachePath = - p.join(testRoot.path, 'application', 'cache', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.applicationCache)) - .thenReturn(applicationCachePath); - - final String? path = await pathProvider.getApplicationCachePath(); - - expect(Directory(path!).existsSync(), isTrue); - }); + test( + 'getApplicationCachePath creates the directory if necessary', + () async { + final PathProviderFoundation pathProvider = PathProviderFoundation(); + final String applicationCachePath = p.join( + testRoot.path, + 'application', + 'cache', + 'path', + ); + when( + mockApi.getDirectoryPath(DirectoryType.applicationCache), + ).thenReturn(applicationCachePath); + + final String? path = await pathProvider.getApplicationCachePath(); + + expect(Directory(path!).existsSync(), isTrue); + }, + ); test('getDownloadsPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String downloadsPath = p.join(testRoot.path, 'downloads', 'path'); - when(mockApi.getDirectoryPath(DirectoryType.downloads)) - .thenReturn(downloadsPath); + when( + mockApi.getDirectoryPath(DirectoryType.downloads), + ).thenReturn(downloadsPath); final String? result = await pathProvider.getDownloadsPath(); @@ -144,38 +176,46 @@ void main() { test('getExternalStoragePath throws', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); expect( - pathProvider.getExternalStoragePath(), throwsA(isUnsupportedError)); + pathProvider.getExternalStoragePath(), + throwsA(isUnsupportedError), + ); }); test('getExternalStoragePaths throws', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); expect( - pathProvider.getExternalStoragePaths(), throwsA(isUnsupportedError)); + pathProvider.getExternalStoragePaths(), + throwsA(isUnsupportedError), + ); }); test('getContainerPath', () async { - final PathProviderFoundation pathProvider = - PathProviderFoundation(platform: FakePlatformProvider(isIOS: true)); + final PathProviderFoundation pathProvider = PathProviderFoundation( + platform: FakePlatformProvider(isIOS: true), + ); const String appGroupIdentifier = 'group.example.test'; final String containerPath = p.join(testRoot.path, 'container', 'path'); - when(mockApi.getContainerPath(appGroupIdentifier)) - .thenReturn(containerPath); + when( + mockApi.getContainerPath(appGroupIdentifier), + ).thenReturn(containerPath); final String? result = await pathProvider.getContainerPath( - appGroupIdentifier: appGroupIdentifier); + appGroupIdentifier: appGroupIdentifier, + ); verify(mockApi.getContainerPath(appGroupIdentifier)); expect(result, containerPath); }); test('getContainerPath throws on macOS', () async { - final PathProviderFoundation pathProvider = - PathProviderFoundation(platform: FakePlatformProvider(isIOS: false)); + final PathProviderFoundation pathProvider = PathProviderFoundation( + platform: FakePlatformProvider(isIOS: false), + ); expect( - pathProvider.getContainerPath( - appGroupIdentifier: 'group.example.test'), - throwsA(isUnsupportedError)); + pathProvider.getContainerPath(appGroupIdentifier: 'group.example.test'), + throwsA(isUnsupportedError), + ); }); }); } diff --git a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.mocks.dart b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.mocks.dart index a8b109ff1b9..93cb1ad2a48 100644 --- a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.mocks.dart +++ b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.mocks.dart @@ -32,15 +32,13 @@ class MockTestPathProviderApi extends _i1.Mock @override String? getDirectoryPath(_i3.DirectoryType? type) => - (super.noSuchMethod(Invocation.method( - #getDirectoryPath, - [type], - )) as String?); + (super.noSuchMethod(Invocation.method(#getDirectoryPath, [type])) + as String?); @override String? getContainerPath(String? appGroupIdentifier) => - (super.noSuchMethod(Invocation.method( - #getContainerPath, - [appGroupIdentifier], - )) as String?); + (super.noSuchMethod( + Invocation.method(#getContainerPath, [appGroupIdentifier]), + ) + as String?); } diff --git a/packages/path_provider/path_provider_linux/CHANGELOG.md b/packages/path_provider/path_provider_linux/CHANGELOG.md index 3b65f376a9e..c7724b7ae6f 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.2.1 diff --git a/packages/path_provider/path_provider_linux/example/lib/main.dart b/packages/path_provider/path_provider_linux/example/lib/main.dart index 3cbb6915277..cd2941240da 100644 --- a/packages/path_provider/path_provider_linux/example/lib/main.dart +++ b/packages/path_provider/path_provider_linux/example/lib/main.dart @@ -89,9 +89,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Path Provider Linux example app'), - ), + appBar: AppBar(title: const Text('Path Provider Linux example app')), body: Center( child: Column( children: [ diff --git a/packages/path_provider/path_provider_linux/example/pubspec.yaml b/packages/path_provider/path_provider_linux/example/pubspec.yaml index d81f04241da..451663c06e3 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart b/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart index 5e16df06c41..a6f2986eed4 100644 --- a/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart +++ b/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart @@ -38,7 +38,8 @@ class GioUtils { } final _GApplicationGetDefaultDart getDefault = _gio! .lookupFunction<_GApplicationGetDefaultC, _GApplicationGetDefaultDart>( - 'g_application_get_default'); + 'g_application_get_default', + ); return getDefault(); } @@ -48,9 +49,10 @@ class GioUtils { return nullptr; } final _GApplicationGetApplicationIdDart gApplicationGetApplicationId = _gio! - .lookupFunction<_GApplicationGetApplicationIdC, - _GApplicationGetApplicationIdDart>( - 'g_application_get_application_id'); + .lookupFunction< + _GApplicationGetApplicationIdC, + _GApplicationGetApplicationIdDart + >('g_application_get_application_id'); return gApplicationGetApplicationId(app); } } diff --git a/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart b/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart index 59097114d3a..86eb2f03cb6 100644 --- a/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart +++ b/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart @@ -20,13 +20,13 @@ class PathProviderLinux extends PathProviderPlatform { /// Constructs an instance of [PathProviderLinux] with the given [environment] @visibleForTesting - PathProviderLinux.private( - {Map environment = const {}, - String? executableName, - String? applicationId}) - : _environment = environment, - _executableName = executableName, - _applicationId = applicationId; + PathProviderLinux.private({ + Map environment = const {}, + String? executableName, + String? applicationId, + }) : _environment = environment, + _executableName = executableName, + _applicationId = applicationId; final Map _environment; String? _executableName; @@ -47,16 +47,18 @@ class PathProviderLinux extends PathProviderPlatform { @override Future getApplicationSupportPath() async { - final Directory directory = - Directory(path.join(xdg.dataHome.path, await _getId())); + final Directory directory = Directory( + path.join(xdg.dataHome.path, await _getId()), + ); if (directory.existsSync()) { return directory.path; } // This plugin originally used the executable name as a directory. // Use that if it exists for backwards compatibility. - final Directory legacyDirectory = - Directory(path.join(xdg.dataHome.path, await _getExecutableName())); + final Directory legacyDirectory = Directory( + path.join(xdg.dataHome.path, await _getExecutableName()), + ); if (legacyDirectory.existsSync()) { return legacyDirectory.path; } @@ -73,8 +75,9 @@ class PathProviderLinux extends PathProviderPlatform { @override Future getApplicationCachePath() async { - final Directory directory = - Directory(path.join(xdg.cacheHome.path, await _getId())); + final Directory directory = Directory( + path.join(xdg.cacheHome.path, await _getId()), + ); if (!directory.existsSync()) { await directory.create(recursive: true); } @@ -89,7 +92,8 @@ class PathProviderLinux extends PathProviderPlatform { // Gets the name of this executable. Future _getExecutableName() async { _executableName ??= path.basenameWithoutExtension( - await File('/proc/self/exe').resolveSymbolicLinks()); + await File('/proc/self/exe').resolveSymbolicLinks(), + ); return _executableName!; } diff --git a/packages/path_provider/path_provider_linux/pubspec.yaml b/packages/path_provider/path_provider_linux/pubspec.yaml index 9b34cc180b5..9b8f8b7622e 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart b/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart index b5dfcce1501..f3ad93efe6d 100644 --- a/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart +++ b/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart @@ -37,20 +37,28 @@ void main() { test('getApplicationSupportPath', () async { final PathProviderPlatform plugin = PathProviderLinux.private( - executableName: 'path_provider_linux_test_binary', - applicationId: 'com.example.Test'); + executableName: 'path_provider_linux_test_binary', + applicationId: 'com.example.Test', + ); // Note this will fail if ${xdg.dataHome.path}/path_provider_linux_test_binary exists on the local filesystem. - expect(await plugin.getApplicationSupportPath(), - '${xdg.dataHome.path}/com.example.Test'); + expect( + await plugin.getApplicationSupportPath(), + '${xdg.dataHome.path}/com.example.Test', + ); }); - test('getApplicationSupportPath uses executable name if no application Id', - () async { - final PathProviderPlatform plugin = PathProviderLinux.private( - executableName: 'path_provider_linux_test_binary'); - expect(await plugin.getApplicationSupportPath(), - '${xdg.dataHome.path}/path_provider_linux_test_binary'); - }); + test( + 'getApplicationSupportPath uses executable name if no application Id', + () async { + final PathProviderPlatform plugin = PathProviderLinux.private( + executableName: 'path_provider_linux_test_binary', + ); + expect( + await plugin.getApplicationSupportPath(), + '${xdg.dataHome.path}/path_provider_linux_test_binary', + ); + }, + ); test('getApplicationDocumentsPath', () async { final PathProviderPlatform plugin = PathProviderPlatform.instance; @@ -59,9 +67,12 @@ void main() { test('getApplicationCachePath', () async { final PathProviderPlatform plugin = PathProviderLinux.private( - executableName: 'path_provider_linux_test_binary'); - expect(await plugin.getApplicationCachePath(), - '${xdg.cacheHome.path}/path_provider_linux_test_binary'); + executableName: 'path_provider_linux_test_binary', + ); + expect( + await plugin.getApplicationCachePath(), + '${xdg.cacheHome.path}/path_provider_linux_test_binary', + ); }); test('getDownloadsPath', () async { diff --git a/packages/path_provider/path_provider_platform_interface/CHANGELOG.md b/packages/path_provider/path_provider_platform_interface/CHANGELOG.md index 1e0e66e53e1..85fa835990b 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.1.2 diff --git a/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart b/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart index 682d1ef0387..2f95c66431c 100644 --- a/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart +++ b/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart @@ -46,7 +46,8 @@ abstract class PathProviderPlatform extends PlatformInterface { /// files. Future getApplicationSupportPath() { throw UnimplementedError( - 'getApplicationSupportPath() has not been implemented.'); + 'getApplicationSupportPath() has not been implemented.', + ); } /// Path to the directory where application can store files that are persistent, @@ -59,13 +60,15 @@ abstract class PathProviderPlatform extends PlatformInterface { /// user-generated, or that cannot otherwise be recreated by your application. Future getApplicationDocumentsPath() { throw UnimplementedError( - 'getApplicationDocumentsPath() has not been implemented.'); + 'getApplicationDocumentsPath() has not been implemented.', + ); } /// Path to a directory where application specific cache data can be stored. Future getApplicationCachePath() { throw UnimplementedError( - 'getApplicationCachePath() has not been implemented.'); + 'getApplicationCachePath() has not been implemented.', + ); } /// Path to a directory where the application may access top level storage. @@ -73,7 +76,8 @@ abstract class PathProviderPlatform extends PlatformInterface { /// function call, as this functionality is only available on Android. Future getExternalStoragePath() { throw UnimplementedError( - 'getExternalStoragePath() has not been implemented.'); + 'getExternalStoragePath() has not been implemented.', + ); } /// Paths to directories where application specific external cache data can be @@ -82,7 +86,8 @@ abstract class PathProviderPlatform extends PlatformInterface { /// available. Future?> getExternalCachePaths() { throw UnimplementedError( - 'getExternalCachePaths() has not been implemented.'); + 'getExternalCachePaths() has not been implemented.', + ); } /// Paths to directories where application specific data can be stored. @@ -94,7 +99,8 @@ abstract class PathProviderPlatform extends PlatformInterface { StorageDirectory? type, }) { throw UnimplementedError( - 'getExternalStoragePaths() has not been implemented.'); + 'getExternalStoragePaths() has not been implemented.', + ); } /// Path to the directory where downloaded files can be stored. diff --git a/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart b/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart index 02729f89616..72fc7548a5c 100644 --- a/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart +++ b/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart @@ -12,8 +12,9 @@ import '../path_provider_platform_interface.dart'; class MethodChannelPathProvider extends PathProviderPlatform { /// The method channel used to interact with the native platform. @visibleForTesting - MethodChannel methodChannel = - const MethodChannel('plugins.flutter.io/path_provider'); + MethodChannel methodChannel = const MethodChannel( + 'plugins.flutter.io/path_provider', + ); // Ideally, this property shouldn't exist, and each platform should // just implement the supported methods. Once all the platforms are @@ -48,8 +49,9 @@ class MethodChannelPathProvider extends PathProviderPlatform { @override Future getApplicationDocumentsPath() { - return methodChannel - .invokeMethod('getApplicationDocumentsDirectory'); + return methodChannel.invokeMethod( + 'getApplicationDocumentsDirectory', + ); } @override @@ -70,8 +72,9 @@ class MethodChannelPathProvider extends PathProviderPlatform { if (!_platform.isAndroid) { throw UnsupportedError('Functionality only available on Android'); } - return methodChannel - .invokeListMethod('getExternalCacheDirectories'); + return methodChannel.invokeListMethod( + 'getExternalCacheDirectories', + ); } @override diff --git a/packages/path_provider/path_provider_platform_interface/pubspec.yaml b/packages/path_provider/path_provider_platform_interface/pubspec.yaml index f30102df552..84360484e9e 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 0b128dd9c7c..2d70d00bf31 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 @@ -27,35 +27,37 @@ void main() { methodChannelPathProvider = MethodChannelPathProvider(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(methodChannelPathProvider.methodChannel, - (MethodCall methodCall) async { - log.add(methodCall); - switch (methodCall.method) { - case 'getTemporaryDirectory': - return kTemporaryPath; - case 'getApplicationSupportDirectory': - return kApplicationSupportPath; - case 'getLibraryDirectory': - return kLibraryPath; - case 'getApplicationDocumentsDirectory': - return kApplicationDocumentsPath; - case 'getApplicationCacheDirectory': - return kApplicationCachePath; - case 'getExternalStorageDirectories': - return [kExternalStoragePaths]; - case 'getExternalCacheDirectories': - return [kExternalCachePaths]; - case 'getDownloadsDirectory': - return kDownloadsPath; - default: - return null; - } - }); + .setMockMethodCallHandler(methodChannelPathProvider.methodChannel, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + switch (methodCall.method) { + case 'getTemporaryDirectory': + return kTemporaryPath; + case 'getApplicationSupportDirectory': + return kApplicationSupportPath; + case 'getLibraryDirectory': + return kLibraryPath; + case 'getApplicationDocumentsDirectory': + return kApplicationDocumentsPath; + case 'getApplicationCacheDirectory': + return kApplicationCachePath; + case 'getExternalStorageDirectories': + return [kExternalStoragePaths]; + case 'getExternalCacheDirectories': + return [kExternalCachePaths]; + case 'getDownloadsDirectory': + return kDownloadsPath; + default: + return null; + } + }); }); setUp(() { methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'android')); + FakePlatform(operatingSystem: 'android'), + ); }); tearDown(() { @@ -64,22 +66,18 @@ void main() { test('getTemporaryPath', () async { final String? path = await methodChannelPathProvider.getTemporaryPath(); - expect( - log, - [isMethodCall('getTemporaryDirectory', arguments: null)], - ); + expect(log, [ + isMethodCall('getTemporaryDirectory', arguments: null), + ]); expect(path, kTemporaryPath); }); test('getApplicationSupportPath', () async { final String? path = await methodChannelPathProvider.getApplicationSupportPath(); - expect( - log, - [ - isMethodCall('getApplicationSupportDirectory', arguments: null) - ], - ); + expect(log, [ + isMethodCall('getApplicationSupportDirectory', arguments: null), + ]); expect(path, kApplicationSupportPath); }); @@ -93,67 +91,61 @@ void main() { }); test('getLibraryPath iOS succeeds', () async { - methodChannelPathProvider - .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); + methodChannelPathProvider.setMockPathProviderPlatform( + FakePlatform(operatingSystem: 'ios'), + ); final String? path = await methodChannelPathProvider.getLibraryPath(); - expect( - log, - [isMethodCall('getLibraryDirectory', arguments: null)], - ); + expect(log, [ + isMethodCall('getLibraryDirectory', arguments: null), + ]); expect(path, kLibraryPath); }); test('getLibraryPath macOS succeeds', () async { - methodChannelPathProvider - .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'macos')); + methodChannelPathProvider.setMockPathProviderPlatform( + FakePlatform(operatingSystem: 'macos'), + ); final String? path = await methodChannelPathProvider.getLibraryPath(); - expect( - log, - [isMethodCall('getLibraryDirectory', arguments: null)], - ); + expect(log, [ + isMethodCall('getLibraryDirectory', arguments: null), + ]); expect(path, kLibraryPath); }); test('getApplicationDocumentsPath', () async { final String? path = await methodChannelPathProvider.getApplicationDocumentsPath(); - expect( - log, - [ - isMethodCall('getApplicationDocumentsDirectory', arguments: null) - ], - ); + expect(log, [ + isMethodCall('getApplicationDocumentsDirectory', arguments: null), + ]); expect(path, kApplicationDocumentsPath); }); test('getApplicationCachePath succeeds', () async { final String? result = await methodChannelPathProvider.getApplicationCachePath(); - expect( - log, - [ - isMethodCall('getApplicationCacheDirectory', arguments: null) - ], - ); + expect(log, [ + isMethodCall('getApplicationCacheDirectory', arguments: null), + ]); expect(result, kApplicationCachePath); }); test('getExternalCachePaths android succeeds', () async { final List? result = await methodChannelPathProvider.getExternalCachePaths(); - expect( - log, - [isMethodCall('getExternalCacheDirectories', arguments: null)], - ); + expect(log, [ + isMethodCall('getExternalCacheDirectories', arguments: null), + ]); expect(result!.length, 1); expect(result.first, kExternalCachePaths); }); test('getExternalCachePaths non-android fails', () async { - methodChannelPathProvider - .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); + methodChannelPathProvider.setMockPathProviderPlatform( + FakePlatform(operatingSystem: 'ios'), + ); try { await methodChannelPathProvider.getExternalCachePaths(); @@ -165,28 +157,26 @@ void main() { for (final StorageDirectory? type in [ null, - ...StorageDirectory.values + ...StorageDirectory.values, ]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { - final List? result = - await methodChannelPathProvider.getExternalStoragePaths(type: type); - expect( - log, - [ - isMethodCall( - 'getExternalStorageDirectories', - arguments: {'type': type?.index}, - ) - ], - ); + final List? result = await methodChannelPathProvider + .getExternalStoragePaths(type: type); + expect(log, [ + isMethodCall( + 'getExternalStorageDirectories', + arguments: {'type': type?.index}, + ), + ]); expect(result!.length, 1); expect(result.first, kExternalStoragePaths); }); test('getExternalStoragePaths (type: $type) non-android fails', () async { - methodChannelPathProvider - .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); + methodChannelPathProvider.setMockPathProviderPlatform( + FakePlatform(operatingSystem: 'ios'), + ); try { await methodChannelPathProvider.getExternalStoragePaths(); @@ -198,19 +188,20 @@ void main() { } // end of for-loop test('getDownloadsPath macos succeeds', () async { - methodChannelPathProvider - .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'macos')); - final String? result = await methodChannelPathProvider.getDownloadsPath(); - expect( - log, - [isMethodCall('getDownloadsDirectory', arguments: null)], + methodChannelPathProvider.setMockPathProviderPlatform( + FakePlatform(operatingSystem: 'macos'), ); + final String? result = await methodChannelPathProvider.getDownloadsPath(); + expect(log, [ + isMethodCall('getDownloadsDirectory', arguments: null), + ]); expect(result, kDownloadsPath); }); test('getDownloadsPath non-macos fails', () async { methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'android')); + FakePlatform(operatingSystem: 'android'), + ); try { await methodChannelPathProvider.getDownloadsPath(); fail('should throw UnsupportedError'); diff --git a/packages/path_provider/path_provider_windows/CHANGELOG.md b/packages/path_provider/path_provider_windows/CHANGELOG.md index d378f151c3c..75dcca7713b 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.3.0 diff --git a/packages/path_provider/path_provider_windows/example/lib/main.dart b/packages/path_provider/path_provider_windows/example/lib/main.dart index 53e46e517d0..d4a89168ef8 100644 --- a/packages/path_provider/path_provider_windows/example/lib/main.dart +++ b/packages/path_provider/path_provider_windows/example/lib/main.dart @@ -83,9 +83,7 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Path Provider example app'), - ), + appBar: AppBar(title: const Text('Path Provider example app')), body: Center( child: Column( children: [ diff --git a/packages/path_provider/path_provider_windows/example/pubspec.yaml b/packages/path_provider/path_provider_windows/example/pubspec.yaml index 122136adaa3..2a6b65176f7 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_windows/lib/src/guid.dart b/packages/path_provider/path_provider_windows/lib/src/guid.dart index 84daffe6bed..7815aa53b83 100644 --- a/packages/path_provider/path_provider_windows/lib/src/guid.dart +++ b/packages/path_provider/path_provider_windows/lib/src/guid.dart @@ -37,7 +37,9 @@ base class GUID extends Struct { final ByteData bytes = ByteData(16); for (int i = 0; i < 16; ++i) { bytes.setUint8( - i, int.parse(hexOnly.substring(i * 2, i * 2 + 2), radix: 16)); + i, + int.parse(hexOnly.substring(i * 2, i * 2 + 2), radix: 16), + ); } data1 = bytes.getInt32(0); data2 = bytes.getInt16(4); 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 50f010ba56f..c24948bc8eb 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 @@ -162,10 +162,18 @@ class PathProviderWindows extends PathProviderPlatform { } String? _getStringValue(Pointer? infoBuffer, String key) => - versionInfoQuerier.getStringValue(infoBuffer, key, - language: languageEn, encoding: encodingCP1252) ?? - versionInfoQuerier.getStringValue(infoBuffer, key, - language: languageEn, encoding: encodingUnicode); + versionInfoQuerier.getStringValue( + infoBuffer, + key, + language: languageEn, + encoding: encodingCP1252, + ) ?? + versionInfoQuerier.getStringValue( + infoBuffer, + key, + language: languageEn, + encoding: encodingUnicode, + ); /// Returns the relative path string to append to the root directory returned /// by Win32 APIs for application storage (such as RoamingAppDir) to get a @@ -187,8 +195,11 @@ class PathProviderWindows extends PathProviderPlatform { Pointer? infoBuffer; try { // Get the module name. - final int moduleNameLength = - GetModuleFileName(0, moduleNameBuffer, MAX_PATH); + final int moduleNameLength = GetModuleFileName( + 0, + moduleNameBuffer, + MAX_PATH, + ); if (moduleNameLength == 0) { final int error = GetLastError(); throw _createWin32Exception(error); @@ -204,14 +215,17 @@ class PathProviderWindows extends PathProviderPlatform { infoBuffer = null; } } - companyName = - _sanitizedDirectoryName(_getStringValue(infoBuffer, 'CompanyName')); - productName = - _sanitizedDirectoryName(_getStringValue(infoBuffer, 'ProductName')); + companyName = _sanitizedDirectoryName( + _getStringValue(infoBuffer, 'CompanyName'), + ); + productName = _sanitizedDirectoryName( + _getStringValue(infoBuffer, 'ProductName'), + ); // If there was no product name, use the executable name. - productName ??= - path.basenameWithoutExtension(moduleNameBuffer.toDartString()); + productName ??= path.basenameWithoutExtension( + moduleNameBuffer.toDartString(), + ); return companyName != null ? path.join(companyName, productName) @@ -252,8 +266,9 @@ class PathProviderWindows extends PathProviderPlatform { if (baseDir == null) { return null; } - final Directory directory = - Directory(path.join(baseDir, _getApplicationSpecificSubdirectory())); + final Directory directory = Directory( + path.join(baseDir, _getApplicationSpecificSubdirectory()), + ); // Ensure that the directory exists if possible, since it will on other // platforms. If the name is longer than MAXPATH, creating will fail, so // skip that step; it's up to the client to decide what to do with the path @@ -269,12 +284,13 @@ class PathProviderWindows extends PathProviderPlatform { Exception _createWin32Exception(int errorCode) { return PlatformException( - code: 'Win32 Error', - // TODO(stuartmorgan): Consider getting the system error message via - // FormatMessage if it turns out to be necessary for debugging issues. - // Plugin-client-level usability isn't a major consideration since per - // https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#platform-exception-handling - // any case that comes up in practice should be handled and returned - // via a plugin-specific exception, not this fallback. - message: 'Error code 0x${errorCode.toRadixString(16)}'); + code: 'Win32 Error', + // TODO(stuartmorgan): Consider getting the system error message via + // FormatMessage if it turns out to be necessary for debugging issues. + // Plugin-client-level usability isn't a major consideration since per + // https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#platform-exception-handling + // any case that comes up in practice should be handled and returned + // via a plugin-specific exception, not this fallback. + message: 'Error code 0x${errorCode.toRadixString(16)}', + ); } diff --git a/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart b/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart index a39488eb0a0..d03f946b21d 100644 --- a/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart +++ b/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart @@ -52,33 +52,38 @@ final DynamicLibrary _dllVersion = DynamicLibrary.open('version.dll'); final DynamicLibrary _dllShell32 = DynamicLibrary.open('shell32.dll'); // https://learn.microsoft.com/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath -typedef _FFITypeSHGetKnownFolderPath = HRESULT Function( - Pointer, DWORD, HANDLE, PWSTR); -typedef FFITypeSHGetKnownFolderPathDart = int Function( - Pointer, int, int, Pointer>); +typedef _FFITypeSHGetKnownFolderPath = + HRESULT Function(Pointer, DWORD, HANDLE, PWSTR); +typedef FFITypeSHGetKnownFolderPathDart = + int Function(Pointer, int, int, Pointer>); // ignore: non_constant_identifier_names -final FFITypeSHGetKnownFolderPathDart SHGetKnownFolderPath = - _dllShell32.lookupFunction<_FFITypeSHGetKnownFolderPath, - FFITypeSHGetKnownFolderPathDart>('SHGetKnownFolderPath'); +final FFITypeSHGetKnownFolderPathDart SHGetKnownFolderPath = _dllShell32 + .lookupFunction< + _FFITypeSHGetKnownFolderPath, + FFITypeSHGetKnownFolderPathDart + >('SHGetKnownFolderPath'); // https://learn.microsoft.com/windows/win32/api/winver/nf-winver-getfileversioninfow -typedef _FFITypeGetFileVersionInfoW = BOOL Function( - LPCWSTR, DWORD, DWORD, LPVOID); -typedef FFITypeGetFileVersionInfoW = int Function( - Pointer, int, int, Pointer); +typedef _FFITypeGetFileVersionInfoW = + BOOL Function(LPCWSTR, DWORD, DWORD, LPVOID); +typedef FFITypeGetFileVersionInfoW = + int Function(Pointer, int, int, Pointer); // ignore: non_constant_identifier_names final FFITypeGetFileVersionInfoW GetFileVersionInfo = _dllVersion .lookupFunction<_FFITypeGetFileVersionInfoW, FFITypeGetFileVersionInfoW>( - 'GetFileVersionInfoW'); + 'GetFileVersionInfoW', + ); // https://learn.microsoft.com/windows/win32/api/winver/nf-winver-getfileversioninfosizew typedef _FFITypeGetFileVersionInfoSizeW = DWORD Function(LPCWSTR, LPDWORD); -typedef FFITypeGetFileVersionInfoSizeW = int Function( - Pointer, Pointer); +typedef FFITypeGetFileVersionInfoSizeW = + int Function(Pointer, Pointer); // ignore: non_constant_identifier_names -final FFITypeGetFileVersionInfoSizeW GetFileVersionInfoSize = - _dllVersion.lookupFunction<_FFITypeGetFileVersionInfoSizeW, - FFITypeGetFileVersionInfoSizeW>('GetFileVersionInfoSizeW'); +final FFITypeGetFileVersionInfoSizeW GetFileVersionInfoSize = _dllVersion + .lookupFunction< + _FFITypeGetFileVersionInfoSizeW, + FFITypeGetFileVersionInfoSizeW + >('GetFileVersionInfoSizeW'); // https://learn.microsoft.com/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror typedef _FFITypeGetLastError = DWORD Function(); @@ -91,18 +96,25 @@ final FFITypeGetLastError GetLastError = _dllKernel32 typedef _FFITypeGetModuleFileNameW = DWORD Function(HMODULE, LPWSTR, DWORD); typedef FFITypeGetModuleFileNameW = int Function(int, Pointer, int); // ignore: non_constant_identifier_names -final FFITypeGetModuleFileNameW GetModuleFileName = _dllKernel32.lookupFunction< - _FFITypeGetModuleFileNameW, - FFITypeGetModuleFileNameW>('GetModuleFileNameW'); +final FFITypeGetModuleFileNameW GetModuleFileName = _dllKernel32 + .lookupFunction<_FFITypeGetModuleFileNameW, FFITypeGetModuleFileNameW>( + 'GetModuleFileNameW', + ); // https://learn.microsoft.com/windows/win32/api/winver/nf-winver-verqueryvaluew typedef _FFITypeVerQueryValueW = BOOL Function(LPCVOID, LPCWSTR, LPVOID, PUINT); -typedef FFITypeVerQueryValueW = int Function( - Pointer, Pointer, Pointer, Pointer); +typedef FFITypeVerQueryValueW = + int Function( + Pointer, + Pointer, + Pointer, + Pointer, + ); // ignore: non_constant_identifier_names -final FFITypeVerQueryValueW VerQueryValue = - _dllVersion.lookupFunction<_FFITypeVerQueryValueW, FFITypeVerQueryValueW>( - 'VerQueryValueW'); +final FFITypeVerQueryValueW VerQueryValue = _dllVersion + .lookupFunction<_FFITypeVerQueryValueW, FFITypeVerQueryValueW>( + 'VerQueryValueW', + ); // https://learn.microsoft.com/windows/win32/api/fileapi/nf-fileapi-gettemppathw typedef _FFITypeGetTempPathW = DWORD Function(DWORD, LPWSTR); diff --git a/packages/path_provider/path_provider_windows/pubspec.yaml b/packages/path_provider/path_provider_windows/pubspec.yaml index bd0fd9197d5..b2e20e6a968 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 561ad3b87d6..afb199e5840 100644 --- a/packages/path_provider/path_provider_windows/test/guid_test.dart +++ b/packages/path_provider/path_provider_windows/test/guid_test.dart @@ -11,13 +11,14 @@ 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); @@ -39,10 +40,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/path_provider/path_provider_windows/test/path_provider_windows_test.dart b/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart index f60b70fb39d..d74e3396597 100644 --- a/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart +++ b/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart @@ -51,8 +51,9 @@ void main() { test('getApplicationSupportPath with no version info', () async { final PathProviderWindows pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = - FakeVersionInfoQuerier({}); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier( + {}, + ); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, contains(r'C:\')); expect(path, contains(r'AppData')); @@ -60,48 +61,62 @@ void main() { expect(path, endsWith(r'flutter_tester')); }, skip: !Platform.isWindows); - test('getApplicationSupportPath with full version info in CP1252', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': 'A Company', - 'ProductName': 'Amazing App', - }, encoding: encodingCP1252); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, isNotNull); - if (path != null) { - expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); - expect(Directory(path).existsSync(), isTrue); - } - }, skip: !Platform.isWindows); + test( + 'getApplicationSupportPath with full version info in CP1252', + () async { + final PathProviderWindows pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ + 'CompanyName': 'A Company', + 'ProductName': 'Amazing App', + }, encoding: encodingCP1252); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, isNotNull); + if (path != null) { + expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); + expect(Directory(path).existsSync(), isTrue); + } + }, + skip: !Platform.isWindows, + ); - test('getApplicationSupportPath with full version info in Unicode', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': 'A Company', - 'ProductName': 'Amazing App', - }); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, isNotNull); - if (path != null) { - expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); - expect(Directory(path).existsSync(), isTrue); - } - }, skip: !Platform.isWindows); + test( + 'getApplicationSupportPath with full version info in Unicode', + () async { + final PathProviderWindows pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ + 'CompanyName': 'A Company', + 'ProductName': 'Amazing App', + }); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, isNotNull); + if (path != null) { + expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); + expect(Directory(path).existsSync(), isTrue); + } + }, + skip: !Platform.isWindows, + ); test( - 'getApplicationSupportPath with full version info in Unsupported Encoding', - () async { - final PathProviderWindows pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': 'A Company', - 'ProductName': 'Amazing App', - }, language: '0000', encoding: '0000'); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, contains(r'C:\')); - expect(path, contains(r'AppData')); - // The last path component should be the executable name. - expect(path, endsWith(r'flutter_tester')); - }, skip: !Platform.isWindows); + 'getApplicationSupportPath with full version info in Unsupported Encoding', + () async { + final PathProviderWindows pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier( + { + 'CompanyName': 'A Company', + 'ProductName': 'Amazing App', + }, + language: '0000', + encoding: '0000', + ); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, contains(r'C:\')); + expect(path, contains(r'AppData')); + // The last path component should be the executable name. + expect(path, endsWith(r'flutter_tester')); + }, + skip: !Platform.isWindows, + ); test('getApplicationSupportPath with missing company', () async { final PathProviderWindows pathProvider = PathProviderWindows(); @@ -126,26 +141,32 @@ void main() { expect(path, isNotNull); if (path != null) { expect( - path, - endsWith( - r'AppData\Roaming\A _Bad_ Company_ Name\A__Terrible__App__Name')); + path, + endsWith( + r'AppData\Roaming\A _Bad_ Company_ Name\A__Terrible__App__Name', + ), + ); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); - test('getApplicationSupportPath with a completely invalid company', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': r'..', - 'ProductName': r'Amazing App', - }); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, isNotNull); - if (path != null) { - expect(path, endsWith(r'AppData\Roaming\Amazing App')); - expect(Directory(path).existsSync(), isTrue); - } - }, skip: !Platform.isWindows); + test( + 'getApplicationSupportPath with a completely invalid company', + () async { + final PathProviderWindows pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ + 'CompanyName': r'..', + 'ProductName': r'Amazing App', + }); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, isNotNull); + if (path != null) { + expect(path, endsWith(r'AppData\Roaming\Amazing App')); + expect(Directory(path).existsSync(), isTrue); + } + }, + skip: !Platform.isWindows, + ); test('getApplicationSupportPath with very long app name', () async { final PathProviderWindows pathProvider = PathProviderWindows(); diff --git a/packages/pigeon/CHANGELOG.md b/packages/pigeon/CHANGELOG.md index 5ebc530e42b..d36975e5b0f 100644 --- a/packages/pigeon/CHANGELOG.md +++ b/packages/pigeon/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 26.0.1 * Improves documentation of `ProxyApi` annotation and internal Dart ProxyAPI helper functions. diff --git a/packages/pigeon/example/README.md b/packages/pigeon/example/README.md index d885e7e304b..b3e895b26c6 100644 --- a/packages/pigeon/example/README.md +++ b/packages/pigeon/example/README.md @@ -13,29 +13,31 @@ needed for your project. ```dart -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - dartOptions: DartOptions(), - cppOptions: CppOptions(namespace: 'pigeon_example'), - cppHeaderOut: 'windows/runner/messages.g.h', - cppSourceOut: 'windows/runner/messages.g.cpp', - gobjectHeaderOut: 'linux/messages.g.h', - gobjectSourceOut: 'linux/messages.g.cc', - gobjectOptions: GObjectOptions(), - kotlinOut: - 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt', - kotlinOptions: KotlinOptions(), - javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java', - javaOptions: JavaOptions(), - swiftOut: 'ios/Runner/Messages.g.swift', - swiftOptions: SwiftOptions(), - objcHeaderOut: 'macos/Runner/messages.g.h', - objcSourceOut: 'macos/Runner/messages.g.m', - // Set this to a unique prefix for your plugin or application, per Objective-C naming conventions. - objcOptions: ObjcOptions(prefix: 'PGN'), - copyrightHeader: 'pigeons/copyright.txt', - dartPackageName: 'pigeon_example_package', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + dartOptions: DartOptions(), + cppOptions: CppOptions(namespace: 'pigeon_example'), + cppHeaderOut: 'windows/runner/messages.g.h', + cppSourceOut: 'windows/runner/messages.g.cpp', + gobjectHeaderOut: 'linux/messages.g.h', + gobjectSourceOut: 'linux/messages.g.cc', + gobjectOptions: GObjectOptions(), + kotlinOut: + 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt', + kotlinOptions: KotlinOptions(), + javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java', + javaOptions: JavaOptions(), + swiftOut: 'ios/Runner/Messages.g.swift', + swiftOptions: SwiftOptions(), + objcHeaderOut: 'macos/Runner/messages.g.h', + objcSourceOut: 'macos/Runner/messages.g.m', + // Set this to a unique prefix for your plugin or application, per Objective-C naming conventions. + objcOptions: ObjcOptions(prefix: 'PGN'), + copyrightHeader: 'pigeons/copyright.txt', + dartPackageName: 'pigeon_example_package', + ), +) ``` Then make a simple call to run pigeon on the Dart file containing your definitions. @@ -250,6 +252,7 @@ app from the host platform. abstract class MessageFlutterApi { String flutterMethod(String? aString); } + ``` ### Dart @@ -372,6 +375,7 @@ This example gives a basic overview of how to use Pigeon to set up an event chan abstract class EventChannelMethods { PlatformEvent streamEvents(); } + ``` ### Dart diff --git a/packages/pigeon/example/app/lib/main.dart b/packages/pigeon/example/app/lib/main.dart index 8c84cd7b906..9f6381d697d 100644 --- a/packages/pigeon/example/app/lib/main.dart +++ b/packages/pigeon/example/app/lib/main.dart @@ -23,9 +23,9 @@ class _ExampleFlutterApi implements MessageFlutterApi { void main() { WidgetsFlutterBinding.ensureInitialized(); -// #docregion main-dart-flutter + // #docregion main-dart-flutter MessageFlutterApi.setUp(_ExampleFlutterApi()); -// #enddocregion main-dart-flutter + // #enddocregion main-dart-flutter runApp(const MyApp()); } @@ -107,15 +107,18 @@ class _MyHomePageState extends State { @override void initState() { super.initState(); - _hostApi.getHostLanguage().then((String response) { - setState(() { - _hostCallResult = 'Hello from $response!'; - }); - }).onError((PlatformException error, StackTrace _) { - setState(() { - _hostCallResult = 'Failed to get host language: ${error.message}'; - }); - }); + _hostApi + .getHostLanguage() + .then((String response) { + setState(() { + _hostCallResult = 'Hello from $response!'; + }); + }) + .onError((PlatformException error, StackTrace _) { + setState(() { + _hostCallResult = 'Failed to get host language: ${error.message}'; + }); + }); } @override @@ -129,15 +132,15 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - _hostCallResult ?? 'Waiting for host language...', - ), + Text(_hostCallResult ?? 'Waiting for host language...'), if (_hostCallResult == null) const CircularProgressIndicator(), if (Platform.isAndroid || Platform.isIOS) StreamBuilder( stream: getEventStream(), - builder: - (BuildContext context, AsyncSnapshot snapshot) { + builder: ( + BuildContext context, + AsyncSnapshot snapshot, + ) { if (snapshot.hasData) { return Text(snapshot.data ?? ''); } else { @@ -146,7 +149,7 @@ class _MyHomePageState extends State { }, ) else - const Text('event channels are not supported on this platform') + const Text('event channels are not supported on this platform'), ], ), ), diff --git a/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart b/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart index dd6985fa0c7..8239f87b1e1 100644 --- a/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart +++ b/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart @@ -14,14 +14,17 @@ import 'package:flutter/services.dart'; bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -29,16 +32,12 @@ bool _deepEquals(Object? a, Object? b) { sealed class PlatformEvent {} class IntEvent extends PlatformEvent { - IntEvent({ - required this.data, - }); + IntEvent({required this.data}); int data; List _toList() { - return [ - data, - ]; + return [data]; } Object encode() { @@ -47,9 +46,7 @@ class IntEvent extends PlatformEvent { static IntEvent decode(Object result) { result as List; - return IntEvent( - data: result[0]! as int, - ); + return IntEvent(data: result[0]! as int); } @override @@ -70,16 +67,12 @@ class IntEvent extends PlatformEvent { } class StringEvent extends PlatformEvent { - StringEvent({ - required this.data, - }); + StringEvent({required this.data}); String data; List _toList() { - return [ - data, - ]; + return [data]; } Object encode() { @@ -88,9 +81,7 @@ class StringEvent extends PlatformEvent { static StringEvent decode(Object result) { result as List; - return StringEvent( - data: result[0]! as String, - ); + return StringEvent(data: result[0]! as String); } @override @@ -141,16 +132,18 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = - StandardMethodCodec(_PigeonCodec()); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( + _PigeonCodec(), +); Stream streamEvents({String instanceName = ''}) { if (instanceName.isNotEmpty) { instanceName = '.$instanceName'; } final EventChannel streamEventsChannel = EventChannel( - 'dev.flutter.pigeon.pigeon_example_package.EventChannelMethods.streamEvents$instanceName', - pigeonMethodCodec); + 'dev.flutter.pigeon.pigeon_example_package.EventChannelMethods.streamEvents$instanceName', + pigeonMethodCodec, + ); return streamEventsChannel.receiveBroadcastStream().map((dynamic event) { return event as PlatformEvent; }); diff --git a/packages/pigeon/example/app/lib/src/messages.g.dart b/packages/pigeon/example/app/lib/src/messages.g.dart index ce88d04b721..1b68ab1073a 100644 --- a/packages/pigeon/example/app/lib/src/messages.g.dart +++ b/packages/pigeon/example/app/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -32,22 +35,22 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } -enum Code { - one, - two, -} +enum Code { one, two } class MessageData { MessageData({ @@ -66,12 +69,7 @@ class MessageData { Map data; List _toList() { - return [ - name, - description, - code, - data, - ]; + return [name, description, code, data]; } Object encode() { @@ -141,11 +139,12 @@ class ExampleHostApi { /// Constructor for [ExampleHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - ExampleHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + ExampleHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -157,10 +156,10 @@ class ExampleHostApi { 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -187,12 +186,13 @@ class ExampleHostApi { 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [a, b], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([a, b]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -218,12 +218,13 @@ class ExampleHostApi { 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [message], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([message]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -258,18 +259,20 @@ abstract class MessageFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod was null.', + ); final List args = (message as List?)!; final String? arg_aString = (args[0] as String?); try { @@ -279,7 +282,8 @@ abstract class MessageFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/example/app/pigeons/event_channel_messages.dart b/packages/pigeon/example/app/pigeons/event_channel_messages.dart index c0b33292235..df97bec027f 100644 --- a/packages/pigeon/example/app/pigeons/event_channel_messages.dart +++ b/packages/pigeon/example/app/pigeons/event_channel_messages.dart @@ -4,23 +4,20 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/event_channel_messages.g.dart', - dartOptions: DartOptions(), - cppOptions: CppOptions(namespace: 'pigeon_example'), - kotlinOut: - 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt', - kotlinOptions: KotlinOptions( - includeErrorClass: false, +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/event_channel_messages.g.dart', + dartOptions: DartOptions(), + cppOptions: CppOptions(namespace: 'pigeon_example'), + kotlinOut: + 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt', + kotlinOptions: KotlinOptions(includeErrorClass: false), + swiftOut: 'ios/Runner/EventChannelMessages.g.swift', + swiftOptions: SwiftOptions(includeErrorClass: false), + copyrightHeader: 'pigeons/copyright.txt', + dartPackageName: 'pigeon_example_package', ), - swiftOut: 'ios/Runner/EventChannelMessages.g.swift', - swiftOptions: SwiftOptions( - includeErrorClass: false, - ), - copyrightHeader: 'pigeons/copyright.txt', - dartPackageName: 'pigeon_example_package', -)) - +) // #docregion sealed-definitions sealed class PlatformEvent {} @@ -40,4 +37,5 @@ class StringEvent extends PlatformEvent { abstract class EventChannelMethods { PlatformEvent streamEvents(); } + // #enddocregion event-definitions diff --git a/packages/pigeon/example/app/pigeons/messages.dart b/packages/pigeon/example/app/pigeons/messages.dart index 421e6ce1c9f..2940ca6dc0b 100644 --- a/packages/pigeon/example/app/pigeons/messages.dart +++ b/packages/pigeon/example/app/pigeons/messages.dart @@ -5,31 +5,32 @@ import 'package:pigeon/pigeon.dart'; // #docregion config -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - dartOptions: DartOptions(), - cppOptions: CppOptions(namespace: 'pigeon_example'), - cppHeaderOut: 'windows/runner/messages.g.h', - cppSourceOut: 'windows/runner/messages.g.cpp', - gobjectHeaderOut: 'linux/messages.g.h', - gobjectSourceOut: 'linux/messages.g.cc', - gobjectOptions: GObjectOptions(), - kotlinOut: - 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt', - kotlinOptions: KotlinOptions(), - javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java', - javaOptions: JavaOptions(), - swiftOut: 'ios/Runner/Messages.g.swift', - swiftOptions: SwiftOptions(), - objcHeaderOut: 'macos/Runner/messages.g.h', - objcSourceOut: 'macos/Runner/messages.g.m', - // Set this to a unique prefix for your plugin or application, per Objective-C naming conventions. - objcOptions: ObjcOptions(prefix: 'PGN'), - copyrightHeader: 'pigeons/copyright.txt', - dartPackageName: 'pigeon_example_package', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + dartOptions: DartOptions(), + cppOptions: CppOptions(namespace: 'pigeon_example'), + cppHeaderOut: 'windows/runner/messages.g.h', + cppSourceOut: 'windows/runner/messages.g.cpp', + gobjectHeaderOut: 'linux/messages.g.h', + gobjectSourceOut: 'linux/messages.g.cc', + gobjectOptions: GObjectOptions(), + kotlinOut: + 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt', + kotlinOptions: KotlinOptions(), + javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java', + javaOptions: JavaOptions(), + swiftOut: 'ios/Runner/Messages.g.swift', + swiftOptions: SwiftOptions(), + objcHeaderOut: 'macos/Runner/messages.g.h', + objcSourceOut: 'macos/Runner/messages.g.m', + // Set this to a unique prefix for your plugin or application, per Objective-C naming conventions. + objcOptions: ObjcOptions(prefix: 'PGN'), + copyrightHeader: 'pigeons/copyright.txt', + dartPackageName: 'pigeon_example_package', + ), +) // #enddocregion config - // #docregion host-definitions enum Code { one, two } @@ -60,4 +61,5 @@ abstract class ExampleHostApi { abstract class MessageFlutterApi { String flutterMethod(String? aString); } + // #enddocregion flutter-definitions diff --git a/packages/pigeon/example/app/pubspec.yaml b/packages/pigeon/example/app/pubspec.yaml index 7b7aa95dbd5..8fbb73e09e3 100644 --- a/packages/pigeon/example/app/pubspec.yaml +++ b/packages/pigeon/example/app/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.6.0 + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/pigeon/lib/src/ast.dart b/packages/pigeon/lib/src/ast.dart index 34cbe557953..7e91fee6639 100644 --- a/packages/pigeon/lib/src/ast.dart +++ b/packages/pigeon/lib/src/ast.dart @@ -170,28 +170,24 @@ class AstProxyApi extends Api { final KotlinProxyApiOptions? kotlinOptions; /// Methods that handled by an implementation of the native type api. - Iterable get hostMethods => methods.where( - (Method method) => method.location == ApiLocation.host, - ); + Iterable get hostMethods => + methods.where((Method method) => method.location == ApiLocation.host); /// Methods that are handled by an instance of the Dart proxy class. - Iterable get flutterMethods => methods.where( - (Method method) => method.location == ApiLocation.flutter, - ); + Iterable get flutterMethods => + methods.where((Method method) => method.location == ApiLocation.flutter); /// All fields that are attached. /// /// See [attached]. - Iterable get attachedFields => fields.where( - (ApiField field) => field.isAttached, - ); + Iterable get attachedFields => + fields.where((ApiField field) => field.isAttached); /// All fields that are not attached. /// /// See [attached]. - Iterable get unattachedFields => fields.where( - (ApiField field) => !field.isAttached, - ); + Iterable get unattachedFields => + fields.where((ApiField field) => !field.isAttached); /// A list of [AstProxyApi]s where each is the [superClass] of the one /// proceeding it. @@ -253,7 +249,7 @@ class AstProxyApi extends Api { /// /// This also includes methods that the [superClass] inherits from interfaces. Iterable<(Method, AstProxyApi)> - flutterMethodsFromSuperClassesWithApis() sync* { + flutterMethodsFromSuperClassesWithApis() sync* { for (final AstProxyApi proxyApi in allSuperClasses().toList().reversed) { yield* proxyApi.flutterMethods.map((Method method) => (method, proxyApi)); } @@ -324,20 +320,18 @@ class AstProxyApi extends Api { final Set allInterfaces = {}; allInterfaces.addAll( - interfaces.map( - (TypeDeclaration type) { - if (!type.isProxyApi) { - throw ArgumentError( - 'Could not find a valid ProxyApi for an interface: $type', - ); - } else if (seenApis.contains(type.associatedProxyApi)) { - throw ArgumentError( - 'A ProxyApi cannot be a super class of itself: ${type.baseName}', - ); - } - return type.associatedProxyApi!; - }, - ), + interfaces.map((TypeDeclaration type) { + if (!type.isProxyApi) { + throw ArgumentError( + 'Could not find a valid ProxyApi for an interface: $type', + ); + } else if (seenApis.contains(type.associatedProxyApi)) { + throw ArgumentError( + 'A ProxyApi cannot be a super class of itself: ${type.baseName}', + ); + } + return type.associatedProxyApi!; + }), ); // Adds the current api since it would be invalid for it to be an interface @@ -394,9 +388,9 @@ class Constructor extends Method { super.swiftFunction = '', super.documentationComments = const [], }) : super( - returnType: const TypeDeclaration.voidDeclaration(), - location: ApiLocation.host, - ); + returnType: const TypeDeclaration.voidDeclaration(), + location: ApiLocation.host, + ); @override String toString() { @@ -491,12 +485,12 @@ class TypeDeclaration { /// Void constructor. const TypeDeclaration.voidDeclaration() - : baseName = 'void', - isNullable = false, - associatedEnum = null, - associatedClass = null, - associatedProxyApi = null, - typeArguments = const []; + : baseName = 'void', + isNullable = false, + associatedEnum = null, + associatedClass = null, + associatedProxyApi = null, + typeArguments = const []; /// The base name of the [TypeDeclaration] (ex 'Foo' to 'Foo?'). final String baseName; @@ -670,10 +664,10 @@ class Parameter extends NamedType { bool? isPositional, bool? isRequired, super.documentationComments, - }) : isNamed = isNamed ?? false, - isOptional = isOptional ?? false, - isPositional = isPositional ?? true, - isRequired = isRequired ?? true; + }) : isNamed = isNamed ?? false, + isOptional = isOptional ?? false, + isPositional = isPositional ?? true, + isRequired = isRequired ?? true; /// Whether this parameter is a named parameter. /// diff --git a/packages/pigeon/lib/src/cpp/cpp_generator.dart b/packages/pigeon/lib/src/cpp/cpp_generator.dart index 4a78d615a04..aeb38fd7a21 100644 --- a/packages/pigeon/lib/src/cpp/cpp_generator.dart +++ b/packages/pigeon/lib/src/cpp/cpp_generator.dart @@ -28,20 +28,27 @@ const String _codecSerializerName = '${classNamePrefix}CodecSerializer'; const String _overflowClassName = '${classNamePrefix}CodecOverflow'; final NamedType _overflowType = NamedType( - name: 'type', - type: const TypeDeclaration(baseName: 'int', isNullable: false)); + name: 'type', + type: const TypeDeclaration(baseName: 'int', isNullable: false), +); final NamedType _overflowObject = NamedType( - name: 'wrapped', - type: const TypeDeclaration(baseName: 'Object', isNullable: false)); + name: 'wrapped', + type: const TypeDeclaration(baseName: 'Object', isNullable: false), +); final List _overflowFields = [ _overflowType, _overflowObject, ]; -final Class _overflowClass = - Class(name: _overflowClassName, fields: _overflowFields); +final Class _overflowClass = Class( + name: _overflowClassName, + fields: _overflowFields, +); final EnumeratedType _enumeratedOverflow = EnumeratedType( - _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass, - associatedClass: _overflowClass); + _overflowClassName, + maximumCodecFieldKey, + CustomTypes.customClass, + associatedClass: _overflowClass, +); /// Options that control how C++ code will be generated. class CppOptions { @@ -115,11 +122,11 @@ class InternalCppOptions extends InternalOptions { required this.cppHeaderOut, required this.cppSourceOut, Iterable? copyrightHeader, - }) : headerIncludePath = - options.headerIncludePath ?? path.basename(cppHeaderOut), - namespace = options.namespace, - copyrightHeader = options.copyrightHeader ?? copyrightHeader, - headerOutPath = options.headerOutPath; + }) : headerIncludePath = + options.headerIncludePath ?? path.basename(cppHeaderOut), + namespace = options.namespace, + copyrightHeader = options.copyrightHeader ?? copyrightHeader, + headerOutPath = options.headerOutPath; /// The path to the header that will get placed in the source file (example: /// "foo.h"). @@ -154,8 +161,10 @@ class CppGenerator extends Generator> { StringSink sink, { required String dartPackageName, }) { - assert(generatorOptions.fileType == FileType.header || - generatorOptions.fileType == FileType.source); + assert( + generatorOptions.fileType == FileType.header || + generatorOptions.fileType == FileType.source, + ); if (generatorOptions.fileType == FileType.header) { const CppHeaderGenerator().generate( generatorOptions.languageOptions, @@ -241,15 +250,22 @@ class CppHeaderGenerator extends StructuredGenerator { }) { indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); + indent, + anEnum.documentationComments, + _docCommentSpec, + ); indent.write('enum class ${anEnum.name} '); indent.addScoped('{', '};', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( - indent, member.documentationComments, _docCommentSpec); + indent, + member.documentationComments, + _docCommentSpec, + ); final String valueName = 'k${_pascalCaseFromCamelCase(member.name)}'; indent.writeln( - '$valueName = $index${index == anEnum.members.length - 1 ? '' : ','}'); + '$valueName = $index${index == anEnum.members.length - 1 ? '' : ','}', + ); }); }); } @@ -318,113 +334,172 @@ class CppHeaderGenerator extends StructuredGenerator { indent.newln(); const List generatedMessages = [ - ' Generated class from Pigeon that represents data sent in messages.' + ' Generated class from Pigeon that represents data sent in messages.', ]; addDocumentationComments( - indent, classDefinition.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + indent, + classDefinition.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); - final Iterable orderedFields = - getFieldsInSerializationOrder(classDefinition); + final Iterable orderedFields = getFieldsInSerializationOrder( + classDefinition, + ); indent.write('class ${classDefinition.name} '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { - final Iterable requiredFields = - orderedFields.where((NamedType type) => !type.type.isNullable); + final Iterable requiredFields = orderedFields.where( + (NamedType type) => !type.type.isNullable, + ); // Minimal constructor, if needed. if (requiredFields.length != orderedFields.length) { - _writeClassConstructor(root, indent, classDefinition, requiredFields, - 'Constructs an object setting all non-nullable fields.'); + _writeClassConstructor( + root, + indent, + classDefinition, + requiredFields, + 'Constructs an object setting all non-nullable fields.', + ); } // All-field constructor. - _writeClassConstructor(root, indent, classDefinition, orderedFields, - 'Constructs an object setting all fields.'); + _writeClassConstructor( + root, + indent, + classDefinition, + orderedFields, + 'Constructs an object setting all fields.', + ); // If any fields are pointer type, then the class requires a custom // copy constructor, so declare the rule-of-five group of functions. - if (orderedFields.any((NamedType field) => _isPointerField( - getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType)))) { + if (orderedFields.any( + (NamedType field) => _isPointerField( + getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType), + ), + )) { final String className = classDefinition.name; // Add the default destructor, since unique_ptr destroys itself. _writeFunctionDeclaration(indent, '~$className', defaultImpl: true); // Declare custom copy/assign to deep-copy the pointer. - _writeFunctionDeclaration(indent, className, - isConstructor: true, - isCopy: true, - parameters: ['const $className& other']); - _writeFunctionDeclaration(indent, 'operator=', - returnType: '$className&', - parameters: ['const $className& other']); + _writeFunctionDeclaration( + indent, + className, + isConstructor: true, + isCopy: true, + parameters: ['const $className& other'], + ); + _writeFunctionDeclaration( + indent, + 'operator=', + returnType: '$className&', + parameters: ['const $className& other'], + ); // Re-add the default move operations, since they work fine with // unique_ptr. - _writeFunctionDeclaration(indent, className, - isConstructor: true, - isCopy: true, - parameters: ['$className&& other'], - defaultImpl: true); - _writeFunctionDeclaration(indent, 'operator=', - returnType: '$className&', - parameters: ['$className&& other'], - defaultImpl: true, - noexcept: true); + _writeFunctionDeclaration( + indent, + className, + isConstructor: true, + isCopy: true, + parameters: ['$className&& other'], + defaultImpl: true, + ); + _writeFunctionDeclaration( + indent, + 'operator=', + returnType: '$className&', + parameters: ['$className&& other'], + defaultImpl: true, + noexcept: true, + ); } for (final NamedType field in orderedFields) { addDocumentationComments( - indent, field.documentationComments, _docCommentSpec); - final HostDatatype baseDatatype = - getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType); + indent, + field.documentationComments, + _docCommentSpec, + ); + final HostDatatype baseDatatype = getFieldHostDatatype( + field, + _baseCppTypeForBuiltinDartType, + ); // Declare a getter and setter. - _writeFunctionDeclaration(indent, _makeGetterName(field), - returnType: _getterReturnType(baseDatatype), isConst: true); + _writeFunctionDeclaration( + indent, + _makeGetterName(field), + returnType: _getterReturnType(baseDatatype), + isConst: true, + ); final String setterName = _makeSetterName(field); - _writeFunctionDeclaration(indent, setterName, - returnType: _voidType, - parameters: [ - '${_unownedArgumentType(baseDatatype)} value_arg' - ]); + _writeFunctionDeclaration( + indent, + setterName, + returnType: _voidType, + parameters: [ + '${_unownedArgumentType(baseDatatype)} value_arg', + ], + ); if (field.type.isNullable) { // Add a second setter that takes the non-nullable version of the // argument for convenience, since setting literal values with the // pointer version is non-trivial. final HostDatatype nonNullType = _nonNullableType(baseDatatype); - _writeFunctionDeclaration(indent, setterName, - returnType: _voidType, - parameters: [ - '${_unownedArgumentType(nonNullType)} value_arg' - ]); + _writeFunctionDeclaration( + indent, + setterName, + returnType: _voidType, + parameters: [ + '${_unownedArgumentType(nonNullType)} value_arg', + ], + ); } indent.newln(); } }); _writeAccessBlock(indent, _ClassAccess.private, () { - _writeFunctionDeclaration(indent, 'FromEncodableList', - returnType: isOverflowClass - ? 'flutter::EncodableValue' - : classDefinition.name, - parameters: ['const flutter::EncodableList& list'], - isStatic: true); - _writeFunctionDeclaration(indent, 'ToEncodableList', - returnType: 'flutter::EncodableList', isConst: true); + _writeFunctionDeclaration( + indent, + 'FromEncodableList', + returnType: + isOverflowClass + ? 'flutter::EncodableValue' + : classDefinition.name, + parameters: ['const flutter::EncodableList& list'], + isStatic: true, + ); + _writeFunctionDeclaration( + indent, + 'ToEncodableList', + returnType: 'flutter::EncodableList', + isConst: true, + ); if (isOverflowClass) { - _writeFunctionDeclaration(indent, 'Unwrap', - returnType: 'flutter::EncodableValue'); + _writeFunctionDeclaration( + indent, + 'Unwrap', + returnType: 'flutter::EncodableValue', + ); } if (!isOverflowClass && root.requiresOverflowClass) { indent.writeln('friend class $_overflowClassName;'); } for (final Class friend in root.classes) { if (friend != classDefinition && - friend.fields.any((NamedType element) => - element.type.baseName == classDefinition.name)) { + friend.fields.any( + (NamedType element) => + element.type.baseName == classDefinition.name, + )) { indent.writeln('friend class ${friend.name};'); } } - for (final Api api in root.apis - .where((Api api) => api is AstFlutterApi || api is AstHostApi)) { + for (final Api api in root.apis.where( + (Api api) => api is AstFlutterApi || api is AstHostApi, + )) { // TODO(gaaclarke): Find a way to be more precise with our // friendships. indent.writeln('friend class ${api.name};'); @@ -435,10 +510,13 @@ class CppHeaderGenerator extends StructuredGenerator { } for (final NamedType field in orderedFields) { - final HostDatatype hostDatatype = - getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType); + final HostDatatype hostDatatype = getFieldHostDatatype( + field, + _baseCppTypeForBuiltinDartType, + ); indent.writeln( - '${_fieldType(hostDatatype)} ${_makeInstanceVariableName(field)};'); + '${_fieldType(hostDatatype)} ${_makeInstanceVariableName(field)};', + ); } }); }, nestCount: 0); @@ -454,36 +532,50 @@ class CppHeaderGenerator extends StructuredGenerator { }) { indent.newln(); indent.write( - 'class $_codecSerializerName : public $_standardCodecSerializer '); + 'class $_codecSerializerName : public $_standardCodecSerializer ', + ); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { - _writeFunctionDeclaration(indent, _codecSerializerName, - isConstructor: true); - _writeFunctionDeclaration(indent, 'GetInstance', - returnType: '$_codecSerializerName&', - isStatic: true, inlineBody: () { - indent.writeln('static $_codecSerializerName sInstance;'); - indent.writeln('return sInstance;'); - }); + _writeFunctionDeclaration( + indent, + _codecSerializerName, + isConstructor: true, + ); + _writeFunctionDeclaration( + indent, + 'GetInstance', + returnType: '$_codecSerializerName&', + isStatic: true, + inlineBody: () { + indent.writeln('static $_codecSerializerName sInstance;'); + indent.writeln('return sInstance;'); + }, + ); indent.newln(); - _writeFunctionDeclaration(indent, 'WriteValue', - returnType: _voidType, - parameters: [ - 'const flutter::EncodableValue& value', - 'flutter::ByteStreamWriter* stream' - ], - isConst: true, - isOverride: true); + _writeFunctionDeclaration( + indent, + 'WriteValue', + returnType: _voidType, + parameters: [ + 'const flutter::EncodableValue& value', + 'flutter::ByteStreamWriter* stream', + ], + isConst: true, + isOverride: true, + ); }); indent.writeScoped(' protected:', '', () { - _writeFunctionDeclaration(indent, 'ReadValueOfType', - returnType: 'flutter::EncodableValue', - parameters: [ - 'uint8_t type', - 'flutter::ByteStreamReader* stream' - ], - isConst: true, - isOverride: true); + _writeFunctionDeclaration( + indent, + 'ReadValueOfType', + returnType: 'flutter::EncodableValue', + parameters: [ + 'uint8_t type', + 'flutter::ByteStreamReader* stream', + ], + isConst: true, + isOverride: true, + ); }); }, nestCount: 0); indent.newln(); @@ -498,42 +590,70 @@ class CppHeaderGenerator extends StructuredGenerator { required String dartPackageName, }) { const List generatedMessages = [ - ' Generated class from Pigeon that represents Flutter messages that can be called from C++.' + ' Generated class from Pigeon that represents Flutter messages that can be called from C++.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); indent.write('class ${api.name} '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { - _writeFunctionDeclaration(indent, api.name, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', - ]); - _writeFunctionDeclaration(indent, api.name, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', - 'const std::string& message_channel_suffix', - ]); - _writeFunctionDeclaration(indent, 'GetCodec', - returnType: 'const flutter::StandardMessageCodec&', isStatic: true); + _writeFunctionDeclaration( + indent, + api.name, + parameters: ['flutter::BinaryMessenger* binary_messenger'], + ); + _writeFunctionDeclaration( + indent, + api.name, + parameters: [ + 'flutter::BinaryMessenger* binary_messenger', + 'const std::string& message_channel_suffix', + ], + ); + _writeFunctionDeclaration( + indent, + 'GetCodec', + returnType: 'const flutter::StandardMessageCodec&', + isStatic: true, + ); for (final Method func in api.methods) { - final HostDatatype returnType = - getHostDatatype(func.returnType, _baseCppTypeForBuiltinDartType); + final HostDatatype returnType = getHostDatatype( + func.returnType, + _baseCppTypeForBuiltinDartType, + ); addDocumentationComments( - indent, func.documentationComments, _docCommentSpec); - - final Iterable argTypes = - func.parameters.map((NamedType arg) { - final HostDatatype hostType = - getFieldHostDatatype(arg, _baseCppTypeForBuiltinDartType); + indent, + func.documentationComments, + _docCommentSpec, + ); + + final Iterable argTypes = func.parameters.map(( + NamedType arg, + ) { + final HostDatatype hostType = getFieldHostDatatype( + arg, + _baseCppTypeForBuiltinDartType, + ); return _flutterApiArgumentType(hostType); }); - final Iterable argNames = - indexMap(func.parameters, _getArgumentName); + final Iterable argNames = indexMap( + func.parameters, + _getArgumentName, + ); final List parameters = [ ...map2(argTypes, argNames, (String x, String y) => '$x $y'), ..._flutterApiCallbackParameters(returnType), ]; - _writeFunctionDeclaration(indent, _makeMethodName(func), - returnType: _voidType, parameters: parameters); + _writeFunctionDeclaration( + indent, + _makeMethodName(func), + returnType: _voidType, + parameters: parameters, + ); } }); indent.addScoped(' private:', null, () { @@ -553,46 +673,71 @@ class CppHeaderGenerator extends StructuredGenerator { required String dartPackageName, }) { const List generatedMessages = [ - ' Generated interface from Pigeon that represents a handler of messages from Flutter.' + ' Generated interface from Pigeon that represents a handler of messages from Flutter.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); indent.write('class ${api.name} '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { // Prevent copying/assigning. - _writeFunctionDeclaration(indent, api.name, - parameters: ['const ${api.name}&'], deleted: true); - _writeFunctionDeclaration(indent, 'operator=', - returnType: '${api.name}&', - parameters: ['const ${api.name}&'], - deleted: true); + _writeFunctionDeclaration( + indent, + api.name, + parameters: ['const ${api.name}&'], + deleted: true, + ); + _writeFunctionDeclaration( + indent, + 'operator=', + returnType: '${api.name}&', + parameters: ['const ${api.name}&'], + deleted: true, + ); // No-op virtual destructor. - _writeFunctionDeclaration(indent, '~${api.name}', - isVirtual: true, inlineNoop: true); + _writeFunctionDeclaration( + indent, + '~${api.name}', + isVirtual: true, + inlineNoop: true, + ); for (final Method method in api.methods) { final HostDatatype returnType = getHostDatatype( - method.returnType, _baseCppTypeForBuiltinDartType); + method.returnType, + _baseCppTypeForBuiltinDartType, + ); final String returnTypeName = _hostApiReturnType(returnType); final List parameters = []; if (method.parameters.isNotEmpty) { - final Iterable argTypes = - method.parameters.map((NamedType arg) { - final HostDatatype hostType = - getFieldHostDatatype(arg, _baseCppTypeForBuiltinDartType); + final Iterable argTypes = method.parameters.map(( + NamedType arg, + ) { + final HostDatatype hostType = getFieldHostDatatype( + arg, + _baseCppTypeForBuiltinDartType, + ); return _hostApiArgumentType(hostType); }); - final Iterable argNames = - method.parameters.map((NamedType e) => _makeVariableName(e)); + final Iterable argNames = method.parameters.map( + (NamedType e) => _makeVariableName(e), + ); parameters.addAll( - map2(argTypes, argNames, (String argType, String argName) { - return '$argType $argName'; - })); + map2(argTypes, argNames, (String argType, String argName) { + return '$argType $argName'; + }), + ); } addDocumentationComments( - indent, method.documentationComments, _docCommentSpec); + indent, + method.documentationComments, + _docCommentSpec, + ); final String methodReturn; if (method.isAsynchronous) { methodReturn = _voidType; @@ -600,41 +745,61 @@ class CppHeaderGenerator extends StructuredGenerator { } else { methodReturn = returnTypeName; } - _writeFunctionDeclaration(indent, _makeMethodName(method), - returnType: methodReturn, - parameters: parameters, - isVirtual: true, - isPureVirtual: true); + _writeFunctionDeclaration( + indent, + _makeMethodName(method), + returnType: methodReturn, + parameters: parameters, + isVirtual: true, + isPureVirtual: true, + ); } indent.newln(); indent.writeln('$_commentPrefix The codec used by ${api.name}.'); - _writeFunctionDeclaration(indent, 'GetCodec', - returnType: 'const flutter::StandardMessageCodec&', isStatic: true); + _writeFunctionDeclaration( + indent, + 'GetCodec', + returnType: 'const flutter::StandardMessageCodec&', + isStatic: true, + ); indent.writeln( - '$_commentPrefix Sets up an instance of `${api.name}` to handle messages through the `binary_messenger`.'); - _writeFunctionDeclaration(indent, 'SetUp', - returnType: _voidType, - isStatic: true, - parameters: [ - 'flutter::BinaryMessenger* binary_messenger', - '${api.name}* api', - ]); - _writeFunctionDeclaration(indent, 'SetUp', - returnType: _voidType, - isStatic: true, - parameters: [ - 'flutter::BinaryMessenger* binary_messenger', - '${api.name}* api', - 'const std::string& message_channel_suffix', - ]); - _writeFunctionDeclaration(indent, 'WrapError', - returnType: 'flutter::EncodableValue', - isStatic: true, - parameters: ['std::string_view error_message']); - _writeFunctionDeclaration(indent, 'WrapError', - returnType: 'flutter::EncodableValue', - isStatic: true, - parameters: ['const FlutterError& error']); + '$_commentPrefix Sets up an instance of `${api.name}` to handle messages through the `binary_messenger`.', + ); + _writeFunctionDeclaration( + indent, + 'SetUp', + returnType: _voidType, + isStatic: true, + parameters: [ + 'flutter::BinaryMessenger* binary_messenger', + '${api.name}* api', + ], + ); + _writeFunctionDeclaration( + indent, + 'SetUp', + returnType: _voidType, + isStatic: true, + parameters: [ + 'flutter::BinaryMessenger* binary_messenger', + '${api.name}* api', + 'const std::string& message_channel_suffix', + ], + ); + _writeFunctionDeclaration( + indent, + 'WrapError', + returnType: 'flutter::EncodableValue', + isStatic: true, + parameters: ['std::string_view error_message'], + ); + _writeFunctionDeclaration( + indent, + 'WrapError', + returnType: 'flutter::EncodableValue', + isStatic: true, + parameters: ['const FlutterError& error'], + ); }); _writeAccessBlock(indent, _ClassAccess.protected, () { indent.writeln('${api.name}() = default;'); @@ -642,16 +807,28 @@ class CppHeaderGenerator extends StructuredGenerator { }, nestCount: 0); } - void _writeClassConstructor(Root root, Indent indent, Class classDefinition, - Iterable params, String docComment) { - final List paramStrings = params.map((NamedType param) { - final HostDatatype hostDatatype = - getFieldHostDatatype(param, _baseCppTypeForBuiltinDartType); - return '${_hostApiArgumentType(hostDatatype)} ${_makeVariableName(param)}'; - }).toList(); + void _writeClassConstructor( + Root root, + Indent indent, + Class classDefinition, + Iterable params, + String docComment, + ) { + 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, classDefinition.name, - isConstructor: true, parameters: paramStrings); + _writeFunctionDeclaration( + indent, + classDefinition.name, + isConstructor: true, + parameters: paramStrings, + ); indent.newln(); } @@ -678,8 +855,10 @@ class FlutterError { };'''); } - void _writeErrorOr(Indent indent, - {Iterable friends = const []}) { + void _writeErrorOr( + Indent indent, { + Iterable friends = const [], + }) { final String friendLines = friends .map((String className) => '\tfriend class $className;') .join('\n'); @@ -798,15 +977,19 @@ class CppSourceGenerator extends StructuredGenerator { indent.writeln('using $using;'); } indent.newln(); - _writeFunctionDefinition(indent, 'CreateConnectionError', - returnType: 'FlutterError', - parameters: ['const std::string channel_name'], body: () { - indent.format(''' + _writeFunctionDefinition( + indent, + 'CreateConnectionError', + returnType: 'FlutterError', + parameters: ['const std::string channel_name'], + body: () { + indent.format(''' return FlutterError( "channel-error", "Unable to establish connection on channel: '" + channel_name + "'.", EncodableValue(""));'''); - }); + }, + ); } @override @@ -820,10 +1003,12 @@ class CppSourceGenerator extends StructuredGenerator { indent.writeln('$_commentPrefix ${classDefinition.name}'); indent.newln(); - final Iterable orderedFields = - getFieldsInSerializationOrder(classDefinition); - final Iterable requiredFields = - orderedFields.where((NamedType type) => !type.type.isNullable); + final Iterable orderedFields = getFieldsInSerializationOrder( + classDefinition, + ); + final Iterable requiredFields = orderedFields.where( + (NamedType type) => !type.type.isNullable, + ); // Minimal constructor, if needed. if (requiredFields.length != orderedFields.length) { _writeClassConstructor(root, indent, classDefinition, requiredFields); @@ -832,8 +1017,11 @@ class CppSourceGenerator extends StructuredGenerator { _writeClassConstructor(root, indent, classDefinition, orderedFields); // Custom copy/assign to handle pointer fields, if necessary. - if (orderedFields.any((NamedType field) => _isPointerField( - getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType)))) { + if (orderedFields.any( + (NamedType field) => _isPointerField( + getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType), + ), + )) { _writeCopyConstructor(root, indent, classDefinition, orderedFields); _writeAssignmentOperator(root, indent, classDefinition, orderedFields); } @@ -841,7 +1029,12 @@ class CppSourceGenerator extends StructuredGenerator { // Getters and setters. for (final NamedType field in orderedFields) { _writeCppSourceClassField( - generatorOptions, root, indent, classDefinition, field); + generatorOptions, + root, + indent, + classDefinition, + field, + ); } // Serialization. @@ -871,27 +1064,34 @@ class CppSourceGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - _writeFunctionDefinition(indent, 'ToEncodableList', - scope: classDefinition.name, - returnType: 'EncodableList', - isConst: true, body: () { - indent.writeln('EncodableList list;'); - indent.writeln('list.reserve(${classDefinition.fields.length});'); - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { - final HostDatatype hostDatatype = - getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); - final String encodableValue = _wrappedHostApiArgumentExpression( - root, - _makeInstanceVariableName(field), - field.type, - hostDatatype, - true, - ); - indent.writeln('list.push_back($encodableValue);'); - } - indent.writeln('return list;'); - }); + _writeFunctionDefinition( + indent, + 'ToEncodableList', + scope: classDefinition.name, + returnType: 'EncodableList', + isConst: true, + body: () { + indent.writeln('EncodableList list;'); + indent.writeln('list.reserve(${classDefinition.fields.length});'); + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { + final HostDatatype hostDatatype = getFieldHostDatatype( + field, + _shortBaseCppTypeForBuiltinDartType, + ); + final String encodableValue = _wrappedHostApiArgumentExpression( + root, + _makeInstanceVariableName(field), + field.type, + hostDatatype, + true, + ); + indent.writeln('list.push_back($encodableValue);'); + } + indent.writeln('return list;'); + }, + ); } @override @@ -908,8 +1108,10 @@ class CppSourceGenerator extends StructuredGenerator { if (field.type.baseName == 'Object') { return encodable; } else { - final HostDatatype hostDatatype = - getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); + final HostDatatype hostDatatype = getFieldHostDatatype( + field, + _shortBaseCppTypeForBuiltinDartType, + ); if (field.type.isClass || field.type.isEnum) { return _classReferenceFromEncodableValue(hostDatatype, encodable); } else { @@ -918,52 +1120,64 @@ class CppSourceGenerator extends StructuredGenerator { } } - _writeFunctionDefinition(indent, 'FromEncodableList', - scope: classDefinition.name, - returnType: classDefinition.name, - parameters: ['const EncodableList& list'], body: () { - const String instanceVariable = 'decoded'; - final Iterable<_IndexedField> indexedFields = indexMap( + _writeFunctionDefinition( + indent, + 'FromEncodableList', + scope: classDefinition.name, + returnType: classDefinition.name, + parameters: ['const EncodableList& list'], + body: () { + const String instanceVariable = 'decoded'; + final Iterable<_IndexedField> indexedFields = indexMap( getFieldsInSerializationOrder(classDefinition), - (int index, NamedType field) => _IndexedField(index, field)); - final Iterable<_IndexedField> nullableFields = indexedFields - .where((_IndexedField field) => field.field.type.isNullable); - final Iterable<_IndexedField> nonNullableFields = indexedFields - .where((_IndexedField field) => !field.field.type.isNullable); - - // Non-nullable fields must be set via the constructor. - String constructorArgs = nonNullableFields - .map((_IndexedField param) => - getValueExpression(param.field, 'list[${param.index}]')) - .join(',\n\t'); - if (constructorArgs.isNotEmpty) { - constructorArgs = '(\n\t$constructorArgs)'; - } - indent - .format('${classDefinition.name} $instanceVariable$constructorArgs;'); - - // Add the nullable fields via setters, since converting the encodable - // values to the pointer types that the convenience constructor uses for - // nullable fields is non-trivial. - for (final _IndexedField entry in nullableFields) { - final NamedType field = entry.field; - final String setterName = _makeSetterName(field); - final String encodableFieldName = - '${_encodablePrefix}_${_makeVariableName(field)}'; - indent.writeln('auto& $encodableFieldName = list[${entry.index}];'); - - final String valueExpression = - getValueExpression(field, encodableFieldName); - indent.writeScoped('if (!$encodableFieldName.IsNull()) {', '}', () { - indent.writeln('$instanceVariable.$setterName($valueExpression);'); - }); - } + (int index, NamedType field) => _IndexedField(index, field), + ); + final Iterable<_IndexedField> nullableFields = indexedFields.where( + (_IndexedField field) => field.field.type.isNullable, + ); + final Iterable<_IndexedField> nonNullableFields = indexedFields.where( + (_IndexedField field) => !field.field.type.isNullable, + ); - // This returns by value, relying on copy elision, since it makes the - // usage more convenient during deserialization than it would be with - // explicit transfer via unique_ptr. - indent.writeln('return $instanceVariable;'); - }); + // Non-nullable fields must be set via the constructor. + String constructorArgs = nonNullableFields + .map( + (_IndexedField param) => + getValueExpression(param.field, 'list[${param.index}]'), + ) + .join(',\n\t'); + if (constructorArgs.isNotEmpty) { + constructorArgs = '(\n\t$constructorArgs)'; + } + indent.format( + '${classDefinition.name} $instanceVariable$constructorArgs;', + ); + + // Add the nullable fields via setters, since converting the encodable + // values to the pointer types that the convenience constructor uses for + // nullable fields is non-trivial. + for (final _IndexedField entry in nullableFields) { + final NamedType field = entry.field; + final String setterName = _makeSetterName(field); + final String encodableFieldName = + '${_encodablePrefix}_${_makeVariableName(field)}'; + indent.writeln('auto& $encodableFieldName = list[${entry.index}];'); + + final String valueExpression = getValueExpression( + field, + encodableFieldName, + ); + indent.writeScoped('if (!$encodableFieldName.IsNull()) {', '}', () { + indent.writeln('$instanceVariable.$setterName($valueExpression);'); + }); + } + + // This returns by value, relying on copy elision, since it makes the + // usage more convenient during deserialization than it would be with + // explicit transfer via unique_ptr. + indent.writeln('return $instanceVariable;'); + }, + ); } void _writeCodecOverflowUtilities( @@ -977,7 +1191,12 @@ class CppSourceGenerator extends StructuredGenerator { // Getters and setters. for (final NamedType field in _overflowFields) { _writeCppSourceClassField( - generatorOptions, root, indent, _overflowClass, field); + generatorOptions, + root, + indent, + _overflowClass, + field, + ); } // Serialization. writeClassEncode( @@ -996,38 +1215,50 @@ EncodableValue $_overflowClassName::FromEncodableList( .Unwrap(); }'''); - indent.writeScoped('EncodableValue $_overflowClassName::Unwrap() {', '}', - () { - indent.writeScoped('if (wrapped_.IsNull()) {', '}', () { + indent.writeScoped( + 'EncodableValue $_overflowClassName::Unwrap() {', + '}', + () { + indent.writeScoped('if (wrapped_.IsNull()) {', '}', () { + indent.writeln('return EncodableValue();'); + }); + indent.writeScoped('switch(type_) {', '}', () { + for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) { + indent.write( + 'case ${types[i].enumeration - maximumCodecFieldKey}: ', + ); + _writeCodecDecode(indent, types[i], 'wrapped_'); + } + }); indent.writeln('return EncodableValue();'); - }); - indent.writeScoped('switch(type_) {', '}', () { - for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) { - indent.write('case ${types[i].enumeration - maximumCodecFieldKey}: '); - _writeCodecDecode(indent, types[i], 'wrapped_'); - } - }); - indent.writeln('return EncodableValue();'); - }); + }, + ); } void _writeCodecDecode( - Indent indent, EnumeratedType customType, String value) { + Indent indent, + EnumeratedType customType, + String value, + ) { indent.addScoped('{', '}', () { if (customType.type == CustomTypes.customClass) { if (customType.name == _overflowClassName) { indent.writeln( - 'return ${customType.name}::FromEncodableList(std::get($value));'); + 'return ${customType.name}::FromEncodableList(std::get($value));', + ); } else { indent.writeln( - 'return CustomEncodableValue(${customType.name}::FromEncodableList(std::get($value)));'); + 'return CustomEncodableValue(${customType.name}::FromEncodableList(std::get($value)));', + ); } } else if (customType.type == CustomTypes.customEnum) { indent.writeln('const auto& encodable_enum_arg = $value;'); indent.writeln( - 'const int64_t enum_arg_value = encodable_enum_arg.IsNull() ? 0 : encodable_enum_arg.LongValue();'); + 'const int64_t enum_arg_value = encodable_enum_arg.IsNull() ? 0 : encodable_enum_arg.LongValue();', + ); indent.writeln( - 'return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast<${customType.name}>(enum_arg_value));'); + 'return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast<${customType.name}>(enum_arg_value));', + ); } }); } @@ -1044,87 +1275,104 @@ EncodableValue $_overflowClassName::FromEncodableList( indent.newln(); if (root.requiresOverflowClass) { _writeCodecOverflowUtilities( - generatorOptions, root, indent, enumeratedTypes, - dartPackageName: dartPackageName); + generatorOptions, + root, + indent, + enumeratedTypes, + dartPackageName: dartPackageName, + ); } - _writeFunctionDefinition(indent, _codecSerializerName, - scope: _codecSerializerName); - _writeFunctionDefinition(indent, 'ReadValueOfType', - scope: _codecSerializerName, - returnType: 'EncodableValue', - parameters: [ - 'uint8_t type', - 'flutter::ByteStreamReader* stream', - ], - isConst: true, body: () { - if (enumeratedTypes.isNotEmpty) { - indent.writeln('switch (type) {'); - indent.inc(); - for (final EnumeratedType customType in enumeratedTypes) { - if (customType.enumeration < maximumCodecFieldKey) { - indent.write('case ${customType.enumeration}: '); - indent.nest(1, () { - _writeCodecDecode(indent, customType, 'ReadValue(stream)'); - }); + _writeFunctionDefinition( + indent, + _codecSerializerName, + scope: _codecSerializerName, + ); + _writeFunctionDefinition( + indent, + 'ReadValueOfType', + scope: _codecSerializerName, + returnType: 'EncodableValue', + parameters: ['uint8_t type', 'flutter::ByteStreamReader* stream'], + isConst: true, + body: () { + if (enumeratedTypes.isNotEmpty) { + indent.writeln('switch (type) {'); + indent.inc(); + for (final EnumeratedType customType in enumeratedTypes) { + if (customType.enumeration < maximumCodecFieldKey) { + indent.write('case ${customType.enumeration}: '); + indent.nest(1, () { + _writeCodecDecode(indent, customType, 'ReadValue(stream)'); + }); + } } + if (root.requiresOverflowClass) { + indent.write('case $maximumCodecFieldKey:'); + _writeCodecDecode(indent, _enumeratedOverflow, 'ReadValue(stream)'); + } + indent.writeln('default:'); + indent.inc(); } - if (root.requiresOverflowClass) { - indent.write('case $maximumCodecFieldKey:'); - _writeCodecDecode(indent, _enumeratedOverflow, 'ReadValue(stream)'); + indent.writeln( + 'return $_standardCodecSerializer::ReadValueOfType(type, stream);', + ); + if (enumeratedTypes.isNotEmpty) { + indent.dec(); + indent.writeln('}'); + indent.dec(); } - indent.writeln('default:'); - indent.inc(); - } - indent.writeln( - 'return $_standardCodecSerializer::ReadValueOfType(type, stream);'); - if (enumeratedTypes.isNotEmpty) { - indent.dec(); - indent.writeln('}'); - indent.dec(); - } - }); - _writeFunctionDefinition(indent, 'WriteValue', - scope: _codecSerializerName, - returnType: _voidType, - parameters: [ - 'const EncodableValue& value', - 'flutter::ByteStreamWriter* stream', - ], - isConst: true, body: () { - if (enumeratedTypes.isNotEmpty) { - indent.write( - 'if (const CustomEncodableValue* custom_value = std::get_if(&value)) '); - indent.addScoped('{', '}', () { - 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))'; - final String valueString = - customType.enumeration < maximumCodecFieldKey - ? encodeString - : 'wrap.ToEncodableList()'; - final int enumeration = - customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; - indent.write( - 'if (custom_value->type() == typeid(${customType.name})) '); - indent.addScoped('{', '}', () { - indent.writeln('stream->WriteByte($enumeration);'); - if (enumeration == maximumCodecFieldKey) { + }, + ); + _writeFunctionDefinition( + indent, + 'WriteValue', + scope: _codecSerializerName, + returnType: _voidType, + parameters: [ + 'const EncodableValue& value', + 'flutter::ByteStreamWriter* stream', + ], + isConst: true, + body: () { + if (enumeratedTypes.isNotEmpty) { + indent.write( + 'if (const CustomEncodableValue* custom_value = std::get_if(&value)) ', + ); + indent.addScoped('{', '}', () { + 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))'; + final String valueString = + customType.enumeration < maximumCodecFieldKey + ? encodeString + : 'wrap.ToEncodableList()'; + final int enumeration = + customType.enumeration < maximumCodecFieldKey + ? customType.enumeration + : maximumCodecFieldKey; + indent.write( + 'if (custom_value->type() == typeid(${customType.name})) ', + ); + indent.addScoped('{', '}', () { + indent.writeln('stream->WriteByte($enumeration);'); + if (enumeration == maximumCodecFieldKey) { + indent.writeln( + 'const auto wrap = $_overflowClassName(${customType.enumeration - maximumCodecFieldKey}, $encodeString);', + ); + } indent.writeln( - 'const auto wrap = $_overflowClassName(${customType.enumeration - maximumCodecFieldKey}, $encodeString);'); - } - indent - .writeln('WriteValue(EncodableValue($valueString), stream);'); - indent.writeln('return;'); - }); - } - }); - } - indent.writeln('$_standardCodecSerializer::WriteValue(value, stream);'); - }); + 'WriteValue(EncodableValue($valueString), stream);', + ); + indent.writeln('return;'); + }); + } + }); + } + indent.writeln('$_standardCodecSerializer::WriteValue(value, stream);'); + }, + ); } @override @@ -1136,17 +1384,16 @@ EncodableValue $_overflowClassName::FromEncodableList( required String dartPackageName, }) { indent.writeln( - '$_commentPrefix Generated class from Pigeon that represents Flutter messages that can be called from C++.'); + '$_commentPrefix Generated class from Pigeon that represents Flutter messages that can be called from C++.', + ); _writeFunctionDefinition( indent, api.name, scope: api.name, - parameters: [ - 'flutter::BinaryMessenger* binary_messenger', - ], + parameters: ['flutter::BinaryMessenger* binary_messenger'], initializers: [ 'binary_messenger_(binary_messenger)', - 'message_channel_suffix_("")' + 'message_channel_suffix_("")', ], ); _writeFunctionDefinition( @@ -1155,11 +1402,11 @@ EncodableValue $_overflowClassName::FromEncodableList( scope: api.name, parameters: [ 'flutter::BinaryMessenger* binary_messenger', - 'const std::string& message_channel_suffix' + 'const std::string& message_channel_suffix', ], initializers: [ 'binary_messenger_(binary_messenger)', - 'message_channel_suffix_(message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "")' + 'message_channel_suffix_(message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "")', ], ); _writeFunctionDefinition( @@ -1169,95 +1416,122 @@ EncodableValue $_overflowClassName::FromEncodableList( returnType: 'const flutter::StandardMessageCodec&', body: () { indent.writeln( - 'return flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());'); + 'return flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());', + ); }, ); for (final Method func in api.methods) { - final HostDatatype returnType = - getHostDatatype(func.returnType, _shortBaseCppTypeForBuiltinDartType); + final HostDatatype returnType = getHostDatatype( + func.returnType, + _shortBaseCppTypeForBuiltinDartType, + ); // Determine the input parameter list, saved in a structured form for later // use as platform channel call arguments. - final Iterable<_HostNamedType> hostParameters = - indexMap(func.parameters, (int i, NamedType arg) { - final HostDatatype hostType = - getFieldHostDatatype(arg, _shortBaseCppTypeForBuiltinDartType); - return _HostNamedType(_getSafeArgumentName(i, arg), hostType, arg.type); - }); + final Iterable<_HostNamedType> hostParameters = indexMap( + func.parameters, + (int i, NamedType arg) { + final HostDatatype hostType = getFieldHostDatatype( + arg, + _shortBaseCppTypeForBuiltinDartType, + ); + return _HostNamedType( + _getSafeArgumentName(i, arg), + hostType, + arg.type, + ); + }, + ); final List parameters = [ - ...hostParameters.map((_HostNamedType arg) => - '${_flutterApiArgumentType(arg.hostType)} ${arg.name}'), + ...hostParameters.map( + (_HostNamedType arg) => + '${_flutterApiArgumentType(arg.hostType)} ${arg.name}', + ), ..._flutterApiCallbackParameters(returnType), ]; - _writeFunctionDefinition(indent, _makeMethodName(func), - scope: api.name, - returnType: _voidType, - parameters: parameters, body: () { - indent.writeln( - 'const std::string channel_name = "${makeChannelName(api, func, dartPackageName)}" + message_channel_suffix_;'); - indent.writeln('BasicMessageChannel<> channel(binary_messenger_, ' - 'channel_name, &GetCodec());'); - - // Convert arguments to EncodableValue versions. - const String argumentListVariableName = 'encoded_api_arguments'; - indent.write('EncodableValue $argumentListVariableName = '); - if (func.parameters.isEmpty) { - indent.addln('EncodableValue();'); - } else { - indent.addScoped('EncodableValue(EncodableList{', '});', () { - for (final _HostNamedType param in hostParameters) { - final String encodedArgument = _wrappedHostApiArgumentExpression( - root, - param.name, - param.originalType, - param.hostType, - false, - ); - indent.writeln('$encodedArgument,'); - } - }); - } + _writeFunctionDefinition( + indent, + _makeMethodName(func), + scope: api.name, + returnType: _voidType, + parameters: parameters, + body: () { + indent.writeln( + 'const std::string channel_name = "${makeChannelName(api, func, dartPackageName)}" + message_channel_suffix_;', + ); + indent.writeln( + 'BasicMessageChannel<> channel(binary_messenger_, ' + 'channel_name, &GetCodec());', + ); + + // Convert arguments to EncodableValue versions. + const String argumentListVariableName = 'encoded_api_arguments'; + indent.write('EncodableValue $argumentListVariableName = '); + if (func.parameters.isEmpty) { + indent.addln('EncodableValue();'); + } else { + indent.addScoped('EncodableValue(EncodableList{', '});', () { + for (final _HostNamedType param in hostParameters) { + final String encodedArgument = + _wrappedHostApiArgumentExpression( + root, + param.name, + param.originalType, + param.hostType, + false, + ); + indent.writeln('$encodedArgument,'); + } + }); + } - indent.write('channel.Send($argumentListVariableName, ' + indent.write( + 'channel.Send($argumentListVariableName, ' // ignore: missing_whitespace_between_adjacent_strings '[channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]' - '(const uint8_t* reply, size_t reply_size) '); - indent.addScoped('{', '});', () { - String successCallbackArgument; - successCallbackArgument = 'return_value'; - final String encodedReplyName = 'encodable_$successCallbackArgument'; - final String listReplyName = 'list_$successCallbackArgument'; - indent.writeln( - 'std::unique_ptr response = GetCodec().DecodeMessage(reply, reply_size);'); - indent.writeln('const auto& $encodedReplyName = *response;'); - indent.writeln( - 'const auto* $listReplyName = std::get_if(&$encodedReplyName);'); - indent.writeScoped('if ($listReplyName) {', '} ', () { - indent.writeScoped('if ($listReplyName->size() > 1) {', '} ', () { - indent.writeln( - 'on_error(FlutterError(std::get($listReplyName->at(0)), std::get($listReplyName->at(1)), $listReplyName->at(2)));'); - }, addTrailingNewline: false); - indent.addScoped('else {', '}', () { - if (func.returnType.isVoid) { - successCallbackArgument = ''; - } else { - _writeEncodableValueArgumentUnwrapping( - indent, - root, - returnType, - argName: successCallbackArgument, - encodableArgName: '$listReplyName->at(0)', - apiType: ApiType.flutter, + '(const uint8_t* reply, size_t reply_size) ', + ); + indent.addScoped('{', '});', () { + String successCallbackArgument; + successCallbackArgument = 'return_value'; + final String encodedReplyName = + 'encodable_$successCallbackArgument'; + final String listReplyName = 'list_$successCallbackArgument'; + indent.writeln( + 'std::unique_ptr response = GetCodec().DecodeMessage(reply, reply_size);', + ); + indent.writeln('const auto& $encodedReplyName = *response;'); + indent.writeln( + 'const auto* $listReplyName = std::get_if(&$encodedReplyName);', + ); + indent.writeScoped('if ($listReplyName) {', '} ', () { + indent.writeScoped('if ($listReplyName->size() > 1) {', '} ', () { + indent.writeln( + 'on_error(FlutterError(std::get($listReplyName->at(0)), std::get($listReplyName->at(1)), $listReplyName->at(2)));', ); - } - indent.writeln('on_success($successCallbackArgument);'); + }, addTrailingNewline: false); + indent.addScoped('else {', '}', () { + if (func.returnType.isVoid) { + successCallbackArgument = ''; + } else { + _writeEncodableValueArgumentUnwrapping( + indent, + root, + returnType, + argName: successCallbackArgument, + encodableArgName: '$listReplyName->at(0)', + apiType: ApiType.flutter, + ); + } + indent.writeln('on_success($successCallbackArgument);'); + }); + }, addTrailingNewline: false); + indent.addScoped('else {', '} ', () { + indent.writeln('on_error(CreateConnectionError(channel_name));'); }); - }, addTrailingNewline: false); - indent.addScoped('else {', '} ', () { - indent.writeln('on_error(CreateConnectionError(channel_name));'); }); - }); - }); + }, + ); } } @@ -1270,14 +1544,20 @@ EncodableValue $_overflowClassName::FromEncodableList( required String dartPackageName, }) { indent.writeln('/// The codec used by ${api.name}.'); - _writeFunctionDefinition(indent, 'GetCodec', - scope: api.name, - returnType: 'const flutter::StandardMessageCodec&', body: () { - indent.writeln( - 'return flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());'); - }); + _writeFunctionDefinition( + indent, + 'GetCodec', + scope: api.name, + returnType: 'const flutter::StandardMessageCodec&', + body: () { + indent.writeln( + 'return flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());', + ); + }, + ); indent.writeln( - '$_commentPrefix Sets up an instance of `${api.name}` to handle messages through the `binary_messenger`.'); + '$_commentPrefix Sets up an instance of `${api.name}` to handle messages through the `binary_messenger`.', + ); _writeFunctionDefinition( indent, 'SetUp', @@ -1291,214 +1571,281 @@ EncodableValue $_overflowClassName::FromEncodableList( indent.writeln('${api.name}::SetUp(binary_messenger, api, "");'); }, ); - _writeFunctionDefinition(indent, 'SetUp', - scope: api.name, - returnType: _voidType, - parameters: [ - 'flutter::BinaryMessenger* binary_messenger', - '${api.name}* api', - 'const std::string& message_channel_suffix', - ], body: () { - indent.writeln( - 'const std::string prepended_suffix = message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "";'); - for (final Method method in api.methods) { - final String channelName = - makeChannelName(api, method, dartPackageName); - indent.writeScoped('{', '}', () { - indent.writeln('BasicMessageChannel<> channel(binary_messenger, ' - '"$channelName" + prepended_suffix, &GetCodec());'); - indent.writeScoped('if (api != nullptr) {', '} else {', () { - indent.write( - 'channel.SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) '); - indent.addScoped('{', '});', () { - indent.writeScoped('try {', '}', () { - final List methodArgument = []; - if (method.parameters.isNotEmpty) { - indent.writeln( - 'const auto& args = std::get(message);'); - - enumerate(method.parameters, (int index, NamedType arg) { - final HostDatatype hostType = getHostDatatype( - arg.type, - (TypeDeclaration x) => - _shortBaseCppTypeForBuiltinDartType(x)); - final String argName = _getSafeArgumentName(index, arg); - - final String encodableArgName = - '${_encodablePrefix}_$argName'; + _writeFunctionDefinition( + indent, + 'SetUp', + scope: api.name, + returnType: _voidType, + parameters: [ + 'flutter::BinaryMessenger* binary_messenger', + '${api.name}* api', + 'const std::string& message_channel_suffix', + ], + body: () { + indent.writeln( + 'const std::string prepended_suffix = message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "";', + ); + for (final Method method in api.methods) { + final String channelName = makeChannelName( + api, + method, + dartPackageName, + ); + indent.writeScoped('{', '}', () { + indent.writeln( + 'BasicMessageChannel<> channel(binary_messenger, ' + '"$channelName" + prepended_suffix, &GetCodec());', + ); + indent.writeScoped('if (api != nullptr) {', '} else {', () { + indent.write( + 'channel.SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) ', + ); + indent.addScoped('{', '});', () { + indent.writeScoped('try {', '}', () { + final List methodArgument = []; + if (method.parameters.isNotEmpty) { indent.writeln( - 'const auto& $encodableArgName = args.at($index);'); - if (!arg.type.isNullable) { - indent.writeScoped( - 'if ($encodableArgName.IsNull()) {', '}', () { - indent.writeln( - 'reply(WrapError("$argName unexpectedly null."));'); - indent.writeln('return;'); - }); - } - _writeEncodableValueArgumentUnwrapping( - indent, - root, - hostType, - argName: argName, - encodableArgName: encodableArgName, - apiType: ApiType.host, + 'const auto& args = std::get(message);', ); - final String unwrapEnum = - arg.type.isEnum && arg.type.isNullable - ? ' ? &(*$argName) : nullptr' - : ''; - methodArgument.add('$argName$unwrapEnum'); - }); - } - final HostDatatype returnType = getHostDatatype( - method.returnType, _shortBaseCppTypeForBuiltinDartType); - final String returnTypeName = _hostApiReturnType(returnType); - if (method.isAsynchronous) { - methodArgument.add( - '[reply]($returnTypeName&& output) {${indent.newline}' - '${_wrapResponse(indent, root, method.returnType, prefix: '\t')}${indent.newline}' - '}', + enumerate(method.parameters, (int index, NamedType arg) { + final HostDatatype hostType = getHostDatatype( + arg.type, + (TypeDeclaration x) => + _shortBaseCppTypeForBuiltinDartType(x), + ); + final String argName = _getSafeArgumentName(index, arg); + + final String encodableArgName = + '${_encodablePrefix}_$argName'; + indent.writeln( + 'const auto& $encodableArgName = args.at($index);', + ); + if (!arg.type.isNullable) { + indent.writeScoped( + 'if ($encodableArgName.IsNull()) {', + '}', + () { + indent.writeln( + 'reply(WrapError("$argName unexpectedly null."));', + ); + indent.writeln('return;'); + }, + ); + } + _writeEncodableValueArgumentUnwrapping( + indent, + root, + hostType, + argName: argName, + encodableArgName: encodableArgName, + apiType: ApiType.host, + ); + final String unwrapEnum = + arg.type.isEnum && arg.type.isNullable + ? ' ? &(*$argName) : nullptr' + : ''; + methodArgument.add('$argName$unwrapEnum'); + }); + } + + final HostDatatype returnType = getHostDatatype( + method.returnType, + _shortBaseCppTypeForBuiltinDartType, ); - } - final String call = - 'api->${_makeMethodName(method)}(${methodArgument.join(', ')})'; - if (method.isAsynchronous) { - indent.format('$call;'); - } else { - indent.writeln('$returnTypeName output = $call;'); - indent.format(_wrapResponse(indent, root, method.returnType)); - } - }, addTrailingNewline: false); - indent.add(' catch (const std::exception& exception) '); - indent.addScoped('{', '}', () { - // There is a potential here for `reply` to be called twice, which - // is a violation of the API contract, because there's no way of - // knowing whether or not the plugin code called `reply` before - // throwing. Since use of `@async` suggests that the reply is - // probably not sent within the scope of the stack, err on the - // side of potential double-call rather than no call (which is - // also an API violation) so that unexpected errors have a better - // chance of being caught and handled in a useful way. - indent.writeln('reply(WrapError(exception.what()));'); + final String returnTypeName = _hostApiReturnType(returnType); + if (method.isAsynchronous) { + methodArgument.add( + '[reply]($returnTypeName&& output) {${indent.newline}' + '${_wrapResponse(indent, root, method.returnType, prefix: '\t')}${indent.newline}' + '}', + ); + } + final String call = + 'api->${_makeMethodName(method)}(${methodArgument.join(', ')})'; + if (method.isAsynchronous) { + indent.format('$call;'); + } else { + indent.writeln('$returnTypeName output = $call;'); + indent.format( + _wrapResponse(indent, root, method.returnType), + ); + } + }, addTrailingNewline: false); + indent.add(' catch (const std::exception& exception) '); + indent.addScoped('{', '}', () { + // There is a potential here for `reply` to be called twice, which + // is a violation of the API contract, because there's no way of + // knowing whether or not the plugin code called `reply` before + // throwing. Since use of `@async` suggests that the reply is + // probably not sent within the scope of the stack, err on the + // side of potential double-call rather than no call (which is + // also an API violation) so that unexpected errors have a better + // chance of being caught and handled in a useful way. + indent.writeln('reply(WrapError(exception.what()));'); + }); }); }); + indent.addScoped(null, '}', () { + indent.writeln('channel.SetMessageHandler(nullptr);'); + }); }); - indent.addScoped(null, '}', () { - indent.writeln('channel.SetMessageHandler(nullptr);'); - }); - }); - } - }); + } + }, + ); - _writeFunctionDefinition(indent, 'WrapError', - scope: api.name, - returnType: 'EncodableValue', - parameters: ['std::string_view error_message'], body: () { - indent.format(''' + _writeFunctionDefinition( + indent, + 'WrapError', + scope: api.name, + returnType: 'EncodableValue', + parameters: ['std::string_view error_message'], + body: () { + indent.format(''' return EncodableValue(EncodableList{ \tEncodableValue(std::string(error_message)), \tEncodableValue("Error"), \tEncodableValue() });'''); - }); - _writeFunctionDefinition(indent, 'WrapError', - scope: api.name, - returnType: 'EncodableValue', - parameters: ['const FlutterError& error'], body: () { - indent.format(''' + }, + ); + _writeFunctionDefinition( + indent, + 'WrapError', + scope: api.name, + returnType: 'EncodableValue', + parameters: ['const FlutterError& error'], + body: () { + indent.format(''' return EncodableValue(EncodableList{ \tEncodableValue(error.code()), \tEncodableValue(error.message()), \terror.details() });'''); - }); + }, + ); } - void _writeClassConstructor(Root root, Indent indent, Class classDefinition, - Iterable params) { + void _writeClassConstructor( + Root root, + Indent indent, + Class classDefinition, + Iterable params, + ) { final Iterable<_HostNamedType> hostParams = params.map((NamedType param) { return _HostNamedType( _makeVariableName(param), - getFieldHostDatatype( - param, - _shortBaseCppTypeForBuiltinDartType, - ), + getFieldHostDatatype(param, _shortBaseCppTypeForBuiltinDartType), param.type, ); }); - 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, - scope: classDefinition.name, - parameters: paramStrings, - initializers: initializerStrings); + 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, + scope: classDefinition.name, + parameters: paramStrings, + initializers: initializerStrings, + ); } - void _writeCopyConstructor(Root root, Indent indent, 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(); - _writeFunctionDefinition(indent, classDefinition.name, - scope: classDefinition.name, - parameters: ['const ${classDefinition.name}& other'], - initializers: initializerStrings); + void _writeCopyConstructor( + Root root, + Indent indent, + 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(); + _writeFunctionDefinition( + indent, + classDefinition.name, + scope: classDefinition.name, + parameters: ['const ${classDefinition.name}& other'], + initializers: initializerStrings, + ); } - void _writeAssignmentOperator(Root root, Indent indent, Class classDefinition, - Iterable fields) { - _writeFunctionDefinition(indent, 'operator=', - scope: classDefinition.name, - returnType: '${classDefinition.name}&', - parameters: ['const ${classDefinition.name}& other'], body: () { - for (final NamedType field in fields) { - final HostDatatype hostDatatype = - getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); - - final String ivarName = _makeInstanceVariableName(field); - final String otherIvar = 'other.$ivarName'; - final String valueExpression; - if (_isPointerField(hostDatatype)) { - final String constructor = - 'std::make_unique<${hostDatatype.datatype}>(*$otherIvar)'; - valueExpression = hostDatatype.isNullable - ? '$otherIvar ? $constructor : nullptr' - : constructor; - } else { - valueExpression = otherIvar; + void _writeAssignmentOperator( + Root root, + Indent indent, + Class classDefinition, + Iterable fields, + ) { + _writeFunctionDefinition( + indent, + 'operator=', + scope: classDefinition.name, + returnType: '${classDefinition.name}&', + parameters: ['const ${classDefinition.name}& other'], + body: () { + for (final NamedType field in fields) { + final HostDatatype hostDatatype = getFieldHostDatatype( + field, + _shortBaseCppTypeForBuiltinDartType, + ); + + final String ivarName = _makeInstanceVariableName(field); + final String otherIvar = 'other.$ivarName'; + final String valueExpression; + if (_isPointerField(hostDatatype)) { + final String constructor = + 'std::make_unique<${hostDatatype.datatype}>(*$otherIvar)'; + valueExpression = + hostDatatype.isNullable + ? '$otherIvar ? $constructor : nullptr' + : constructor; + } else { + valueExpression = otherIvar; + } + indent.writeln('$ivarName = $valueExpression;'); } - indent.writeln('$ivarName = $valueExpression;'); - } - indent.writeln('return *this;'); - }); + indent.writeln('return *this;'); + }, + ); } - void _writeCppSourceClassField(InternalCppOptions generatorOptions, Root root, - Indent indent, Class classDefinition, NamedType field) { - final HostDatatype hostDatatype = - getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); + void _writeCppSourceClassField( + InternalCppOptions generatorOptions, + Root root, + Indent indent, + Class classDefinition, + NamedType field, + ) { + final HostDatatype hostDatatype = getFieldHostDatatype( + field, + _shortBaseCppTypeForBuiltinDartType, + ); final String instanceVariableName = _makeInstanceVariableName(field); final String setterName = _makeSetterName(field); 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 = @@ -1517,11 +1864,12 @@ return EncodableValue(EncodableList{ scope: classDefinition.name, returnType: _voidType, parameters: [ - '${_unownedArgumentType(type)} $setterArgumentName' + '${_unownedArgumentType(type)} $setterArgumentName', ], body: () { indent.writeln( - '$instanceVariableName = ${_fieldValueExpression(type, setterArgumentName)};'); + '$instanceVariableName = ${_fieldValueExpression(type, setterArgumentName)};', + ); }, ); } @@ -1552,8 +1900,11 @@ return EncodableValue(EncodableList{ /// itself, but for other values this handles the conversion between an /// argument type (a pointer or value/reference) and the field type /// (a std::optional or std::unique_ptr). - String _fieldValueExpression(HostDatatype type, String variable, - {bool sourceIsField = false}) { + String _fieldValueExpression( + HostDatatype type, + String variable, { + bool sourceIsField = false, + }) { if (_isPointerField(type)) { final String constructor = 'std::make_unique<${type.datatype}>'; // If the source is a pointer field, it always needs dereferencing. @@ -1567,8 +1918,12 @@ return EncodableValue(EncodableList{ : variable; } - String _wrapResponse(Indent indent, Root root, TypeDeclaration returnType, - {String prefix = ''}) { + String _wrapResponse( + Indent indent, + Root root, + TypeDeclaration returnType, { + String prefix = '', + }) { final String nonErrorPath; final String errorCondition; final String errorGetter; @@ -1579,8 +1934,10 @@ return EncodableValue(EncodableList{ errorCondition = 'output.has_value()'; errorGetter = 'value'; } else { - final HostDatatype hostType = - getHostDatatype(returnType, _shortBaseCppTypeForBuiltinDartType); + final HostDatatype hostType = getHostDatatype( + returnType, + _shortBaseCppTypeForBuiltinDartType, + ); const String extractedValue = 'std::move(output).TakeValue()'; final String wrapperType = @@ -1677,7 +2034,8 @@ ${prefix}reply(EncodableValue(std::move(wrapped)));'''; indent.writeln('const auto* $argName = &$encodableArgName;'); } else if (hostType.isBuiltin) { indent.writeln( - 'const auto* $argName = std::get_if<${hostType.datatype}>(&$encodableArgName);'); + 'const auto* $argName = std::get_if<${hostType.datatype}>(&$encodableArgName);', + ); } else if (hostType.isEnum) { indent.format(''' ${hostType.datatype} ${argName}_value; @@ -1688,7 +2046,8 @@ if (!$encodableArgName.IsNull()) { }'''); } else { indent.writeln( - 'const auto* $argName = $encodableArgName.IsNull() ? nullptr : &(${_classReferenceFromEncodableValue(hostType, encodableArgName)});'); + 'const auto* $argName = $encodableArgName.IsNull() ? nullptr : &(${_classReferenceFromEncodableValue(hostType, encodableArgName)});', + ); } } else { // Non-nullable arguments are either passed by value or reference, but the @@ -1698,8 +2057,9 @@ if (!$encodableArgName.IsNull()) { // The EncodableValue will either be an int32_t or an int64_t depending // on the value, but the generated API requires an int64_t so that it can // handle any case. - indent - .writeln('const int64_t $argName = $encodableArgName.LongValue();'); + indent.writeln( + 'const int64_t $argName = $encodableArgName.LongValue();', + ); } else if (hostType.datatype == 'EncodableValue') { // Generic objects just pass the EncodableValue through directly. This // creates an alias just to avoid having to special-case the @@ -1707,10 +2067,12 @@ if (!$encodableArgName.IsNull()) { indent.writeln('const auto& $argName = $encodableArgName;'); } else if (hostType.isBuiltin) { indent.writeln( - 'const auto& $argName = std::get<${hostType.datatype}>($encodableArgName);'); + 'const auto& $argName = std::get<${hostType.datatype}>($encodableArgName);', + ); } else { indent.writeln( - 'const auto& $argName = ${_classReferenceFromEncodableValue(hostType, encodableArgName)};'); + 'const auto& $argName = ${_classReferenceFromEncodableValue(hostType, encodableArgName)};', + ); } } } @@ -1725,7 +2087,9 @@ if (!$encodableArgName.IsNull()) { /// Returns the code to extract a `const {type.datatype}&` from an EncodableValue /// variable [variableName] that contains an instance of [type]. String _classReferenceFromEncodableValue( - HostDatatype type, String variableName) { + HostDatatype type, + String variableName, + ) { return 'std::any_cast(std::get($variableName))'; } } @@ -1772,13 +2136,17 @@ String _pascalCaseFromCamelCase(String camelCase) => camelCase[0].toUpperCase() + camelCase.substring(1); String _snakeCaseFromCamelCase(String camelCase) { - return camelCase.replaceAllMapped(RegExp(r'[A-Z]'), - (Match m) => '${m.start == 0 ? '' : '_'}${m[0]!.toLowerCase()}'); + return camelCase.replaceAllMapped( + RegExp(r'[A-Z]'), + (Match m) => '${m.start == 0 ? '' : '_'}${m[0]!.toLowerCase()}', + ); } String _pascalCaseFromSnakeCase(String snakeCase) { final String camelCase = snakeCase.replaceAllMapped( - RegExp(r'_([a-z])'), (Match m) => m[1]!.toUpperCase()); + RegExp(r'_([a-z])'), + (Match m) => m[1]!.toUpperCase(), + ); return _pascalCaseFromCamelCase(camelCase); } @@ -2026,8 +2394,11 @@ void _writeFunction( // own lines indented two extra levels, with no comma or newline after the // last one. The easiest way to express the special casing of the first and // last is with a join+format. - indent.format(initializers.join(',\n\t\t'), - leadingSpace: false, trailingNewline: false); + indent.format( + initializers.join(',\n\t\t'), + leadingSpace: false, + trailingNewline: false, + ); } // Write the body or end the declaration. if (type == _FunctionOutputType.declaration) { @@ -2061,8 +2432,10 @@ void _writeFunctionDeclaration( }) { assert(!(isVirtual && isOverride), 'virtual is redundant with override'); assert(isVirtual || !isPureVirtual, 'pure virtual methods must be virtual'); - assert(returnType == null || !isConstructor, - 'constructors cannot have return types'); + assert( + returnType == null || !isConstructor, + 'constructors cannot have return types', + ); assert(!(deleted && defaultImpl), 'a function cannot be deleted and default'); _writeFunction( indent, @@ -2076,7 +2449,7 @@ void _writeFunctionDeclaration( if (inlineBody != null) 'inline', if (isStatic) 'static', if (isVirtual) 'virtual', - if (isConstructor && parameters.isNotEmpty && !isCopy) 'explicit' + if (isConstructor && parameters.isNotEmpty && !isCopy) 'explicit', ], trailingAnnotations: [ if (isConst) 'const', @@ -2107,9 +2480,7 @@ void _writeFunctionDefinition( scope: scope, returnType: returnType, parameters: parameters, - trailingAnnotations: [ - if (isConst) 'const', - ], + trailingAnnotations: [if (isConst) 'const'], initializers: initializers, body: body, ); @@ -2119,7 +2490,10 @@ void _writeFunctionDefinition( enum _ClassAccess { public, protected, private } void _writeAccessBlock( - Indent indent, _ClassAccess access, void Function() body) { + Indent indent, + _ClassAccess access, + void Function() body, +) { final String accessLabel; switch (access) { case _ClassAccess.public: @@ -2140,9 +2514,12 @@ List validateCpp(InternalCppOptions options, Root root) { for (final NamedType arg in method.parameters) { if (arg.type.isEnum) { // TODO(gaaclarke): Add line number and filename. - result.add(Error( + result.add( + Error( message: - "Nullable enum types aren't supported in C++ arguments in method:${api.name}.${method.name} argument:(${arg.type.baseName} ${arg.name}).")); + "Nullable enum types aren't supported in C++ arguments in method:${api.name}.${method.name} argument:(${arg.type.baseName} ${arg.name}).", + ), + ); } } } diff --git a/packages/pigeon/lib/src/dart/dart_generator.dart b/packages/pigeon/lib/src/dart/dart_generator.dart index 49df0efaeda..80fe59908ba 100644 --- a/packages/pigeon/lib/src/dart/dart_generator.dart +++ b/packages/pigeon/lib/src/dart/dart_generator.dart @@ -93,11 +93,7 @@ class DartOptions { /// Options that control how Dart code will be generated. class InternalDartOptions extends InternalOptions { /// Constructor for InternalDartOptions. - const InternalDartOptions({ - this.copyrightHeader, - this.dartOut, - this.testOut, - }); + const InternalDartOptions({this.copyrightHeader, this.dartOut, this.testOut}); /// Creates InternalDartOptions from DartOptions. InternalDartOptions.fromDartOptions( @@ -105,9 +101,9 @@ class InternalDartOptions extends InternalOptions { Iterable? copyrightHeader, String? dartOut, String? testOut, - }) : copyrightHeader = copyrightHeader ?? options.copyrightHeader, - dartOut = (dartOut ?? options.sourceOutPath)!, - testOut = testOut ?? options.testOutPath; + }) : copyrightHeader = copyrightHeader ?? options.copyrightHeader, + dartOut = (dartOut ?? options.sourceOutPath)!, + testOut = testOut ?? options.testOutPath; /// A copyright header that will get prepended to generated code. final Iterable? copyrightHeader; @@ -164,7 +160,8 @@ class DartGenerator extends StructuredGenerator { indent.newln(); indent.writeln( - "import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer${root.containsProxyApi ? ', immutable, protected, visibleForTesting' : ''};"); + "import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer${root.containsProxyApi ? ', immutable, protected, visibleForTesting' : ''};", + ); indent.writeln("import 'package:flutter/services.dart';"); if (root.containsProxyApi) { indent.writeln( @@ -183,12 +180,18 @@ class DartGenerator extends StructuredGenerator { }) { indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, docCommentSpec); + indent, + anEnum.documentationComments, + docCommentSpec, + ); indent.write('enum ${anEnum.name} '); indent.addScoped('{', '}', () { for (final EnumMember member in anEnum.members) { addDocumentationComments( - indent, member.documentationComments, docCommentSpec); + indent, + member.documentationComments, + docCommentSpec, + ); indent.writeln('${member.name},'); } }); @@ -204,11 +207,15 @@ class DartGenerator extends StructuredGenerator { }) { indent.newln(); addDocumentationComments( - indent, classDefinition.documentationComments, docCommentSpec); + indent, + classDefinition.documentationComments, + 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('{', '}', () { @@ -217,10 +224,14 @@ class DartGenerator extends StructuredGenerator { } _writeConstructor(indent, classDefinition); indent.newln(); - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { addDocumentationComments( - indent, field.documentationComments, docCommentSpec); + indent, + field.documentationComments, + docCommentSpec, + ); final String datatype = addGenericTypesNullable(field.type); indent.writeln('$datatype ${field.name};'); @@ -257,8 +268,9 @@ class DartGenerator extends StructuredGenerator { void _writeConstructor(Indent indent, Class classDefinition) { indent.write(classDefinition.name); indent.addScoped('({', '});', () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final String required = !field.type.isNullable && field.defaultValue == null ? 'required ' @@ -273,8 +285,9 @@ class DartGenerator extends StructuredGenerator { void _writeToList(Indent indent, Class classDefinition) { indent.writeScoped('List _toList() {', '}', () { indent.writeScoped('return [', '];', () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { indent.writeln('${field.name},'); } }); @@ -291,9 +304,7 @@ class DartGenerator extends StructuredGenerator { }) { indent.write('Object encode() '); indent.addScoped('{', '}', () { - indent.write( - 'return _toList();', - ); + indent.write('return _toList();'); }); } @@ -312,30 +323,27 @@ class DartGenerator extends StructuredGenerator { final String castCall = _makeGenericCastCall(field.type); final String nullableTag = field.type.isNullable ? '?' : ''; if (field.type.typeArguments.isNotEmpty) { - indent.add( - '($resultAt as $genericType?)$castCallPrefix$castCall', - ); + 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', - ); + indent.add('$resultAt$castCallForcePrefix$castString'); } } - indent.write( - 'static ${classDefinition.name} decode(Object result) ', - ); + indent.write('static ${classDefinition.name} decode(Object result) '); indent.addScoped('{', '}', () { indent.writeln('result as List;'); indent.write('return ${classDefinition.name}'); indent.addScoped('(', ');', () { - enumerate(getFieldsInSerializationOrder(classDefinition), - (int index, final NamedType field) { + enumerate(getFieldsInSerializationOrder(classDefinition), ( + int index, + final NamedType field, + ) { indent.write('${field.name}: '); writeValueDecode(field, index); indent.addln(','); @@ -356,10 +364,12 @@ class DartGenerator extends StructuredGenerator { indent.writeln('// ignore: avoid_equals_and_hash_code_on_mutable_classes'); indent.writeScoped('bool operator ==(Object other) {', '}', () { indent.writeScoped( - 'if (other is! ${classDefinition.name} || other.runtimeType != runtimeType) {', - '}', () { - indent.writeln('return false;'); - }); + 'if (other is! ${classDefinition.name} || other.runtimeType != runtimeType) {', + '}', + () { + indent.writeln('return false;'); + }, + ); indent.writeScoped('if (identical(this, other)) {', '}', () { indent.writeln('return true;'); }); @@ -380,22 +390,27 @@ class DartGenerator extends StructuredGenerator { required String dartPackageName, }) { void writeEncodeLogic( - EnumeratedType customType, int nonSerializedClassCount) { + EnumeratedType customType, + int nonSerializedClassCount, + ) { indent.writeScoped('else if (value is ${customType.name}) {', '}', () { if (customType.offset(nonSerializedClassCount) < maximumCodecFieldKey) { indent.writeln( - 'buffer.putUint8(${customType.offset(nonSerializedClassCount)});'); + 'buffer.putUint8(${customType.offset(nonSerializedClassCount)});', + ); if (customType.type == CustomTypes.customClass) { indent.writeln('writeValue(buffer, value.encode());'); } else if (customType.type == CustomTypes.customEnum) { 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);'); + 'final $_overflowClassName wrap = $_overflowClassName(type: ${customType.offset(nonSerializedClassCount) - maximumCodecFieldKey}, wrapped: value$encodeString);', + ); indent.writeln('buffer.putUint8($maximumCodecFieldKey);'); indent.writeln('writeValue(buffer, wrap.encode());'); } @@ -403,29 +418,37 @@ class DartGenerator extends StructuredGenerator { } void writeDecodeLogic( - EnumeratedType customType, int nonSerializedClassCount) { + EnumeratedType customType, + int nonSerializedClassCount, + ) { indent.writeln('case ${customType.offset(nonSerializedClassCount)}: '); indent.nest(1, () { if (customType.type == CustomTypes.customClass) { if (customType.offset(nonSerializedClassCount) == maximumCodecFieldKey) { indent.writeln( - 'final ${customType.name} wrapper = ${customType.name}.decode(readValue(buffer)!);'); + 'final ${customType.name} wrapper = ${customType.name}.decode(readValue(buffer)!);', + ); indent.writeln('return wrapper.unwrap();'); } else { indent.writeln( - 'return ${customType.name}.decode(readValue(buffer)!);'); + 'return ${customType.name}.decode(readValue(buffer)!);', + ); } } else if (customType.type == CustomTypes.customEnum) { indent.writeln('final int? value = readValue(buffer) as int?;'); indent.writeln( - 'return value == null ? null : ${customType.name}.values[value];'); + 'return value == null ? null : ${customType.name}.values[value];', + ); } }); } final EnumeratedType overflowClass = EnumeratedType( - _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass); + _overflowClassName, + maximumCodecFieldKey, + CustomTypes.customClass, + ); indent.newln(); final List enumeratedTypes = @@ -445,8 +468,10 @@ class DartGenerator extends StructuredGenerator { indent.writeln('buffer.putInt64(value);'); }, addTrailingNewline: false); int nonSerializedClassCount = 0; - enumerate(enumeratedTypes, - (int index, final EnumeratedType customType) { + enumerate(enumeratedTypes, ( + int index, + final EnumeratedType customType, + ) { if (customType.associatedClass?.isSealed ?? false) { nonSerializedClassCount += 1; return; @@ -485,7 +510,8 @@ class DartGenerator extends StructuredGenerator { if (root.containsEventChannel) { indent.newln(); indent.writeln( - 'const StandardMethodCodec $_pigeonMethodChannelCodec = StandardMethodCodec($_pigeonMessageCodec());'); + 'const StandardMethodCodec $_pigeonMethodChannelCodec = StandardMethodCodec($_pigeonMessageCodec());', + ); } } @@ -515,29 +541,38 @@ class DartGenerator extends StructuredGenerator { indent.addScoped('{', '}', () { if (isMockHandler) { indent.writeln( - 'static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance;'); + 'static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance;', + ); } indent.writeln( - 'static const MessageCodec $pigeonChannelCodec = $_pigeonMessageCodec();'); + 'static const MessageCodec $pigeonChannelCodec = $_pigeonMessageCodec();', + ); indent.newln(); for (final Method func in api.methods) { addDocumentationComments( - indent, func.documentationComments, docCommentSpec); + indent, + func.documentationComments, + docCommentSpec, + ); final bool isAsync = func.isAsynchronous; - final String returnType = isAsync - ? 'Future<${addGenericTypesNullable(func.returnType)}>' - : addGenericTypesNullable(func.returnType); - final String argSignature = - _getMethodParameterSignature(func.parameters); + final String returnType = + isAsync + ? 'Future<${addGenericTypesNullable(func.returnType)}>' + : addGenericTypesNullable(func.returnType); + final String argSignature = _getMethodParameterSignature( + func.parameters, + ); indent.writeln('$returnType ${func.name}($argSignature);'); indent.newln(); } indent.write( - "static void setUp(${api.name}? api, {BinaryMessenger? binaryMessenger, String messageChannelSuffix = '',}) "); + "static void setUp(${api.name}? api, {BinaryMessenger? binaryMessenger, String messageChannelSuffix = '',}) ", + ); indent.addScoped('{', '}', () { indent.writeln( - r"messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';"); + r"messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';", + ); for (final Method func in api.methods) { writeFlutterMethodMessageHandler( @@ -546,9 +581,10 @@ 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, ); @@ -598,7 +634,8 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; '''); indent.writeln( - 'static const MessageCodec $pigeonChannelCodec = $_pigeonMessageCodec();'); + 'static const MessageCodec $pigeonChannelCodec = $_pigeonMessageCodec();', + ); indent.newln(); indent.writeln('final String $_suffixVarName;'); indent.newln(); @@ -658,9 +695,9 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; indent.format( instanceManagerTemplate( - allProxyApiNames: root.apis - .whereType() - .map((AstProxyApi api) => api.name), + allProxyApiNames: root.apis.whereType().map( + (AstProxyApi api) => api.name, + ), ), ); } @@ -673,81 +710,79 @@ 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) { + (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) { + }), + ]) + ..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), @@ -759,7 +794,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; baseName: 'int', isNullable: false, ), - ) + ), ], returnType: const TypeDeclaration.voidDeclaration(), channelName: makeRemoveStrongReferenceChannelName( @@ -780,55 +815,49 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; builder.statements.add( cb.Code(messageHandlerSink.toString()), ); - }, - ).statements, - ); - }, - ), - ) - ..methods.addAll( - [ - cb.Method( - (cb.MethodBuilder builder) { + }).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'), + (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, - ), + ..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, ), - ], - returnType: const TypeDeclaration.voidDeclaration(), - ); - builder.statements.addAll([ - cb.Code(messageCallSink.toString()), - ]); - }, - ); - }, - ), - cb.Method( - (cb.MethodBuilder builder) { + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ); + builder.statements.addAll([ + cb.Code(messageCallSink.toString()), + ]); + }); + }), + cb.Method((cb.MethodBuilder builder) { builder ..name = 'clear' ..returns = cb.refer('Future') @@ -838,31 +867,28 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; '///', '/// 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()), - ]); - }, - ); - }, - ), - ], - ), + ..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); indent.format( - DartFormatter(languageVersion: Version(3, 6, 0)) - .format('${instanceManagerApi.accept(emitter)}'), + DartFormatter( + languageVersion: Version(3, 6, 0), + ).format('${instanceManagerApi.accept(emitter)}'), ); } @@ -891,110 +917,119 @@ 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, + (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, + ), ), - ]) - ..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); @@ -1017,8 +1052,9 @@ 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( + final String relativeDartPath = path.Context( + style: path.Style.posix, + ).relative( _posixify(sourceOutPath), from: _posixify(path.dirname(testOutPath)), ); @@ -1028,14 +1064,21 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; // certain (older) versions of Dart. // TODO(gaaclarke): We should add a command-line parameter to override this import. indent.writeln( - "import '${_escapeForDartSingleQuotedString(relativeDartPath)}';"); + "import '${_escapeForDartSingleQuotedString(relativeDartPath)}';", + ); } else { - final String path = - relativeDartPath.replaceFirst(RegExp(r'^.*/lib/'), ''); + final String path = relativeDartPath.replaceFirst( + RegExp(r'^.*/lib/'), + '', + ); indent.writeln("import 'package:$dartOutputPackageName/$path';"); } - writeGeneralCodec(generatorOptions, root, indent, - dartPackageName: dartPackageName); + writeGeneralCodec( + generatorOptions, + root, + indent, + dartPackageName: dartPackageName, + ); for (final AstHostApi api in root.apis.whereType()) { if (api.dartHostTestHandler != null) { final AstFlutterApi mockApi = AstFlutterApi( @@ -1048,8 +1091,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, ); @@ -1077,7 +1120,8 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; "import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;", ); indent.writeln( - "import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;"); + "import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;", + ); indent.writeln("import 'package:flutter/services.dart';"); indent.writeln("import 'package:flutter_test/flutter_test.dart';"); indent.newln(); @@ -1114,17 +1158,20 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; void _writeWrapResponse(InternalDartOptions opt, Root root, Indent indent) { indent.newln(); indent.writeScoped( - 'List wrapResponse({Object? result, PlatformException? error, bool empty = false}) {', - '}', () { - indent.writeScoped('if (empty) {', '}', () { - indent.writeln('return [];'); - }); - indent.writeScoped('if (error == null) {', '}', () { - indent.writeln('return [result];'); - }); - indent.writeln( - 'return [error.code, error.message, error.details];'); - }); + 'List wrapResponse({Object? result, PlatformException? error, bool empty = false}) {', + '}', + () { + indent.writeScoped('if (empty) {', '}', () { + indent.writeln('return [];'); + }); + indent.writeScoped('if (error == null) {', '}', () { + indent.writeln('return [result];'); + }); + indent.writeln( + 'return [error.code, error.message, error.details];', + ); + }, + ); } void _writeDeepEquals(Indent indent) { @@ -1191,15 +1238,18 @@ if (wrapped == null) { nonSerializedClassCount++; } else { indent.writeScoped( - 'case ${i - nonSerializedClassCount - totalCustomCodecKeysAllowed}:', - '', () { - if (types[i].type == CustomTypes.customClass) { - indent.writeln('return ${types[i].name}.decode(wrapped!);'); - } else if (types[i].type == CustomTypes.customEnum) { - indent.writeln( - 'return ${types[i].name}.values[wrapped! as int];'); - } - }); + 'case ${i - nonSerializedClassCount - totalCustomCodecKeysAllowed}:', + '', + () { + if (types[i].type == CustomTypes.customClass) { + indent.writeln('return ${types[i].name}.decode(wrapped!);'); + } else if (types[i].type == CustomTypes.customEnum) { + indent.writeln( + 'return ${types[i].name}.values[wrapped! as int];', + ); + } + }, + ); } } }); @@ -1244,8 +1294,10 @@ if (wrapped == null) { }) { String sendArgument = 'null'; if (parameters.isNotEmpty) { - final Iterable argExpressions = - indexMap(parameters, (int index, NamedType type) { + final Iterable argExpressions = indexMap(parameters, ( + int index, + NamedType type, + ) { final String name = getParameterName(index, type); return name; }); @@ -1254,21 +1306,25 @@ if (wrapped == null) { final String channelSuffix = addSuffixVariable ? '\$$_suffixVarName' : ''; final String constOrFinal = addSuffixVariable ? 'final' : 'const'; indent.writeln( - "$constOrFinal String ${varNamePrefix}channelName = '$channelName$channelSuffix';"); + "$constOrFinal String ${varNamePrefix}channelName = '$channelName$channelSuffix';", + ); indent.writeScoped( - 'final BasicMessageChannel ${varNamePrefix}channel = BasicMessageChannel(', - ');', () { - indent.writeln('${varNamePrefix}channelName,'); - indent.writeln('$pigeonChannelCodec,'); - indent.writeln('binaryMessenger: ${varNamePrefix}binaryMessenger,'); - }); + 'final BasicMessageChannel ${varNamePrefix}channel = BasicMessageChannel(', + ');', + () { + indent.writeln('${varNamePrefix}channelName,'); + indent.writeln('$pigeonChannelCodec,'); + indent.writeln('binaryMessenger: ${varNamePrefix}binaryMessenger,'); + }, + ); final String returnTypeName = _makeGenericTypeArguments(returnType); 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 nullablyTypedAccessor = + returnTypeName == 'Object' + ? accessor + : '($accessor as $returnTypeName?)'; final String nullHandler = returnType.isNullable ? (genericCastCall.isEmpty ? '' : '?') : '!'; String returnStatement = 'return'; @@ -1334,9 +1390,13 @@ if (${varNamePrefix}replyList == null) { required bool isAsynchronous, bool addSuffixVariable = false, String nullHandlerExpression = 'api == null', - String Function(String methodName, Iterable parameters, - Iterable safeArgumentNames) - onCreateApiCall = _createFlutterApiMethodCall, + String Function( + String methodName, + Iterable parameters, + Iterable safeArgumentNames, + ) + onCreateApiCall = + _createFlutterApiMethodCall, }) { indent.write(''); indent.addScoped('{', '}', () { @@ -1347,13 +1407,12 @@ if (${varNamePrefix}replyList == null) { final String channelSuffix = addSuffixVariable ? r'$messageChannelSuffix' : ''; indent.writeln("'$channelName$channelSuffix', $pigeonChannelCodec,"); - indent.writeln( - 'binaryMessenger: binaryMessenger);', - ); + 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);'); @@ -1376,7 +1435,8 @@ if (${varNamePrefix}replyList == null) { indent.writeln("'Argument for $channelName was null.');"); const String argsArray = 'args'; indent.writeln( - 'final List $argsArray = (message as List?)!;'); + 'final List $argsArray = (message as List?)!;', + ); String argNameFunc(int index, NamedType type) => _getSafeArgumentName(index, type); enumerate(parameters, (int count, NamedType arg) { @@ -1388,16 +1448,20 @@ if (${varNamePrefix}replyList == null) { final String leftHandSide = 'final $argType? $argName'; indent.writeln( - '$leftHandSide = ($argsArray[$count] as $genericArgType?)${castCall.isEmpty ? '' : '?$castCall'};'); + '$leftHandSide = ($argsArray[$count] as $genericArgType?)${castCall.isEmpty ? '' : '?$castCall'};', + ); if (!arg.type.isNullable) { indent.writeln('assert($argName != null,'); indent.writeln( - " 'Argument for $channelName was null, expected non-null $argType.');"); + " 'Argument for $channelName was null, expected non-null $argType.');", + ); } }); - final Iterable argNames = - indexMap(parameters, (int index, Parameter field) { + final Iterable argNames = indexMap(parameters, ( + int index, + Parameter field, + ) { final String name = _getSafeArgumentName(index, field); return '${field.isNamed ? '${field.name}: ' : ''}$name${field.type.isNullable ? '' : '!'}'; }); @@ -1419,9 +1483,10 @@ 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); @@ -1431,7 +1496,8 @@ if (${varNamePrefix}replyList == null) { indent.writeScoped('catch (e) {', '}', () { indent.writeln( - "return wrapResponse(error: PlatformException(code: 'error', message: e.toString()));"); + "return wrapResponse(error: PlatformException(code: 'error', message: e.toString()));", + ); }); }); }); @@ -1494,12 +1560,14 @@ 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 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(); @@ -1519,8 +1587,9 @@ String _getMethodParameterSignature( final String optionalParameterString = optionalPositionalParams .map((Parameter p) => getParameterString(p)) .join(', '); - final String namedParameterString = - namedParams.map((Parameter p) => getParameterString(p)).join(', '); + final String namedParameterString = namedParams + .map((Parameter p) => getParameterString(p)) + .join(', '); // Parameter lists can end with either named or optional positional parameters, but not both. if (requiredPositionalParams.isNotEmpty) { @@ -1538,10 +1607,11 @@ String _getMethodParameterSignature( return '$baseParams[$optionalParameterString$trailingComma]'; } if (namedParams.isNotEmpty) { - final String trailingComma = addTrailingComma || - requiredPositionalParams.length + namedParams.length > 2 - ? ', ' - : ''; + final String trailingComma = + addTrailingComma || + requiredPositionalParams.length + namedParams.length > 2 + ? ', ' + : ''; return '$baseParams{$namedParameterString$trailingComma}'; } return signature; @@ -1551,9 +1621,12 @@ String _getMethodParameterSignature( /// used in Dart code. String _flattenTypeArguments(List args) { return args - .map((TypeDeclaration arg) => arg.typeArguments.isEmpty - ? '${arg.baseName}${arg.isNullable ? '?' : ''}' - : '${arg.baseName}<${_flattenTypeArguments(arg.typeArguments)}>${arg.isNullable ? '?' : ''}') + .map( + (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 dc8f4504f05..89c12288dea 100644 --- a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart +++ b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart @@ -26,79 +26,95 @@ 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, ), ); } @@ -113,44 +129,46 @@ Iterable overridesClassConstructors( final String lowerCamelCaseApiName = toLowerCamelCase(api.name); for (final Constructor constructor in api.constructors) { - yield cb.Field( - (cb.FieldBuilder builder) { - 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(), - declaredFlutterMethods: api.flutterMethods, - includeBinaryMessengerAndInstanceManager: false, + yield cb.Field((cb.FieldBuilder builder) { + 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(), + declaredFlutterMethods: api.flutterMethods, + includeBinaryMessengerAndInstanceManager: false, + ); + builder + ..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!, + }), ); - builder - ..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!, - }), - ); - }, - ); + }); } } } @@ -164,8 +182,9 @@ Iterable overridesClassStaticFields( for (final AstProxyApi api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); - for (final ApiField field - in api.fields.where((ApiField field) => field.isStatic)) { + for (final ApiField field in api.fields.where( + (ApiField field) => field.isStatic, + )) { yield cb.Field((cb.FieldBuilder builder) { builder ..name = '${lowerCamelCaseApiName}_${field.name}' @@ -186,8 +205,9 @@ Iterable overridesClassStaticMethods( for (final AstProxyApi api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); - for (final Method method - in api.hostMethods.where((Method method) => method.isStatic)) { + for (final Method method in api.hostMethods.where( + (Method method) => method.isStatic, + )) { yield cb.Field((cb.FieldBuilder builder) { builder ..name = '${lowerCamelCaseApiName}_${method.name}' @@ -209,9 +229,7 @@ Iterable overridesClassStaticMethods( /// Creates the reset method for the `PigeonOverrides` class that sets all /// overrideable methods to null. -cb.Method overridesClassResetMethod( - Iterable proxyApis, -) { +cb.Method overridesClassResetMethod(Iterable proxyApis) { return cb.Method.returnsVoid((cb.MethodBuilder builder) { builder ..name = '${classMemberNamePrefix}reset' @@ -225,13 +243,15 @@ cb.Method overridesClassResetMethod( cb.Code( '${toLowerCamelCase(api.name)}_${constructor.name.isEmpty ? 'new' : constructor.name} = null;', ), - for (final ApiField attachedField - in api.fields.where((ApiField field) => field.isStatic)) + for (final ApiField attachedField in api.fields.where( + (ApiField field) => field.isStatic, + )) cb.Code( '${toLowerCamelCase(api.name)}_${attachedField.name} = null;', ), - for (final Method staticMethod - in api.methods.where((Method method) => method.isStatic)) + for (final Method staticMethod in api.methods.where( + (Method method) => method.isStatic, + )) cb.Code( '${toLowerCamelCase(api.name)}_${staticMethod.name} = null;', ), @@ -242,28 +262,24 @@ cb.Method overridesClassResetMethod( /// Converts a method to a `code_builder` FunctionType with all parameters as /// positional arguments. -cb.FunctionType methodAsFunctionType( - Method method, { - required String apiName, -}) { +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)}', + ); + }), + ]), ); } @@ -283,19 +299,24 @@ Iterable staticAttachedFieldsGetters( required String apiName, }) 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}', - )); + 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}', + ), + ); } } @@ -307,28 +328,23 @@ 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); @@ -352,10 +368,11 @@ 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) { @@ -363,96 +380,98 @@ Iterable constructors( 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. - yield cb.Constructor( - (cb.ConstructorBuilder builder) { - final Iterable parameters = asConstructorParameters( - apiName: apiName, - parameters: constructor.parameters, - unattachedFields: unattachedFields, - flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, - flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, - declaredFlutterMethods: declaredFlutterMethods, - ); - final Iterable parametersWithoutMessengerAndManager = - asConstructorParameters( - apiName: apiName, - parameters: constructor.parameters, - unattachedFields: unattachedFields, - flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, - flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, - declaredFlutterMethods: declaredFlutterMethods, - includeBinaryMessengerAndInstanceManager: false, - ); - builder - ..name = factoryConstructorName - ..factory = true - ..docs.addAll(asDocumentationComments( + yield cb.Constructor((cb.ConstructorBuilder builder) { + final Iterable parameters = asConstructorParameters( + apiName: apiName, + parameters: constructor.parameters, + unattachedFields: unattachedFields, + flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, + flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, + declaredFlutterMethods: declaredFlutterMethods, + ); + final Iterable parametersWithoutMessengerAndManager = + asConstructorParameters( + apiName: apiName, + parameters: constructor.parameters, + unattachedFields: unattachedFields, + flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, + flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, + declaredFlutterMethods: declaredFlutterMethods, + includeBinaryMessengerAndInstanceManager: false, + ); + builder + ..name = factoryConstructorName + ..factory = true + ..docs.addAll( + asDocumentationComments( constructor.documentationComments, docCommentSpec, - )) - ..optionalParameters.addAll(parameters) - ..body = cb.Block( - (cb.BlockBuilder builder) { - final Map forwardedParams = - { + ), + ) + ..optionalParameters.addAll(parameters) + ..body = cb.Block((cb.BlockBuilder builder) { + final Map forwardedParams = + { for (final cb.Parameter parameter in parameters) - parameter.name: cb.refer(parameter.name) - }; - final Map - forwardedParamsWithoutMessengerAndManager = - { - for (final cb.Parameter parameter - in parametersWithoutMessengerAndManager) - parameter.name: cb.refer(parameter.name) + parameter.name: cb.refer(parameter.name), }; + final Map + forwardedParamsWithoutMessengerAndManager = { + for (final cb.Parameter parameter + in parametersWithoutMessengerAndManager) + parameter.name: cb.refer(parameter.name), + }; - builder.statements.addAll([ - cb.Code( - 'if ($proxyApiOverridesClassName.$overridesConstructorName != null) {'), - cb.CodeExpression( + builder.statements.addAll([ + cb.Code( + 'if ($proxyApiOverridesClassName.$overridesConstructorName != null) {', + ), + cb.CodeExpression( cb.Code( - '$proxyApiOverridesClassName.$overridesConstructorName!'), + '$proxyApiOverridesClassName.$overridesConstructorName!', + ), ) - .call( - [], - forwardedParamsWithoutMessengerAndManager, - ) - .returned - .statement, - const cb.Code('}'), - cb.CodeExpression(cb.Code('$apiName.$constructorName')) - .call([], forwardedParams) - .returned - .statement, - ]); - }, - ); - }, - ); + .call( + [], + forwardedParamsWithoutMessengerAndManager, + ) + .returned + .statement, + const cb.Code('}'), + cb.CodeExpression( + cb.Code('$apiName.$constructorName'), + ).call([], forwardedParams).returned.statement, + ]); + }); + }); - yield cb.Constructor( - (cb.ConstructorBuilder builder) { - final String channelName = makeChannelNameWithStrings( - apiName: apiName, - methodName: constructor.name.isNotEmpty - ? constructor.name - : '${classMemberNamePrefix}defaultConstructor', - dartPackageName: dartPackageName, - ); - builder - ..name = constructorName - ..annotations.add(cb.refer('protected')) - ..docs.addAll(asDocumentationComments( + yield cb.Constructor((cb.ConstructorBuilder builder) { + final String channelName = makeChannelNameWithStrings( + apiName: apiName, + methodName: + constructor.name.isNotEmpty + ? constructor.name + : '${classMemberNamePrefix}defaultConstructor', + dartPackageName: dartPackageName, + ); + builder + ..name = constructorName + ..annotations.add(cb.refer('protected')) + ..docs.addAll( + asDocumentationComments( constructor.documentationComments, docCommentSpec, - )) - ..optionalParameters.addAll(asConstructorParameters( + ), + ) + ..optionalParameters.addAll( + asConstructorParameters( apiName: apiName, parameters: constructor.parameters, unattachedFields: unattachedFields, @@ -460,55 +479,48 @@ Iterable constructors( flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, declaredFlutterMethods: declaredFlutterMethods, defineType: false, - )) - ..initializers.addAll( - [ - if (superClassApi != null) - const cb.Code('super.${classMemberNamePrefix}detached()') + ), + ) + ..initializers.addAll([ + if (superClassApi != null) + const cb.Code('super.${classMemberNamePrefix}detached()'), + ]) + ..body = cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageCallSink = StringBuffer(); + DartGenerator.writeHostMethodMessageCall( + Indent(messageCallSink), + addSuffixVariable: false, + channelName: channelName, + insideAsyncMethod: false, + parameters: [ + Parameter( + name: '${varNamePrefix}instanceIdentifier', + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ), + ...unattachedFields.map( + (ApiField field) => + Parameter(name: field.name, type: field.type), + ), + ...constructor.parameters, ], - ) - ..body = cb.Block( - (cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); - DartGenerator.writeHostMethodMessageCall( - Indent(messageCallSink), - addSuffixVariable: false, - channelName: channelName, - insideAsyncMethod: false, - parameters: [ - Parameter( - name: '${varNamePrefix}instanceIdentifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ...unattachedFields.map( - (ApiField field) => Parameter( - name: field.name, - type: field.type, - ), - ), - ...constructor.parameters, - ], - returnType: const TypeDeclaration.voidDeclaration(), - ); - - builder.statements.addAll([ - const cb.Code( - 'final int ${varNamePrefix}instanceIdentifier = $instanceManagerVarName.addDartCreatedInstance(this);', - ), - cb.Code('final $codecName $pigeonChannelCodec =\n' - ' $codecInstanceName;'), - cb.Code( - 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${binaryMessengerParameter.name};', - ), - cb.Code(messageCallSink.toString()), - ]); - }, + returnType: const TypeDeclaration.voidDeclaration(), ); - }, - ); + + builder.statements.addAll([ + const cb.Code( + 'final int ${varNamePrefix}instanceIdentifier = $instanceManagerVarName.addDartCreatedInstance(this);', + ), + cb.Code( + 'final $codecName $pigeonChannelCodec =\n' + ' $codecInstanceName;', + ), + cb.Code( + 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${binaryMessengerParameter.name};', + ), + cb.Code(messageCallSink.toString()), + ]); + }); + }); } } @@ -528,28 +540,31 @@ 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()'), + ]), ); } @@ -559,30 +574,32 @@ 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)'), ); } /// Converts unattached fields from the pigeon AST to `code_builder` /// Fields. -Iterable unattachedFields( - Iterable fields, -) sync* { +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, + ), + ), ); } } @@ -598,37 +615,37 @@ 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), ); } } @@ -649,34 +666,39 @@ 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, - )) - ..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)}', - ); - }, + (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, + ) + ..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)}', + ); + }), + ]), + ), ); } } @@ -695,17 +717,20 @@ 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}()'), ); } } @@ -729,184 +754,197 @@ 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)}', - ); - }, - ), - ), + (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)}', - ); - }, - ), - ]), + 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;', - ) - ], - 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); - }, - ), - ], - 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);', ), - 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(); + 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, + ), + ), + ...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(); - return '($instanceManagerVarName ?? $dartInstanceManagerClassName.instance)\n' - ' .addHostCreatedInstance(\n' - ' $methodName?.call(${safeArgumentNames.skip(1).join(',')}) ??\n' - ' $apiName.${classMemberNamePrefix}detached(' - ' ${classMemberNamePrefix}binaryMessenger: ${classMemberNamePrefix}binaryMessenger,\n' - ' $instanceManagerVarName: $instanceManagerVarName,\n' - ' $argsAsNamedParams\n' - ' ),\n' - ' ${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, + return '($instanceManagerVarName ?? $dartInstanceManagerClassName.instance)\n' + ' .addHostCreatedInstance(\n' + ' $methodName?.call(${safeArgumentNames.skip(1).join(',')}) ??\n' + ' $apiName.${classMemberNamePrefix}detached(' + ' ${classMemberNamePrefix}binaryMessenger: ${classMemberNamePrefix}binaryMessenger,\n' + ' $instanceManagerVarName: $instanceManagerVarName,\n' + ' $argsAsNamedParams\n' + ' ),\n' + ' ${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, ), - ), - ...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, - ) { - final String nullability = method.isRequired ? '' : '?'; - return '($methodName ?? ${safeArgumentNames.first}.$methodName)$nullability.call(${safeArgumentNames.join(',')})'; - }, - ); - builder.statements.add(cb.Code(messageHandlerSink.toString())); - }).statements, - ]), + channelName: makeChannelNameWithStrings( + apiName: apiName, + methodName: method.name, + dartPackageName: dartPackageName, + ), + isMockHandler: false, + isAsynchronous: method.isAsynchronous, + nullHandlerExpression: + '${classMemberNamePrefix}clearHandlers', + onCreateApiCall: ( + String methodName, + Iterable parameters, + Iterable safeArgumentNames, + ) { + final String nullability = method.isRequired ? '' : '?'; + return '($methodName ?? ${safeArgumentNames.first}.$methodName)$nullability.call(${safeArgumentNames.join(',')})'; + }, + ); + builder.statements.add(cb.Code(messageHandlerSink.toString())); + }).statements, + ]), ); } @@ -923,85 +961,77 @@ Iterable attachedFieldMethods( required String codecName, }) sync* { for (final ApiField field in fields) { - yield cb.Method( - (cb.MethodBuilder builder) { - final String type = addGenericTypesNullable(field.type); - const String instanceName = '${varNamePrefix}instance'; - const String identifierInstanceName = - '${varNamePrefix}instanceIdentifier'; - builder - ..name = '$varNamePrefix${field.name}' - ..static = field.isStatic - ..returns = cb.refer(type) - ..body = cb.Block( - (cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); - DartGenerator.writeHostMethodMessageCall( - Indent(messageCallSink), - addSuffixVariable: false, - channelName: makeChannelNameWithStrings( - apiName: apiName, - methodName: field.name, - dartPackageName: dartPackageName, + yield cb.Method((cb.MethodBuilder builder) { + final String type = addGenericTypesNullable(field.type); + const String instanceName = '${varNamePrefix}instance'; + const String identifierInstanceName = + '${varNamePrefix}instanceIdentifier'; + builder + ..name = '$varNamePrefix${field.name}' + ..static = field.isStatic + ..returns = cb.refer(type) + ..body = cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageCallSink = StringBuffer(); + DartGenerator.writeHostMethodMessageCall( + Indent(messageCallSink), + addSuffixVariable: false, + channelName: makeChannelNameWithStrings( + apiName: apiName, + methodName: field.name, + dartPackageName: dartPackageName, + ), + parameters: [ + if (!field.isStatic) + Parameter( + name: 'this', + type: TypeDeclaration(baseName: apiName, isNullable: false), ), - parameters: [ - if (!field.isStatic) - Parameter( - name: 'this', - type: TypeDeclaration( - baseName: apiName, - isNullable: false, - ), - ), - Parameter( - name: identifierInstanceName, - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ], - returnType: const TypeDeclaration.voidDeclaration(), - ); - builder.statements.addAll([ - if (!field.isStatic) ...[ - cb.Code( - 'final $type $instanceName = $type.${classMemberNamePrefix}detached(\n' - ' ${classMemberNamePrefix}binaryMessenger: ${classMemberNamePrefix}binaryMessenger,\n' - ' ${classMemberNamePrefix}instanceManager: ${classMemberNamePrefix}instanceManager,\n' - ');', - ), - cb.Code('final $codecName $pigeonChannelCodec =\n' - ' $codecInstanceName;'), - const cb.Code( - 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', - ), - const cb.Code( - 'final int $identifierInstanceName = $instanceManagerVarName.addDartCreatedInstance($instanceName);', - ), - ] else ...[ - cb.Code( - 'final $type $instanceName = $type.${classMemberNamePrefix}detached();', - ), - cb.Code( - 'final $codecName $pigeonChannelCodec = $codecName($dartInstanceManagerClassName.instance);', - ), - const cb.Code( - 'final BinaryMessenger ${varNamePrefix}binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger;', - ), - const cb.Code( - 'final int $identifierInstanceName = $dartInstanceManagerClassName.instance.addDartCreatedInstance($instanceName);', - ), - ], - const cb.Code('() async {'), - cb.Code(messageCallSink.toString()), - const cb.Code('}();'), - const cb.Code('return $instanceName;'), - ]); - }, + Parameter( + name: identifierInstanceName, + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), ); - }, - ); + builder.statements.addAll([ + if (!field.isStatic) ...[ + cb.Code( + 'final $type $instanceName = $type.${classMemberNamePrefix}detached(\n' + ' ${classMemberNamePrefix}binaryMessenger: ${classMemberNamePrefix}binaryMessenger,\n' + ' ${classMemberNamePrefix}instanceManager: ${classMemberNamePrefix}instanceManager,\n' + ');', + ), + cb.Code( + 'final $codecName $pigeonChannelCodec =\n' + ' $codecInstanceName;', + ), + const cb.Code( + 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', + ), + const cb.Code( + 'final int $identifierInstanceName = $instanceManagerVarName.addDartCreatedInstance($instanceName);', + ), + ] else ...[ + cb.Code( + 'final $type $instanceName = $type.${classMemberNamePrefix}detached();', + ), + cb.Code( + 'final $codecName $pigeonChannelCodec = $codecName($dartInstanceManagerClassName.instance);', + ), + const cb.Code( + 'final BinaryMessenger ${varNamePrefix}binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger;', + ), + const cb.Code( + 'final int $identifierInstanceName = $dartInstanceManagerClassName.instance.addDartCreatedInstance($instanceName);', + ), + ], + const cb.Code('() async {'), + cb.Code(messageCallSink.toString()), + const cb.Code('}();'), + const cb.Code('return $instanceName;'), + ]); + }); + }); } } @@ -1020,94 +1050,100 @@ 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, ), - parameters: [ - if (!method.isStatic) - Parameter( - name: 'this', - type: TypeDeclaration( - baseName: apiName, - isNullable: false, - ), - ), - ...method.parameters, + ) + ..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?'), + ), ], - returnType: method.returnType, - ); - builder.statements.addAll([ - if (method.isStatic) ...[ - cb.Code( - 'if ($proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name} != null) {', + ]) + ..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.CodeExpression( + 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( - '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name}!', + 'if ($proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name} != null) {', ), - ) - .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);', + 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;', ), - const cb.Code( - 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', - ), - cb.Code(messageCallSink.toString()), - ]); - }, - ), + cb.Code(messageCallSink.toString()), + ]); + }), ); } } @@ -1133,22 +1169,20 @@ 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 b156ad9ecb9..36f2ec56bd8 100644 --- a/packages/pigeon/lib/src/dart/templates.dart +++ b/packages/pigeon/lib/src/dart/templates.dart @@ -19,14 +19,10 @@ const String dartInstanceManagerApiClassName = '_${classNamePrefix}InstanceManagerApi'; /// Creates the `InstanceManager` with the passed string values. -String instanceManagerTemplate({ - required Iterable allProxyApiNames, -}) { - final Iterable apiHandlerSetUps = allProxyApiNames.map( - (String name) { - return '$name.${classMemberNamePrefix}setUpMessageHandlers(${classMemberNamePrefix}instanceManager: instanceManager);'; - }, - ); +String instanceManagerTemplate({required Iterable allProxyApiNames}) { + final Iterable apiHandlerSetUps = allProxyApiNames.map((String name) { + return '$name.${classMemberNamePrefix}setUpMessageHandlers(${classMemberNamePrefix}instanceManager: instanceManager);'; + }); return ''' /// Maintains instances used to communicate with the native objects they diff --git a/packages/pigeon/lib/src/functional.dart b/packages/pigeon/lib/src/functional.dart index 8e23950e9e7..219b6c49a12 100644 --- a/packages/pigeon/lib/src/functional.dart +++ b/packages/pigeon/lib/src/functional.dart @@ -5,7 +5,9 @@ /// A [map] function that calls the function with an enumeration as well as the /// value. Iterable indexMap( - Iterable iterable, U Function(int index, T value) func) sync* { + Iterable iterable, + U Function(int index, T value) func, +) sync* { int index = 0; for (final T value in iterable) { yield func(index, value); @@ -25,7 +27,10 @@ void enumerate(Iterable iterable, void Function(int, T) func) { /// A [map] function that takes in 2 iterables. The [Iterable]s must be of /// equal length. Iterable map2( - Iterable ts, Iterable us, V Function(T t, U u) func) sync* { + Iterable ts, + Iterable us, + V Function(T t, U u) func, +) sync* { final Iterator itt = ts.iterator; final Iterator itu = us.iterator; while (itu.moveNext() && itt.moveNext()) { @@ -38,8 +43,12 @@ Iterable map2( /// A [map] function that takes in 3 iterables. The [Iterable]s must be of /// equal length. -Iterable map3(Iterable ts, Iterable us, Iterable ws, - V Function(T t, U u, W w) func) sync* { +Iterable map3( + Iterable ts, + Iterable us, + Iterable ws, + V Function(T t, U u, W w) func, +) sync* { final Iterator itt = ts.iterator; final Iterator itu = us.iterator; final Iterator itw = ws.iterator; diff --git a/packages/pigeon/lib/src/generator.dart b/packages/pigeon/lib/src/generator.dart index 8c582dfb8a0..a185ec3f9c0 100644 --- a/packages/pigeon/lib/src/generator.dart +++ b/packages/pigeon/lib/src/generator.dart @@ -109,12 +109,7 @@ abstract class StructuredGenerator dartPackageName: dartPackageName, ); - writeApis( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); + writeApis(generatorOptions, root, indent, dartPackageName: dartPackageName); writeCloseNamespace( generatorOptions, @@ -352,11 +347,7 @@ abstract class StructuredGenerator /// an `InstanceManager`. The write implementation should convert an instance /// to an identifier. The read implementation should covert the identifier /// to an instance. - void writeProxyApiBaseCodec( - T generatorOptions, - Root root, - Indent indent, - ) {} + void writeProxyApiBaseCodec(T generatorOptions, Root root, Indent indent) {} /// Writes a single Proxy Api to [indent]. void writeProxyApi( diff --git a/packages/pigeon/lib/src/generator_tools.dart b/packages/pigeon/lib/src/generator_tools.dart index 3017193d842..169d0eb6309 100644 --- a/packages/pigeon/lib/src/generator_tools.dart +++ b/packages/pigeon/lib/src/generator_tools.dart @@ -83,17 +83,19 @@ 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)); @@ -237,10 +239,16 @@ class HostDatatype { /// /// [customResolver] can modify the datatype of custom types. HostDatatype getFieldHostDatatype( - NamedType field, String? Function(TypeDeclaration) builtinResolver, - {String Function(String)? customResolver}) { - return _getHostDatatype(field.type, builtinResolver, - customResolver: customResolver, fieldName: field.name); + NamedType field, + String? Function(TypeDeclaration) builtinResolver, { + String Function(String)? customResolver, +}) { + return _getHostDatatype( + field.type, + builtinResolver, + customResolver: customResolver, + fieldName: field.name, + ); } /// Calculates the [HostDatatype] for the provided [TypeDeclaration]. @@ -251,21 +259,30 @@ HostDatatype getFieldHostDatatype( /// /// [customResolver] can modify the datatype of custom types. HostDatatype getHostDatatype( - TypeDeclaration type, String? Function(TypeDeclaration) builtinResolver, - {String Function(String)? customResolver}) { - return _getHostDatatype(type, builtinResolver, - customResolver: customResolver); + TypeDeclaration type, + String? Function(TypeDeclaration) builtinResolver, { + String Function(String)? customResolver, +}) { + return _getHostDatatype( + type, + builtinResolver, + customResolver: customResolver, + ); } HostDatatype _getHostDatatype( - TypeDeclaration type, String? Function(TypeDeclaration) builtinResolver, - {String Function(String)? customResolver, String? fieldName}) { + TypeDeclaration type, + String? Function(TypeDeclaration) builtinResolver, { + String Function(String)? customResolver, + String? fieldName, +}) { 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, @@ -273,9 +290,10 @@ 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, @@ -284,7 +302,8 @@ HostDatatype _getHostDatatype( ); } else { throw Exception( - 'unrecognized datatype ${fieldName == null ? '' : 'for field:"$fieldName" '}of type:"${type.baseName}"'); + 'unrecognized datatype ${fieldName == null ? '' : 'for field:"$fieldName" '}of type:"${type.baseName}"', + ); } } else { return HostDatatype( @@ -351,7 +370,7 @@ const List disallowedPrefixes = [ hostProxyApiPrefix, proxyApiClassNamePrefix, varNamePrefix, - 'pigeonChannelCodec' + 'pigeonChannelCodec', ]; /// Collection of keys used in dictionaries across generators. @@ -399,8 +418,10 @@ Map mergeMaps( final Object entryValue = entry.value; if (entryValue is Map) { assert(base[entry.key] is Map); - result[entry.key] = - mergeMaps((base[entry.key] as Map?)!, entryValue); + result[entry.key] = mergeMaps( + (base[entry.key] as Map?)!, + entryValue, + ); } else { result[entry.key] = entry.value; } @@ -419,8 +440,13 @@ Map mergeMaps( /// A type name that is enumerated. class EnumeratedType { /// Constructor. - EnumeratedType(this.name, this.enumeration, this.type, - {this.associatedClass, this.associatedEnum}); + EnumeratedType( + this.name, + this.enumeration, + this.type, { + this.associatedClass, + this.associatedEnum, + }); /// The name of the type. final String name; @@ -486,7 +512,9 @@ Iterable _getTypeArguments(TypeDeclaration type) sync* { } bool _isUnseenCustomType( - TypeDeclaration type, Set referencedTypeNames) { + TypeDeclaration type, + Set referencedTypeNames, +) { return !referencedTypeNames.contains(type.baseName) && !validTypes.contains(type.baseName); } @@ -513,7 +541,9 @@ class _Bag { /// Recurses into a list of [Api]s and produces a list of all referenced types /// and an associated [List] of the offsets where they are found. Map> getReferencedTypes( - List apis, List classes) { + List apis, + List classes, +) { final _Bag references = _Bag(); for (final Api api in apis) { for (final Method method in api.methods) { @@ -542,8 +572,10 @@ Map> getReferencedTypes( final List classesToCheck = List.from(referencedTypeNames); while (classesToCheck.isNotEmpty) { final String next = classesToCheck.removeLast(); - final Class aClass = classes.firstWhere((Class x) => x.name == next, - orElse: () => Class(name: '', fields: [])); + final Class aClass = classes.firstWhere( + (Class x) => x.name == next, + orElse: () => Class(name: '', fields: []), + ); for (final NamedType field in aClass.fields) { if (_isUnseenCustomType(field.type, referencedTypeNames)) { references.add(field.type, field.offset); @@ -566,7 +598,7 @@ Map> getReferencedTypes( /// [T] depends on the language. For example, Android uses an int while iOS uses /// semantic versioning. ({TypeDeclaration type, T version})? - findHighestApiRequirement( +findHighestApiRequirement( Iterable types, { required T? Function(TypeDeclaration) onGetApiRequirement, required Comparator onCompare, @@ -588,13 +620,14 @@ Map> getReferencedTypes( return null; } - final TypeDeclaration typeWithHighestRequirement = allReferencedTypes.reduce( - (TypeDeclaration one, TypeDeclaration two) { - return onCompare(onGetApiRequirement(one)!, onGetApiRequirement(two)!) > 0 - ? one - : two; - }, - ); + final TypeDeclaration typeWithHighestRequirement = allReferencedTypes.reduce(( + TypeDeclaration one, + TypeDeclaration two, + ) { + return onCompare(onGetApiRequirement(one)!, onGetApiRequirement(two)!) > 0 + ? one + : two; + }); return ( type: typeWithHighestRequirement, @@ -834,7 +867,9 @@ String toLowerCamelCase(String text) { String toScreamingSnakeCase(String string) { return string .replaceAllMapped( - RegExp(r'(?<=[a-z])[A-Z]'), (Match m) => '_${m.group(0)}') + RegExp(r'(?<=[a-z])[A-Z]'), + (Match m) => '_${m.group(0)}', + ) .toUpperCase(); } diff --git a/packages/pigeon/lib/src/gobject/gobject_generator.dart b/packages/pigeon/lib/src/gobject/gobject_generator.dart index ca58a25d44e..d5eafdcf531 100644 --- a/packages/pigeon/lib/src/gobject/gobject_generator.dart +++ b/packages/pigeon/lib/src/gobject/gobject_generator.dart @@ -10,8 +10,11 @@ import '../generator_tools.dart'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = - DocumentCommentSpecification('/**', - closeCommentToken: ' */', blockContinuationToken: ' *'); + DocumentCommentSpecification( + '/**', + closeCommentToken: ' */', + blockContinuationToken: ' *', + ); /// Name for codec class. const String _codecBaseName = 'MessageCodec'; @@ -91,11 +94,11 @@ class InternalGObjectOptions extends InternalOptions { required this.gobjectHeaderOut, required this.gobjectSourceOut, Iterable? copyrightHeader, - }) : headerIncludePath = - options.headerIncludePath ?? path.basename(gobjectHeaderOut), - module = options.module, - copyrightHeader = options.copyrightHeader ?? copyrightHeader, - headerOutPath = options.headerOutPath; + }) : headerIncludePath = + options.headerIncludePath ?? path.basename(gobjectHeaderOut), + module = options.module, + copyrightHeader = options.copyrightHeader ?? copyrightHeader, + headerOutPath = options.headerOutPath; /// The path to the header that will get placed in the source file (example: /// "foo.h"). @@ -131,8 +134,10 @@ class GObjectGenerator StringSink sink, { required String dartPackageName, }) { - assert(generatorOptions.fileType == FileType.header || - generatorOptions.fileType == FileType.source); + assert( + generatorOptions.fileType == FileType.header || + generatorOptions.fileType == FileType.source, + ); if (generatorOptions.fileType == FileType.header) { const GObjectHeaderGenerator().generate( generatorOptions.languageOptions, @@ -213,27 +218,31 @@ class GObjectHeaderGenerator final List enumValueCommentLines = []; for (int i = 0; i < anEnum.members.length; i++) { final EnumMember member = anEnum.members[i]; - final String itemName = - _getEnumValue(dartPackageName, anEnum.name, member.name); + final String itemName = _getEnumValue( + dartPackageName, + anEnum.name, + member.name, + ); enumValueCommentLines.add('$itemName:'); enumValueCommentLines.addAll(member.documentationComments); } - addDocumentationComments( - indent, - [ - '$enumName:', - ...enumValueCommentLines, - '', - ...anEnum.documentationComments - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '$enumName:', + ...enumValueCommentLines, + '', + ...anEnum.documentationComments, + ], _docCommentSpec); indent.writeScoped('typedef enum {', '} $enumName;', () { for (int i = 0; i < anEnum.members.length; i++) { final EnumMember member = anEnum.members[i]; - final String itemName = - _getEnumValue(dartPackageName, anEnum.name, member.name); + final String itemName = _getEnumValue( + dartPackageName, + anEnum.name, + member.name, + ); indent.writeln( - '$itemName = $i${i == anEnum.members.length - 1 ? '' : ','}'); + '$itemName = $i${i == anEnum.members.length - 1 ? '' : ','}', + ); } }); } @@ -251,14 +260,11 @@ class GObjectHeaderGenerator final String methodPrefix = _getMethodPrefix(module, classDefinition.name); indent.newln(); - addDocumentationComments( - indent, - [ - '$className:', - '', - ...classDefinition.documentationComments, - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '$className:', + '', + ...classDefinition.documentationComments, + ], _docCommentSpec); indent.newln(); _writeDeclareFinalType(indent, module, classDefinition.name); @@ -278,52 +284,49 @@ class GObjectHeaderGenerator final String fieldName = _getFieldName(field.name); constructorFieldCommentLines.add('$fieldName: field in this object.'); if (_isNumericListType(field.type)) { - constructorFieldCommentLines - .add('${fieldName}_length: length of @$fieldName.'); + constructorFieldCommentLines.add( + '${fieldName}_length: length of @$fieldName.', + ); } } - addDocumentationComments( - indent, - [ - '${methodPrefix}_new:', - ...constructorFieldCommentLines, - '', - 'Creates a new #${classDefinition.name} object.', - '', - 'Returns: a new #$className', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_new:', + ...constructorFieldCommentLines, + '', + 'Creates a new #${classDefinition.name} object.', + '', + 'Returns: a new #$className', + ], _docCommentSpec); indent.writeln( - "$className* ${methodPrefix}_new(${constructorArgs.join(', ')});"); + "$className* ${methodPrefix}_new(${constructorArgs.join(', ')});", + ); for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); final String returnType = _getType(module, field.type); indent.newln(); - addDocumentationComments( - indent, - [ - '${methodPrefix}_get_$fieldName', - '@object: a #$className.', - if (_isNumericListType(field.type)) - '@length: location to write the length of this value.', - '', - if (field.documentationComments.isNotEmpty) - ...field.documentationComments - else - 'Gets the value of the ${field.name} field of @object.', - '', - 'Returns: the field value.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_get_$fieldName', + '@object: a #$className.', + if (_isNumericListType(field.type)) + '@length: location to write the length of this value.', + '', + if (field.documentationComments.isNotEmpty) + ...field.documentationComments + else + 'Gets the value of the ${field.name} field of @object.', + '', + 'Returns: the field value.', + ], _docCommentSpec); final List getterArgs = [ '$className* object', - if (_isNumericListType(field.type)) 'size_t* length' + if (_isNumericListType(field.type)) 'size_t* length', ]; indent.writeln( - '$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')});'); + '$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')});', + ); } } @@ -336,24 +339,27 @@ class GObjectHeaderGenerator }) { final String module = _getModule(generatorOptions, dartPackageName); indent.newln(); - _writeDeclareFinalType(indent, module, _codecBaseName, - parentClassName: _standardCodecName); + _writeDeclareFinalType( + indent, + module, + _codecBaseName, + parentClassName: _standardCodecName, + ); - final Iterable customTypes = - getEnumeratedTypes(root, excludeSealedClasses: true); + final Iterable customTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ); if (customTypes.isNotEmpty) { indent.newln(); - addDocumentationComments( - indent, - [ - 'Custom type ID constants:', - '', - 'Constants used to identify custom types in the codec.', - 'They are used in the codec to encode and decode custom types.', - 'They may be used in custom object creation functions to identify the type.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + 'Custom type ID constants:', + '', + 'Constants used to identify custom types in the codec.', + 'They are used in the codec to encode and decode custom types.', + 'They may be used in custom object creation functions to identify the type.', + ], _docCommentSpec); } for (final EnumeratedType customType in customTypes) { @@ -379,33 +385,28 @@ class GObjectHeaderGenerator final String methodPrefix = _getMethodPrefix(module, api.name); indent.newln(); - addDocumentationComments( - indent, - [ - '$className:', - '', - ...api.documentationComments, - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '$className:', + '', + ...api.documentationComments, + ], _docCommentSpec); indent.newln(); _writeDeclareFinalType(indent, module, api.name); indent.newln(); - addDocumentationComments( - indent, - [ - '${methodPrefix}_new:', - '@messenger: an #FlBinaryMessenger.', - '@suffix: (allow-none): a suffix to add to the API or %NULL for none.', - '', - 'Creates a new object to access the ${api.name} API.', - '', - 'Returns: a new #$className', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_new:', + '@messenger: an #FlBinaryMessenger.', + '@suffix: (allow-none): a suffix to add to the API or %NULL for none.', + '', + 'Creates a new object to access the ${api.name} API.', + '', + 'Returns: a new #$className', + ], _docCommentSpec); indent.writeln( - '$className* ${methodPrefix}_new(FlBinaryMessenger* messenger, const gchar* suffix);'); + '$className* ${methodPrefix}_new(FlBinaryMessenger* messenger, const gchar* suffix);', + ); for (final Method method in api.methods) { final String methodName = _getMethodName(method.name); @@ -423,154 +424,150 @@ class GObjectHeaderGenerator asyncArgs.addAll([ 'GCancellable* cancellable', 'GAsyncReadyCallback callback', - 'gpointer user_data' + 'gpointer user_data', ]); indent.newln(); final List methodParameterCommentLines = []; for (final Parameter param in method.parameters) { final String paramName = _snakeCaseFromCamelCase(param.name); methodParameterCommentLines.add( - '@$paramName: ${param.type.isNullable ? '(allow-none): ' : ''}parameter for this method.'); + '@$paramName: ${param.type.isNullable ? '(allow-none): ' : ''}parameter for this method.', + ); if (_isNumericListType(param.type)) { - methodParameterCommentLines - .add('@${paramName}_length: length of $paramName.'); + methodParameterCommentLines.add( + '@${paramName}_length: length of $paramName.', + ); } } - addDocumentationComments( - indent, - [ - '${methodPrefix}_$methodName:', - '@api: a #$className.', - ...methodParameterCommentLines, - '@cancellable: (allow-none): a #GCancellable or %NULL.', - '@callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when the call is complete or %NULL to ignore the response.', - '@user_data: (closure): user data to pass to @callback.', - '', - ...method.documentationComments - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_$methodName:', + '@api: a #$className.', + ...methodParameterCommentLines, + '@cancellable: (allow-none): a #GCancellable or %NULL.', + '@callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when the call is complete or %NULL to ignore the response.', + '@user_data: (closure): user data to pass to @callback.', + '', + ...method.documentationComments, + ], _docCommentSpec); indent.writeln( - "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')});"); + "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')});", + ); final List finishArgs = [ '$className* api', 'GAsyncResult* result', - 'GError** error' + 'GError** error', ]; indent.newln(); - addDocumentationComments( - indent, - [ - '${methodPrefix}_${methodName}_finish:', - '@api: a #$className.', - '@result: a #GAsyncResult.', - '@error: (allow-none): #GError location to store the error occurring, or %NULL to ignore.', - '', - 'Completes a ${methodPrefix}_$methodName() call.', - '', - 'Returns: a #$responseClassName or %NULL on error.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_${methodName}_finish:', + '@api: a #$className.', + '@result: a #GAsyncResult.', + '@error: (allow-none): #GError location to store the error occurring, or %NULL to ignore.', + '', + 'Completes a ${methodPrefix}_$methodName() call.', + '', + 'Returns: a #$responseClassName or %NULL on error.', + ], _docCommentSpec); indent.writeln( - "$responseClassName* ${methodPrefix}_${methodName}_finish(${finishArgs.join(', ')});"); + "$responseClassName* ${methodPrefix}_${methodName}_finish(${finishArgs.join(', ')});", + ); } } // Write the API response classes. void _writeFlutterApiRespondClass( - Indent indent, String module, Api api, Method method) { + Indent indent, + String module, + Api api, + Method method, + ) { final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); final String responseMethodPrefix = _getMethodPrefix(module, responseName); - final String primitiveType = - _getType(module, method.returnType, primitive: true); + final String primitiveType = _getType( + module, + method.returnType, + primitive: true, + ); indent.newln(); _writeDeclareFinalType(indent, module, responseName); indent.newln(); - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_is_error:', - '@response: a #$responseClassName.', - '', - 'Checks if a response to ${api.name}.${method.name} is an error.', - '', - 'Returns: a %TRUE if this response is an error.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${responseMethodPrefix}_is_error:', + '@response: a #$responseClassName.', + '', + 'Checks if a response to ${api.name}.${method.name} is an error.', + '', + 'Returns: a %TRUE if this response is an error.', + ], _docCommentSpec); indent.writeln( - 'gboolean ${responseMethodPrefix}_is_error($responseClassName* response);'); + 'gboolean ${responseMethodPrefix}_is_error($responseClassName* response);', + ); indent.newln(); - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_get_error_code:', - '@response: a #$responseClassName.', - '', - 'Get the error code for this response.', - '', - 'Returns: an error code or %NULL if not an error.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${responseMethodPrefix}_get_error_code:', + '@response: a #$responseClassName.', + '', + 'Get the error code for this response.', + '', + 'Returns: an error code or %NULL if not an error.', + ], _docCommentSpec); indent.writeln( - 'const gchar* ${responseMethodPrefix}_get_error_code($responseClassName* response);'); + 'const gchar* ${responseMethodPrefix}_get_error_code($responseClassName* response);', + ); indent.newln(); - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_get_error_message:', - '@response: a #$responseClassName.', - '', - 'Get the error message for this response.', - '', - 'Returns: an error message.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${responseMethodPrefix}_get_error_message:', + '@response: a #$responseClassName.', + '', + 'Get the error message for this response.', + '', + 'Returns: an error message.', + ], _docCommentSpec); indent.writeln( - 'const gchar* ${responseMethodPrefix}_get_error_message($responseClassName* response);'); + 'const gchar* ${responseMethodPrefix}_get_error_message($responseClassName* response);', + ); indent.newln(); - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_get_error_details:', - '@response: a #$responseClassName.', - '', - 'Get the error details for this response.', - '', - 'Returns: (allow-none): an error details or %NULL.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${responseMethodPrefix}_get_error_details:', + '@response: a #$responseClassName.', + '', + 'Get the error details for this response.', + '', + 'Returns: (allow-none): an error details or %NULL.', + ], _docCommentSpec); indent.writeln( - 'FlValue* ${responseMethodPrefix}_get_error_details($responseClassName* response);'); + 'FlValue* ${responseMethodPrefix}_get_error_details($responseClassName* response);', + ); if (!method.returnType.isVoid) { indent.newln(); - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_get_return_value:', - '@response: a #$responseClassName.', - if (_isNumericListType(method.returnType)) - '@return_value_length: (allow-none): location to write length of the return value or %NULL to ignore.', - '', - 'Get the return value for this response.', - '', - if (method.returnType.isNullable) - 'Returns: (allow-none): a return value or %NULL.' - else - 'Returns: a return value.', - ], - _docCommentSpec); - final String returnType = _isNullablePrimitiveType(method.returnType) - ? '$primitiveType*' - : primitiveType; + addDocumentationComments(indent, [ + '${responseMethodPrefix}_get_return_value:', + '@response: a #$responseClassName.', + if (_isNumericListType(method.returnType)) + '@return_value_length: (allow-none): location to write length of the return value or %NULL to ignore.', + '', + 'Get the return value for this response.', + '', + if (method.returnType.isNullable) + 'Returns: (allow-none): a return value or %NULL.' + else + 'Returns: a return value.', + ], _docCommentSpec); + 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' : ''});'); + '$returnType ${responseMethodPrefix}_get_return_value($responseClassName* response${_isNumericListType(method.returnType) ? ', size_t* return_value_length' : ''});', + ); } } @@ -589,15 +586,17 @@ class GObjectHeaderGenerator indent.newln(); _writeDeclareFinalType(indent, module, api.name); - final bool hasAsyncMethod = - api.methods.any((Method method) => method.isAsynchronous); + final bool hasAsyncMethod = api.methods.any( + (Method method) => method.isAsynchronous, + ); if (hasAsyncMethod) { indent.newln(); _writeDeclareFinalType(indent, module, '${api.name}ResponseHandle'); } - for (final Method method - in api.methods.where((Method method) => !method.isAsynchronous)) { + for (final Method method in api.methods.where( + (Method method) => !method.isAsynchronous, + )) { _writeHostApiRespondClass(indent, module, api, method); } @@ -605,47 +604,48 @@ class GObjectHeaderGenerator _writeApiVTable(indent, module, api); indent.newln(); - addDocumentationComments( - indent, - [ - '${methodPrefix}_set_method_handlers:', - '', - '@messenger: an #FlBinaryMessenger.', - '@suffix: (allow-none): a suffix to add to the API or %NULL for none.', - '@vtable: implementations of the methods in this API.', - '@user_data: (closure): user data to pass to the functions in @vtable.', - '@user_data_free_func: (allow-none): a function which gets called to free @user_data, or %NULL.', - '', - 'Connects the method handlers in the ${api.name} API.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_set_method_handlers:', + '', + '@messenger: an #FlBinaryMessenger.', + '@suffix: (allow-none): a suffix to add to the API or %NULL for none.', + '@vtable: implementations of the methods in this API.', + '@user_data: (closure): user data to pass to the functions in @vtable.', + '@user_data_free_func: (allow-none): a function which gets called to free @user_data, or %NULL.', + '', + 'Connects the method handlers in the ${api.name} API.', + ], _docCommentSpec); indent.writeln( - 'void ${methodPrefix}_set_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix, const $vtableName* vtable, gpointer user_data, GDestroyNotify user_data_free_func);'); + 'void ${methodPrefix}_set_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix, const $vtableName* vtable, gpointer user_data, GDestroyNotify user_data_free_func);', + ); indent.newln(); - addDocumentationComments( - indent, - [ - '${methodPrefix}_clear_method_handlers:', - '', - '@messenger: an #FlBinaryMessenger.', - '@suffix: (allow-none): a suffix to add to the API or %NULL for none.', - '', - 'Clears the method handlers in the ${api.name} API.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_clear_method_handlers:', + '', + '@messenger: an #FlBinaryMessenger.', + '@suffix: (allow-none): a suffix to add to the API or %NULL for none.', + '', + 'Clears the method handlers in the ${api.name} API.', + ], _docCommentSpec); indent.writeln( - 'void ${methodPrefix}_clear_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix);'); + 'void ${methodPrefix}_clear_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix);', + ); - for (final Method method - in api.methods.where((Method method) => method.isAsynchronous)) { + for (final Method method in api.methods.where( + (Method method) => method.isAsynchronous, + )) { _writeHostApiRespondFunctionPrototype(indent, module, api, method); } } // Write the API response classes. void _writeHostApiRespondClass( - Indent indent, String module, Api api, Method method) { + Indent indent, + String module, + Api api, + Method method, + ) { final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); final String responseMethodPrefix = _getMethodPrefix(module, responseName); @@ -657,37 +657,33 @@ class GObjectHeaderGenerator indent.newln(); final List constructorArgs = [ if (returnType != 'void') '$returnType return_value', - if (_isNumericListType(method.returnType)) 'size_t return_value_length' + if (_isNumericListType(method.returnType)) 'size_t return_value_length', ]; - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_new:', - '', - 'Creates a new response to ${api.name}.${method.name}.', - '', - 'Returns: a new #$responseClassName', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${responseMethodPrefix}_new:', + '', + 'Creates a new response to ${api.name}.${method.name}.', + '', + 'Returns: a new #$responseClassName', + ], _docCommentSpec); indent.writeln( - '$responseClassName* ${responseMethodPrefix}_new(${constructorArgs.join(', ')});'); + '$responseClassName* ${responseMethodPrefix}_new(${constructorArgs.join(', ')});', + ); indent.newln(); - addDocumentationComments( - indent, - [ - '${responseMethodPrefix}_new_error:', - '@code: error code.', - '@message: error message.', - '@details: (allow-none): error details or %NULL.', - '', - 'Creates a new error response to ${api.name}.${method.name}.', - '', - 'Returns: a new #$responseClassName', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${responseMethodPrefix}_new_error:', + '@code: error code.', + '@message: error message.', + '@details: (allow-none): error details or %NULL.', + '', + 'Creates a new error response to ${api.name}.${method.name}.', + '', + 'Returns: a new #$responseClassName', + ], _docCommentSpec); indent.writeln( - '$responseClassName* ${responseMethodPrefix}_new_error(const gchar* code, const gchar* message, FlValue* details);'); + '$responseClassName* ${responseMethodPrefix}_new_error(const gchar* code, const gchar* message, FlValue* details);', + ); } // Write the vtable for an API. @@ -695,14 +691,11 @@ class GObjectHeaderGenerator final String className = _getClassName(module, api.name); final String vtableName = _getVTableName(module, api.name); - addDocumentationComments( - indent, - [ - '$vtableName:', - '', - 'Table of functions exposed by ${api.name} to be implemented by the API provider.', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '$vtableName:', + '', + 'Table of functions exposed by ${api.name} to be implemented by the API provider.', + ], _docCommentSpec); indent.writeScoped('typedef struct {', '} $vtableName;', () { for (final Method method in api.methods) { final String methodName = _getMethodName(method.name); @@ -731,7 +724,11 @@ class GObjectHeaderGenerator // Write the function prototype for an API method response. void _writeHostApiRespondFunctionPrototype( - Indent indent, String module, Api api, Method method) { + Indent indent, + String module, + Api api, + Method method, + ) { final String className = _getClassName(module, api.name); final String methodPrefix = _getMethodPrefix(module, api.name); final String methodName = _getMethodName(method.name); @@ -741,45 +738,41 @@ class GObjectHeaderGenerator final List respondArgs = [ '${className}ResponseHandle* response_handle', if (returnType != 'void') '$returnType return_value', - if (_isNumericListType(method.returnType)) 'size_t return_value_length' + if (_isNumericListType(method.returnType)) 'size_t return_value_length', ]; - addDocumentationComments( - indent, - [ - '${methodPrefix}_respond_$methodName:', - '@response_handle: a #${className}ResponseHandle.', - if (returnType != 'void') - '@return_value: location to write the value returned by this method.', - if (_isNumericListType(method.returnType)) - '@return_value_length: (allow-none): location to write length of @return_value or %NULL to ignore.', - '', - 'Responds to ${api.name}.${method.name}. ', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_respond_$methodName:', + '@response_handle: a #${className}ResponseHandle.', + if (returnType != 'void') + '@return_value: location to write the value returned by this method.', + if (_isNumericListType(method.returnType)) + '@return_value_length: (allow-none): location to write length of @return_value or %NULL to ignore.', + '', + 'Responds to ${api.name}.${method.name}. ', + ], _docCommentSpec); indent.writeln( - "void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')});"); + "void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')});", + ); indent.newln(); final List respondErrorArgs = [ '${className}ResponseHandle* response_handle', 'const gchar* code', 'const gchar* message', - 'FlValue* details' + 'FlValue* details', ]; - addDocumentationComments( - indent, - [ - '${methodPrefix}_respond_error_$methodName:', - '@response_handle: a #${className}ResponseHandle.', - '@code: error code.', - '@message: error message.', - '@details: (allow-none): error details or %NULL.', - '', - 'Responds with an error to ${api.name}.${method.name}. ', - ], - _docCommentSpec); + addDocumentationComments(indent, [ + '${methodPrefix}_respond_error_$methodName:', + '@response_handle: a #${className}ResponseHandle.', + '@code: error code.', + '@message: error message.', + '@details: (allow-none): error details or %NULL.', + '', + 'Responds with an error to ${api.name}.${method.name}. ', + ], _docCommentSpec); indent.writeln( - "void ${methodPrefix}_respond_error_$methodName(${respondErrorArgs.join(', ')});"); + "void ${methodPrefix}_respond_error_$methodName(${respondErrorArgs.join(', ')});", + ); } @override @@ -892,48 +885,61 @@ class GObjectSourceGenerator } indent.newln(); indent.writeScoped( - "$className* ${methodPrefix}_new(${constructorArgs.join(', ')}) {", '}', - () { - _writeObjectNew(indent, module, classDefinition.name); - for (final NamedType field in classDefinition.fields) { - final String fieldName = _getFieldName(field.name); - final String value = _referenceValue(module, field.type, fieldName, - lengthVariableName: '${fieldName}_length'); - - if (_isNullablePrimitiveType(field.type)) { - final String primitiveType = - _getType(module, field.type, primitive: true); - indent.writeScoped('if ($value != nullptr) {', '}', () { - indent.writeln( - 'self->$fieldName = static_cast<$primitiveType*>(malloc(sizeof($primitiveType)));'); - indent.writeln('*self->$fieldName = *$value;'); - }); - indent.writeScoped('else {', '}', () { - indent.writeln('self->$fieldName = nullptr;'); - }); - } else if (field.type.isNullable) { - indent.writeScoped('if ($fieldName != nullptr) {', '}', () { + "$className* ${methodPrefix}_new(${constructorArgs.join(', ')}) {", + '}', + () { + _writeObjectNew(indent, module, classDefinition.name); + for (final NamedType field in classDefinition.fields) { + final String fieldName = _getFieldName(field.name); + final String value = _referenceValue( + module, + field.type, + fieldName, + lengthVariableName: '${fieldName}_length', + ); + + if (_isNullablePrimitiveType(field.type)) { + final String primitiveType = _getType( + module, + field.type, + primitive: true, + ); + indent.writeScoped('if ($value != nullptr) {', '}', () { + indent.writeln( + 'self->$fieldName = static_cast<$primitiveType*>(malloc(sizeof($primitiveType)));', + ); + indent.writeln('*self->$fieldName = *$value;'); + }); + indent.writeScoped('else {', '}', () { + indent.writeln('self->$fieldName = nullptr;'); + }); + } else if (field.type.isNullable) { + indent.writeScoped('if ($fieldName != nullptr) {', '}', () { + indent.writeln('self->$fieldName = $value;'); + if (_isNumericListType(field.type)) { + indent.writeln( + 'self->${fieldName}_length = ${fieldName}_length;', + ); + } + }); + indent.writeScoped('else {', '}', () { + indent.writeln('self->$fieldName = nullptr;'); + if (_isNumericListType(field.type)) { + indent.writeln('self->${fieldName}_length = 0;'); + } + }); + } else { indent.writeln('self->$fieldName = $value;'); if (_isNumericListType(field.type)) { - indent - .writeln('self->${fieldName}_length = ${fieldName}_length;'); - } - }); - indent.writeScoped('else {', '}', () { - indent.writeln('self->$fieldName = nullptr;'); - if (_isNumericListType(field.type)) { - indent.writeln('self->${fieldName}_length = 0;'); + indent.writeln( + 'self->${fieldName}_length = ${fieldName}_length;', + ); } - }); - } else { - indent.writeln('self->$fieldName = $value;'); - if (_isNumericListType(field.type)) { - indent.writeln('self->${fieldName}_length = ${fieldName}_length;'); } } - } - indent.writeln('return self;'); - }); + indent.writeln('return self;'); + }, + ); for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); @@ -942,81 +948,98 @@ class GObjectSourceGenerator indent.newln(); final List getterArgs = [ '$className* self', - if (_isNumericListType(field.type)) 'size_t* length' + if (_isNumericListType(field.type)) 'size_t* length', ]; indent.writeScoped( - '$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')}) {', - '}', () { - indent.writeln( - 'g_return_val_if_fail($testMacro(self), ${_getDefaultValue(module, field.type)});'); - if (_isNumericListType(field.type)) { - indent.writeln('*length = self->${fieldName}_length;'); - } - indent.writeln('return self->$fieldName;'); - }); + '$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')}) {', + '}', + () { + indent.writeln( + 'g_return_val_if_fail($testMacro(self), ${_getDefaultValue(module, field.type)});', + ); + if (_isNumericListType(field.type)) { + indent.writeln('*length = self->${fieldName}_length;'); + } + indent.writeln('return self->$fieldName;'); + }, + ); } indent.newln(); indent.writeScoped( - 'static FlValue* ${methodPrefix}_to_list($className* self) {', '}', () { - indent.writeln('FlValue* values = fl_value_new_list();'); - for (final NamedType field in classDefinition.fields) { - final String fieldName = _getFieldName(field.name); - indent.writeln( - 'fl_value_append_take(values, ${_makeFlValue(root, module, field.type, 'self->$fieldName', lengthVariableName: 'self->${fieldName}_length')});'); - } - indent.writeln('return values;'); - }); + 'static FlValue* ${methodPrefix}_to_list($className* self) {', + '}', + () { + indent.writeln('FlValue* values = fl_value_new_list();'); + for (final NamedType field in classDefinition.fields) { + final String fieldName = _getFieldName(field.name); + indent.writeln( + 'fl_value_append_take(values, ${_makeFlValue(root, module, field.type, 'self->$fieldName', lengthVariableName: 'self->${fieldName}_length')});', + ); + } + indent.writeln('return values;'); + }, + ); indent.newln(); indent.writeScoped( - 'static $className* ${methodPrefix}_new_from_list(FlValue* values) {', - '}', () { - final List args = []; - for (int i = 0; i < classDefinition.fields.length; i++) { - final NamedType field = classDefinition.fields[i]; - final String fieldName = _getFieldName(field.name); - final String fieldType = _getType(module, field.type); - final String fieldValue = _fromFlValue(module, field.type, 'value$i'); - indent - .writeln('FlValue* value$i = fl_value_get_list_value(values, $i);'); - args.add(fieldName); - if (_isNullablePrimitiveType(field.type)) { - indent.writeln('$fieldType $fieldName = nullptr;'); + 'static $className* ${methodPrefix}_new_from_list(FlValue* values) {', + '}', + () { + final List args = []; + for (int i = 0; i < classDefinition.fields.length; i++) { + final NamedType field = classDefinition.fields[i]; + final String fieldName = _getFieldName(field.name); + final String fieldType = _getType(module, field.type); + final String fieldValue = _fromFlValue(module, field.type, 'value$i'); indent.writeln( - '${_getType(module, field.type, isOutput: true, primitive: true)} ${fieldName}_value;'); - indent.writeScoped( - 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', '}', + 'FlValue* value$i = fl_value_get_list_value(values, $i);', + ); + args.add(fieldName); + if (_isNullablePrimitiveType(field.type)) { + indent.writeln('$fieldType $fieldName = nullptr;'); + indent.writeln( + '${_getType(module, field.type, isOutput: true, primitive: true)} ${fieldName}_value;', + ); + indent.writeScoped( + 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', + '}', () { - indent.writeln('${fieldName}_value = $fieldValue;'); - indent.writeln('$fieldName = &${fieldName}_value;'); - }); - } else if (field.type.isNullable) { - indent.writeln('$fieldType $fieldName = nullptr;'); - if (_isNumericListType(field.type)) { - indent.writeln('size_t ${fieldName}_length = 0;'); - args.add('${fieldName}_length'); - } - indent.writeScoped( - 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', '}', + indent.writeln('${fieldName}_value = $fieldValue;'); + indent.writeln('$fieldName = &${fieldName}_value;'); + }, + ); + } else if (field.type.isNullable) { + indent.writeln('$fieldType $fieldName = nullptr;'); + if (_isNumericListType(field.type)) { + indent.writeln('size_t ${fieldName}_length = 0;'); + args.add('${fieldName}_length'); + } + indent.writeScoped( + 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', + '}', () { - indent.writeln('$fieldName = $fieldValue;'); + indent.writeln('$fieldName = $fieldValue;'); + if (_isNumericListType(field.type)) { + indent.writeln( + '${fieldName}_length = fl_value_get_length(value$i);', + ); + } + }, + ); + } else { + indent.writeln('$fieldType $fieldName = $fieldValue;'); if (_isNumericListType(field.type)) { indent.writeln( - '${fieldName}_length = fl_value_get_length(value$i);'); + 'size_t ${fieldName}_length = fl_value_get_length(value$i);', + ); + args.add('${fieldName}_length'); } - }); - } else { - indent.writeln('$fieldType $fieldName = $fieldValue;'); - if (_isNumericListType(field.type)) { - indent.writeln( - 'size_t ${fieldName}_length = fl_value_get_length(value$i);'); - args.add('${fieldName}_length'); } } - } - indent.writeln('return ${methodPrefix}_new(${args.join(', ')});'); - }); + indent.writeln('return ${methodPrefix}_new(${args.join(', ')});'); + }, + ); } @override @@ -1030,16 +1053,27 @@ class GObjectSourceGenerator final String codecClassName = _getClassName(module, _codecBaseName); final String codecMethodPrefix = _getMethodPrefix(module, _codecBaseName); - final Iterable customTypes = - getEnumeratedTypes(root, excludeSealedClasses: true); + final Iterable customTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ); indent.newln(); - _writeObjectStruct(indent, module, _codecBaseName, () {}, - parentClassName: _standardCodecName); + _writeObjectStruct( + indent, + module, + _codecBaseName, + () {}, + parentClassName: _standardCodecName, + ); indent.newln(); - _writeDefineType(indent, module, _codecBaseName, - parentType: 'fl_standard_message_codec_get_type()'); + _writeDefineType( + indent, + module, + _codecBaseName, + parentType: 'fl_standard_message_codec_get_type()', + ); indent.newln(); for (final EnumeratedType customType in customTypes) { @@ -1049,123 +1083,167 @@ class GObjectSourceGenerator for (final EnumeratedType customType in customTypes) { final String customTypeName = _getClassName(module, customType.name); - final String snakeCustomTypeName = - _snakeCaseFromCamelCase(customTypeName); + final String snakeCustomTypeName = _snakeCaseFromCamelCase( + customTypeName, + ); 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) {', - '}', () { - indent.writeln('uint8_t type = $customTypeId;'); - indent.writeln('g_byte_array_append(buffer, &type, sizeof(uint8_t));'); - if (customType.type == CustomTypes.customClass) { - indent.writeln( - 'g_autoptr(FlValue) values = ${snakeCustomTypeName}_to_list(value);'); - indent.writeln( - 'return fl_standard_message_codec_write_value(codec, buffer, values, error);'); - } else if (customType.type == CustomTypes.customEnum) { + 'static gboolean ${codecMethodPrefix}_write_$snakeCustomTypeName($_standardCodecName* codec, GByteArray* buffer, $valueType value, GError** error) {', + '}', + () { + indent.writeln('uint8_t type = $customTypeId;'); indent.writeln( - 'return fl_standard_message_codec_write_value(codec, buffer, value, error);'); - } - }); + 'g_byte_array_append(buffer, &type, sizeof(uint8_t));', + ); + if (customType.type == CustomTypes.customClass) { + indent.writeln( + 'g_autoptr(FlValue) values = ${snakeCustomTypeName}_to_list(value);', + ); + indent.writeln( + 'return fl_standard_message_codec_write_value(codec, buffer, values, error);', + ); + } else if (customType.type == CustomTypes.customEnum) { + indent.writeln( + 'return fl_standard_message_codec_write_value(codec, buffer, value, error);', + ); + } + }, + ); } indent.newln(); indent.writeScoped( - 'static gboolean ${codecMethodPrefix}_write_value($_standardCodecName* codec, GByteArray* buffer, FlValue* value, GError** error) {', - '}', () { - indent.writeScoped( - 'if (fl_value_get_type(value) == FL_VALUE_TYPE_CUSTOM) {', '}', () { - indent.writeScoped('switch (fl_value_get_custom_type(value)) {', '}', - () { - for (final EnumeratedType customType in customTypes) { - final String customTypeId = _getCustomTypeId(module, customType); - indent.writeln('case $customTypeId:'); - indent.nest(1, () { - final String customTypeName = - _getClassName(module, customType.name); - final String snakeCustomTypeName = - _snakeCaseFromCamelCase(customTypeName); - final String castMacro = - _getClassCastMacro(module, customType.name); - if (customType.type == CustomTypes.customClass) { - indent.writeln( - 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, $castMacro(fl_value_get_custom_value_object(value)), error);'); - } else if (customType.type == CustomTypes.customEnum) { - indent.writeln( - 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, reinterpret_cast(const_cast(fl_value_get_custom_value(value))), error);'); - } - }); - } - }); - }); + 'static gboolean ${codecMethodPrefix}_write_value($_standardCodecName* codec, GByteArray* buffer, FlValue* value, GError** error) {', + '}', + () { + indent.writeScoped( + 'if (fl_value_get_type(value) == FL_VALUE_TYPE_CUSTOM) {', + '}', + () { + indent.writeScoped( + 'switch (fl_value_get_custom_type(value)) {', + '}', + () { + for (final EnumeratedType customType in customTypes) { + final String customTypeId = _getCustomTypeId( + module, + customType, + ); + indent.writeln('case $customTypeId:'); + indent.nest(1, () { + final String customTypeName = _getClassName( + module, + customType.name, + ); + final String snakeCustomTypeName = _snakeCaseFromCamelCase( + customTypeName, + ); + final String castMacro = _getClassCastMacro( + module, + customType.name, + ); + if (customType.type == CustomTypes.customClass) { + indent.writeln( + 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, $castMacro(fl_value_get_custom_value_object(value)), error);', + ); + } else if (customType.type == CustomTypes.customEnum) { + indent.writeln( + 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, reinterpret_cast(const_cast(fl_value_get_custom_value(value))), error);', + ); + } + }); + } + }, + ); + }, + ); - indent.newln(); - indent.writeln( - 'return FL_STANDARD_MESSAGE_CODEC_CLASS(${codecMethodPrefix}_parent_class)->write_value(codec, buffer, value, error);'); - }); + indent.newln(); + indent.writeln( + 'return FL_STANDARD_MESSAGE_CODEC_CLASS(${codecMethodPrefix}_parent_class)->write_value(codec, buffer, value, error);', + ); + }, + ); for (final EnumeratedType customType in customTypes) { final String customTypeName = _getClassName(module, customType.name); - final String snakeCustomTypeName = - _snakeCaseFromCamelCase(customTypeName); + final String snakeCustomTypeName = _snakeCaseFromCamelCase( + customTypeName, + ); final String customTypeId = _getCustomTypeId(module, customType); indent.newln(); indent.writeScoped( - 'static FlValue* ${codecMethodPrefix}_read_$snakeCustomTypeName($_standardCodecName* codec, GBytes* buffer, size_t* offset, GError** error) {', - '}', () { - if (customType.type == CustomTypes.customClass) { - indent.writeln( - 'g_autoptr(FlValue) values = fl_standard_message_codec_read_value(codec, buffer, offset, error);'); - indent.writeScoped('if (values == nullptr) {', '}', () { - indent.writeln('return nullptr;'); - }); - indent.newln(); - indent.writeln( - 'g_autoptr($customTypeName) value = ${snakeCustomTypeName}_new_from_list(values);'); - indent.writeScoped('if (value == nullptr) {', '}', () { + 'static FlValue* ${codecMethodPrefix}_read_$snakeCustomTypeName($_standardCodecName* codec, GBytes* buffer, size_t* offset, GError** error) {', + '}', + () { + if (customType.type == CustomTypes.customClass) { indent.writeln( - 'g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Invalid data received for MessageData");'); - indent.writeln('return nullptr;'); - }); - indent.newln(); - indent.writeln( - 'return fl_value_new_custom_object($customTypeId, G_OBJECT(value));'); - } else if (customType.type == CustomTypes.customEnum) { - indent.writeln( - 'return fl_value_new_custom($customTypeId, fl_standard_message_codec_read_value(codec, buffer, offset, error), (GDestroyNotify)fl_value_unref);'); - } - }); + 'g_autoptr(FlValue) values = fl_standard_message_codec_read_value(codec, buffer, offset, error);', + ); + indent.writeScoped('if (values == nullptr) {', '}', () { + indent.writeln('return nullptr;'); + }); + indent.newln(); + indent.writeln( + 'g_autoptr($customTypeName) value = ${snakeCustomTypeName}_new_from_list(values);', + ); + indent.writeScoped('if (value == nullptr) {', '}', () { + indent.writeln( + 'g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Invalid data received for MessageData");', + ); + indent.writeln('return nullptr;'); + }); + indent.newln(); + indent.writeln( + 'return fl_value_new_custom_object($customTypeId, G_OBJECT(value));', + ); + } else if (customType.type == CustomTypes.customEnum) { + indent.writeln( + 'return fl_value_new_custom($customTypeId, fl_standard_message_codec_read_value(codec, buffer, offset, error), (GDestroyNotify)fl_value_unref);', + ); + } + }, + ); } indent.newln(); indent.writeScoped( - 'static FlValue* ${codecMethodPrefix}_read_value_of_type($_standardCodecName* codec, GBytes* buffer, size_t* offset, int type, GError** error) {', - '}', () { - indent.writeScoped('switch (type) {', '}', () { - for (final EnumeratedType customType in customTypes) { - final String customTypeName = _getClassName(module, customType.name); - final String customTypeId = _getCustomTypeId(module, customType); - final String snakeCustomTypeName = - _snakeCaseFromCamelCase(customTypeName); - indent.writeln('case $customTypeId:'); + 'static FlValue* ${codecMethodPrefix}_read_value_of_type($_standardCodecName* codec, GBytes* buffer, size_t* offset, int type, GError** error) {', + '}', + () { + indent.writeScoped('switch (type) {', '}', () { + for (final EnumeratedType customType in customTypes) { + final String customTypeName = _getClassName( + module, + customType.name, + ); + final String customTypeId = _getCustomTypeId(module, customType); + final String snakeCustomTypeName = _snakeCaseFromCamelCase( + customTypeName, + ); + indent.writeln('case $customTypeId:'); + indent.nest(1, () { + indent.writeln( + 'return ${codecMethodPrefix}_read_$snakeCustomTypeName(codec, buffer, offset, error);', + ); + }); + } + + indent.writeln('default:'); indent.nest(1, () { indent.writeln( - 'return ${codecMethodPrefix}_read_$snakeCustomTypeName(codec, buffer, offset, error);'); + 'return FL_STANDARD_MESSAGE_CODEC_CLASS(${codecMethodPrefix}_parent_class)->read_value_of_type(codec, buffer, offset, type, error);', + ); }); - } - - indent.writeln('default:'); - indent.nest(1, () { - indent.writeln( - 'return FL_STANDARD_MESSAGE_CODEC_CLASS(${codecMethodPrefix}_parent_class)->read_value_of_type(codec, buffer, offset, type, error);'); }); - }); - }); + }, + ); indent.newln(); _writeInit(indent, module, _codecBaseName, () {}); @@ -1173,17 +1251,22 @@ class GObjectSourceGenerator indent.newln(); _writeClassInit(indent, module, _codecBaseName, () { indent.writeln( - 'FL_STANDARD_MESSAGE_CODEC_CLASS(klass)->write_value = ${codecMethodPrefix}_write_value;'); + 'FL_STANDARD_MESSAGE_CODEC_CLASS(klass)->write_value = ${codecMethodPrefix}_write_value;', + ); indent.writeln( - 'FL_STANDARD_MESSAGE_CODEC_CLASS(klass)->read_value_of_type = ${codecMethodPrefix}_read_value_of_type;'); + 'FL_STANDARD_MESSAGE_CODEC_CLASS(klass)->read_value_of_type = ${codecMethodPrefix}_read_value_of_type;', + ); }, hasDispose: false); indent.newln(); indent.writeScoped( - 'static $codecClassName* ${codecMethodPrefix}_new() {', '}', () { - _writeObjectNew(indent, module, _codecBaseName); - indent.writeln('return self;'); - }); + 'static $codecClassName* ${codecMethodPrefix}_new() {', + '}', + () { + _writeObjectNew(indent, module, _codecBaseName); + indent.writeln('return self;'); + }, + ); } @override @@ -1224,22 +1307,28 @@ class GObjectSourceGenerator indent.newln(); indent.writeScoped( - '$className* ${methodPrefix}_new(FlBinaryMessenger* messenger, const gchar* suffix) {', - '}', () { - _writeObjectNew(indent, module, api.name); - indent.writeln( - 'self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));'); - indent.writeln( - 'self->suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");'); - indent.writeln('return self;'); - }); + '$className* ${methodPrefix}_new(FlBinaryMessenger* messenger, const gchar* suffix) {', + '}', + () { + _writeObjectNew(indent, module, api.name); + indent.writeln( + 'self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));', + ); + indent.writeln( + 'self->suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");', + ); + indent.writeln('return self;'); + }, + ); for (final Method method in api.methods) { final String methodName = _getMethodName(method.name); final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final String responseMethodPrefix = - _getMethodPrefix(module, responseName); + final String responseMethodPrefix = _getMethodPrefix( + module, + responseName, + ); final String testResponseMacro = '${_snakeCaseFromCamelCase(module)}_IS_${_snakeCaseFromCamelCase(responseName)}' .toUpperCase(); @@ -1250,8 +1339,11 @@ class GObjectSourceGenerator if (!method.returnType.isVoid) { indent.writeln('FlValue* return_value;'); if (_isNullablePrimitiveType(method.returnType)) { - final String primitiveType = - _getType(module, method.returnType, primitive: true); + final String primitiveType = _getType( + module, + method.returnType, + primitive: true, + ); indent.writeln('$primitiveType return_value_;'); } } @@ -1265,8 +1357,9 @@ class GObjectSourceGenerator _writeCastSelf(indent, module, responseName, 'object'); indent.writeln('g_clear_pointer(&self->error, fl_value_unref);'); if (!method.returnType.isVoid) { - indent - .writeln('g_clear_pointer(&self->return_value, fl_value_unref);'); + indent.writeln( + 'g_clear_pointer(&self->return_value, fl_value_unref);', + ); } }); @@ -1278,109 +1371,151 @@ class GObjectSourceGenerator indent.newln(); indent.writeScoped( - 'static $responseClassName* ${responseMethodPrefix}_new(FlValue* response) {', - '}', () { - _writeObjectNew(indent, module, responseName); - indent.writeScoped('if (fl_value_get_length(response) > 1) {', '}', () { - indent.writeln('self->error = fl_value_ref(response);'); - }); - if (!method.returnType.isVoid) { - indent.writeScoped('else {', '}', () { - indent.writeln( - 'FlValue* value = fl_value_get_list_value(response, 0);'); - indent.writeln('self->return_value = fl_value_ref(value);'); - }); - } - indent.writeln('return self;'); - }); + 'static $responseClassName* ${responseMethodPrefix}_new(FlValue* response) {', + '}', + () { + _writeObjectNew(indent, module, responseName); + indent.writeScoped( + 'if (fl_value_get_length(response) > 1) {', + '}', + () { + indent.writeln('self->error = fl_value_ref(response);'); + }, + ); + if (!method.returnType.isVoid) { + indent.writeScoped('else {', '}', () { + indent.writeln( + 'FlValue* value = fl_value_get_list_value(response, 0);', + ); + indent.writeln('self->return_value = fl_value_ref(value);'); + }); + } + indent.writeln('return self;'); + }, + ); indent.newln(); indent.writeScoped( - 'gboolean ${responseMethodPrefix}_is_error($responseClassName* self) {', - '}', () { - indent - .writeln('g_return_val_if_fail($testResponseMacro(self), FALSE);'); - indent.writeln('return self->error != nullptr;'); - }); + 'gboolean ${responseMethodPrefix}_is_error($responseClassName* self) {', + '}', + () { + indent.writeln( + 'g_return_val_if_fail($testResponseMacro(self), FALSE);', + ); + indent.writeln('return self->error != nullptr;'); + }, + ); indent.newln(); indent.writeScoped( - 'const gchar* ${responseMethodPrefix}_get_error_code($responseClassName* self) {', - '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), nullptr);'); - indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); - indent.writeln( - 'return fl_value_get_string(fl_value_get_list_value(self->error, 0));'); - }); + 'const gchar* ${responseMethodPrefix}_get_error_code($responseClassName* self) {', + '}', + () { + indent.writeln( + 'g_return_val_if_fail($testResponseMacro(self), nullptr);', + ); + indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); + indent.writeln( + 'return fl_value_get_string(fl_value_get_list_value(self->error, 0));', + ); + }, + ); indent.newln(); indent.writeScoped( - 'const gchar* ${responseMethodPrefix}_get_error_message($responseClassName* self) {', - '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), nullptr);'); - indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); - indent.writeln( - 'return fl_value_get_string(fl_value_get_list_value(self->error, 1));'); - }); + 'const gchar* ${responseMethodPrefix}_get_error_message($responseClassName* self) {', + '}', + () { + indent.writeln( + 'g_return_val_if_fail($testResponseMacro(self), nullptr);', + ); + indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); + indent.writeln( + 'return fl_value_get_string(fl_value_get_list_value(self->error, 1));', + ); + }, + ); indent.newln(); indent.writeScoped( - 'FlValue* ${responseMethodPrefix}_get_error_details($responseClassName* self) {', - '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), nullptr);'); - indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); - indent.writeln('return fl_value_get_list_value(self->error, 2);'); - }); + 'FlValue* ${responseMethodPrefix}_get_error_details($responseClassName* self) {', + '}', + () { + indent.writeln( + 'g_return_val_if_fail($testResponseMacro(self), nullptr);', + ); + indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); + indent.writeln('return fl_value_get_list_value(self->error, 2);'); + }, + ); if (!method.returnType.isVoid) { - final String primitiveType = - _getType(module, method.returnType, primitive: true); + final String primitiveType = _getType( + module, + method.returnType, + primitive: true, + ); 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' : ''}) {', - '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), ${_getDefaultValue(module, method.returnType)});'); - indent.writeln('g_assert(!${responseMethodPrefix}_is_error(self));'); - if (method.returnType.isNullable) { - indent.writeScoped( + '$returnType ${responseMethodPrefix}_get_return_value($responseClassName* self${_isNumericListType(method.returnType) ? ', size_t* return_value_length' : ''}) {', + '}', + () { + indent.writeln( + 'g_return_val_if_fail($testResponseMacro(self), ${_getDefaultValue(module, method.returnType)});', + ); + indent.writeln( + 'g_assert(!${responseMethodPrefix}_is_error(self));', + ); + if (method.returnType.isNullable) { + indent.writeScoped( 'if (fl_value_get_type(self->return_value) == FL_VALUE_TYPE_NULL) {', - '}', () { - indent.writeln('return nullptr;'); - }); - } - if (_isNumericListType(method.returnType)) { - indent.writeScoped('if (return_value_length != nullptr) {', '}', + '}', () { + indent.writeln('return nullptr;'); + }, + ); + } + if (_isNumericListType(method.returnType)) { + indent.writeScoped( + 'if (return_value_length != nullptr) {', + '}', + () { + indent.writeln( + '*return_value_length = fl_value_get_length(self->return_value);', + ); + }, + ); + } + if (_isNullablePrimitiveType(method.returnType)) { indent.writeln( - '*return_value_length = fl_value_get_length(self->return_value);'); - }); - } - if (_isNullablePrimitiveType(method.returnType)) { - indent.writeln( - 'self->return_value_ = ${_fromFlValue(module, method.returnType, 'self->return_value')};'); - indent.writeln('return &self->return_value_;'); - } else { - indent.writeln( - 'return ${_fromFlValue(module, method.returnType, 'self->return_value')};'); - } - }); + 'self->return_value_ = ${_fromFlValue(module, method.returnType, 'self->return_value')};', + ); + indent.writeln('return &self->return_value_;'); + } else { + indent.writeln( + 'return ${_fromFlValue(module, method.returnType, 'self->return_value')};', + ); + } + }, + ); } indent.newln(); indent.writeScoped( - 'static void ${methodPrefix}_${methodName}_cb(GObject* object, GAsyncResult* result, gpointer user_data) {', - '}', () { - indent.writeln('GTask* task = G_TASK(user_data);'); - indent.writeln('g_task_return_pointer(task, result, g_object_unref);'); - }); + 'static void ${methodPrefix}_${methodName}_cb(GObject* object, GAsyncResult* result, gpointer user_data) {', + '}', + () { + indent.writeln('GTask* task = G_TASK(user_data);'); + indent.writeln( + 'g_task_return_pointer(task, result, g_object_unref);', + ); + }, + ); final List asyncArgs = ['$className* self']; for (final Parameter param in method.parameters) { @@ -1397,29 +1532,46 @@ class GObjectSourceGenerator ]); indent.newln(); indent.writeScoped( - "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')}) {", '}', - () { - indent.writeln('g_autoptr(FlValue) args = fl_value_new_list();'); - for (final Parameter param in method.parameters) { - final String name = _snakeCaseFromCamelCase(param.name); - final String value = _makeFlValue(root, module, param.type, name, - lengthVariableName: '${name}_length'); - indent.writeln('fl_value_append_take(args, $value);'); - } - final String channelName = - makeChannelName(api, method, dartPackageName); - indent.writeln( - 'g_autofree gchar* channel_name = g_strdup_printf("$channelName%s", self->suffix);'); - indent.writeln( - 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();'); - indent.writeln( - 'FlBasicMessageChannel* channel = fl_basic_message_channel_new(self->messenger, channel_name, FL_MESSAGE_CODEC(codec));'); - indent.writeln( - 'GTask* task = g_task_new(self, cancellable, callback, user_data);'); - indent.writeln('g_task_set_task_data(task, channel, g_object_unref);'); - indent.writeln( - 'fl_basic_message_channel_send(channel, args, cancellable, ${methodPrefix}_${methodName}_cb, task);'); - }); + "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')}) {", + '}', + () { + indent.writeln('g_autoptr(FlValue) args = fl_value_new_list();'); + for (final Parameter param in method.parameters) { + final String name = _snakeCaseFromCamelCase(param.name); + final String value = _makeFlValue( + root, + module, + param.type, + name, + lengthVariableName: '${name}_length', + ); + indent.writeln('fl_value_append_take(args, $value);'); + } + final String channelName = makeChannelName( + api, + method, + dartPackageName, + ); + indent.writeln( + 'g_autofree gchar* channel_name = g_strdup_printf("$channelName%s", self->suffix);', + ); + indent.writeln( + 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();', + ); + indent.writeln( + 'FlBasicMessageChannel* channel = fl_basic_message_channel_new(self->messenger, channel_name, FL_MESSAGE_CODEC(codec));', + ); + indent.writeln( + 'GTask* task = g_task_new(self, cancellable, callback, user_data);', + ); + indent.writeln( + 'g_task_set_task_data(task, channel, g_object_unref);', + ); + indent.writeln( + 'fl_basic_message_channel_send(channel, args, cancellable, ${methodPrefix}_${methodName}_cb, task);', + ); + }, + ); final List finishArgs = [ '$className* self', @@ -1428,20 +1580,25 @@ class GObjectSourceGenerator ]; indent.newln(); indent.writeScoped( - "$responseClassName* ${methodPrefix}_${methodName}_finish(${finishArgs.join(', ')}) {", - '}', () { - indent.writeln('g_autoptr(GTask) task = G_TASK(result);'); - indent.writeln( - 'GAsyncResult* r = G_ASYNC_RESULT(g_task_propagate_pointer(task, nullptr));'); - indent.writeln( - 'FlBasicMessageChannel* channel = FL_BASIC_MESSAGE_CHANNEL(g_task_get_task_data(task));'); - indent.writeln( - 'g_autoptr(FlValue) response = fl_basic_message_channel_send_finish(channel, r, error);'); - indent.writeScoped('if (response == nullptr) { ', '}', () { - indent.writeln('return nullptr;'); - }); - indent.writeln('return ${responseMethodPrefix}_new(response);'); - }); + "$responseClassName* ${methodPrefix}_${methodName}_finish(${finishArgs.join(', ')}) {", + '}', + () { + indent.writeln('g_autoptr(GTask) task = G_TASK(result);'); + indent.writeln( + 'GAsyncResult* r = G_ASYNC_RESULT(g_task_propagate_pointer(task, nullptr));', + ); + indent.writeln( + 'FlBasicMessageChannel* channel = FL_BASIC_MESSAGE_CHANNEL(g_task_get_task_data(task));', + ); + indent.writeln( + 'g_autoptr(FlValue) response = fl_basic_message_channel_send_finish(channel, r, error);', + ); + indent.writeScoped('if (response == nullptr) { ', '}', () { + indent.writeln('return nullptr;'); + }); + indent.writeln('return ${responseMethodPrefix}_new(response);'); + }, + ); } } @@ -1462,8 +1619,9 @@ class GObjectSourceGenerator final String codecClassName = _getClassName(module, _codecBaseName); final String codecMethodPrefix = _getMethodPrefix(module, _codecBaseName); - final bool hasAsyncMethod = - api.methods.any((Method method) => method.isAsynchronous); + final bool hasAsyncMethod = api.methods.any( + (Method method) => method.isAsynchronous, + ); if (hasAsyncMethod) { indent.newln(); _writeObjectStruct(indent, module, '${api.name}ResponseHandle', () { @@ -1489,22 +1647,28 @@ class GObjectSourceGenerator indent.newln(); indent.writeScoped( - 'static ${className}ResponseHandle* ${methodPrefix}_response_handle_new(FlBasicMessageChannel* channel, FlBasicMessageChannelResponseHandle* response_handle) {', - '}', () { - _writeObjectNew(indent, module, '${api.name}ResponseHandle'); - indent.writeln( - 'self->channel = FL_BASIC_MESSAGE_CHANNEL(g_object_ref(channel));'); - indent.writeln( - 'self->response_handle = FL_BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE(g_object_ref(response_handle));'); - indent.writeln('return self;'); - }); + 'static ${className}ResponseHandle* ${methodPrefix}_response_handle_new(FlBasicMessageChannel* channel, FlBasicMessageChannelResponseHandle* response_handle) {', + '}', + () { + _writeObjectNew(indent, module, '${api.name}ResponseHandle'); + indent.writeln( + 'self->channel = FL_BASIC_MESSAGE_CHANNEL(g_object_ref(channel));', + ); + indent.writeln( + 'self->response_handle = FL_BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE(g_object_ref(response_handle));', + ); + indent.writeln('return self;'); + }, + ); } for (final Method method in api.methods) { final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final String responseMethodPrefix = - _getMethodPrefix(module, responseName); + final String responseMethodPrefix = _getMethodPrefix( + module, + responseName, + ); if (method.isAsynchronous) { indent.newln(); @@ -1535,32 +1699,40 @@ class GObjectSourceGenerator indent.newln(); final List constructorArgs = [ if (returnType != 'void') '$returnType return_value', - if (_isNumericListType(method.returnType)) 'size_t return_value_length' + if (_isNumericListType(method.returnType)) 'size_t return_value_length', ]; indent.writeScoped( - "${method.isAsynchronous ? 'static ' : ''}$responseClassName* ${responseMethodPrefix}_new(${constructorArgs.join(', ')}) {", - '}', () { - _writeObjectNew(indent, module, responseName); - indent.writeln('self->value = fl_value_new_list();'); - indent.writeln( - "fl_value_append_take(self->value, ${_makeFlValue(root, module, method.returnType, 'return_value', lengthVariableName: 'return_value_length')});"); - indent.writeln('return self;'); - }); + "${method.isAsynchronous ? 'static ' : ''}$responseClassName* ${responseMethodPrefix}_new(${constructorArgs.join(', ')}) {", + '}', + () { + _writeObjectNew(indent, module, responseName); + indent.writeln('self->value = fl_value_new_list();'); + indent.writeln( + "fl_value_append_take(self->value, ${_makeFlValue(root, module, method.returnType, 'return_value', lengthVariableName: 'return_value_length')});", + ); + indent.writeln('return self;'); + }, + ); indent.newln(); indent.writeScoped( - '${method.isAsynchronous ? 'static ' : ''}$responseClassName* ${responseMethodPrefix}_new_error(const gchar* code, const gchar* message, FlValue* details) {', - '}', () { - _writeObjectNew(indent, module, responseName); - indent.writeln('self->value = fl_value_new_list();'); - indent.writeln( - 'fl_value_append_take(self->value, fl_value_new_string(code));'); - indent.writeln( - 'fl_value_append_take(self->value, fl_value_new_string(message != nullptr ? message : ""));'); - indent.writeln( - 'fl_value_append_take(self->value, details != nullptr ? fl_value_ref(details) : fl_value_new_null());'); - indent.writeln('return self;'); - }); + '${method.isAsynchronous ? 'static ' : ''}$responseClassName* ${responseMethodPrefix}_new_error(const gchar* code, const gchar* message, FlValue* details) {', + '}', + () { + _writeObjectNew(indent, module, responseName); + indent.writeln('self->value = fl_value_new_list();'); + indent.writeln( + 'fl_value_append_take(self->value, fl_value_new_string(code));', + ); + indent.writeln( + 'fl_value_append_take(self->value, fl_value_new_string(message != nullptr ? message : ""));', + ); + indent.writeln( + 'fl_value_append_take(self->value, details != nullptr ? fl_value_ref(details) : fl_value_new_null());', + ); + indent.writeln('return self;'); + }, + ); } indent.newln(); @@ -1590,14 +1762,16 @@ class GObjectSourceGenerator indent.newln(); indent.writeScoped( - 'static $className* ${methodPrefix}_new(const $vtableName* vtable, gpointer user_data, GDestroyNotify user_data_free_func) {', - '}', () { - _writeObjectNew(indent, module, api.name); - indent.writeln('self->vtable = vtable;'); - indent.writeln('self->user_data = user_data;'); - indent.writeln('self->user_data_free_func = user_data_free_func;'); - indent.writeln('return self;'); - }); + 'static $className* ${methodPrefix}_new(const $vtableName* vtable, gpointer user_data, GDestroyNotify user_data_free_func) {', + '}', + () { + _writeObjectNew(indent, module, api.name); + indent.writeln('self->vtable = vtable;'); + indent.writeln('self->user_data = user_data;'); + indent.writeln('self->user_data_free_func = user_data_free_func;'); + indent.writeln('return self;'); + }, + ); for (final Method method in api.methods) { final String methodName = _getMethodName(method.name); @@ -1606,189 +1780,252 @@ class GObjectSourceGenerator indent.newln(); indent.writeScoped( - 'static void ${methodPrefix}_${methodName}_cb(FlBasicMessageChannel* channel, FlValue* message_, FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) {', - '}', () { - _writeCastSelf(indent, module, api.name, 'user_data'); + 'static void ${methodPrefix}_${methodName}_cb(FlBasicMessageChannel* channel, FlValue* message_, FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) {', + '}', + () { + _writeCastSelf(indent, module, api.name, 'user_data'); - indent.newln(); - indent.writeScoped( + indent.newln(); + indent.writeScoped( 'if (self->vtable == nullptr || self->vtable->$methodName == nullptr) {', - '}', () { - indent.writeln('return;'); - }); + '}', + () { + indent.writeln('return;'); + }, + ); - indent.newln(); - final List methodArgs = []; - for (int i = 0; i < method.parameters.length; i++) { - final Parameter param = method.parameters[i]; - final String paramName = _snakeCaseFromCamelCase(param.name); - final String paramType = _getType(module, param.type); - indent.writeln( - 'FlValue* value$i = fl_value_get_list_value(message_, $i);'); - if (_isNullablePrimitiveType(param.type)) { - final String primitiveType = - _getType(module, param.type, primitive: true); - indent.writeln('$paramType $paramName = nullptr;'); - indent.writeln('$primitiveType ${paramName}_value;'); - indent.writeScoped( - 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', '}', + indent.newln(); + final List methodArgs = []; + for (int i = 0; i < method.parameters.length; i++) { + final Parameter param = method.parameters[i]; + final String paramName = _snakeCaseFromCamelCase(param.name); + final String paramType = _getType(module, param.type); + indent.writeln( + 'FlValue* value$i = fl_value_get_list_value(message_, $i);', + ); + if (_isNullablePrimitiveType(param.type)) { + final String primitiveType = _getType( + module, + param.type, + primitive: true, + ); + indent.writeln('$paramType $paramName = nullptr;'); + indent.writeln('$primitiveType ${paramName}_value;'); + indent.writeScoped( + 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', + '}', () { - final String paramValue = - _fromFlValue(module, method.parameters[i].type, 'value$i'); - indent.writeln('${paramName}_value = $paramValue;'); - indent.writeln('$paramName = &${paramName}_value;'); - }); - } else { - final String paramValue = - _fromFlValue(module, method.parameters[i].type, 'value$i'); - indent.writeln('$paramType $paramName = $paramValue;'); + final String paramValue = _fromFlValue( + module, + method.parameters[i].type, + 'value$i', + ); + indent.writeln('${paramName}_value = $paramValue;'); + indent.writeln('$paramName = &${paramName}_value;'); + }, + ); + } else { + final String paramValue = _fromFlValue( + module, + method.parameters[i].type, + 'value$i', + ); + indent.writeln('$paramType $paramName = $paramValue;'); + } + methodArgs.add(paramName); + if (_isNumericListType(method.parameters[i].type)) { + indent.writeln( + 'size_t ${paramName}_length = fl_value_get_length(value$i);', + ); + methodArgs.add('${paramName}_length'); + } } - methodArgs.add(paramName); - if (_isNumericListType(method.parameters[i].type)) { + if (method.isAsynchronous) { + final List vfuncArgs = []; + vfuncArgs.addAll(methodArgs); + vfuncArgs.addAll(['handle', 'self->user_data']); indent.writeln( - 'size_t ${paramName}_length = fl_value_get_length(value$i);'); - methodArgs.add('${paramName}_length'); - } - } - if (method.isAsynchronous) { - final List vfuncArgs = []; - vfuncArgs.addAll(methodArgs); - vfuncArgs.addAll(['handle', 'self->user_data']); - indent.writeln( - 'g_autoptr(${className}ResponseHandle) handle = ${methodPrefix}_response_handle_new(channel, response_handle);'); - indent.writeln("self->vtable->$methodName(${vfuncArgs.join(', ')});"); - } else { - final List vfuncArgs = []; - vfuncArgs.addAll(methodArgs); - vfuncArgs.add('self->user_data'); - indent.writeln( - "g_autoptr($responseClassName) response = self->vtable->$methodName(${vfuncArgs.join(', ')});"); - indent.writeScoped('if (response == nullptr) {', '}', () { + 'g_autoptr(${className}ResponseHandle) handle = ${methodPrefix}_response_handle_new(channel, response_handle);', + ); indent.writeln( - 'g_warning("No response returned to %s.%s", "${api.name}", "${method.name}");'); - indent.writeln('return;'); - }); + "self->vtable->$methodName(${vfuncArgs.join(', ')});", + ); + } else { + final List vfuncArgs = []; + vfuncArgs.addAll(methodArgs); + vfuncArgs.add('self->user_data'); + indent.writeln( + "g_autoptr($responseClassName) response = self->vtable->$methodName(${vfuncArgs.join(', ')});", + ); + indent.writeScoped('if (response == nullptr) {', '}', () { + indent.writeln( + 'g_warning("No response returned to %s.%s", "${api.name}", "${method.name}");', + ); + indent.writeln('return;'); + }); - indent.newln(); - indent.writeln('g_autoptr(GError) error = NULL;'); - indent.writeScoped( + indent.newln(); + indent.writeln('g_autoptr(GError) error = NULL;'); + indent.writeScoped( 'if (!fl_basic_message_channel_respond(channel, response_handle, response->value, &error)) {', - '}', () { - indent.writeln( - 'g_warning("Failed to send response to %s.%s: %s", "${api.name}", "${method.name}", error->message);'); - }); - } - }); + '}', + () { + indent.writeln( + 'g_warning("Failed to send response to %s.%s: %s", "${api.name}", "${method.name}", error->message);', + ); + }, + ); + } + }, + ); } indent.newln(); indent.writeScoped( - 'void ${methodPrefix}_set_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix, const $vtableName* vtable, gpointer user_data, GDestroyNotify user_data_free_func) {', - '}', () { - indent.writeln( - 'g_autofree gchar* dot_suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");'); - indent.writeln( - 'g_autoptr($className) api_data = ${methodPrefix}_new(vtable, user_data, user_data_free_func);'); - - indent.newln(); - indent.writeln( - 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();'); - for (final Method method in api.methods) { - final String methodName = _getMethodName(method.name); - final String channelName = - makeChannelName(api, method, dartPackageName); + 'void ${methodPrefix}_set_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix, const $vtableName* vtable, gpointer user_data, GDestroyNotify user_data_free_func) {', + '}', + () { indent.writeln( - 'g_autofree gchar* ${methodName}_channel_name = g_strdup_printf("$channelName%s", dot_suffix);'); + 'g_autofree gchar* dot_suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");', + ); indent.writeln( - 'g_autoptr(FlBasicMessageChannel) ${methodName}_channel = fl_basic_message_channel_new(messenger, ${methodName}_channel_name, FL_MESSAGE_CODEC(codec));'); + 'g_autoptr($className) api_data = ${methodPrefix}_new(vtable, user_data, user_data_free_func);', + ); + + indent.newln(); indent.writeln( - 'fl_basic_message_channel_set_message_handler(${methodName}_channel, ${methodPrefix}_${methodName}_cb, g_object_ref(api_data), g_object_unref);'); - } - }); + 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();', + ); + for (final Method method in api.methods) { + final String methodName = _getMethodName(method.name); + final String channelName = makeChannelName( + api, + method, + dartPackageName, + ); + indent.writeln( + 'g_autofree gchar* ${methodName}_channel_name = g_strdup_printf("$channelName%s", dot_suffix);', + ); + indent.writeln( + 'g_autoptr(FlBasicMessageChannel) ${methodName}_channel = fl_basic_message_channel_new(messenger, ${methodName}_channel_name, FL_MESSAGE_CODEC(codec));', + ); + indent.writeln( + 'fl_basic_message_channel_set_message_handler(${methodName}_channel, ${methodPrefix}_${methodName}_cb, g_object_ref(api_data), g_object_unref);', + ); + } + }, + ); indent.newln(); indent.writeScoped( - 'void ${methodPrefix}_clear_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix) {', - '}', () { - indent.writeln( - 'g_autofree gchar* dot_suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");'); - - indent.newln(); - indent.writeln( - 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();'); - for (final Method method in api.methods) { - final String methodName = _getMethodName(method.name); - final String channelName = - makeChannelName(api, method, dartPackageName); - indent.writeln( - 'g_autofree gchar* ${methodName}_channel_name = g_strdup_printf("$channelName%s", dot_suffix);'); + 'void ${methodPrefix}_clear_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix) {', + '}', + () { indent.writeln( - 'g_autoptr(FlBasicMessageChannel) ${methodName}_channel = fl_basic_message_channel_new(messenger, ${methodName}_channel_name, FL_MESSAGE_CODEC(codec));'); + 'g_autofree gchar* dot_suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");', + ); + + indent.newln(); indent.writeln( - 'fl_basic_message_channel_set_message_handler(${methodName}_channel, nullptr, nullptr, nullptr);'); - } - }); + 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();', + ); + for (final Method method in api.methods) { + final String methodName = _getMethodName(method.name); + final String channelName = makeChannelName( + api, + method, + dartPackageName, + ); + indent.writeln( + 'g_autofree gchar* ${methodName}_channel_name = g_strdup_printf("$channelName%s", dot_suffix);', + ); + indent.writeln( + 'g_autoptr(FlBasicMessageChannel) ${methodName}_channel = fl_basic_message_channel_new(messenger, ${methodName}_channel_name, FL_MESSAGE_CODEC(codec));', + ); + indent.writeln( + 'fl_basic_message_channel_set_message_handler(${methodName}_channel, nullptr, nullptr, nullptr);', + ); + } + }, + ); - for (final Method method - in api.methods.where((Method method) => method.isAsynchronous)) { + for (final Method method in api.methods.where( + (Method method) => method.isAsynchronous, + )) { final String returnType = _getType(module, method.returnType); final String methodName = _getMethodName(method.name); final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final String responseMethodPrefix = - _getMethodPrefix(module, responseName); + final String responseMethodPrefix = _getMethodPrefix( + module, + responseName, + ); indent.newln(); final List respondArgs = [ '${className}ResponseHandle* response_handle', if (returnType != 'void') '$returnType return_value', - if (_isNumericListType(method.returnType)) 'size_t return_value_length' + if (_isNumericListType(method.returnType)) 'size_t return_value_length', ]; indent.writeScoped( - "void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')}) {", - '}', () { - final List returnArgs = [ - if (returnType != 'void') 'return_value', - if (_isNumericListType(method.returnType)) 'return_value_length' - ]; - indent.writeln( - 'g_autoptr($responseClassName) response = ${responseMethodPrefix}_new(${returnArgs.join(', ')});'); - indent.writeln('g_autoptr(GError) error = nullptr;'); - indent.writeScoped( - 'if (!fl_basic_message_channel_respond(response_handle->channel, response_handle->response_handle, response->value, &error)) {', - '}', () { + "void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')}) {", + '}', + () { + final List returnArgs = [ + if (returnType != 'void') 'return_value', + if (_isNumericListType(method.returnType)) 'return_value_length', + ]; indent.writeln( - 'g_warning("Failed to send response to %s.%s: %s", "${api.name}", "${method.name}", error->message);'); - }); - }); + 'g_autoptr($responseClassName) response = ${responseMethodPrefix}_new(${returnArgs.join(', ')});', + ); + indent.writeln('g_autoptr(GError) error = nullptr;'); + indent.writeScoped( + 'if (!fl_basic_message_channel_respond(response_handle->channel, response_handle->response_handle, response->value, &error)) {', + '}', + () { + indent.writeln( + 'g_warning("Failed to send response to %s.%s: %s", "${api.name}", "${method.name}", error->message);', + ); + }, + ); + }, + ); indent.newln(); final List respondErrorArgs = [ '${className}ResponseHandle* response_handle', 'const gchar* code', 'const gchar* message', - 'FlValue* details' + 'FlValue* details', ]; indent.writeScoped( - "void ${methodPrefix}_respond_error_$methodName(${respondErrorArgs.join(', ')}) {", - '}', () { - indent.writeln( - 'g_autoptr($responseClassName) response = ${responseMethodPrefix}_new_error(code, message, details);'); - indent.writeln('g_autoptr(GError) error = nullptr;'); - indent.writeScoped( - 'if (!fl_basic_message_channel_respond(response_handle->channel, response_handle->response_handle, response->value, &error)) {', - '}', () { + "void ${methodPrefix}_respond_error_$methodName(${respondErrorArgs.join(', ')}) {", + '}', + () { indent.writeln( - 'g_warning("Failed to send response to %s.%s: %s", "${api.name}", "${method.name}", error->message);'); - }); - }); + 'g_autoptr($responseClassName) response = ${responseMethodPrefix}_new_error(code, message, details);', + ); + indent.writeln('g_autoptr(GError) error = nullptr;'); + indent.writeScoped( + 'if (!fl_basic_message_channel_respond(response_handle->channel, response_handle->response_handle, response->value, &error)) {', + '}', + () { + indent.writeln( + 'g_warning("Failed to send response to %s.%s: %s", "${api.name}", "${method.name}", error->message);', + ); + }, + ); + }, + ); } } } // Returns the module name to use. String _getModule( - InternalGObjectOptions generatorOptions, String dartPackageName) { + InternalGObjectOptions generatorOptions, + String dartPackageName, +) { return generatorOptions.module ?? _camelCaseFromSnakeCase(dartPackageName); } @@ -1803,8 +2040,12 @@ String _getGuardName(String? headerFileName) { } // Writes the GObject macro to generate a new type. -void _writeDeclareFinalType(Indent indent, String module, String name, - {String parentClassName = 'GObject'}) { +void _writeDeclareFinalType( + Indent indent, + String module, + String name, { + String parentClassName = 'GObject', +}) { final String upperModule = _snakeCaseFromCamelCase(module).toUpperCase(); final String className = _getClassName(module, name); final String snakeClassName = _snakeCaseFromCamelCase(name); @@ -1812,12 +2053,17 @@ void _writeDeclareFinalType(Indent indent, String module, String name, final String methodPrefix = _getMethodPrefix(module, name); indent.writeln( - 'G_DECLARE_FINAL_TYPE($className, $methodPrefix, $upperModule, $upperSnakeClassName, $parentClassName)'); + 'G_DECLARE_FINAL_TYPE($className, $methodPrefix, $upperModule, $upperSnakeClassName, $parentClassName)', + ); } // Writes the GObject macro to define a new type. -void _writeDefineType(Indent indent, String module, String name, - {String parentType = 'G_TYPE_OBJECT'}) { +void _writeDefineType( + Indent indent, + String module, + String name, { + String parentType = 'G_TYPE_OBJECT', +}) { final String className = _getClassName(module, name); final String methodPrefix = _getMethodPrefix(module, name); @@ -1826,8 +2072,12 @@ void _writeDefineType(Indent indent, String module, String name, // Writes the struct for a GObject. void _writeObjectStruct( - Indent indent, String module, String name, void Function() func, - {String parentClassName = 'GObject'}) { + Indent indent, + String module, + String name, + void Function() func, { + String parentClassName = 'GObject', +}) { final String className = _getClassName(module, name); indent.writeScoped('struct _$className {', '};', () { @@ -1840,45 +2090,67 @@ void _writeObjectStruct( // Writes the dispose method for a GObject. void _writeDispose( - Indent indent, String module, String name, void Function() func) { + Indent indent, + String module, + String name, + void Function() func, +) { final String methodPrefix = _getMethodPrefix(module, name); indent.writeScoped( - 'static void ${methodPrefix}_dispose(GObject* object) {', '}', () { - func(); - indent.writeln( - 'G_OBJECT_CLASS(${methodPrefix}_parent_class)->dispose(object);'); - }); + 'static void ${methodPrefix}_dispose(GObject* object) {', + '}', + () { + func(); + indent.writeln( + 'G_OBJECT_CLASS(${methodPrefix}_parent_class)->dispose(object);', + ); + }, + ); } // Writes the init function for a GObject. void _writeInit( - Indent indent, String module, String name, void Function() func) { + Indent indent, + String module, + String name, + void Function() func, +) { final String className = _getClassName(module, name); final String methodPrefix = _getMethodPrefix(module, name); indent.writeScoped( - 'static void ${methodPrefix}_init($className* self) {', '}', () { - func(); - }); + 'static void ${methodPrefix}_init($className* self) {', + '}', + () { + func(); + }, + ); } // Writes the class init function for a GObject. void _writeClassInit( - Indent indent, String module, String name, void Function() func, - {bool hasDispose = true}) { + Indent indent, + String module, + String name, + void Function() func, { + bool hasDispose = true, +}) { final String className = _getClassName(module, name); final String methodPrefix = _getMethodPrefix(module, name); indent.writeScoped( - 'static void ${methodPrefix}_class_init(${className}Class* klass) {', '}', - () { - if (hasDispose) { - indent - .writeln('G_OBJECT_CLASS(klass)->dispose = ${methodPrefix}_dispose;'); - } - func(); - }); + 'static void ${methodPrefix}_class_init(${className}Class* klass) {', + '}', + () { + if (hasDispose) { + indent.writeln( + 'G_OBJECT_CLASS(klass)->dispose = ${methodPrefix}_dispose;', + ); + } + func(); + }, + ); } // Writes the constructor for a GObject. @@ -1888,12 +2160,17 @@ void _writeObjectNew(Indent indent, String module, String name) { final String castMacro = _getClassCastMacro(module, name); indent.writeln( - '$className* self = $castMacro(g_object_new(${methodPrefix}_get_type(), nullptr));'); + '$className* self = $castMacro(g_object_new(${methodPrefix}_get_type(), nullptr));', + ); } // Writes the cast used at the top of GObject methods. void _writeCastSelf( - Indent indent, String module, String name, String variableName) { + Indent indent, + String module, + String name, + String variableName, +) { final String className = _getClassName(module, name); final String castMacro = _getClassCastMacro(module, name); indent.writeln('$className* self = $castMacro($variableName);'); @@ -1901,8 +2178,10 @@ void _writeCastSelf( // Converts a string from CamelCase to snake_case. String _snakeCaseFromCamelCase(String camelCase) { - return camelCase.replaceAllMapped(RegExp(r'[A-Z]'), - (Match m) => '${m.start == 0 ? '' : '_'}${m[0]!.toLowerCase()}'); + return camelCase.replaceAllMapped( + RegExp(r'[A-Z]'), + (Match m) => '${m.start == 0 ? '' : '_'}${m[0]!.toLowerCase()}', + ); } // Converts a string from snake_case to CamelCase @@ -1973,8 +2252,12 @@ String _getEnumValue(String module, String enumName, String memberName) { } // Returns code for storing a value of [type]. -String _getType(String module, TypeDeclaration type, - {bool isOutput = false, bool primitive = false}) { +String _getType( + String module, + TypeDeclaration type, { + bool isOutput = false, + bool primitive = false, +}) { if (type.isClass) { return '${_getClassName(module, type.baseName)}*'; } else if (type.isEnum) { @@ -2052,8 +2335,11 @@ String? _getClearFunction(TypeDeclaration type, String variableName) { } // Returns code for the default value for [type]. -String _getDefaultValue(String module, TypeDeclaration type, - {bool primitive = false}) { +String _getDefaultValue( + String module, + TypeDeclaration type, { + bool primitive = false, +}) { if (type.isClass || (type.isNullable && !primitive)) { return 'nullptr'; } else if (type.isEnum) { @@ -2081,8 +2367,12 @@ String _getDefaultValue(String module, TypeDeclaration type, // Returns code to copy the native data type stored in [variableName]. // // [lengthVariableName] must be provided for the typed numeric *List types. -String _referenceValue(String module, TypeDeclaration type, String variableName, - {String? lengthVariableName}) { +String _referenceValue( + String module, + TypeDeclaration type, + String variableName, { + String? lengthVariableName, +}) { if (type.isClass) { final String castMacro = _getClassCastMacro(module, type.baseName); return '$castMacro(g_object_ref($variableName))'; @@ -2106,30 +2396,45 @@ String _referenceValue(String module, TypeDeclaration type, String variableName, } String _getCustomTypeIdFromDeclaration( - Root root, TypeDeclaration type, String module) { + Root root, + TypeDeclaration type, + String module, +) { return _getCustomTypeId( - module, - getEnumeratedTypes(root, excludeSealedClasses: true).firstWhere( - (EnumeratedType t) => - (type.isClass && t.associatedClass == type.associatedClass) || - (type.isEnum && t.associatedEnum == type.associatedEnum))); + module, + getEnumeratedTypes(root, excludeSealedClasses: true).firstWhere( + (EnumeratedType t) => + (type.isClass && t.associatedClass == type.associatedClass) || + (type.isEnum && t.associatedEnum == type.associatedEnum), + ), + ); } // Returns code to convert the native data type stored in [variableName] to a FlValue. // // [lengthVariableName] must be provided for the typed numeric *List types. String _makeFlValue( - Root root, String module, TypeDeclaration type, String variableName, - {String? lengthVariableName}) { + Root root, + String module, + TypeDeclaration type, + String variableName, { + String? lengthVariableName, +}) { final String value; if (type.isClass) { - final String customTypeId = - _getCustomTypeIdFromDeclaration(root, type, module); + final String customTypeId = _getCustomTypeIdFromDeclaration( + root, + type, + module, + ); value = 'fl_value_new_custom_object($customTypeId, G_OBJECT($variableName))'; } else if (type.isEnum) { - final String customTypeId = - _getCustomTypeIdFromDeclaration(root, type, module); + final String customTypeId = _getCustomTypeIdFromDeclaration( + root, + type, + module, + ); value = 'fl_value_new_custom($customTypeId, fl_value_new_int(${type.isNullable ? '*$variableName' : variableName}), (GDestroyNotify)fl_value_unref)'; } else if (_isFlValueWrappedType(type)) { @@ -2137,17 +2442,20 @@ 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 4b9c1e4db76..25e481124d6 100644 --- a/packages/pigeon/lib/src/java/java_generator.dart +++ b/packages/pigeon/lib/src/java/java_generator.dart @@ -22,10 +22,10 @@ const String _docCommentSuffix = ' */'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification( - _docCommentPrefix, - closeCommentToken: _docCommentSuffix, - blockContinuationToken: _docCommentContinuation, -); + _docCommentPrefix, + closeCommentToken: _docCommentSuffix, + blockContinuationToken: _docCommentContinuation, + ); /// The standard codec for Flutter, used for any non custom codecs and extended for custom codecs. const String _codecName = 'PigeonCodec'; @@ -105,10 +105,10 @@ class InternalJavaOptions extends InternalOptions { JavaOptions options, { required this.javaOut, Iterable? copyrightHeader, - }) : className = options.className ?? path.basenameWithoutExtension(javaOut), - package = options.package, - copyrightHeader = options.copyrightHeader ?? copyrightHeader, - useGeneratedAnnotation = options.useGeneratedAnnotation; + }) : className = options.className ?? path.basenameWithoutExtension(javaOut), + package = options.package, + copyrightHeader = options.copyrightHeader ?? copyrightHeader, + useGeneratedAnnotation = options.useGeneratedAnnotation; /// Path to the java file that will be generated. final String javaOut; @@ -161,8 +161,9 @@ class JavaGenerator extends StructuredGenerator { } if (root.classes.isNotEmpty) { indent.writeln('import static java.lang.annotation.ElementType.METHOD;'); - indent - .writeln('import static java.lang.annotation.RetentionPolicy.CLASS;'); + indent.writeln( + 'import static java.lang.annotation.RetentionPolicy.CLASS;', + ); indent.newln(); } indent.writeln('import android.util.Log;'); @@ -196,9 +197,11 @@ class JavaGenerator extends StructuredGenerator { required String dartPackageName, }) { indent.writeln( - '$_docCommentPrefix Generated class from Pigeon.$_docCommentSuffix'); + '$_docCommentPrefix Generated class from Pigeon.$_docCommentSuffix', + ); indent.writeln( - '@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})'); + '@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})', + ); if (generatorOptions.useGeneratedAnnotation ?? false) { indent.writeln('@javax.annotation.Generated("dev.flutter.pigeon")'); } @@ -223,15 +226,22 @@ class JavaGenerator extends StructuredGenerator { indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); + indent, + anEnum.documentationComments, + _docCommentSpec, + ); indent.write('public enum ${anEnum.name} '); indent.addScoped('{', '}', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( - indent, member.documentationComments, _docCommentSpec); + indent, + member.documentationComments, + _docCommentSpec, + ); indent.writeln( - '${camelToSnake(member.name)}($index)${index == anEnum.members.length - 1 ? ';' : ','}'); + '${camelToSnake(member.name)}($index)${index == anEnum.members.length - 1 ? ';' : ','}', + ); }); indent.newln(); // This uses default access (package-private), because private causes @@ -254,19 +264,23 @@ class JavaGenerator extends StructuredGenerator { required String dartPackageName, }) { const List generatedMessages = [ - ' Generated class from Pigeon that represents data sent in messages.' + ' Generated class from Pigeon that represents data sent in messages.', ]; indent.newln(); addDocumentationComments( - indent, classDefinition.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + indent, + classDefinition.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); _writeDataClassSignature(generatorOptions, indent, classDefinition, () { - if (getFieldsInSerializationOrder(classDefinition) - .map((NamedType e) => !e.type.isNullable) - .any((bool e) => e)) { + if (getFieldsInSerializationOrder( + classDefinition, + ).map((NamedType e) => !e.type.isNullable).any((bool e) => e)) { indent.writeln( - '$_docCommentPrefix Constructor is non-public to enforce null safety; use Builder.$_docCommentSuffix'); + '$_docCommentPrefix Constructor is non-public to enforce null safety; use Builder.$_docCommentSuffix', + ); indent.writeln('${classDefinition.name}() {}'); indent.newln(); } @@ -291,34 +305,47 @@ class JavaGenerator extends StructuredGenerator { } void _writeClassField( - InternalJavaOptions generatorOptions, Indent indent, NamedType field) { + InternalJavaOptions generatorOptions, + Indent indent, + NamedType field, + ) { final HostDatatype hostDatatype = getFieldHostDatatype( - field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x)); + field, + (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), + ); final String nullability = field.type.isNullable ? '@Nullable ' : '@NonNull '; addDocumentationComments( - indent, field.documentationComments, _docCommentSpec); + indent, + field.documentationComments, + _docCommentSpec, + ); - indent - .writeln('private $nullability${hostDatatype.datatype} ${field.name};'); + indent.writeln( + 'private $nullability${hostDatatype.datatype} ${field.name};', + ); indent.newln(); indent.write( - 'public $nullability${hostDatatype.datatype} ${_makeGetter(field)}() '); + 'public $nullability${hostDatatype.datatype} ${_makeGetter(field)}() ', + ); indent.addScoped('{', '}', () { indent.writeln('return ${field.name};'); }); indent.newln(); indent.writeScoped( - 'public void ${_makeSetter(field)}($nullability${hostDatatype.datatype} setterArg) {', - '}', () { - if (!field.type.isNullable) { - indent.writeScoped('if (setterArg == null) {', '}', () { - indent.writeln( - 'throw new IllegalStateException("Nonnull field \\"${field.name}\\" is null.");'); - }); - } - indent.writeln('this.${field.name} = setterArg;'); - }); + 'public void ${_makeSetter(field)}($nullability${hostDatatype.datatype} setterArg) {', + '}', + () { + if (!field.type.isNullable) { + indent.writeScoped('if (setterArg == null) {', '}', () { + indent.writeln( + 'throw new IllegalStateException("Nonnull field \\"${field.name}\\" is null.");', + ); + }); + } + indent.writeln('this.${field.name} = setterArg;'); + }, + ); } void _writeDataClassSignature( @@ -329,15 +356,13 @@ class JavaGenerator extends StructuredGenerator { bool private = false, }) { indent.write( - '${private ? 'private' : 'public'} static final class ${classDefinition.name} '); + '${private ? 'private' : 'public'} static final class ${classDefinition.name} ', + ); indent.addScoped('{', '}', () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { - _writeClassField( - generatorOptions, - indent, - field, - ); + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { + _writeClassField(generatorOptions, indent, field); indent.newln(); } dataClassBody(); @@ -350,20 +375,22 @@ class JavaGenerator extends StructuredGenerator { indent.writeScoped('public boolean equals(Object o) {', '}', () { indent.writeln('if (this == o) { return true; }'); indent.writeln( - 'if (o == null || getClass() != o.getClass()) { return false; }'); + 'if (o == null || getClass() != o.getClass()) { return false; }', + ); indent.writeln( - '${classDefinition.name} that = (${classDefinition.name}) o;'); - final Iterable checks = classDefinition.fields.map( - (NamedType field) { - // Objects.equals only does pointer equality for array types. - if (_javaTypeIsArray(field.type)) { - return 'Arrays.equals(${field.name}, that.${field.name})'; - } - return field.type.isNullable - ? 'Objects.equals(${field.name}, that.${field.name})' - : '${field.name}.equals(that.${field.name})'; - }, + '${classDefinition.name} that = (${classDefinition.name}) o;', ); + final Iterable checks = classDefinition.fields.map(( + NamedType field, + ) { + // Objects.equals only does pointer equality for array types. + if (_javaTypeIsArray(field.type)) { + return 'Arrays.equals(${field.name}, that.${field.name})'; + } + return field.type.isNullable + ? 'Objects.equals(${field.name}, that.${field.name})' + : '${field.name}.equals(that.${field.name})'; + }); indent.writeln('return ${checks.join(' && ')};'); }); indent.newln(); @@ -378,9 +405,10 @@ 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 @@ -392,7 +420,8 @@ class JavaGenerator extends StructuredGenerator { // Manually mix in the Arrays.hashCode values. for (final String name in arrayFieldNames) { indent.writeln( - '$resultVar = 31 * $resultVar + Arrays.hashCode($name);'); + '$resultVar = 31 * $resultVar + Arrays.hashCode($name);', + ); } indent.writeln('return $resultVar;'); } @@ -408,32 +437,40 @@ class JavaGenerator extends StructuredGenerator { ) { indent.write('public static final class Builder '); indent.addScoped('{', '}', () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final HostDatatype hostDatatype = getFieldHostDatatype( - field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x)); + field, + (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), + ); final String nullability = field.type.isNullable ? '@Nullable' : '@NonNull'; indent.newln(); indent.writeln( - 'private @Nullable ${hostDatatype.datatype} ${field.name};'); + 'private @Nullable ${hostDatatype.datatype} ${field.name};', + ); indent.newln(); indent.writeln('@CanIgnoreReturnValue'); indent.writeScoped( - 'public @NonNull Builder ${_makeSetter(field)}($nullability ${hostDatatype.datatype} setterArg) {', - '}', () { - indent.writeln('this.${field.name} = setterArg;'); - indent.writeln('return this;'); - }); + 'public @NonNull Builder ${_makeSetter(field)}($nullability ${hostDatatype.datatype} setterArg) {', + '}', + () { + indent.writeln('this.${field.name} = setterArg;'); + indent.writeln('return this;'); + }, + ); } indent.newln(); indent.write('public @NonNull ${classDefinition.name} build() '); indent.addScoped('{', '}', () { const String returnVal = 'pigeonReturn'; indent.writeln( - '${classDefinition.name} $returnVal = new ${classDefinition.name}();'); - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + '${classDefinition.name} $returnVal = new ${classDefinition.name}();', + ); + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { indent.writeln('$returnVal.${_makeSetter(field)}(${field.name});'); } indent.writeln('return $returnVal;'); @@ -454,9 +491,11 @@ class JavaGenerator extends StructuredGenerator { indent.write('ArrayList toList() '); indent.addScoped('{', '}', () { indent.writeln( - 'ArrayList toListResult = new ArrayList<>(${classDefinition.fields.length});'); - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + 'ArrayList toListResult = new ArrayList<>(${classDefinition.fields.length});', + ); + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { indent.writeln('toListResult.add(${field.name});'); } indent.writeln('return toListResult;'); @@ -473,19 +512,25 @@ class JavaGenerator extends StructuredGenerator { }) { indent.newln(); indent.write( - 'static @NonNull ${classDefinition.name} fromList(@NonNull ArrayList ${varNamePrefix}list) '); + 'static @NonNull ${classDefinition.name} fromList(@NonNull ArrayList ${varNamePrefix}list) ', + ); indent.addScoped('{', '}', () { const String result = 'pigeonResult'; indent.writeln( - '${classDefinition.name} $result = new ${classDefinition.name}();'); - enumerate(getFieldsInSerializationOrder(classDefinition), - (int index, final NamedType field) { + '${classDefinition.name} $result = new ${classDefinition.name}();', + ); + enumerate(getFieldsInSerializationOrder(classDefinition), ( + int index, + final NamedType field, + ) { final String fieldVariable = field.name; final String setter = _makeSetter(field); indent.writeln( - 'Object $fieldVariable = ${varNamePrefix}list.get($index);'); - indent - .writeln('$result.$setter(${_castObject(field, fieldVariable)});'); + 'Object $fieldVariable = ${varNamePrefix}list.get($index);', + ); + indent.writeln( + '$result.$setter(${_castObject(field, fieldVariable)});', + ); }); indent.writeln('return $result;'); }); @@ -504,25 +549,31 @@ class JavaGenerator extends StructuredGenerator { 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 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 ', () { if (customType.enumeration >= maximumCodecFieldKey) { - indent - .writeln('$_overflowClassName wrap = new $_overflowClassName();'); indent.writeln( - 'wrap.setType(${customType.enumeration - maximumCodecFieldKey}L);'); + '$_overflowClassName wrap = new $_overflowClassName();', + ); indent.writeln( - 'wrap.setWrapped($nullCheck((${customType.name}) value).$encodeString);'); + 'wrap.setType(${customType.enumeration - maximumCodecFieldKey}L);', + ); + indent.writeln( + 'wrap.setWrapped($nullCheck((${customType.name}) value).$encodeString);', + ); } indent.writeln('stream.write($enumeration);'); indent.writeln('writeValue(stream, $valueString);'); @@ -535,19 +586,24 @@ class JavaGenerator extends StructuredGenerator { indent.newln(); indent.nest(1, () { indent.writeln( - 'return ${customType.name}.fromList((ArrayList) readValue(buffer));'); + 'return ${customType.name}.fromList((ArrayList) readValue(buffer));', + ); }); } else if (customType.type == CustomTypes.customEnum) { indent.addScoped(' {', '}', () { indent.writeln('Object value = readValue(buffer);'); - indent - .writeln('return ${_intToEnum('value', customType.name, true)};'); + indent.writeln( + 'return ${_intToEnum('value', customType.name, true)};', + ); }); } } final EnumeratedType overflowClass = EnumeratedType( - _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass); + _overflowClassName, + maximumCodecFieldKey, + CustomTypes.customClass, + ); if (root.requiresOverflowClass) { _writeCodecOverflowUtilities( @@ -560,36 +616,41 @@ class JavaGenerator extends StructuredGenerator { } indent.newln(); indent.write( - 'private static class $_codecName extends StandardMessageCodec '); + 'private static class $_codecName extends StandardMessageCodec ', + ); indent.addScoped('{', '}', () { indent.writeln( - 'public static final $_codecName INSTANCE = new $_codecName();'); + 'public static final $_codecName INSTANCE = new $_codecName();', + ); indent.newln(); indent.writeln('private $_codecName() {}'); indent.newln(); indent.writeln('@Override'); indent.writeScoped( - 'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) {', - '}', () { - indent.writeScoped('switch (type) {', '}', () { - for (final EnumeratedType customType in enumeratedTypes) { - if (customType.enumeration < maximumCodecFieldKey) { - writeDecodeLogic(customType); + 'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) {', + '}', + () { + indent.writeScoped('switch (type) {', '}', () { + for (final EnumeratedType customType in enumeratedTypes) { + if (customType.enumeration < maximumCodecFieldKey) { + writeDecodeLogic(customType); + } } - } - if (root.requiresOverflowClass) { - writeDecodeLogic(overflowClass); - } - indent.writeln('default:'); - indent.nest(1, () { - indent.writeln('return super.readValueOfType(type, buffer);'); + if (root.requiresOverflowClass) { + writeDecodeLogic(overflowClass); + } + indent.writeln('default:'); + indent.nest(1, () { + indent.writeln('return super.readValueOfType(type, buffer);'); + }); }); - }); - }); + }, + ); indent.newln(); indent.writeln('@Override'); indent.write( - 'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) '); + 'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) ', + ); indent.addScoped('{', '}', () { indent.write(''); enumeratedTypes.forEach(writeEncodeLogic); @@ -609,32 +670,32 @@ class JavaGenerator extends StructuredGenerator { required String dartPackageName, }) { final NamedType overflowInteration = NamedType( - name: 'type', - type: const TypeDeclaration(baseName: 'int', isNullable: false)); + name: 'type', + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ); final NamedType overflowObject = NamedType( - name: 'wrapped', - type: const TypeDeclaration(baseName: 'Object', isNullable: true)); + name: 'wrapped', + type: const TypeDeclaration(baseName: 'Object', isNullable: true), + ); final List overflowFields = [ overflowInteration, overflowObject, ]; - final Class overflowClass = - Class(name: _overflowClassName, fields: overflowFields); + final Class overflowClass = Class( + name: _overflowClassName, + fields: overflowFields, + ); - _writeDataClassSignature( - generatorOptions, - indent, - overflowClass, - () { - writeClassEncode( - generatorOptions, - root, - indent, - overflowClass, - dartPackageName: dartPackageName, - ); + _writeDataClassSignature(generatorOptions, indent, overflowClass, () { + writeClassEncode( + generatorOptions, + root, + indent, + overflowClass, + dartPackageName: dartPackageName, + ); - indent.format(''' + indent.format(''' static @Nullable Object fromList(@NonNull ArrayList ${varNamePrefix}list) { $_overflowClassName wrapper = new $_overflowClassName(); wrapper.setType((Long) ${varNamePrefix}list.get(0)); @@ -643,31 +704,31 @@ static @Nullable Object fromList(@NonNull ArrayList ${varNamePrefix}list } '''); - indent.writeScoped('@Nullable Object unwrap() {', '}', () { - indent.format(''' + indent.writeScoped('@Nullable Object unwrap() {', '}', () { + indent.format(''' if (wrapped == null) { return null; } '''); - indent.writeScoped('switch (type.intValue()) {', '}', () { - for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) { - indent.writeln('case ${i - totalCustomCodecKeysAllowed}:'); - indent.nest(1, () { - if (types[i].type == CustomTypes.customClass) { - indent.writeln( - 'return ${types[i].name}.fromList((ArrayList) wrapped);'); - } else if (types[i].type == CustomTypes.customEnum) { - indent.writeln( - 'return ${_intToEnum('wrapped', types[i].name, false)};'); - } - }); - } - }); - indent.writeln('return null;'); + indent.writeScoped('switch (type.intValue()) {', '}', () { + for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) { + indent.writeln('case ${i - totalCustomCodecKeysAllowed}:'); + indent.nest(1, () { + if (types[i].type == CustomTypes.customClass) { + indent.writeln( + 'return ${types[i].name}.fromList((ArrayList) wrapped);', + ); + } else if (types[i].type == CustomTypes.customEnum) { + indent.writeln( + 'return ${_intToEnum('wrapped', types[i].name, false)};', + ); + } + }); + } }); - }, - private: true, - ); + indent.writeln('return null;'); + }); + }, private: true); } /// Writes the code for a flutter [Api], [api]. @@ -693,10 +754,14 @@ if (wrapped == null) { } const List generatedMessages = [ - ' Generated class from Pigeon that represents Flutter messages that can be called from Java.' + ' Generated class from Pigeon that represents Flutter messages that can be called from Java.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); indent.write('public static class ${api.name} '); indent.addScoped('{', '}', () { @@ -704,23 +769,30 @@ if (wrapped == null) { indent.writeln('private final String messageChannelSuffix;'); indent.newln(); indent.write( - 'public ${api.name}(@NonNull BinaryMessenger argBinaryMessenger) '); + 'public ${api.name}(@NonNull BinaryMessenger argBinaryMessenger) ', + ); indent.addScoped('{', '}', () { indent.writeln('this(argBinaryMessenger, "");'); }); indent.write( - 'public ${api.name}(@NonNull BinaryMessenger argBinaryMessenger, @NonNull String messageChannelSuffix) '); + 'public ${api.name}(@NonNull BinaryMessenger argBinaryMessenger, @NonNull String messageChannelSuffix) ', + ); indent.addScoped('{', '}', () { indent.writeln('this.binaryMessenger = argBinaryMessenger;'); indent.writeln( - 'this.messageChannelSuffix = messageChannelSuffix.isEmpty() ? "" : "." + messageChannelSuffix;'); + 'this.messageChannelSuffix = messageChannelSuffix.isEmpty() ? "" : "." + messageChannelSuffix;', + ); }); indent.newln(); - addDocumentationComments(indent, [], _docCommentSpec, - generatorComments: [ - 'Public interface for sending reply.', - 'The codec used by ${api.name}.' - ]); + addDocumentationComments( + indent, + [], + _docCommentSpec, + generatorComments: [ + 'Public interface for sending reply.', + 'The codec used by ${api.name}.', + ], + ); indent.write('static @NonNull MessageCodec getCodec() '); indent.addScoped('{', '}', () { indent.writeln('return $_codecName.INSTANCE;'); @@ -728,23 +800,33 @@ 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, func.documentationComments, _docCommentSpec); + indent, + func.documentationComments, + _docCommentSpec, + ); if (func.parameters.isEmpty) { - indent - .write('public void ${func.name}(@NonNull $resultType result) '); + indent.write( + 'public void ${func.name}(@NonNull $resultType result) ', + ); sendArgument = 'null'; } else { - final Iterable argTypes = func.parameters - .map((NamedType e) => _nullsafeJavaTypeForDartType(e.type)); - final Iterable argNames = - indexMap(func.parameters, _getSafeArgumentName); - final Iterable enumSafeArgNames = - indexMap(func.parameters, getSafeArgumentExpression); + final Iterable argTypes = func.parameters.map( + (NamedType e) => _nullsafeJavaTypeForDartType(e.type), + ); + final Iterable argNames = indexMap( + func.parameters, + _getSafeArgumentName, + ); + final Iterable enumSafeArgNames = indexMap( + func.parameters, + getSafeArgumentExpression, + ); if (func.parameters.length == 1) { sendArgument = 'new ArrayList<>(Collections.singletonList(${enumSafeArgNames.first}))'; @@ -752,16 +834,20 @@ if (wrapped == null) { sendArgument = 'new ArrayList<>(Arrays.asList(${enumSafeArgNames.join(', ')}))'; } - final String argsSignature = - map2(argTypes, argNames, (String x, String y) => '$x $y') - .join(', '); + final String argsSignature = map2( + argTypes, + argNames, + (String x, String y) => '$x $y', + ).join(', '); indent.write( - 'public void ${func.name}($argsSignature, @NonNull $resultType result) '); + 'public void ${func.name}($argsSignature, @NonNull $resultType result) ', + ); } indent.addScoped('{', '}', () { const String channel = 'channel'; indent.writeln( - 'final String channelName = "${makeChannelName(api, func, dartPackageName)}" + messageChannelSuffix;'); + 'final String channelName = "${makeChannelName(api, func, dartPackageName)}" + messageChannelSuffix;', + ); indent.writeln('BasicMessageChannel $channel ='); indent.nest(2, () { indent.writeln('new BasicMessageChannel<>('); @@ -774,38 +860,50 @@ if (wrapped == null) { indent.writeln('$sendArgument,'); indent.write('channelReply -> '); indent.addScoped('{', '});', () { - indent.writeScoped('if (channelReply instanceof List) {', '} ', - () { - indent.writeln( - 'List listReply = (List) channelReply;'); - indent.writeScoped('if (listReply.size() > 1) {', '} ', () { + indent.writeScoped( + 'if (channelReply instanceof List) {', + '} ', + () { indent.writeln( - 'result.error(new FlutterError((String) listReply.get(0), (String) listReply.get(1), listReply.get(2)));'); - }, addTrailingNewline: false); - if (!func.returnType.isNullable && !func.returnType.isVoid) { - indent.addScoped('else if (listReply.get(0) == null) {', '} ', - () { + 'List listReply = (List) channelReply;', + ); + indent.writeScoped('if (listReply.size() > 1) {', '} ', () { indent.writeln( - 'result.error(new FlutterError("null-error", "Flutter api returned null value for non-null return value.", ""));'); + 'result.error(new FlutterError((String) listReply.get(0), (String) listReply.get(1), listReply.get(2)));', + ); }, addTrailingNewline: false); - } - indent.addScoped('else {', '}', () { - if (func.returnType.isVoid) { - indent.writeln('result.success();'); - } else { - const String output = 'output'; - final String outputExpression; - indent.writeln('@SuppressWarnings("ConstantConditions")'); - outputExpression = - '${_cast('listReply.get(0)', javaType: returnType)};'; - indent.writeln('$returnType $output = $outputExpression'); - indent.writeln('result.success($output);'); + if (!func.returnType.isNullable && !func.returnType.isVoid) { + indent.addScoped( + 'else if (listReply.get(0) == null) {', + '} ', + () { + indent.writeln( + 'result.error(new FlutterError("null-error", "Flutter api returned null value for non-null return value.", ""));', + ); + }, + addTrailingNewline: false, + ); } - }); - }, addTrailingNewline: false); + indent.addScoped('else {', '}', () { + if (func.returnType.isVoid) { + indent.writeln('result.success();'); + } else { + const String output = 'output'; + final String outputExpression; + indent.writeln('@SuppressWarnings("ConstantConditions")'); + outputExpression = + '${_cast('listReply.get(0)', javaType: returnType)};'; + indent.writeln('$returnType $output = $outputExpression'); + indent.writeln('result.success($output);'); + } + }); + }, + addTrailingNewline: false, + ); indent.addScoped(' else {', '} ', () { indent.writeln( - 'result.error(createConnectionError(channelName));'); + 'result.error(createConnectionError(channelName));', + ); }); }); }); @@ -821,15 +919,21 @@ if (wrapped == null) { Indent indent, { required String dartPackageName, }) { - if (root.apis.any((Api api) => - api is AstHostApi && - api.methods.any((Method it) => it.isAsynchronous) || - api is AstFlutterApi)) { + if (root.apis.any( + (Api api) => + api is AstHostApi && + api.methods.any((Method it) => it.isAsynchronous) || + api is AstFlutterApi, + )) { indent.newln(); _writeResultInterfaces(indent); } - super.writeApis(generatorOptions, root, indent, - dartPackageName: dartPackageName); + super.writeApis( + generatorOptions, + root, + indent, + dartPackageName: dartPackageName, + ); } /// Write the java code that represents a host [Api], [api]. @@ -847,10 +951,14 @@ if (wrapped == null) { required String dartPackageName, }) { const List generatedMessages = [ - ' Generated interface from Pigeon that represents a handler of messages from Flutter.' + ' Generated interface from Pigeon that represents a handler of messages from Flutter.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); indent.write('public interface ${api.name} '); indent.addScoped('{', '}', () { @@ -865,32 +973,44 @@ if (wrapped == null) { }); indent.writeln( - '${_docCommentPrefix}Sets up an instance of `${api.name}` to handle messages through the `binaryMessenger`.$_docCommentSuffix'); + '${_docCommentPrefix}Sets up an instance of `${api.name}` to handle messages through the `binaryMessenger`.$_docCommentSuffix', + ); indent.writeScoped( - 'static void setUp(@NonNull BinaryMessenger binaryMessenger, @Nullable ${api.name} api) {', - '}', () { - indent.writeln('setUp(binaryMessenger, "", api);'); - }); + 'static void setUp(@NonNull BinaryMessenger binaryMessenger, @Nullable ${api.name} api) {', + '}', + () { + indent.writeln('setUp(binaryMessenger, "", api);'); + }, + ); indent.write( - 'static void setUp(@NonNull BinaryMessenger binaryMessenger, @NonNull String messageChannelSuffix, @Nullable ${api.name} api) '); + 'static void setUp(@NonNull BinaryMessenger binaryMessenger, @NonNull String messageChannelSuffix, @Nullable ${api.name} api) ', + ); indent.addScoped('{', '}', () { indent.writeln( - 'messageChannelSuffix = messageChannelSuffix.isEmpty() ? "" : "." + messageChannelSuffix;'); + 'messageChannelSuffix = messageChannelSuffix.isEmpty() ? "" : "." + messageChannelSuffix;', + ); String? serialBackgroundQueue; - if (api.methods.any((Method m) => - m.taskQueueType == TaskQueueType.serialBackgroundThread)) { + if (api.methods.any( + (Method m) => m.taskQueueType == TaskQueueType.serialBackgroundThread, + )) { serialBackgroundQueue = 'taskQueue'; indent.writeln( - 'BinaryMessenger.TaskQueue $serialBackgroundQueue = binaryMessenger.makeBackgroundTaskQueue();'); + 'BinaryMessenger.TaskQueue $serialBackgroundQueue = binaryMessenger.makeBackgroundTaskQueue();', + ); } for (final Method method in api.methods) { _writeHostMethodMessageHandler( - generatorOptions, root, indent, api, method, - dartPackageName: dartPackageName, - serialBackgroundQueue: - method.taskQueueType == TaskQueueType.serialBackgroundThread - ? serialBackgroundQueue - : null); + generatorOptions, + root, + indent, + api, + method, + dartPackageName: dartPackageName, + serialBackgroundQueue: + method.taskQueueType == TaskQueueType.serialBackgroundThread + ? serialBackgroundQueue + : null, + ); } }); }); @@ -899,32 +1019,45 @@ if (wrapped == null) { /// Write a method in the interface. /// Example: /// int add(int x, int y); - void _writeInterfaceMethod(InternalJavaOptions generatorOptions, Root root, - Indent indent, Api api, final Method method) { + void _writeInterfaceMethod( + InternalJavaOptions generatorOptions, + Root root, + Indent indent, + Api api, + 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((NamedType e) => _nullsafeJavaTypeForDartType(e.type)); - final Iterable argNames = - method.parameters.map((NamedType e) => e.name); - argSignature - .addAll(map2(argTypes, argNames, (String argType, String argName) { - return '$argType $argName'; - })); + final Iterable argTypes = method.parameters.map( + (NamedType e) => _nullsafeJavaTypeForDartType(e.type), + ); + final Iterable argNames = method.parameters.map( + (NamedType e) => e.name, + ); + argSignature.addAll( + map2(argTypes, argNames, (String argType, String argName) { + return '$argType $argName'; + }), + ); } if (method.isAsynchronous) { argSignature.add('@NonNull $resultType result'); } if (method.documentationComments.isNotEmpty) { addDocumentationComments( - indent, method.documentationComments, _docCommentSpec); + indent, + method.documentationComments, + _docCommentSpec, + ); } else { indent.newln(); } @@ -952,7 +1085,8 @@ if (wrapped == null) { indent.writeln('new BasicMessageChannel<>('); indent.nest(2, () { indent.write( - 'binaryMessenger, "$channelName" + messageChannelSuffix, getCodec()'); + 'binaryMessenger, "$channelName" + messageChannelSuffix, getCodec()', + ); if (serialBackgroundQueue != null) { indent.addln(', $serialBackgroundQueue);'); } else { @@ -966,14 +1100,16 @@ 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) { indent.writeln( - 'ArrayList args = (ArrayList) message;'); + 'ArrayList args = (ArrayList) message;', + ); enumerate(method.parameters, (int index, NamedType arg) { final String argType = _javaTypeForDartType(arg.type); final String argName = _getSafeArgumentName(index, arg); @@ -1047,48 +1183,58 @@ $resultType $resultName = void _writeResultInterfaces(Indent indent) { indent.writeln( - '/** Asynchronous error handling return type for non-nullable API method returns. */'); + '/** Asynchronous error handling return type for non-nullable API method returns. */', + ); indent.write('public interface Result '); indent.addScoped('{', '}', () { - indent - .writeln('/** Success case callback method for handling returns. */'); + indent.writeln( + '/** Success case callback method for handling returns. */', + ); indent.writeln('void success(@NonNull T result);'); indent.newln(); - indent - .writeln('/** Failure case callback method for handling errors. */'); + indent.writeln( + '/** Failure case callback method for handling errors. */', + ); indent.writeln('void error(@NonNull Throwable error);'); }); indent.writeln( - '/** Asynchronous error handling return type for nullable API method returns. */'); + '/** Asynchronous error handling return type for nullable API method returns. */', + ); indent.write('public interface NullableResult '); indent.addScoped('{', '}', () { - indent - .writeln('/** Success case callback method for handling returns. */'); + indent.writeln( + '/** Success case callback method for handling returns. */', + ); indent.writeln('void success(@Nullable T result);'); indent.newln(); - indent - .writeln('/** Failure case callback method for handling errors. */'); + indent.writeln( + '/** Failure case callback method for handling errors. */', + ); indent.writeln('void error(@NonNull Throwable error);'); }); indent.writeln( - '/** Asynchronous error handling return type for void API method returns. */'); + '/** Asynchronous error handling return type for void API method returns. */', + ); indent.write('public interface VoidResult '); indent.addScoped('{', '}', () { - indent - .writeln('/** Success case callback method for handling returns. */'); + indent.writeln( + '/** Success case callback method for handling returns. */', + ); indent.writeln('void success();'); indent.newln(); - indent - .writeln('/** Failure case callback method for handling errors. */'); + indent.writeln( + '/** Failure case callback method for handling errors. */', + ); indent.writeln('void error(@NonNull Throwable error);'); }); } void _writeErrorClass(Indent indent) { indent.writeln( - '/** Error class for passing custom error details to Flutter via a thrown PlatformException. */'); + '/** Error class for passing custom error details to Flutter via a thrown PlatformException. */', + ); indent.write('public static class FlutterError extends RuntimeException '); indent.addScoped('{', '}', () { indent.newln(); @@ -1096,11 +1242,13 @@ $resultType $resultName = indent.writeln('public final String code;'); indent.newln(); indent.writeln( - '/** The error details. Must be a datatype supported by the api codec. */'); + '/** The error details. Must be a datatype supported by the api codec. */', + ); indent.writeln('public final Object details;'); indent.newln(); indent.writeln( - 'public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) '); + 'public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) ', + ); indent.writeScoped('{', '}', () { indent.writeln('super(message);'); indent.writeln('this.code = code;'); @@ -1132,18 +1280,24 @@ protected static ArrayList wrapError(@NonNull Throwable exception) { void _writeCreateConnectionError(Indent indent) { indent.writeln('@NonNull'); indent.writeScoped( - 'protected static FlutterError createConnectionError(@NonNull String channelName) {', - '}', () { - indent.writeln( - 'return new FlutterError("channel-error", "Unable to establish connection on channel: " + channelName + ".", "");'); - }); + 'protected static FlutterError createConnectionError(@NonNull String channelName) {', + '}', + () { + indent.writeln( + 'return new FlutterError("channel-error", "Unable to establish connection on channel: " + channelName + ".", "");', + ); + }, + ); } // We are emitting our own definition of [@CanIgnoreReturnValue] to support // clients who use CheckReturnValue, without having to force Pigeon clients // to take a new dependency on error_prone_annotations. void _writeCanIgnoreReturnValueAnnotation( - InternalJavaOptions opt, Root root, Indent indent) { + InternalJavaOptions opt, + Root root, + Indent indent, + ) { indent.newln(); indent.writeln('@Target(METHOD)'); indent.writeln('@Retention(CLASS)'); @@ -1279,7 +1433,9 @@ String _cast(String variable, {required String javaType}) { /// object. String _castObject(NamedType field, String varName) { final HostDatatype hostDatatype = getFieldHostDatatype( - field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x)); + field, + (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), + ); return _cast(varName, javaType: hostDatatype.datatype); } diff --git a/packages/pigeon/lib/src/kotlin/kotlin_generator.dart b/packages/pigeon/lib/src/kotlin/kotlin_generator.dart index bd2719d92d4..992b1b65971 100644 --- a/packages/pigeon/lib/src/kotlin/kotlin_generator.dart +++ b/packages/pigeon/lib/src/kotlin/kotlin_generator.dart @@ -23,10 +23,10 @@ const String _docCommentSuffix = ' */'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification( - _docCommentPrefix, - closeCommentToken: _docCommentSuffix, - blockContinuationToken: _docCommentContinuation, -); + _docCommentPrefix, + closeCommentToken: _docCommentSuffix, + blockContinuationToken: _docCommentContinuation, + ); const String _codecName = 'PigeonCodec'; @@ -115,13 +115,13 @@ class InternalKotlinOptions extends InternalOptions { KotlinOptions options, { required this.kotlinOut, Iterable? copyrightHeader, - }) : package = options.package, - copyrightHeader = options.copyrightHeader ?? copyrightHeader, - errorClassName = options.errorClassName, - includeErrorClass = options.includeErrorClass, - fileSpecificClassNameComponent = - options.fileSpecificClassNameComponent ?? - kotlinOut.split('/').lastOrNull?.split('.').first; + }) : package = options.package, + copyrightHeader = options.copyrightHeader ?? copyrightHeader, + errorClassName = options.errorClassName, + includeErrorClass = options.includeErrorClass, + fileSpecificClassNameComponent = + options.fileSpecificClassNameComponent ?? + kotlinOut.split('/').lastOrNull?.split('.').first; /// The package where the generated class will live. final String? package; @@ -227,12 +227,18 @@ class KotlinGenerator extends StructuredGenerator { }) { indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); + indent, + anEnum.documentationComments, + _docCommentSpec, + ); indent.write('enum class ${anEnum.name}(val raw: Int) '); indent.addScoped('{', '}', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( - indent, member.documentationComments, _docCommentSpec); + indent, + member.documentationComments, + _docCommentSpec, + ); final String nameScreamingSnakeCase = toScreamingSnakeCase(member.name); indent.write('$nameScreamingSnakeCase($index)'); if (index != anEnum.members.length - 1) { @@ -262,16 +268,20 @@ class KotlinGenerator extends StructuredGenerator { required String dartPackageName, }) { final List generatedMessages = [ - ' Generated class from Pigeon that represents data sent in messages.' + ' Generated class from Pigeon that represents data sent in messages.', ]; if (classDefinition.isSealed) { generatedMessages.add( - ' This class should not be extended by any user class outside of the generated file.'); + ' This class should not be extended by any user class outside of the generated file.', + ); } indent.newln(); addDocumentationComments( - indent, classDefinition.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + indent, + classDefinition.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); _writeDataClassSignature(indent, classDefinition); if (classDefinition.isSealed) { return; @@ -317,7 +327,8 @@ class KotlinGenerator extends StructuredGenerator { indent.writeln('return true'); }); indent.write( - 'return ${_getUtilsClassName(generatorOptions)}.deepEquals(toList(), other.toList())'); + 'return ${_getUtilsClassName(generatorOptions)}.deepEquals(toList(), other.toList())', + ); }); indent.newln(); @@ -331,16 +342,18 @@ 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; } indent.addScoped('(', ')$inheritance', () { - for (final NamedType element - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType element in getFieldsInSerializationOrder( + classDefinition, + )) { _writeClassField(indent, element); if (getFieldsInSerializationOrder(classDefinition).last != element) { indent.addln(','); @@ -363,8 +376,9 @@ class KotlinGenerator extends StructuredGenerator { indent.addScoped('{', '}', () { indent.write('return listOf'); indent.addScoped('(', ')', () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final String fieldName = field.name; indent.writeln('$fieldName,'); } @@ -384,20 +398,25 @@ class KotlinGenerator extends StructuredGenerator { indent.write('companion object '); indent.addScoped('{', '}', () { - indent - .write('fun fromList(${varNamePrefix}list: List): $className '); + indent.write( + 'fun fromList(${varNamePrefix}list: List): $className ', + ); indent.addScoped('{', '}', () { - enumerate(getFieldsInSerializationOrder(classDefinition), - (int index, final NamedType field) { + enumerate(getFieldsInSerializationOrder(classDefinition), ( + int index, + final NamedType field, + ) { final String listValue = '${varNamePrefix}list[$index]'; indent.writeln( - 'val ${field.name} = ${_cast(indent, listValue, type: field.type)}'); + 'val ${field.name} = ${_cast(indent, listValue, type: field.type)}', + ); }); indent.write('return $className('); - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final String comma = getFieldsInSerializationOrder(classDefinition).last == field ? '' @@ -411,9 +430,13 @@ class KotlinGenerator extends StructuredGenerator { void _writeClassField(Indent indent, NamedType field) { addDocumentationComments( - indent, field.documentationComments, _docCommentSpec); + indent, + field.documentationComments, + _docCommentSpec, + ); indent.write( - 'val ${field.name}: ${_nullSafeKotlinTypeForDartType(field.type)}'); + 'val ${field.name}: ${_nullSafeKotlinTypeForDartType(field.type)}', + ); final String defaultNil = field.type.isNullable ? ' = null' : ''; indent.add(defaultNil); } @@ -425,13 +448,19 @@ class KotlinGenerator extends StructuredGenerator { Indent indent, { required String dartPackageName, }) { - if (root.apis.any((Api api) => - api is AstHostApi && - api.methods.any((Method it) => it.isAsynchronous))) { + if (root.apis.any( + (Api api) => + api is AstHostApi && + api.methods.any((Method it) => it.isAsynchronous), + )) { indent.newln(); } - super.writeApis(generatorOptions, root, indent, - dartPackageName: dartPackageName); + super.writeApis( + generatorOptions, + root, + indent, + dartPackageName: dartPackageName, + ); } @override @@ -447,16 +476,19 @@ class KotlinGenerator extends StructuredGenerator { void writeEncodeLogic(EnumeratedType customType) { final String encodeString = customType.type == CustomTypes.customClass ? 'toList()' : 'raw'; - final String valueString = customType.enumeration < maximumCodecFieldKey - ? 'value.$encodeString' - : 'wrap.toList()'; - final int enumeration = customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; + 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( - 'val wrap = ${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName(type = ${customType.enumeration - maximumCodecFieldKey}, wrapped = value.$encodeString)'); + 'val wrap = ${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName(type = ${customType.enumeration - maximumCodecFieldKey}, wrapped = value.$encodeString)', + ); } indent.writeln('stream.write($enumeration)'); indent.writeln('writeValue(stream, $valueString)'); @@ -481,9 +513,10 @@ class KotlinGenerator extends StructuredGenerator { } final EnumeratedType overflowClass = EnumeratedType( - '${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName', - maximumCodecFieldKey, - CustomTypes.customClass); + '${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName', + maximumCodecFieldKey, + CustomTypes.customClass, + ); if (root.requiresOverflowClass) { _writeCodecOverflowUtilities( @@ -496,10 +529,12 @@ class KotlinGenerator extends StructuredGenerator { } indent.write( - 'private open class ${generatorOptions.fileSpecificClassNameComponent}$_codecName : StandardMessageCodec() '); + 'private open class ${generatorOptions.fileSpecificClassNameComponent}$_codecName : StandardMessageCodec() ', + ); indent.addScoped('{', '}', () { indent.write( - 'override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? '); + 'override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? ', + ); indent.addScoped('{', '}', () { indent.write('return '); if (root.classes.isNotEmpty || root.enums.isNotEmpty) { @@ -521,7 +556,8 @@ class KotlinGenerator extends StructuredGenerator { }); indent.write( - 'override fun writeValue(stream: ByteArrayOutputStream, value: Any?) '); + 'override fun writeValue(stream: ByteArrayOutputStream, value: Any?) ', + ); indent.writeScoped('{', '}', () { if (root.classes.isNotEmpty || root.enums.isNotEmpty) { indent.write('when (value) '); @@ -537,7 +573,8 @@ class KotlinGenerator extends StructuredGenerator { indent.newln(); if (root.containsEventChannel) { indent.writeln( - 'val ${generatorOptions.fileSpecificClassNameComponent}$_pigeonMethodChannelCodec = StandardMethodCodec(${generatorOptions.fileSpecificClassNameComponent}$_codecName())'); + 'val ${generatorOptions.fileSpecificClassNameComponent}$_pigeonMethodChannelCodec = StandardMethodCodec(${generatorOptions.fileSpecificClassNameComponent}$_codecName())', + ); indent.newln(); } } @@ -550,19 +587,22 @@ class KotlinGenerator extends StructuredGenerator { required String dartPackageName, }) { final NamedType overflowInt = NamedType( - name: 'type', - type: const TypeDeclaration(baseName: 'int', isNullable: false)); + name: 'type', + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ); final NamedType overflowObject = NamedType( - name: 'wrapped', - type: const TypeDeclaration(baseName: 'Object', isNullable: true)); + name: 'wrapped', + type: const TypeDeclaration(baseName: 'Object', isNullable: true), + ); final List overflowFields = [ overflowInt, overflowObject, ]; final Class overflowClass = Class( - name: - '${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName', - fields: overflowFields); + name: + '${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName', + fields: overflowFields, + ); _writeDataClassSignature(indent, overflowClass, private: true); indent.addScoped(' {', '}', () { @@ -597,10 +637,12 @@ if (wrapped == null) { indent.writeScoped('${i - totalCustomCodecKeysAllowed} ->', '', () { if (types[i].type == CustomTypes.customClass) { indent.writeln( - 'return ${types[i].name}.fromList(wrapped as List)'); + 'return ${types[i].name}.fromList(wrapped as List)', + ); } else if (types[i].type == CustomTypes.customEnum) { indent.writeln( - 'return ${types[i].name}.ofRaw((wrapped as Long).toInt())'); + 'return ${types[i].name}.ofRaw((wrapped as Long).toInt())', + ); } }); } @@ -624,14 +666,19 @@ if (wrapped == null) { required String dartPackageName, }) { const List generatedMessages = [ - ' Generated class from Pigeon that represents Flutter messages that can be called from Kotlin.' + ' Generated class from Pigeon that represents Flutter messages that can be called from Kotlin.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); final String apiName = api.name; indent.write( - 'class $apiName(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "") '); + 'class $apiName(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "") ', + ); indent.addScoped('{', '}', () { indent.write('companion object '); indent.addScoped('{', '}', () { @@ -639,7 +686,8 @@ if (wrapped == null) { indent.write('val codec: MessageCodec by lazy '); indent.addScoped('{', '}', () { indent.writeln( - '${generatorOptions.fileSpecificClassNameComponent}$_codecName()'); + '${generatorOptions.fileSpecificClassNameComponent}$_codecName()', + ); }); }); @@ -698,10 +746,14 @@ if (wrapped == null) { final String apiName = api.name; const List generatedMessages = [ - ' Generated interface from Pigeon that represents a handler of messages from Flutter.' + ' Generated interface from Pigeon that represents a handler of messages from Flutter.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedMessages); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedMessages, + ); indent.write('interface $apiName '); indent.addScoped('{', '}', () { @@ -723,22 +775,29 @@ if (wrapped == null) { indent.write('val codec: MessageCodec by lazy '); indent.addScoped('{', '}', () { indent.writeln( - '${generatorOptions.fileSpecificClassNameComponent}$_codecName()'); + '${generatorOptions.fileSpecificClassNameComponent}$_codecName()', + ); }); indent.writeln( - '/** Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`. */'); + '/** Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`. */', + ); indent.writeln('@JvmOverloads'); indent.write( - 'fun setUp(binaryMessenger: BinaryMessenger, api: $apiName?, messageChannelSuffix: String = "") '); + 'fun setUp(binaryMessenger: BinaryMessenger, api: $apiName?, messageChannelSuffix: String = "") ', + ); indent.addScoped('{', '}', () { indent.writeln( - r'val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else ""'); + r'val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else ""', + ); String? serialBackgroundQueue; - if (api.methods.any((Method m) => - m.taskQueueType == TaskQueueType.serialBackgroundThread)) { + if (api.methods.any( + (Method m) => + m.taskQueueType == TaskQueueType.serialBackgroundThread, + )) { serialBackgroundQueue = 'taskQueue'; indent.writeln( - 'val $serialBackgroundQueue = binaryMessenger.makeBackgroundTaskQueue()'); + 'val $serialBackgroundQueue = binaryMessenger.makeBackgroundTaskQueue()', + ); } for (final Method method in api.methods) { _writeHostMethodMessageHandler( @@ -783,42 +842,28 @@ if (wrapped == null) { final String instanceManagerApiName = '${kotlinInstanceManagerClassName(generatorOptions)}Api'; - addDocumentationComments( - indent, - [ - ' Generated API for managing the Dart and native `InstanceManager`s.', - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Generated API for managing the Dart and native `InstanceManager`s.', + ], _docCommentSpec); indent.writeScoped( 'private class $instanceManagerApiName(val binaryMessenger: BinaryMessenger) {', '}', () { indent.writeScoped('companion object {', '}', () { - addDocumentationComments( - indent, - [' The codec used by $instanceManagerApiName.'], - _docCommentSpec, - ); - indent.writeScoped( - 'val codec: MessageCodec by lazy {', - '}', - () { - indent.writeln( - '${generatorOptions.fileSpecificClassNameComponent}$_codecName()', - ); - }, - ); + addDocumentationComments(indent, [ + ' The codec used by $instanceManagerApiName.', + ], _docCommentSpec); + indent.writeScoped('val codec: MessageCodec by lazy {', '}', () { + indent.writeln( + '${generatorOptions.fileSpecificClassNameComponent}$_codecName()', + ); + }); indent.newln(); - addDocumentationComments( - indent, - [ - ' Sets up an instance of `$instanceManagerApiName` to handle messages from the', - ' `binaryMessenger`.', - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Sets up an instance of `$instanceManagerApiName` to handle messages from the', + ' `binaryMessenger`.', + ], _docCommentSpec); indent.writeScoped( 'fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, instanceManager: ${kotlinInstanceManagerClassName(generatorOptions)}?) {', '}', @@ -828,8 +873,9 @@ if (wrapped == null) { indent, generatorOptions: generatorOptions, name: 'removeStrongReference', - channelName: - makeRemoveStrongReferenceChannelName(dartPackageName), + channelName: makeRemoveStrongReferenceChannelName( + dartPackageName, + ), taskQueueType: TaskQueueType.serial, parameters: [ Parameter( @@ -878,7 +924,7 @@ if (wrapped == null) { Parameter( name: 'identifier', type: const TypeDeclaration(baseName: 'int', isNullable: false), - ) + ), ], returnType: const TypeDeclaration.voidDeclaration(), channelName: makeRemoveStrongReferenceChannelName(dartPackageName), @@ -917,26 +963,24 @@ if (wrapped == null) { // class SomeClass { // Shape giveMeAShape() => Circle(); // } - final List sortedApis = topologicalSort( - allProxyApis, - (AstProxyApi api) { - return [ - if (api.superClass?.associatedProxyApi != null) - api.superClass!.associatedProxyApi!, - ...api.interfaces.map( - (TypeDeclaration interface) => interface.associatedProxyApi!, - ), - ]; - }, - ); + final List sortedApis = topologicalSort(allProxyApis, ( + AstProxyApi api, + ) { + return [ + if (api.superClass?.associatedProxyApi != null) + api.superClass!.associatedProxyApi!, + ...api.interfaces.map( + (TypeDeclaration interface) => interface.associatedProxyApi!, + ), + ]; + }); indent.writeScoped( 'private class ${proxyApiCodecName(generatorOptions)}(val registrar: ${proxyApiRegistrarName(generatorOptions)}) : ' '${generatorOptions.fileSpecificClassNameComponent}$_codecName() {', '}', () { - indent.format( - ''' + indent.format(''' override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { $proxyApiCodecInstanceManagerKey.toByte() -> { @@ -952,8 +996,7 @@ if (wrapped == null) { } else -> super.readValueOfType(type, buffer) } - }''', - ); + }'''); indent.newln(); indent.writeScoped( @@ -977,7 +1020,8 @@ if (wrapped == null) { ]; final String isSupportedExpression = nonProxyApiTypes .map((String kotlinType) => 'value is $kotlinType') - .followedBy(['value == null']).join(' || '); + .followedBy(['value == null']) + .join(' || '); // Non ProxyApi types are checked first to handle the scenario // where a client wraps the `Object` class which all the // classes above extend. @@ -987,37 +1031,31 @@ if (wrapped == null) { }); indent.newln(); - enumerate( - sortedApis, - (int index, AstProxyApi api) { - final String className = - api.kotlinOptions?.fullClassName ?? api.name; + enumerate(sortedApis, (int index, AstProxyApi api) { + final String className = + api.kotlinOptions?.fullClassName ?? api.name; - final int? minApi = api.kotlinOptions?.minAndroidApi; - final String versionCheck = minApi != null - ? 'android.os.Build.VERSION.SDK_INT >= $minApi && ' - : ''; + final int? minApi = api.kotlinOptions?.minAndroidApi; + final String versionCheck = + minApi != null + ? 'android.os.Build.VERSION.SDK_INT >= $minApi && ' + : ''; - indent.format( - ''' + indent.format(''' ${index > 0 ? ' else ' : ''}if (${versionCheck}value is $className) { registrar.get$hostProxyApiPrefix${api.name}().${classMemberNamePrefix}newInstance(value) { } - }''', - ); - }, - ); + }'''); + }); indent.newln(); - indent.format( - ''' + indent.format(''' when { registrar.instanceManager.containsInstance(value) -> { stream.write($proxyApiCodecInstanceManagerKey) writeValue(stream, registrar.instanceManager.getIdentifierForStrongReference(value)) } else -> throw IllegalArgumentException("Unsupported value: '\$value' of type '\${value.javaClass.name}'") - }''', - ); + }'''); }, ); }, @@ -1172,7 +1210,10 @@ if (wrapped == null) { '''); } addDocumentationComments( - indent, api.documentationComments, _docCommentSpec); + indent, + api.documentationComments, + _docCommentSpec, + ); for (final Method func in api.methods) { indent.format(''' abstract class ${toUpperCamelCase(func.name)}StreamHandler : ${generatorOptions.fileSpecificClassNameComponent}PigeonEventChannelWrapper<${_kotlinTypeForDartType(func.returnType)}> { @@ -1204,7 +1245,8 @@ if (wrapped == null) { indent.write('fun wrapError(exception: Throwable): List '); indent.addScoped('{', '}', () { indent.write( - 'return if (exception is ${_getErrorClassName(generatorOptions)}) '); + 'return if (exception is ${_getErrorClassName(generatorOptions)}) ', + ); indent.addScoped('{', '}', () { indent.writeScoped('listOf(', ')', () { indent.writeln('exception.code,'); @@ -1217,7 +1259,8 @@ if (wrapped == null) { indent.writeln('exception.javaClass.simpleName,'); indent.writeln('exception.toString(),'); indent.writeln( - '"Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception)'); + '"Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception)', + ); }); }); }); @@ -1227,11 +1270,13 @@ if (wrapped == null) { indent.newln(); indent.writeln('/**'); indent.writeln( - ' * Error class for passing custom error details to Flutter via a thrown PlatformException.'); + ' * Error class for passing custom error details to Flutter via a thrown PlatformException.', + ); indent.writeln(' * @property code The error code.'); indent.writeln(' * @property message The error message.'); indent.writeln( - ' * @property details The error details. Must be a datatype supported by the api codec.'); + ' * @property details The error details. Must be a datatype supported by the api codec.', + ); indent.writeln(' */'); indent.write('class ${_getErrorClassName(generatorOptions)} '); indent.addScoped('(', ')', () { @@ -1243,14 +1288,18 @@ if (wrapped == null) { } void _writeCreateConnectionError( - InternalKotlinOptions generatorOptions, Indent indent) { + InternalKotlinOptions generatorOptions, + Indent indent, + ) { final String errorClassName = _getErrorClassName(generatorOptions); indent.newln(); indent.write( - 'fun createConnectionError(channelName: String): $errorClassName '); + 'fun createConnectionError(channelName: String): $errorClassName ', + ); indent.addScoped('{', '}', () { indent.write( - 'return $errorClassName("channel-error", "Unable to establish connection on channel: \'\$channelName\'.", "")'); + 'return $errorClassName("channel-error", "Unable to establish connection on channel: \'\$channelName\'.", "")', + ); }); } @@ -1332,17 +1381,14 @@ fun deepEquals(a: Any?, b: Any?): Boolean { }) { final List argSignature = []; if (parameters.isNotEmpty) { - final Iterable argTypes = parameters - .map((NamedType e) => _nullSafeKotlinTypeForDartType(e.type)); + final Iterable argTypes = parameters.map( + (NamedType e) => _nullSafeKotlinTypeForDartType(e.type), + ); final Iterable argNames = indexMap(parameters, getArgumentName); argSignature.addAll( - map2( - argTypes, - argNames, - (String argType, String argName) { - return '$argName: $argType'; - }, - ), + map2(argTypes, argNames, (String argType, String argName) { + return '$argName: $argType'; + }), ); } @@ -1389,7 +1435,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { bool isAsynchronous = false, String? serialBackgroundQueue, String Function(List safeArgNames, {required String apiVarName})? - onCreateCall, + onCreateCall, }) { indent.write('run '); indent.addScoped('{', '}', () { @@ -1416,33 +1462,39 @@ fun deepEquals(a: Any?, b: Any?): Boolean { final String argName = _getSafeArgumentName(index, arg); final String argIndex = 'args[$index]'; indent.writeln( - 'val $argName = ${_castForceUnwrap(argIndex, arg.type, indent)}'); + 'val $argName = ${_castForceUnwrap(argIndex, arg.type, indent)}', + ); 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()'); indent.writeScoped('if (error != null) {', '}', () { indent.writeln( - 'reply.reply(${_getUtilsClassName(generatorOptions)}.wrapError(error))'); + 'reply.reply(${_getUtilsClassName(generatorOptions)}.wrapError(error))', + ); }, addTrailingNewline: false); indent.addScoped(' else {', '}', () { if (returnType.isVoid) { indent.writeln( - 'reply.reply(${_getUtilsClassName(generatorOptions)}.wrapResult(null))'); + 'reply.reply(${_getUtilsClassName(generatorOptions)}.wrapResult(null))', + ); } else { indent.writeln('val data = result.getOrNull()'); indent.writeln( - 'reply.reply(${_getUtilsClassName(generatorOptions)}.wrapResult(data))'); + 'reply.reply(${_getUtilsClassName(generatorOptions)}.wrapResult(data))', + ); } }); }); @@ -1458,7 +1510,8 @@ fun deepEquals(a: Any?, b: Any?): Boolean { indent.add(' catch (exception: Throwable) '); indent.addScoped('{', '}', () { indent.writeln( - '${_getUtilsClassName(generatorOptions)}.wrapError(exception)'); + '${_getUtilsClassName(generatorOptions)}.wrapError(exception)', + ); }); indent.writeln('reply.reply(wrapped)'); } @@ -1481,13 +1534,15 @@ fun deepEquals(a: Any?, b: Any?): Boolean { List documentationComments = const [], int? minApiRequirement, void Function( - Indent indent, { - required InternalKotlinOptions generatorOptions, - required List parameters, - required TypeDeclaration returnType, - required String channelName, - required String errorClassName, - }) onWriteBody = _writeFlutterMethodMessageCall, + Indent indent, { + required InternalKotlinOptions generatorOptions, + required List parameters, + required TypeDeclaration returnType, + required String channelName, + required String errorClassName, + }) + onWriteBody = + _writeFlutterMethodMessageCall, }) { _writeMethodDeclaration( indent, @@ -1527,26 +1582,30 @@ fun deepEquals(a: Any?, b: Any?): Boolean { sendArgument = 'null'; } else { final Iterable enumSafeArgNames = indexMap( - parameters, - (int count, NamedType type) => - _getEnumSafeArgumentExpression(count, type)); + parameters, + (int count, NamedType type) => + _getEnumSafeArgumentExpression(count, type), + ); sendArgument = 'listOf(${enumSafeArgNames.join(', ')})'; } const String channel = 'channel'; indent.writeln('val channelName = "$channelName"'); indent.writeln( - 'val $channel = BasicMessageChannel(binaryMessenger, channelName, codec)'); + 'val $channel = BasicMessageChannel(binaryMessenger, channelName, codec)', + ); indent.writeScoped('$channel.send($sendArgument) {', '}', () { indent.writeScoped('if (it is List<*>) {', '} ', () { indent.writeScoped('if (it.size > 1) {', '} ', () { indent.writeln( - 'callback(Result.failure($errorClassName(it[0] as String, it[1] as String, it[2] as String?)))'); + 'callback(Result.failure($errorClassName(it[0] as String, it[1] as String, it[2] as String?)))', + ); }, addTrailingNewline: false); if (!returnType.isNullable && !returnType.isVoid) { indent.addScoped('else if (it[0] == null) {', '} ', () { indent.writeln( - 'callback(Result.failure($errorClassName("null-error", "Flutter api returned null value for non-null return value.", "")))'); + 'callback(Result.failure($errorClassName("null-error", "Flutter api returned null value for non-null return value.", "")))', + ); }, addTrailingNewline: false); } indent.addScoped('else {', '}', () { @@ -1554,7 +1613,8 @@ fun deepEquals(a: Any?, b: Any?): Boolean { indent.writeln('callback(Result.success(Unit))'); } else { indent.writeln( - 'val output = ${_cast(indent, 'it[0]', type: returnType)}'); + 'val output = ${_cast(indent, 'it[0]', type: returnType)}', + ); indent.writeln('callback(Result.success(output))'); } @@ -1562,7 +1622,8 @@ fun deepEquals(a: Any?, b: Any?): Boolean { }, addTrailingNewline: false); indent.addScoped('else {', '} ', () { indent.writeln( - 'callback(Result.failure(${_getUtilsClassName(generatorOptions)}.createConnectionError(channelName)))'); + 'callback(Result.failure(${_getUtilsClassName(generatorOptions)}.createConnectionError(channelName)))', + ); }); }); } @@ -1578,26 +1639,19 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ); final String instanceManagerApiName = '${instanceManagerName}Api'; - addDocumentationComments( - indent, - [ - ' Provides implementations for each ProxyApi implementation and provides access to resources', - ' needed by any implementation.', - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Provides implementations for each ProxyApi implementation and provides access to resources', + ' needed by any implementation.', + ], _docCommentSpec); indent.writeScoped( 'abstract class $registrarName(val binaryMessenger: BinaryMessenger) {', '}', () { - addDocumentationComments( - indent, - [' Whether APIs should ignore calling to Dart.'], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Whether APIs should ignore calling to Dart.', + ], _docCommentSpec); indent.writeln('public var ignoreCallsToDart = false'); - indent.format( - ''' + indent.format(''' val instanceManager: $instanceManagerName private var _codec: MessageCodec? = null val codec: MessageCodec @@ -1624,8 +1678,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { } } ) - }''', - ); + }'''); for (final AstProxyApi api in allProxyApis) { _writeMethodDeclaration( indent, @@ -1636,7 +1689,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { !api.hasAnyHostMessageCalls() && api.unattachedFields.isEmpty, documentationComments: [ ' An implementation of [$hostProxyApiPrefix${api.name}] used to add a new Dart instance of', - ' `${api.name}` to the Dart `InstanceManager`.' + ' `${api.name}` to the Dart `InstanceManager`.', ], returnType: TypeDeclaration( baseName: '$hostProxyApiPrefix${api.name}', @@ -1660,7 +1713,8 @@ fun deepEquals(a: Any?, b: Any?): Boolean { '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger, instanceManager)', ); for (final AstProxyApi api in allProxyApis) { - final bool hasHostMessageCalls = api.constructors.isNotEmpty || + final bool hasHostMessageCalls = + api.constructors.isNotEmpty || api.attachedFields.isNotEmpty || api.hostMethods.isNotEmpty; if (hasHostMessageCalls) { @@ -1697,23 +1751,25 @@ 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) { return Parameter(name: field.name, type: field.type); }), - ...constructor.parameters + ...constructor.parameters, ], ); indent.newln(); @@ -1733,10 +1789,11 @@ 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( @@ -1762,10 +1819,11 @@ 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', @@ -1792,13 +1850,12 @@ 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( @@ -1847,11 +1904,14 @@ fun deepEquals(a: Any?, b: Any?): Boolean { addTrailingNewline: false, ); indent.writeScoped(' else {', '}', () { - final String className = typeWithRequirement - .type.associatedProxyApi!.kotlinOptions?.fullClassName ?? + final String className = + typeWithRequirement + .type + .associatedProxyApi! + .kotlinOptions + ?.fullClassName ?? typeWithRequirement.type.baseName; - indent.format( - ''' + indent.format(''' val channel = BasicMessageChannel( binaryMessenger, "$channelName", @@ -1865,8 +1925,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { } } else { channel.setMessageHandler(null) - }''', - ); + }'''); }); } else { onWrite(); @@ -1874,9 +1933,10 @@ 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, @@ -1913,10 +1973,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ), ), ...api.unattachedFields.map((ApiField field) { - return Parameter( - name: field.name, - type: field.type, - ); + return Parameter(name: field.name, type: field.type); }), ...constructor.parameters, ], @@ -1971,8 +2028,11 @@ fun deepEquals(a: Any?, b: Any?): Boolean { } for (final Method method in api.hostMethods) { - final String channelName = - makeChannelName(api, method, dartPackageName); + final String channelName = makeChannelName( + api, + method, + dartPackageName, + ); writeWithApiCheckIfNecessary( [ if (!method.isStatic) apiAsTypeDeclaration, @@ -2032,10 +2092,11 @@ 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( @@ -2055,19 +2116,14 @@ fun deepEquals(a: Any?, b: Any?): Boolean { required String channelName, required String errorClassName, }) { - indent.writeScoped( - 'if (pigeonRegistrar.ignoreCallsToDart) {', - '}', - () { - indent.format( - ''' + indent.writeScoped('if (pigeonRegistrar.ignoreCallsToDart) {', '}', () { + indent.format( + ''' callback( Result.failure( $errorClassName("ignore-calls-error", "Calls to Dart are being ignored.", "")))''', - ); - }, - addTrailingNewline: false, - ); + ); + }, addTrailingNewline: false); indent.writeScoped( ' else if (pigeonRegistrar.instanceManager.containsInstance(${classMemberNamePrefix}instanceArg)) {', '}', @@ -2089,7 +2145,8 @@ fun deepEquals(a: Any?, b: Any?): Boolean { }); indent.writeln( - 'val binaryMessenger = pigeonRegistrar.binaryMessenger'); + 'val binaryMessenger = pigeonRegistrar.binaryMessenger', + ); indent.writeln('val codec = pigeonRegistrar.codec'); _writeFlutterMethodMessageCall( indent, @@ -2105,11 +2162,9 @@ fun deepEquals(a: Any?, b: Any?): Boolean { isNullable: false, ), ), - ...api.unattachedFields.map( - (ApiField field) { - return Parameter(name: field.name, type: field.type); - }, - ), + ...api.unattachedFields.map((ApiField field) { + return Parameter(name: field.name, type: field.type); + }), ], ); } else { @@ -2143,11 +2198,12 @@ 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', @@ -2171,17 +2227,16 @@ fun deepEquals(a: Any?, b: Any?): Boolean { 'if (pigeonRegistrar.ignoreCallsToDart) {', '}', () { - indent.format( - ''' + indent.format(''' callback( Result.failure( $errorClassName("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return''', - ); + return'''); }, ); - indent - .writeln('val binaryMessenger = pigeonRegistrar.binaryMessenger'); + indent.writeln( + 'val binaryMessenger = pigeonRegistrar.binaryMessenger', + ); indent.writeln('val codec = pigeonRegistrar.codec'); _writeFlutterMethodMessageCall( indent, diff --git a/packages/pigeon/lib/src/objc/objc_generator.dart b/packages/pigeon/lib/src/objc/objc_generator.dart index 1755bc29d48..3cce6cadeaa 100644 --- a/packages/pigeon/lib/src/objc/objc_generator.dart +++ b/packages/pigeon/lib/src/objc/objc_generator.dart @@ -20,20 +20,27 @@ const DocumentCommentSpecification _docCommentSpec = const String _overflowClassName = '${classNamePrefix}CodecOverflow'; final NamedType _overflowInt = NamedType( - name: 'type', - type: const TypeDeclaration(baseName: 'int', isNullable: false)); + name: 'type', + type: const TypeDeclaration(baseName: 'int', isNullable: false), +); final NamedType _overflowObject = NamedType( - name: 'wrapped', - type: const TypeDeclaration(baseName: 'Object', isNullable: true)); + name: 'wrapped', + type: const TypeDeclaration(baseName: 'Object', isNullable: true), +); final List _overflowFields = [ _overflowInt, _overflowObject, ]; -final Class _overflowClass = - Class(name: _overflowClassName, fields: _overflowFields); +final Class _overflowClass = Class( + name: _overflowClassName, + fields: _overflowFields, +); final EnumeratedType _enumeratedOverflow = EnumeratedType( - _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass, - associatedClass: _overflowClass); + _overflowClassName, + maximumCodecFieldKey, + CustomTypes.customClass, + associatedClass: _overflowClass, +); /// Options that control how Objective-C code will be generated. class ObjcOptions { @@ -111,13 +118,13 @@ class InternalObjcOptions extends InternalOptions { required this.objcSourceOut, String? fileSpecificClassNameComponent, Iterable? copyrightHeader, - }) : headerIncludePath = - options.headerIncludePath ?? path.basename(objcHeaderOut), - prefix = options.prefix, - copyrightHeader = options.copyrightHeader ?? copyrightHeader, - fileSpecificClassNameComponent = - options.fileSpecificClassNameComponent ?? - fileSpecificClassNameComponent; + }) : headerIncludePath = + options.headerIncludePath ?? path.basename(objcHeaderOut), + prefix = options.prefix, + copyrightHeader = options.copyrightHeader ?? copyrightHeader, + fileSpecificClassNameComponent = + options.fileSpecificClassNameComponent ?? + fileSpecificClassNameComponent; /// The path to the header that will get placed in the source file (example: /// "foo.h"). @@ -216,20 +223,29 @@ class ObjcHeaderGenerator extends StructuredGenerator { Enum anEnum, { required String dartPackageName, }) { - final String enumName = - _enumName(anEnum.name, prefix: generatorOptions.prefix); + final String enumName = _enumName( + anEnum.name, + prefix: generatorOptions.prefix, + ); indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); + indent, + anEnum.documentationComments, + _docCommentSpec, + ); indent.write('typedef NS_ENUM(NSUInteger, $enumName) '); indent.addScoped('{', '};', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( - indent, member.documentationComments, _docCommentSpec); + indent, + member.documentationComments, + _docCommentSpec, + ); // Capitalized first letter to ensure Swift compatibility indent.writeln( - '$enumName${member.name[0].toUpperCase()}${member.name.substring(1)} = $index,'); + '$enumName${member.name[0].toUpperCase()}${member.name.substring(1)} = $index,', + ); }); }); _writeEnumWrapper(indent, enumName); @@ -239,7 +255,8 @@ class ObjcHeaderGenerator extends StructuredGenerator { indent.newln(); indent.writeln('/// Wrapper for $enumName to allow for nullability.'); indent.writeln( - '@interface ${_enumName(enumName, prefix: '', box: true)} : NSObject'); + '@interface ${_enumName(enumName, prefix: '', box: true)} : NSObject', + ); indent.writeln('@property(nonatomic, assign) $enumName value;'); indent.writeln('- (instancetype)initWithValue:($enumName)value;'); indent.writeln('@end'); @@ -255,7 +272,8 @@ class ObjcHeaderGenerator extends StructuredGenerator { indent.newln(); for (final Class classDefinition in root.classes) { indent.writeln( - '@class ${_className(generatorOptions.prefix, classDefinition.name)};'); + '@class ${_className(generatorOptions.prefix, classDefinition.name)};', + ); } indent.newln(); super.writeDataClasses( @@ -274,12 +292,7 @@ class ObjcHeaderGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - _writeDataClassDeclaration( - generatorOptions, - root, - indent, - classDefinition, - ); + _writeDataClassDeclaration(generatorOptions, root, indent, classDefinition); } @override @@ -309,7 +322,8 @@ class ObjcHeaderGenerator extends StructuredGenerator { }) { indent.writeln('$_docCommentPrefix The codec used by all APIs.'); indent.writeln( - 'NSObject *${generatorOptions.prefix}Get${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}Codec(void);'); + 'NSObject *${generatorOptions.prefix}Get${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}Codec(void);', + ); } @override @@ -319,8 +333,12 @@ class ObjcHeaderGenerator extends StructuredGenerator { Indent indent, { required String dartPackageName, }) { - super.writeApis(generatorOptions, root, indent, - dartPackageName: dartPackageName); + super.writeApis( + generatorOptions, + root, + indent, + dartPackageName: dartPackageName, + ); indent.writeln('NS_ASSUME_NONNULL_END'); } @@ -335,31 +353,39 @@ class ObjcHeaderGenerator extends StructuredGenerator { indent.newln(); final String apiName = _className(generatorOptions.prefix, api.name); addDocumentationComments( - indent, api.documentationComments, _docCommentSpec); + indent, + api.documentationComments, + _docCommentSpec, + ); indent.writeln('@interface $apiName : NSObject'); indent.writeln( - '- (instancetype)initWithBinaryMessenger:(id)binaryMessenger;'); + '- (instancetype)initWithBinaryMessenger:(id)binaryMessenger;', + ); indent.writeln( - '- (instancetype)initWithBinaryMessenger:(id)binaryMessenger messageChannelSuffix:(nullable NSString *)messageChannelSuffix;'); + '- (instancetype)initWithBinaryMessenger:(id)binaryMessenger messageChannelSuffix:(nullable NSString *)messageChannelSuffix;', + ); for (final Method func in api.methods) { final _ObjcType returnType = _objcTypeForDartType( - generatorOptions.prefix, func.returnType, + generatorOptions.prefix, + func.returnType, // Nullability is required since the return must be nil if NSError is set. forceBox: true, ); - final String callbackType = - _callbackForType(func.returnType, returnType, generatorOptions); + final String callbackType = _callbackForType( + func.returnType, + returnType, + generatorOptions, + ); addDocumentationComments( - indent, func.documentationComments, _docCommentSpec); + indent, + func.documentationComments, + _docCommentSpec, + ); - indent.writeln('${_makeObjcSignature( - func: func, - options: generatorOptions, - returnType: 'void', - lastArgName: 'completion', - lastArgType: callbackType, - )};'); + indent.writeln( + '${_makeObjcSignature(func: func, options: generatorOptions, returnType: 'void', lastArgName: 'completion', lastArgType: callbackType)};', + ); } indent.writeln('@end'); indent.newln(); @@ -376,7 +402,10 @@ class ObjcHeaderGenerator extends StructuredGenerator { indent.newln(); final String apiName = _className(generatorOptions.prefix, api.name); addDocumentationComments( - indent, api.documentationComments, _docCommentSpec); + indent, + api.documentationComments, + _docCommentSpec, + ); indent.writeln('@protocol $apiName'); for (final Method func in api.methods) { @@ -427,8 +456,11 @@ class ObjcHeaderGenerator extends StructuredGenerator { generatorComments.add(' @return `nil` only when `error != nil`.'); } addDocumentationComments( - indent, func.documentationComments, _docCommentSpec, - generatorComments: generatorComments); + indent, + func.documentationComments, + _docCommentSpec, + generatorComments: generatorComments, + ); final String signature = _makeObjcSignature( func: func, @@ -442,10 +474,12 @@ class ObjcHeaderGenerator extends StructuredGenerator { indent.writeln('@end'); indent.newln(); indent.writeln( - 'extern void SetUp$apiName(id binaryMessenger, NSObject<$apiName> *_Nullable api);'); + 'extern void SetUp$apiName(id binaryMessenger, NSObject<$apiName> *_Nullable api);', + ); indent.newln(); indent.writeln( - 'extern void SetUp${apiName}WithSuffix(id binaryMessenger, NSObject<$apiName> *_Nullable api, NSString *messageChannelSuffix);'); + 'extern void SetUp${apiName}WithSuffix(id binaryMessenger, NSObject<$apiName> *_Nullable api, NSString *messageChannelSuffix);', + ); indent.newln(); } } @@ -500,22 +534,31 @@ class ObjcSourceGenerator extends StructuredGenerator { Enum anEnum, { required String dartPackageName, }) { - final String enumName = - _enumName(anEnum.name, prefix: generatorOptions.prefix); + final String enumName = _enumName( + anEnum.name, + prefix: generatorOptions.prefix, + ); indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); + indent, + anEnum.documentationComments, + _docCommentSpec, + ); indent.writeln( - '@implementation ${_enumName(enumName, prefix: '', box: true)}'); - indent.writeScoped('- (instancetype)initWithValue:($enumName)value {', '}', - () { - indent.writeln('self = [super init];'); - indent.writeScoped('if (self) {', '}', () { - indent.writeln('_value = value;'); - }); + '@implementation ${_enumName(enumName, prefix: '', box: true)}', + ); + indent.writeScoped( + '- (instancetype)initWithValue:($enumName)value {', + '}', + () { + indent.writeln('self = [super init];'); + indent.writeScoped('if (self) {', '}', () { + indent.writeln('_value = value;'); + }); - indent.writeln('return self;'); - }); + indent.writeln('return self;'); + }, + ); indent.writeln('@end'); } @@ -550,12 +593,19 @@ class ObjcSourceGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - final String className = - _className(generatorOptions.prefix, classDefinition.name); + final String className = _className( + generatorOptions.prefix, + classDefinition.name, + ); indent.writeln('@implementation $className'); _writeObjcSourceClassInitializer( - generatorOptions, root, indent, classDefinition, className); + generatorOptions, + root, + indent, + classDefinition, + className, + ); writeClassDecode( generatorOptions, root, @@ -601,17 +651,22 @@ class ObjcSourceGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - final String className = - _className(generatorOptions.prefix, classDefinition.name); + final String className = _className( + generatorOptions.prefix, + classDefinition.name, + ); indent.write('+ ($className *)fromList:(NSArray *)list '); indent.addScoped('{', '}', () { const String resultName = 'pigeonResult'; indent.writeln('$className *$resultName = [[$className alloc] init];'); - enumerate(getFieldsInSerializationOrder(classDefinition), - (int index, final NamedType field) { + enumerate(getFieldsInSerializationOrder(classDefinition), ( + int index, + final NamedType field, + ) { final String valueGetter = 'GetNullableObjectAtIndex(list, $index)'; - final String? primitiveExtractionMethod = - _nsnumberExtractionMethod(field.type); + final String? primitiveExtractionMethod = _nsnumberExtractionMethod( + field.type, + ); final String ivarValueExpression; if (field.type.isEnum && !field.type.isNullable) { final String varName = @@ -635,7 +690,8 @@ class ObjcSourceGenerator extends StructuredGenerator { }); indent.write( - '+ (nullable $className *)nullableFromList:(NSArray *)list '); + '+ (nullable $className *)nullableFromList:(NSArray *)list ', + ); indent.addScoped('{', '}', () { indent.writeln('return (list) ? [$className fromList:list] : nil;'); }); @@ -657,14 +713,16 @@ class ObjcSourceGenerator extends StructuredGenerator { ); indent.newln(); indent.writeln( - '@implementation ${_className(generatorOptions.prefix, _overflowClassName)}'); + '@implementation ${_className(generatorOptions.prefix, _overflowClassName)}', + ); _writeObjcSourceClassInitializer( - generatorOptions, - root, - indent, - _overflowClass, - _className(generatorOptions.prefix, _overflowClassName)); + generatorOptions, + root, + indent, + _overflowClass, + _className(generatorOptions.prefix, _overflowClassName), + ); writeClassEncode( generatorOptions, root, @@ -707,8 +765,11 @@ if (self.wrapped == nil) { } void _writeCodecDecode( - Indent indent, EnumeratedType customType, String? prefix, - {bool isOverflowClass = false}) { + Indent indent, + EnumeratedType customType, + String? prefix, { + bool isOverflowClass = false, + }) { String readValue = '[self readValue]'; if (isOverflowClass) { readValue = 'self.wrapped'; @@ -716,22 +777,28 @@ if (self.wrapped == nil) { if (customType.type == CustomTypes.customClass) { indent.addScoped('', null, () { indent.writeln( - 'return [${_className(prefix, customType.name)} fromList:$readValue];'); + 'return [${_className(prefix, customType.name)} fromList:$readValue];', + ); }, addTrailingNewline: false); } else if (customType.type == CustomTypes.customEnum) { indent.addScoped( - !isOverflowClass ? '{' : '', !isOverflowClass ? '}' : null, () { - String enumAsNumber = 'enumAsNumber'; - if (!isOverflowClass) { - indent.writeln('NSNumber *$enumAsNumber = $readValue;'); - indent.write('return $enumAsNumber == nil ? nil : '); - } else { - enumAsNumber = 'self.wrapped'; - indent.write('return '); - } - indent.addln( - '[[${_enumName(customType.name, prefix: prefix, box: true)} alloc] initWithValue:[$enumAsNumber integerValue]];'); - }, addTrailingNewline: !isOverflowClass); + !isOverflowClass ? '{' : '', + !isOverflowClass ? '}' : null, + () { + String enumAsNumber = 'enumAsNumber'; + if (!isOverflowClass) { + indent.writeln('NSNumber *$enumAsNumber = $readValue;'); + indent.write('return $enumAsNumber == nil ? nil : '); + } else { + enumAsNumber = 'self.wrapped'; + indent.write('return '); + } + indent.addln( + '[[${_enumName(customType.name, prefix: prefix, box: true)} alloc] initWithValue:[$enumAsNumber integerValue]];', + ); + }, + addTrailingNewline: !isOverflowClass, + ); } } @@ -754,8 +821,12 @@ if (self.wrapped == nil) { if (root.requiresOverflowClass) { _writeCodecOverflowUtilities( - generatorOptions, root, indent, enumeratedTypes, - dartPackageName: dartPackageName); + generatorOptions, + root, + indent, + enumeratedTypes, + dartPackageName: dartPackageName, + ); } indent.writeln('@interface $readerName : FlutterStandardReader'); @@ -768,7 +839,10 @@ if (self.wrapped == nil) { if (customType.enumeration < maximumCodecFieldKey) { indent.write('case ${customType.enumeration}: '); _writeCodecDecode( - indent, customType, generatorOptions.prefix ?? ''); + indent, + customType, + generatorOptions.prefix ?? '', + ); } } if (root.requiresOverflowClass) { @@ -794,31 +868,43 @@ 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 ', () { - if (customType.type == CustomTypes.customEnum) { - indent.writeln('$className *box = ($className *)value;'); - } - final int enumeration = 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];'); - } - indent.writeln('[self writeByte:$enumeration];'); - indent.writeln('[self writeValue:$valueString];'); - }, addTrailingNewline: false); + 'if ([value isKindOfClass:[$className class]]) {', + '} else ', + () { + if (customType.type == CustomTypes.customEnum) { + indent.writeln('$className *box = ($className *)value;'); + } + final int enumeration = + 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];', + ); + } + indent.writeln('[self writeByte:$enumeration];'); + indent.writeln('[self writeValue:$valueString];'); + }, + addTrailingNewline: false, + ); } indent.addScoped('{', '}', () { indent.writeln('[super writeValue:value];'); @@ -840,18 +926,22 @@ if (self.wrapped == nil) { indent.newln(); indent.write( - 'NSObject *${generatorOptions.prefix}Get${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}Codec(void) '); + 'NSObject *${generatorOptions.prefix}Get${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}Codec(void) ', + ); indent.addScoped('{', '}', () { - indent - .writeln('static FlutterStandardMessageCodec *sSharedObject = nil;'); + indent.writeln( + 'static FlutterStandardMessageCodec *sSharedObject = nil;', + ); indent.writeln('static dispatch_once_t sPred = 0;'); indent.write('dispatch_once(&sPred, ^'); indent.addScoped('{', '});', () { indent.writeln( - '$readerWriterName *readerWriter = [[$readerWriterName alloc] init];'); + '$readerWriterName *readerWriter = [[$readerWriterName alloc] init];', + ); indent.writeln( - 'sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];'); + 'sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];', + ); }); indent.writeln('return sSharedObject;'); @@ -899,19 +989,23 @@ if (self.wrapped == nil) { const String channelName = 'channel'; indent.write( - 'void SetUp$apiName(id binaryMessenger, NSObject<$apiName> *api) '); + 'void SetUp$apiName(id binaryMessenger, NSObject<$apiName> *api) ', + ); indent.addScoped('{', '}', () { indent.writeln('SetUp${apiName}WithSuffix(binaryMessenger, api, @"");'); }); indent.newln(); indent.write( - 'void SetUp${apiName}WithSuffix(id binaryMessenger, NSObject<$apiName> *api, NSString *messageChannelSuffix) '); + 'void SetUp${apiName}WithSuffix(id binaryMessenger, NSObject<$apiName> *api, NSString *messageChannelSuffix) ', + ); indent.addScoped('{', '}', () { indent.writeln( - 'messageChannelSuffix = messageChannelSuffix.length > 0 ? [NSString stringWithFormat: @".%@", messageChannelSuffix] : @"";'); + 'messageChannelSuffix = messageChannelSuffix.length > 0 ? [NSString stringWithFormat: @".%@", messageChannelSuffix] : @"";', + ); String? serialBackgroundQueue; - if (api.methods.any((Method m) => - m.taskQueueType == TaskQueueType.serialBackgroundThread)) { + if (api.methods.any( + (Method m) => m.taskQueueType == TaskQueueType.serialBackgroundThread, + )) { serialBackgroundQueue = 'taskQueue'; // See https://github.com/flutter/flutter/issues/162613 for why this // is an ifdef instead of just a respondsToSelector: check. @@ -924,7 +1018,10 @@ if (self.wrapped == nil) { } for (final Method func in api.methods) { addDocumentationComments( - indent, func.documentationComments, _docCommentSpec); + indent, + func.documentationComments, + _docCommentSpec, + ); indent.writeScoped('{', '}', () { _writeChannelAllocation( @@ -941,7 +1038,13 @@ if (self.wrapped == nil) { indent.write('if (api) '); indent.addScoped('{', '}', () { _writeChannelApiBinding( - generatorOptions, root, indent, apiName, func, channelName); + generatorOptions, + root, + indent, + apiName, + func, + channelName, + ); }, addTrailingNewline: false); indent.add(' else '); indent.addScoped('{', '}', () { @@ -1009,16 +1112,23 @@ static FlutterError *createConnectionError(NSString *channelName) { }'''); } - void _writeChannelApiBinding(InternalObjcOptions generatorOptions, Root root, - Indent indent, String apiName, Method func, String channel) { + void _writeChannelApiBinding( + InternalObjcOptions generatorOptions, + Root root, + Indent indent, + String apiName, + Method func, + String channel, + ) { void unpackArgs(String variable) { indent.writeln('NSArray *args = $variable;'); int count = 0; for (final NamedType arg in func.parameters) { final String argName = _getSafeArgName(count, arg); final String valueGetter = 'GetNullableObjectAtIndex(args, $count)'; - final String? primitiveExtractionMethod = - _nsnumberExtractionMethod(arg.type); + final String? primitiveExtractionMethod = _nsnumberExtractionMethod( + arg.type, + ); final _ObjcType objcArgType = _objcTypeForDartType( generatorOptions.prefix, arg.type, @@ -1054,22 +1164,29 @@ static FlutterError *createConnectionError(NSString *channelName) { } } - void writeAsyncBindings(Iterable selectorComponents, - String callSignature, _ObjcType returnType) { + void writeAsyncBindings( + Iterable selectorComponents, + String callSignature, + _ObjcType returnType, + ) { if (func.returnType.isVoid) { const String callback = 'callback(wrapResult(nil, error));'; if (func.parameters.isEmpty) { indent.writeScoped( - '[api ${selectorComponents.first}:^(FlutterError *_Nullable error) {', - '}];', () { - indent.writeln(callback); - }); + '[api ${selectorComponents.first}:^(FlutterError *_Nullable error) {', + '}];', + () { + indent.writeln(callback); + }, + ); } else { indent.writeScoped( - '[api $callSignature ${selectorComponents.last}:^(FlutterError *_Nullable error) {', - '}];', () { - indent.writeln(callback); - }); + '[api $callSignature ${selectorComponents.last}:^(FlutterError *_Nullable error) {', + '}];', + () { + indent.writeln(callback); + }, + ); } } else { const String callback = 'callback(wrapResult(output, error));'; @@ -1081,16 +1198,20 @@ static FlutterError *createConnectionError(NSString *channelName) { } if (func.parameters.isEmpty) { indent.writeScoped( - '[api ${selectorComponents.first}:^($returnTypeString, FlutterError *_Nullable error) {', - '}];', () { - indent.writeln(callback); - }); + '[api ${selectorComponents.first}:^($returnTypeString, FlutterError *_Nullable error) {', + '}];', + () { + indent.writeln(callback); + }, + ); } else { indent.writeScoped( - '[api $callSignature ${selectorComponents.last}:^($returnTypeString, FlutterError *_Nullable error) {', - '}];', () { - indent.writeln(callback); - }); + '[api $callSignature ${selectorComponents.last}:^($returnTypeString, FlutterError *_Nullable error) {', + '}];', + () { + indent.writeln(callback); + }, + ); } } } @@ -1103,7 +1224,8 @@ static FlutterError *createConnectionError(NSString *channelName) { } else { if (func.returnType.isEnum) { indent.writeln( - '${_enumName(func.returnType.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)} output = $call;'); + '${_enumName(func.returnType.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)} output = $call;', + ); } else { indent.writeln('${returnType.beforeString}output = $call;'); } @@ -1116,33 +1238,43 @@ static FlutterError *createConnectionError(NSString *channelName) { 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);'); + 'NSCAssert([api respondsToSelector:@selector($selector)], @"$apiName api (%@) doesn\'t respond to @selector($selector)", api);', + ); indent.write( - '[$channel setMessageHandler:^(id _Nullable message, FlutterReply callback) '); + '[$channel setMessageHandler:^(id _Nullable message, FlutterReply callback) ', + ); indent.addScoped('{', '}];', () { final _ObjcType returnType = _objcTypeForDartType( - generatorOptions.prefix, func.returnType, + generatorOptions.prefix, + func.returnType, // Nullability is required since the return must be nil if NSError is set. forceBox: true, ); - final Iterable selectorComponents = - _getSelectorComponents(func, lastSelectorComponent); - final Iterable argNames = - indexMap(func.parameters, _getSafeArgName); - final String callSignature = - map2(selectorComponents.take(argNames.length), argNames, - (String selectorComponent, String argName) { - return '$selectorComponent:$argName'; - }).join(' '); + final Iterable selectorComponents = _getSelectorComponents( + func, + lastSelectorComponent, + ); + final Iterable argNames = indexMap( + func.parameters, + _getSafeArgName, + ); + final String callSignature = map2( + selectorComponents.take(argNames.length), + argNames, + (String selectorComponent, String argName) { + return '$selectorComponent:$argName'; + }, + ).join(' '); if (func.parameters.isNotEmpty) { unpackArgs('message'); } 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); } }); @@ -1162,11 +1294,13 @@ static FlutterError *createConnectionError(NSString *channelName) { indent.writeln('[[FlutterBasicMessageChannel alloc]'); indent.nest(1, () { indent.writeln( - 'initWithName:[NSString stringWithFormat:@"%@%@", @"${makeChannelName(api, func, dartPackageName)}", messageChannelSuffix]'); + 'initWithName:[NSString stringWithFormat:@"%@%@", @"${makeChannelName(api, func, dartPackageName)}", messageChannelSuffix]', + ); indent.writeln('binaryMessenger:binaryMessenger'); indent.write('codec:'); indent.add( - '${generatorOptions.prefix}Get${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}Codec()'); + '${generatorOptions.prefix}Get${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}Codec()', + ); if (taskQueue != null) { indent.newln(); @@ -1193,16 +1327,20 @@ taskQueue:$taskQueue String? returnType, bool isOverflowClass = false, }) { - final String className = - _className(languageOptions.prefix, classDefinition.name); + final String className = _className( + languageOptions.prefix, + classDefinition.name, + ); returnType = returnType ?? className; indent.newln(); indent.writeln('@interface $className ()'); indent.writeln( - '+ ($returnType${isOverflowClass ? '' : ' *'})fromList:(NSArray *)list;'); + '+ ($returnType${isOverflowClass ? '' : ' *'})fromList:(NSArray *)list;', + ); if (!isOverflowClass) { indent.writeln( - '+ (nullable $returnType *)nullableFromList:(NSArray *)list;'); + '+ (nullable $returnType *)nullableFromList:(NSArray *)list;', + ); } indent.writeln('- (NSArray *)toList;'); indent.writeln('@end'); @@ -1225,8 +1363,9 @@ taskQueue:$taskQueue indent.writeScoped(' {', '}', () { const String result = 'pigeonResult'; indent.writeln('$className* $result = [[$className alloc] init];'); - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { indent.writeln('$result.${field.name} = ${field.name};'); } indent.writeln('return $result;'); @@ -1248,8 +1387,11 @@ void _writeMethod( // Nullability is required since the return must be nil if NSError is set. forceBox: true, ); - final String callbackType = - _callbackForType(func.returnType, returnType, languageOptions); + final String callbackType = _callbackForType( + func.returnType, + returnType, + languageOptions, + ); String argNameFunc(int count, NamedType arg) => _getSafeArgName(count, arg); String sendArgument; @@ -1265,8 +1407,11 @@ void _writeMethod( varExpression = '${argNameFunc(count, arg)} == nil ? [NSNull null] : $argName'; } else { - varExpression = _getEnumToEnumBox(arg, argNameFunc(count, arg), - prefix: languageOptions.prefix); + varExpression = _getEnumToEnumBox( + arg, + argNameFunc(count, arg), + prefix: languageOptions.prefix, + ); } } count++; @@ -1276,17 +1421,20 @@ void _writeMethod( sendArgument = '@[${func.parameters.map(makeVarOrNSNullExpression).join(', ')}]'; } - indent.write(_makeObjcSignature( - func: func, - options: languageOptions, - returnType: 'void', - lastArgName: 'completion', - lastArgType: callbackType, - argNameFunc: argNameFunc, - )); + indent.write( + _makeObjcSignature( + func: func, + options: languageOptions, + returnType: 'void', + lastArgName: 'completion', + lastArgType: callbackType, + argNameFunc: argNameFunc, + ), + ); indent.addScoped(' {', '}', () { indent.writeln( - 'NSString *channelName = [NSString stringWithFormat:@"%@%@", @"${makeChannelName(api, func, dartPackageName)}", _messageChannelSuffix];'); + 'NSString *channelName = [NSString stringWithFormat:@"%@%@", @"${makeChannelName(api, func, dartPackageName)}", _messageChannelSuffix];', + ); indent.writeln('FlutterBasicMessageChannel *channel ='); indent.nest(1, () { @@ -1295,18 +1443,21 @@ void _writeMethod( indent.writeln('messageChannelWithName:channelName'); indent.writeln('binaryMessenger:self.binaryMessenger'); indent.write( - 'codec:${languageOptions.prefix}Get${toUpperCamelCase(languageOptions.fileSpecificClassNameComponent ?? '')}Codec()'); + 'codec:${languageOptions.prefix}Get${toUpperCamelCase(languageOptions.fileSpecificClassNameComponent ?? '')}Codec()', + ); indent.addln('];'); }); }); final String valueOnErrorResponse = func.returnType.isVoid ? '' : 'nil, '; indent.write( - '[channel sendMessage:$sendArgument reply:^(NSArray *reply) '); + '[channel sendMessage:$sendArgument reply:^(NSArray *reply) ', + ); indent.addScoped('{', '}];', () { indent.writeScoped('if (reply != nil) {', '} ', () { indent.writeScoped('if (reply.count > 1) {', '} ', () { indent.writeln( - 'completion($valueOnErrorResponse[FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]);'); + 'completion($valueOnErrorResponse[FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]);', + ); }, addTrailingNewline: false); indent.addScoped('else {', '}', () { const String nullCheck = 'reply[0] == [NSNull null] ? nil : reply[0]'; @@ -1314,8 +1465,11 @@ void _writeMethod( indent.writeln('completion(nil);'); } else { if (func.returnType.isEnum) { - final String enumName = _enumName(func.returnType.baseName, - prefix: languageOptions.prefix, box: true); + final String enumName = _enumName( + func.returnType.baseName, + prefix: languageOptions.prefix, + box: true, + ); indent.writeln('$enumName *output = $nullCheck;'); } else { indent.writeln('${returnType.beforeString}output = $nullCheck;'); @@ -1326,7 +1480,8 @@ void _writeMethod( }, addTrailingNewline: false); indent.addScoped('else {', '} ', () { indent.writeln( - 'completion(${valueOnErrorResponse}createConnectionError(channelName));'); + 'completion(${valueOnErrorResponse}createConnectionError(channelName));', + ); }); }); }); @@ -1345,34 +1500,42 @@ void _writeObjcSourceClassInitializerDeclaration( indent.write('+ (instancetype)makeWith'); bool isFirst = true; indent.nest(2, () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + 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)} *'); + 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)} *', + ); final String nullable = field.type.isNullable ? 'nullable ' : ''; printer('$label:($nullable${hostDatatype.datatype})${field.name}'); } }); } -String _enumName(String name, - {required String? prefix, String suffix = '', bool box = false}) => - '${prefix ?? ''}$name${box ? 'Box' : ''}$suffix'; +String _enumName( + String name, { + required String? prefix, + String suffix = '', + bool box = false, +}) => '${prefix ?? ''}$name${box ? 'Box' : ''}$suffix'; /// Calculates the ObjC class name, possibly prefixed. String _className(String? prefix, String className) { @@ -1385,7 +1548,10 @@ String _className(String? prefix, String className) { /// Calculates callback block signature for async methods. String _callbackForType( - TypeDeclaration type, _ObjcType objcType, InternalObjcOptions options) { + TypeDeclaration type, + _ObjcType objcType, + InternalObjcOptions options, +) { if (type.isVoid) { return 'void (^)(FlutterError *_Nullable)'; } else if (type.isEnum) { @@ -1399,7 +1565,7 @@ String _callbackForType( /// primitive (BOOL, NSInteger, etc.) types. class _ObjcType { const _ObjcType({required this.baseName, bool isPointer = true}) - : hasAsterisk = isPointer && baseName != 'id'; + : hasAsterisk = isPointer && baseName != 'id'; final String baseName; final bool hasAsterisk; @@ -1418,34 +1584,34 @@ class _ObjcType { /// Maps between Dart types to ObjC pointer types (ex 'String' => 'NSString *'). const Map _objcTypeForNullableDartTypeMap = { - 'bool': _ObjcType(baseName: 'NSNumber'), - 'int': _ObjcType(baseName: 'NSNumber'), - 'String': _ObjcType(baseName: 'NSString'), - 'double': _ObjcType(baseName: 'NSNumber'), - 'Uint8List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'Int32List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'Int64List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'Float64List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'List': _ObjcType(baseName: 'NSArray'), - 'Map': _ObjcType(baseName: 'NSDictionary'), - 'Object': _ObjcType(baseName: 'id'), -}; + 'bool': _ObjcType(baseName: 'NSNumber'), + 'int': _ObjcType(baseName: 'NSNumber'), + 'String': _ObjcType(baseName: 'NSString'), + 'double': _ObjcType(baseName: 'NSNumber'), + 'Uint8List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'Int32List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'Int64List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'Float64List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'List': _ObjcType(baseName: 'NSArray'), + 'Map': _ObjcType(baseName: 'NSDictionary'), + 'Object': _ObjcType(baseName: 'id'), + }; /// Maps between Dart types to ObjC pointer types (ex 'String' => 'NSString *'). const Map _objcTypeForNonNullableDartTypeMap = { - 'bool': _ObjcType(baseName: 'BOOL', isPointer: false), - 'int': _ObjcType(baseName: 'NSInteger', isPointer: false), - 'String': _ObjcType(baseName: 'NSString'), - 'double': _ObjcType(baseName: 'double', isPointer: false), - 'Uint8List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'Int32List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'Int64List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'Float64List': _ObjcType(baseName: 'FlutterStandardTypedData'), - 'List': _ObjcType(baseName: 'NSArray'), - 'Map': _ObjcType(baseName: 'NSDictionary'), - 'Object': _ObjcType(baseName: 'id'), -}; + 'bool': _ObjcType(baseName: 'BOOL', isPointer: false), + 'int': _ObjcType(baseName: 'NSInteger', isPointer: false), + 'String': _ObjcType(baseName: 'NSString'), + 'double': _ObjcType(baseName: 'double', isPointer: false), + 'Uint8List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'Int32List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'Int64List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'Float64List': _ObjcType(baseName: 'FlutterStandardTypedData'), + 'List': _ObjcType(baseName: 'NSArray'), + 'Map': _ObjcType(baseName: 'NSDictionary'), + 'Object': _ObjcType(baseName: 'id'), + }; bool _usesPrimitive(TypeDeclaration type) { // Only non-nullable types are unboxed. @@ -1463,10 +1629,7 @@ bool _usesPrimitive(TypeDeclaration type) { return false; } -String _collectionSafeExpression( - String expression, - TypeDeclaration type, -) { +String _collectionSafeExpression(String expression, TypeDeclaration type) { return _usesPrimitive(type) ? '@($expression)' : '$expression ?: [NSNull null]'; @@ -1474,9 +1637,7 @@ String _collectionSafeExpression( /// Returns the method to convert [type] from a boxed NSNumber to its /// corresponding primitive value, if any. -String? _nsnumberExtractionMethod( - TypeDeclaration type, -) { +String? _nsnumberExtractionMethod(TypeDeclaration type) { // Only non-nullable types are unboxed. if (!type.isNullable) { if (type.isEnum) { @@ -1498,60 +1659,83 @@ String? _nsnumberExtractionMethod( /// arguments for use in generics. /// Example: ('FOO', ['Foo', 'Bar']) -> 'FOOFoo *, FOOBar *'). String _flattenTypeArguments(String? classPrefix, List args) { - final String result = args.map((TypeDeclaration e) { - if (e.isEnum) { - return _enumName(e.baseName, - prefix: classPrefix, box: true, suffix: ' *'); - } - return _objcTypeForDartType(classPrefix, e, forceBox: true).toString(); - }).join(', '); + final String result = args + .map((TypeDeclaration e) { + if (e.isEnum) { + return _enumName( + e.baseName, + prefix: classPrefix, + box: true, + suffix: ' *', + ); + } + return _objcTypeForDartType(classPrefix, e, forceBox: true).toString(); + }) + .join(', '); return result; } -_ObjcType? _objcTypeForPrimitiveDartType(TypeDeclaration type, - {bool forceBox = false}) { +_ObjcType? _objcTypeForPrimitiveDartType( + TypeDeclaration type, { + bool forceBox = false, +}) { return forceBox || type.isNullable ? _objcTypeForNullableDartTypeMap[type.baseName] : _objcTypeForNonNullableDartTypeMap[type.baseName]; } String? _objcTypeStringForPrimitiveDartType( - String? classPrefix, TypeDeclaration type, - {required bool beforeString, bool forceBox = false}) { + String? classPrefix, + TypeDeclaration type, { + required bool beforeString, + bool forceBox = false, +}) { 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(); } /// Returns the Objective-C type for a Dart [field], prepending the /// [classPrefix] for generated classes. -_ObjcType _objcTypeForDartType(String? classPrefix, TypeDeclaration field, - {bool forceBox = false}) { - final _ObjcType? primitiveType = - _objcTypeForPrimitiveDartType(field, forceBox: forceBox); +_ObjcType _objcTypeForDartType( + String? classPrefix, + TypeDeclaration field, { + bool forceBox = false, +}) { + final _ObjcType? primitiveType = _objcTypeForPrimitiveDartType( + field, + forceBox: forceBox, + ); 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)}>'); + ? primitiveType + : _ObjcType( + baseName: + '${primitiveType.baseName}<${_flattenTypeArguments(classPrefix, field.typeArguments)}>', + ); } /// Maps a type to a properties memory semantics (ie strong, copy). -String _propertyTypeForDartType(TypeDeclaration type, - {required bool isNullable, required bool isEnum}) { +String _propertyTypeForDartType( + TypeDeclaration type, { + required bool isNullable, + required bool isEnum, +}) { if (isEnum) { // Only the nullable versions are objects. return isNullable ? 'strong' : 'assign'; @@ -1583,7 +1767,9 @@ String _capitalize(String str) => /// Example: /// f('void add(int x, int y)', 'count') -> ['addX', 'y', 'count'] Iterable _getSelectorComponents( - Method func, String lastSelectorComponent) sync* { + Method func, + String lastSelectorComponent, +) sync* { if (func.objcSelector.isEmpty) { final Iterator it = func.parameters.iterator; final bool hasArguments = it.moveNext(); @@ -1623,21 +1809,28 @@ String _makeObjcSignature({ required String lastArgName, String Function(int, NamedType)? argNameFunc, }) { - argNameFunc = argNameFunc ?? + argNameFunc = + argNameFunc ?? (int _, NamedType e) => e.type.isNullable && e.type.isEnum ? '${e.name}Boxed' : e.name; - final Iterable argNames = - followedByOne(indexMap(func.parameters, argNameFunc), lastArgName); - final Iterable selectorComponents = - _getSelectorComponents(func, lastArgName); + final Iterable argNames = followedByOne( + indexMap(func.parameters, argNameFunc), + lastArgName, + ); + final Iterable selectorComponents = _getSelectorComponents( + func, + lastArgName, + ); final Iterable argTypes = followedByOne( func.parameters.map((NamedType arg) { if (arg.type.isEnum) { return '${arg.type.isNullable ? 'nullable ' : ''}${_enumName(arg.type.baseName, suffix: arg.type.isNullable ? ' *' : '', prefix: options.prefix, box: arg.type.isNullable)}'; } else { final String nullable = arg.type.isNullable ? 'nullable ' : ''; - final _ObjcType argType = - _objcTypeForDartType(options.prefix, arg.type); + final _ObjcType argType = _objcTypeForDartType( + options.prefix, + arg.type, + ); return '$nullable$argType'; } }), @@ -1657,16 +1850,16 @@ String _makeObjcSignature({ /// Generates the ".h" file for the AST represented by [root] to [sink] with the /// provided [options]. void generateObjcHeader( - InternalObjcOptions options, Root root, Indent indent) {} + InternalObjcOptions options, + Root root, + Indent indent, +) {} String _arrayValue(NamedType field, String? prefix) { if (field.type.isEnum && !field.type.isNullable) { return _getEnumToEnumBox(field, 'self.${field.name}', prefix: prefix); } else { - return _collectionSafeExpression( - 'self.${field.name}', - field.type, - ); + return _collectionSafeExpression('self.${field.name}', field.type); } } @@ -1680,28 +1873,34 @@ String _getSafeArgName(int count, NamedType arg) => void _writeExtension(Indent indent, String apiName) { indent.writeln('@interface $apiName ()'); indent.writeln( - '@property(nonatomic, strong) NSObject *binaryMessenger;'); - indent - .writeln('@property(nonatomic, strong) NSString *messageChannelSuffix;'); + '@property(nonatomic, strong) NSObject *binaryMessenger;', + ); + indent.writeln( + '@property(nonatomic, strong) NSString *messageChannelSuffix;', + ); indent.writeln('@end'); } void _writeInitializers(Indent indent) { indent.write( - '- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger '); + '- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger ', + ); indent.addScoped('{', '}', () { indent.writeln( - 'return [self initWithBinaryMessenger:binaryMessenger messageChannelSuffix:@""];'); + 'return [self initWithBinaryMessenger:binaryMessenger messageChannelSuffix:@""];', + ); }); indent.write( - '- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger messageChannelSuffix:(nullable NSString*)messageChannelSuffix'); + '- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger messageChannelSuffix:(nullable NSString*)messageChannelSuffix', + ); indent.addScoped('{', '}', () { indent.writeln('self = [self init];'); indent.write('if (self) '); indent.addScoped('{', '}', () { indent.writeln('_binaryMessenger = binaryMessenger;'); indent.writeln( - '_messageChannelSuffix = [messageChannelSuffix length] == 0 ? @"" : [NSString stringWithFormat: @".%@", messageChannelSuffix];'); + '_messageChannelSuffix = [messageChannelSuffix length] == 0 ? @"" : [NSString stringWithFormat: @".%@", messageChannelSuffix];', + ); }); indent.writeln('return self;'); }); @@ -1716,9 +1915,12 @@ List validateObjc(InternalObjcOptions options, Root root) { for (final NamedType arg in method.parameters) { if (arg.type.isEnum && arg.type.isNullable) { // TODO(gaaclarke): Add line number. - errors.add(Error( + errors.add( + Error( message: - "Nullable enum types aren't support in ObjC arguments in method:${api.name}.${method.name} argument:(${arg.type.baseName} ${arg.name}).")); + "Nullable enum types aren't support in ObjC arguments in method:${api.name}.${method.name} argument:(${arg.type.baseName} ${arg.name}).", + ), + ); } } } @@ -1735,7 +1937,8 @@ void _writeEnumBoxToEnum( String? prefix = '', }) { indent.writeln( - '${_enumName(field.type.baseName, prefix: prefix, box: true, suffix: ' *')}$varName = $valueGetter;'); + '${_enumName(field.type.baseName, prefix: prefix, box: true, suffix: ' *')}$varName = $valueGetter;', + ); } String _getEnumToEnumBox( @@ -1755,16 +1958,21 @@ void _writeDataClassDeclaration( final String? prefix = generatorOptions.prefix; addDocumentationComments( - indent, classDefinition.documentationComments, _docCommentSpec); + indent, + classDefinition.documentationComments, + _docCommentSpec, + ); indent.writeln( - '@interface ${_className(prefix, classDefinition.name)} : NSObject'); + '@interface ${_className(prefix, classDefinition.name)} : NSObject', + ); if (getFieldsInSerializationOrder(classDefinition).isNotEmpty) { - if (getFieldsInSerializationOrder(classDefinition) - .map((NamedType e) => !e.type.isNullable) - .any((bool e) => e)) { + if (getFieldsInSerializationOrder( + classDefinition, + ).map((NamedType e) => !e.type.isNullable).any((bool e) => e)) { indent.writeln( - '$_docCommentPrefix `init` unavailable to enforce nonnull fields, see the `make` class method.'); + '$_docCommentPrefix `init` unavailable to enforce nonnull fields, see the `make` class method.', + ); indent.writeln('- (instancetype)init NS_UNAVAILABLE;'); } _writeObjcSourceClassInitializerDeclaration( @@ -1776,29 +1984,42 @@ void _writeDataClassDeclaration( ); indent.addln(';'); } - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final HostDatatype hostDatatype = getFieldHostDatatype( - field, - (TypeDeclaration x) => - _objcTypeStringForPrimitiveDartType(prefix, x, beforeString: true), - customResolver: field.type.isEnum - ? (String x) => _enumName(x, prefix: prefix) - : (String x) => '${_className(prefix, x)} *'); + field, + (TypeDeclaration x) => + _objcTypeStringForPrimitiveDartType(prefix, x, beforeString: true), + customResolver: + field.type.isEnum + ? (String x) => _enumName(x, prefix: prefix) + : (String x) => '${_className(prefix, x)} *', + ); late final String propertyType; addDocumentationComments( - indent, field.documentationComments, _docCommentSpec); - propertyType = _propertyTypeForDartType(field.type, - isNullable: field.type.isNullable, isEnum: field.type.isEnum); + indent, + field.documentationComments, + _docCommentSpec, + ); + propertyType = _propertyTypeForDartType( + field.type, + isNullable: field.type.isNullable, + 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};'); + '@property(nonatomic, $propertyType$nullability) $fieldType ${field.name};', + ); } indent.writeln('@end'); indent.newln(); diff --git a/packages/pigeon/lib/src/pigeon_cl.dart b/packages/pigeon/lib/src/pigeon_cl.dart index 6c24939161e..5e5023367fc 100644 --- a/packages/pigeon/lib/src/pigeon_cl.dart +++ b/packages/pigeon/lib/src/pigeon_cl.dart @@ -9,7 +9,10 @@ import 'pigeon_lib.dart'; /// command line arguments and there is an optional [packageConfig] to /// accommodate users that want to integrate pigeon with other build systems. /// [sdkPath] for specifying an optional Dart SDK path. -Future runCommandLine(List args, - {Uri? packageConfig, String? sdkPath}) async { +Future runCommandLine( + List args, { + Uri? packageConfig, + String? sdkPath, +}) async { return Pigeon.run(args, sdkPath: sdkPath); } diff --git a/packages/pigeon/lib/src/pigeon_lib.dart b/packages/pigeon/lib/src/pigeon_lib.dart index bae0d164aa7..64ed9584eeb 100644 --- a/packages/pigeon/lib/src/pigeon_lib.dart +++ b/packages/pigeon/lib/src/pigeon_lib.dart @@ -343,35 +343,47 @@ 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?, @@ -445,7 +457,7 @@ class Pigeon { /// [AnalysisContextCollection]. ParseResults parseFile(String inputPath, {String? sdkPath}) { final List includedPaths = [ - path.absolute(path.normalize(inputPath)) + path.absolute(path.normalize(inputPath)), ]; final AnalysisContextCollection collection = AnalysisContextCollection( includedPaths: includedPaths, @@ -453,8 +465,9 @@ class Pigeon { ); final List compilationErrors = []; - final RootBuilder rootBuilder = - RootBuilder(File(inputPath).readAsStringSync()); + final RootBuilder rootBuilder = RootBuilder( + File(inputPath).readAsStringSync(), + ); for (final AnalysisContext context in collection.contexts) { for (final String path in context.contextRoot.analyzedFiles()) { final AnalysisSession session = context.currentSession; @@ -465,11 +478,16 @@ class Pigeon { unit.accept(rootBuilder); } else { for (final AnalysisError error in result.errors) { - compilationErrors.add(Error( + compilationErrors.add( + Error( message: error.message, filename: error.source.fullName, lineNumber: calculateLineNumber( - error.source.contents.data, error.offset))); + error.source.contents.data, + error.offset, + ), + ), + ); } } } @@ -498,80 +516,115 @@ 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) { @@ -587,9 +640,7 @@ ${_argParser.usage}'''; dartTestOut: results['dart_test_out'] as String?, objcHeaderOut: results['objc_header_out'] as String?, objcSourceOut: results['objc_source_out'] as String?, - objcOptions: ObjcOptions( - prefix: results['objc_prefix'] as String?, - ), + objcOptions: ObjcOptions(prefix: results['objc_prefix'] as String?), javaOut: results['java_out'] as String?, javaOptions: JavaOptions( package: results['java_package'] as String?, @@ -603,9 +654,7 @@ ${_argParser.usage}'''; ), cppHeaderOut: results['cpp_header_out'] as String?, cppSourceOut: results['cpp_source_out'] as String?, - cppOptions: CppOptions( - namespace: results['cpp_namespace'] as String?, - ), + cppOptions: CppOptions(namespace: results['cpp_namespace'] as String?), gobjectHeaderOut: results['gobject_header_out'] as String?, gobjectSourceOut: results['gobject_source_out'] as String?, gobjectOptions: GObjectOptions( @@ -643,8 +692,11 @@ ${_argParser.usage}'''; /// command-line arguments. The optional parameter [adapters] allows you to /// customize the generators that pigeon will use. The optional parameter /// [sdkPath] allows you to specify the Dart SDK path. - static Future run(List args, - {List? adapters, String? sdkPath}) { + static Future run( + List args, { + List? adapters, + String? sdkPath, + }) { final PigeonOptions options = Pigeon.parseArgs(args); return runWithOptions(options, adapters: adapters, sdkPath: sdkPath); } @@ -664,7 +716,8 @@ ${_argParser.usage}'''; if (options.debugGenerators ?? false) { generator_tools.debugGenerators = true; } - final List safeGeneratorAdapters = adapters ?? + final List safeGeneratorAdapters = + adapters ?? [ DartGeneratorAdapter(), JavaGeneratorAdapter(), @@ -698,30 +751,40 @@ ${_argParser.usage}'''; if (parseResults.pigeonOptions != null && mergeDefinitionFileOptions) { options = PigeonOptions.fromMap( - mergeMaps(options.toMap(), parseResults.pigeonOptions!)); + mergeMaps(options.toMap(), parseResults.pigeonOptions!), + ); } final InternalPigeonOptions internalOptions = InternalPigeonOptions.fromPigeonOptions(options); for (final GeneratorAdapter adapter in safeGeneratorAdapters) { - final IOSink? sink = - adapter.shouldGenerate(internalOptions, FileType.source); + final IOSink? sink = adapter.shouldGenerate( + internalOptions, + FileType.source, + ); if (sink != null) { - final List adapterErrors = - adapter.validate(internalOptions, parseResults.root); + final List adapterErrors = adapter.validate( + internalOptions, + parseResults.root, + ); errors.addAll(adapterErrors); await releaseSink(sink); } } if (errors.isNotEmpty) { - printErrors(errors - .map((Error err) => Error( - message: err.message, - filename: internalOptions.input, - lineNumber: err.lineNumber)) - .toList()); + printErrors( + errors + .map( + (Error err) => Error( + message: err.message, + filename: internalOptions.input, + lineNumber: err.lineNumber, + ), + ) + .toList(), + ); return 1; } @@ -745,7 +808,8 @@ ${_argParser.usage}'''; if (err.filename != null) { if (err.lineNumber != null) { stderr.writeln( - 'Error: ${err.filename}:${err.lineNumber}: ${err.message}'); + 'Error: ${err.filename}:${err.lineNumber}: ${err.message}', + ); } else { stderr.writeln('Error: ${err.filename}: ${err.message}'); } @@ -759,11 +823,7 @@ ${_argParser.usage}'''; /// Represents an error as a result of parsing and generating code. class Error { /// Parametric constructor for Error. - Error({ - required this.message, - this.filename, - this.lineNumber, - }); + Error({required this.message, this.filename, this.lineNumber}); /// A description of the error. String message; diff --git a/packages/pigeon/lib/src/pigeon_lib_internal.dart b/packages/pigeon/lib/src/pigeon_lib_internal.dart index 08de99a311c..f35dcac93a0 100644 --- a/packages/pigeon/lib/src/pigeon_lib_internal.dart +++ b/packages/pigeon/lib/src/pigeon_lib_internal.dart @@ -48,89 +48,104 @@ class InternalPigeonOptions { }); InternalPigeonOptions._fromPigeonOptionsWithHeader( - PigeonOptions options, Iterable? copyrightHeader) - : 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( + PigeonOptions options, + Iterable? copyrightHeader, + ) : 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( + swiftOptions = + options.swiftOut == null + ? null + : InternalSwiftOptions.fromSwiftOptions( options.swiftOptions ?? const SwiftOptions(), swiftOut: options.swiftOut!, copyrightHeader: copyrightHeader, ), - kotlinOptions = options.kotlinOut == null - ? null - : InternalKotlinOptions.fromKotlinOptions( + 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, - ), - gobjectOptions = - options.gobjectHeaderOut == null || options.gobjectSourceOut == null - ? 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( + cppOptions = + (options.cppHeaderOut == null || options.cppSourceOut == null) + ? 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, + ), + 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, - astOut = options.astOut, - debugGenerators = options.debugGenerators, - basePath = options.basePath, - dartPackageName = options.getPackageName(); + copyrightHeader = + options.copyrightHeader != null + ? _lineReader( + path.posix.join( + options.basePath ?? '', + options.copyrightHeader, + ), + ) + : null, + astOut = options.astOut, + debugGenerators = options.debugGenerators, + basePath = options.basePath, + dartPackageName = options.getPackageName(); /// 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, copyrightHeader); + options, + copyrightHeader, + ); } /// Path to the file which will be processed. @@ -214,8 +229,12 @@ abstract class GeneratorAdapter { IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType); /// Write the generated code described in [root] to [sink] using the [options]. - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType); + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ); /// Generates errors that would only be appropriate for this [GeneratorAdapter]. /// @@ -230,19 +249,16 @@ void _errorOnEventChannelApi(List errors, String generator, Root root) { } void _errorOnSealedClass(List errors, String generator, Root root) { - if (root.classes.any( - (Class element) => element.isSealed, - )) { + if (root.classes.any((Class element) => element.isSealed)) { errors.add(Error(message: '$generator does not support sealed classes')); } } void _errorOnInheritedClass(List errors, String generator, Root root) { - if (root.classes.any( - (Class element) => element.superClass != null, - )) { + if (root.classes.any((Class element) => element.superClass != null)) { errors.add( - Error(message: '$generator does not support inheritance in classes')); + Error(message: '$generator does not support inheritance in classes'), + ); } } @@ -255,8 +271,12 @@ class AstGeneratorAdapter implements GeneratorAdapter { List fileTypeList = const [FileType.na]; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { generateAst(root, sink); } @@ -280,8 +300,12 @@ class DartGeneratorAdapter implements GeneratorAdapter { List fileTypeList = const [FileType.na]; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.dartOptions == null) { return; } @@ -312,8 +336,12 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { List fileTypeList = const [FileType.na]; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.dartOptions == null) { return; } @@ -322,7 +350,7 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { // the package name has been overridden for other uses. final String outputPackageName = deducePackageName(options.dartOptions?.dartOut ?? '') ?? - options.dartPackageName; + options.dartPackageName; testGenerator.generateTest( options.dartOptions!, root, @@ -350,8 +378,9 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Objective-C code. class ObjcGeneratorAdapter implements GeneratorAdapter { /// Constructor for [ObjcGeneratorAdapter]. - ObjcGeneratorAdapter( - {this.fileTypeList = const [FileType.header, FileType.source]}); + ObjcGeneratorAdapter({ + this.fileTypeList = const [FileType.header, FileType.source], + }); /// A string representing the name of the language being generated. String languageString = 'Objective-C'; @@ -360,14 +389,20 @@ class ObjcGeneratorAdapter implements GeneratorAdapter { List fileTypeList; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.objcOptions == null) { return; } final OutputFileOptions outputFileOptions = OutputFileOptions( - fileType: fileType, languageOptions: options.objcOptions!); + fileType: fileType, + languageOptions: options.objcOptions!, + ); const ObjcGenerator generator = ObjcGenerator(); generator.generate( outputFileOptions, @@ -414,8 +449,12 @@ class JavaGeneratorAdapter implements GeneratorAdapter { List fileTypeList = const [FileType.na]; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.javaOptions == null) { return; } @@ -454,8 +493,12 @@ class SwiftGeneratorAdapter implements GeneratorAdapter { List fileTypeList = const [FileType.na]; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.swiftOptions == null) { return; } @@ -470,8 +513,10 @@ class SwiftGeneratorAdapter implements GeneratorAdapter { @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) => - _openSink(options.swiftOptions?.swiftOut, - basePath: options.basePath ?? ''); + _openSink( + options.swiftOptions?.swiftOut, + basePath: options.basePath ?? '', + ); @override List validate(InternalPigeonOptions options, Root root) => []; @@ -480,8 +525,9 @@ class SwiftGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates C++ source code. class CppGeneratorAdapter implements GeneratorAdapter { /// Constructor for [CppGeneratorAdapter]. - CppGeneratorAdapter( - {this.fileTypeList = const [FileType.header, FileType.source]}); + CppGeneratorAdapter({ + this.fileTypeList = const [FileType.header, FileType.source], + }); /// A string representing the name of the language being generated. String languageString = 'C++'; @@ -490,14 +536,20 @@ class CppGeneratorAdapter implements GeneratorAdapter { List fileTypeList; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.cppOptions == null) { return; } final OutputFileOptions outputFileOptions = OutputFileOptions( - fileType: fileType, languageOptions: options.cppOptions!); + fileType: fileType, + languageOptions: options.cppOptions!, + ); const CppGenerator generator = CppGenerator(); generator.generate( outputFileOptions, @@ -510,11 +562,15 @@ class CppGeneratorAdapter implements GeneratorAdapter { @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType) { if (fileType == FileType.source) { - return _openSink(options.cppOptions?.cppSourceOut, - basePath: options.basePath ?? ''); + return _openSink( + options.cppOptions?.cppSourceOut, + basePath: options.basePath ?? '', + ); } else { - return _openSink(options.cppOptions?.cppHeaderOut, - basePath: options.basePath ?? ''); + return _openSink( + options.cppOptions?.cppHeaderOut, + basePath: options.basePath ?? '', + ); } } @@ -531,8 +587,9 @@ class CppGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates GObject source code. class GObjectGeneratorAdapter implements GeneratorAdapter { /// Constructor for [GObjectGeneratorAdapter]. - GObjectGeneratorAdapter( - {this.fileTypeList = const [FileType.header, FileType.source]}); + GObjectGeneratorAdapter({ + this.fileTypeList = const [FileType.header, FileType.source], + }); /// A string representing the name of the language being generated. String languageString = 'GObject'; @@ -541,14 +598,20 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { List fileTypeList; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.gobjectOptions == null) { return; } final OutputFileOptions outputFileOptions = OutputFileOptions( - fileType: fileType, languageOptions: options.gobjectOptions!); + fileType: fileType, + languageOptions: options.gobjectOptions!, + ); const GObjectGenerator generator = GObjectGenerator(); generator.generate( outputFileOptions, @@ -561,11 +624,15 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType) { if (fileType == FileType.source) { - return _openSink(options.gobjectOptions?.gobjectSourceOut, - basePath: options.basePath ?? ''); + return _openSink( + options.gobjectOptions?.gobjectSourceOut, + basePath: options.basePath ?? '', + ); } else { - return _openSink(options.gobjectOptions?.gobjectHeaderOut, - basePath: options.basePath ?? ''); + return _openSink( + options.gobjectOptions?.gobjectHeaderOut, + basePath: options.basePath ?? '', + ); } } @@ -575,9 +642,12 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { // TODO(tarrinneal): Remove once overflow class is added to gobject generator. // https://github.com/flutter/flutter/issues/152916 if (root.classes.length + root.enums.length > totalCustomCodecKeysAllowed) { - errors.add(Error( + errors.add( + Error( message: - 'GObject generator does not yet support more than $totalCustomCodecKeysAllowed custom types.')); + 'GObject generator does not yet support more than $totalCustomCodecKeysAllowed custom types.', + ), + ); } _errorOnEventChannelApi(errors, languageString, root); _errorOnSealedClass(errors, languageString, root); @@ -596,8 +666,12 @@ class KotlinGeneratorAdapter implements GeneratorAdapter { List fileTypeList; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) { + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) { if (options.kotlinOptions == null) { return; } @@ -612,22 +686,29 @@ class KotlinGeneratorAdapter implements GeneratorAdapter { @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) => - _openSink(options.kotlinOptions?.kotlinOut, - basePath: options.basePath ?? ''); + _openSink( + options.kotlinOptions?.kotlinOut, + basePath: options.basePath ?? '', + ); @override List validate(InternalPigeonOptions options, Root root) => []; } dart_ast.Annotation? _findMetadata( - dart_ast.NodeList metadata, String query) { - final Iterable annotations = metadata - .where((dart_ast.Annotation element) => element.name.name == query); + dart_ast.NodeList metadata, + String query, +) { + final Iterable annotations = metadata.where( + (dart_ast.Annotation element) => element.name.name == query, + ); return annotations.isEmpty ? null : annotations.first; } bool _hasMetadata( - dart_ast.NodeList metadata, String query) { + dart_ast.NodeList metadata, + String query, +) { return _findMetadata(metadata, query) != null; } @@ -647,10 +728,12 @@ List _validateAst(Root root, String source) { prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Enum name must not begin with "$matchingPrefix" in enum "${enumDefinition.name}"', - )); + result.add( + Error( + message: + 'Enum name must not begin with "$matchingPrefix" in enum "${enumDefinition.name}"', + ), + ); } for (final EnumMember enumMember in enumDefinition.members) { final String? matchingPrefix = _findMatchingPrefixOrNull( @@ -658,10 +741,12 @@ List _validateAst(Root root, String source) { prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Enum member name must not begin with "$matchingPrefix" in enum member "${enumMember.name}" of enum "${enumDefinition.name}"', - )); + result.add( + Error( + message: + 'Enum member name must not begin with "$matchingPrefix" in enum member "${enumMember.name}" of enum "${enumDefinition.name}"', + ), + ); } } } @@ -671,49 +756,60 @@ List _validateAst(Root root, String source) { prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Class name must not begin with "$matchingPrefix" in class "${classDefinition.name}"', - )); + result.add( + Error( + message: + 'Class name must not begin with "$matchingPrefix" in class "${classDefinition.name}"', + ), + ); } - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final String? matchingPrefix = _findMatchingPrefixOrNull( field.name, prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Class field name must not begin with "$matchingPrefix" in field "${field.name}" of class "${classDefinition.name}"', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Class field name must not begin with "$matchingPrefix" in field "${field.name}" of class "${classDefinition.name}"', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } if (!(validTypes.contains(field.type.baseName) || customClasses.contains(field.type.baseName) || customEnums.contains(field.type.baseName))) { - result.add(Error( - message: - 'Unsupported datatype:"${field.type.baseName}" in class "${classDefinition.name}".', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Unsupported datatype:"${field.type.baseName}" in class "${classDefinition.name}".', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } if (classDefinition.isSealed) { if (classDefinition.fields.isNotEmpty) { - result.add(Error( - message: - 'Sealed class: "${classDefinition.name}" must not contain fields.', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Sealed class: "${classDefinition.name}" must not contain fields.', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } } if (classDefinition.superClass != null) { if (!classDefinition.superClass!.isSealed) { - result.add(Error( - message: - 'Child class: "${classDefinition.name}" must extend a sealed class.', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Child class: "${classDefinition.name}" must extend a sealed class.', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } } } @@ -727,27 +823,33 @@ List _validateAst(Root root, String source) { prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'API name must not begin with "$matchingPrefix" in API "${api.name}"', - )); + result.add( + Error( + message: + 'API name must not begin with "$matchingPrefix" in API "${api.name}"', + ), + ); } if (api is AstEventChannelApi) { if (containsEventChannelApi) { - result.add(Error( - message: - 'Event Channel methods must all be included in a single EventChannelApi', - )); + result.add( + Error( + message: + 'Event Channel methods must all be included in a single EventChannelApi', + ), + ); } containsEventChannelApi = true; } if (api is AstProxyApi) { - result.addAll(_validateProxyApi( - api, - source, - customClasses: customClasses.toSet(), - proxyApis: root.apis.whereType().toSet(), - )); + result.addAll( + _validateProxyApi( + api, + source, + customClasses: customClasses.toSet(), + proxyApis: root.apis.whereType().toSet(), + ), + ); } for (final Method method in api.methods) { final String? matchingPrefix = _findMatchingPrefixOrNull( @@ -755,82 +857,101 @@ List _validateAst(Root root, String source) { prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Method name must not begin with "$matchingPrefix" in method "${method.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: + 'Method name must not begin with "$matchingPrefix" in method "${method.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } if (api is AstEventChannelApi && method.parameters.isNotEmpty) { - result.add(Error( - message: - 'event channel methods must not be contain parameters, in method "${method.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: + 'event channel methods must not be contain parameters, in method "${method.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } for (final Parameter param in method.parameters) { if (param.type.baseName.isEmpty) { - result.add(Error( - message: - 'Parameters must specify their type in method "${method.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, param.offset), - )); + result.add( + Error( + message: + 'Parameters must specify their type in method "${method.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, param.offset), + ), + ); } else { final String? matchingPrefix = _findMatchingPrefixOrNull( param.name, prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Parameter name must not begin with "$matchingPrefix" in method "${method.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, param.offset), - )); + result.add( + Error( + message: + 'Parameter name must not begin with "$matchingPrefix" in method "${method.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, param.offset), + ), + ); } } if (api is AstFlutterApi) { if (!param.isPositional) { - result.add(Error( - message: - 'FlutterApi method parameters must be positional, in method "${method.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, param.offset), - )); + result.add( + Error( + message: + 'FlutterApi method parameters must be positional, in method "${method.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, param.offset), + ), + ); } else if (param.isOptional) { - result.add(Error( - message: - 'FlutterApi method parameters must not be optional, in method "${method.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, param.offset), - )); + result.add( + Error( + message: + 'FlutterApi method parameters must not be optional, in method "${method.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, param.offset), + ), + ); } } } if (method.objcSelector.isNotEmpty) { if (':'.allMatches(method.objcSelector).length != method.parameters.length) { - result.add(Error( - message: - 'Invalid selector, expected ${method.parameters.length} parameters.', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: + 'Invalid selector, expected ${method.parameters.length} parameters.', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } } if (method.swiftFunction.isNotEmpty) { - final RegExp signatureRegex = - RegExp('\\w+ *\\((\\w+:){${method.parameters.length}}\\)'); + final RegExp signatureRegex = RegExp( + '\\w+ *\\((\\w+:){${method.parameters.length}}\\)', + ); if (!signatureRegex.hasMatch(method.swiftFunction)) { - result.add(Error( - message: - 'Invalid function signature, expected ${method.parameters.length} parameters.', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: + 'Invalid function signature, expected ${method.parameters.length} parameters.', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } } if (method.taskQueueType != TaskQueueType.serial && method.location == ApiLocation.flutter) { - result.add(Error( - message: 'Unsupported TaskQueue specification on ${method.name}', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: 'Unsupported TaskQueue specification on ${method.name}', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } } } @@ -848,9 +969,8 @@ List _validateProxyApi( bool isDataClass(NamedType type) => customClasses.contains(type.type.baseName); - bool isProxyApi(NamedType type) => proxyApis.any( - (AstProxyApi api) => api.name == type.type.baseName, - ); + bool isProxyApi(NamedType type) => + proxyApis.any((AstProxyApi api) => api.name == type.type.baseName); Error unsupportedDataClassError(NamedType type) { return Error( message: 'ProxyApis do not support data classes: ${type.type.baseName}.', @@ -879,14 +999,16 @@ List _validateProxyApi( // Validate that the api does not inherit an unattached field from its super class. if (directSuperClass != null && directSuperClass.unattachedFields.isNotEmpty) { - result.add(Error( - message: - 'Unattached fields can not be inherited. Unattached field found for parent class: ${directSuperClass.unattachedFields.first.name}', - lineNumber: _calculateLineNumberNullable( - source, - directSuperClass.unattachedFields.first.offset, + result.add( + Error( + message: + 'Unattached fields can not be inherited. Unattached field found for parent class: ${directSuperClass.unattachedFields.first.name}', + lineNumber: _calculateLineNumberNullable( + source, + directSuperClass.unattachedFields.first.offset, + ), ), - )); + ); } // Validate all interfaces are annotated with @ProxyApi @@ -895,16 +1017,19 @@ List _validateProxyApi( ); for (final String interfaceName in interfaceNames) { if (!proxyApis.any((AstProxyApi api) => api.name == interfaceName)) { - result.add(Error( - message: - 'Interface of ${api.name} is not annotated with a @ProxyApi: $interfaceName', - )); + result.add( + Error( + message: + 'Interface of ${api.name} is not annotated with a @ProxyApi: $interfaceName', + ), + ); } } final bool hasUnattachedField = api.unattachedFields.isNotEmpty; - final bool hasRequiredFlutterMethod = - api.flutterMethods.any((Method method) => method.isRequired); + final bool hasRequiredFlutterMethod = api.flutterMethods.any( + (Method method) => method.isRequired, + ); for (final AstProxyApi proxyApi in proxyApis) { // Validate this api is not used as an attached field while either: // 1. Having an unattached field. @@ -913,24 +1038,22 @@ List _validateProxyApi( for (final ApiField field in proxyApi.attachedFields) { if (field.type.baseName == api.name) { if (hasUnattachedField) { - result.add(Error( - message: - 'ProxyApis with unattached fields can not be used as attached fields: ${field.name}', - lineNumber: _calculateLineNumberNullable( - source, - field.offset, + result.add( + Error( + message: + 'ProxyApis with unattached fields can not be used as attached fields: ${field.name}', + lineNumber: _calculateLineNumberNullable(source, field.offset), ), - )); + ); } if (hasRequiredFlutterMethod) { - result.add(Error( - message: - 'ProxyApis with required callback methods can not be used as attached fields: ${field.name}', - lineNumber: _calculateLineNumberNullable( - source, - field.offset, + result.add( + Error( + message: + 'ProxyApis with required callback methods can not be used as attached fields: ${field.name}', + lineNumber: _calculateLineNumberNullable(source, field.offset), ), - )); + ); } } } @@ -938,7 +1061,8 @@ List _validateProxyApi( // Validate this api isn't used as an interface and contains anything except // Flutter methods, a static host method, attached methods. - final bool isValidInterfaceProxyApi = api.constructors.isEmpty && + final bool isValidInterfaceProxyApi = + api.constructors.isEmpty && api.fields.where((ApiField field) => !field.isStatic).isEmpty && api.hostMethods.where((Method method) => !method.isStatic).isEmpty; if (!isValidInterfaceProxyApi) { @@ -947,10 +1071,12 @@ List _validateProxyApi( ); for (final String interfaceName in interfaceNames) { if (interfaceName == api.name) { - result.add(Error( - message: - 'ProxyApis used as interfaces can only have callback methods: `${proxyApi.name}` implements `${api.name}`', - )); + result.add( + Error( + message: + 'ProxyApis used as interfaces can only have callback methods: `${proxyApi.name}` implements `${api.name}`', + ), + ); } } } @@ -964,44 +1090,60 @@ List _validateProxyApi( } if (api.fields.any((ApiField field) => field.name == parameter.name) || - api.flutterMethods - .any((Method method) => method.name == parameter.name)) { - result.add(Error( - message: - 'Parameter names must not share a name with a field or callback method in constructor "${constructor.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, parameter.offset), - )); + api.flutterMethods.any( + (Method method) => method.name == parameter.name, + )) { + result.add( + Error( + message: + 'Parameter names must not share a name with a field or callback method in constructor "${constructor.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, parameter.offset), + ), + ); } if (parameter.type.baseName.isEmpty) { - result.add(Error( - message: - 'Parameters must specify their type in constructor "${constructor.name}" in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, parameter.offset), - )); + result.add( + Error( + message: + 'Parameters must specify their type in constructor "${constructor.name}" in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, parameter.offset), + ), + ); } else { final String? matchingPrefix = _findMatchingPrefixOrNull( parameter.name, prefixes: disallowedPrefixes, ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Parameter name must not begin with "$matchingPrefix" in constructor "${constructor.name} in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, parameter.offset), - )); + result.add( + Error( + message: + 'Parameter name must not begin with "$matchingPrefix" in constructor "${constructor.name} in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable( + source, + parameter.offset, + ), + ), + ); } } } if (constructor.swiftFunction.isNotEmpty) { - final RegExp signatureRegex = - RegExp('\\w+ *\\((\\w+:){${constructor.parameters.length}}\\)'); + final RegExp signatureRegex = RegExp( + '\\w+ *\\((\\w+:){${constructor.parameters.length}}\\)', + ); if (!signatureRegex.hasMatch(constructor.swiftFunction)) { - result.add(Error( - message: - 'Invalid constructor signature, expected ${constructor.parameters.length} parameters.', - lineNumber: _calculateLineNumberNullable(source, constructor.offset), - )); + result.add( + Error( + message: + 'Invalid constructor signature, expected ${constructor.parameters.length} parameters.', + lineNumber: _calculateLineNumberNullable( + source, + constructor.offset, + ), + ), + ); } } } @@ -1015,17 +1157,16 @@ List _validateProxyApi( final String? matchingPrefix = _findMatchingPrefixOrNull( parameter.name, - prefixes: [ - classNamePrefix, - varNamePrefix, - ], + prefixes: [classNamePrefix, varNamePrefix], ); if (matchingPrefix != null) { - result.add(Error( - message: - 'Parameter name must not begin with "$matchingPrefix" in method "${method.name} in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable(source, parameter.offset), - )); + result.add( + Error( + message: + 'Parameter name must not begin with "$matchingPrefix" in method "${method.name} in API: "${api.name}"', + lineNumber: _calculateLineNumberNullable(source, parameter.offset), + ), + ); } } @@ -1033,17 +1174,22 @@ List _validateProxyApi( if (!method.returnType.isVoid && !method.returnType.isNullable && !method.isRequired) { - result.add(Error( - message: - 'Callback methods that return a non-null value must be non-null: ${method.name}.', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: + 'Callback methods that return a non-null value must be non-null: ${method.name}.', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } if (method.isStatic) { - result.add(Error( - message: 'Static callback methods are not supported: ${method.name}.', - lineNumber: _calculateLineNumberNullable(source, method.offset), - )); + result.add( + Error( + message: + 'Static callback methods are not supported: ${method.name}.', + lineNumber: _calculateLineNumberNullable(source, method.offset), + ), + ); } } } @@ -1054,31 +1200,40 @@ List _validateProxyApi( result.add(unsupportedDataClassError(field)); } else if (field.isStatic) { if (!isProxyApi(field)) { - result.add(Error( - message: - 'Static fields are considered attached fields and must be a ProxyApi: ${field.type.baseName}', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Static fields are considered attached fields and must be a ProxyApi: ${field.type.baseName}', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } else if (field.type.isNullable) { - result.add(Error( - message: - 'Static fields are considered attached fields and must not be nullable: ${field.type.baseName}?', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Static fields are considered attached fields and must not be nullable: ${field.type.baseName}?', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } } else if (field.isAttached) { if (!isProxyApi(field)) { - result.add(Error( - message: 'Attached fields must be a ProxyApi: ${field.type.baseName}', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Attached fields must be a ProxyApi: ${field.type.baseName}', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } if (field.type.isNullable) { - result.add(Error( - message: - 'Attached fields must not be nullable: ${field.type.baseName}?', - lineNumber: _calculateLineNumberNullable(source, field.offset), - )); + result.add( + Error( + message: + 'Attached fields must not be nullable: ${field.type.baseName}?', + lineNumber: _calculateLineNumberNullable(source, field.offset), + ), + ); } } } @@ -1149,13 +1304,16 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { _storeCurrentApi(); _storeCurrentClass(); - final Map> referencedTypes = - getReferencedTypes(_apis, _classes); + final Map> referencedTypes = getReferencedTypes( + _apis, + _classes, + ); 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)); + nonReferencedTypes.removeWhere( + (Class x) => referencedTypeNames.contains(x.name), + ); for (final Class x in nonReferencedTypes) { x.isReferenced = false; } @@ -1206,12 +1364,16 @@ 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); - totalErrors.add(Error( + final int? lineNumber = + element.value.isEmpty + ? null + : calculateLineNumber(source, element.value.first); + totalErrors.add( + Error( message: 'Unknown type: ${element.key.baseName}', - lineNumber: lineNumber)); + lineNumber: lineNumber, + ), + ); } } for (final Class classDefinition in _classes) { @@ -1250,9 +1412,10 @@ 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, ); @@ -1260,13 +1423,16 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { TypeDeclaration _attachAssociatedDefinition(TypeDeclaration type) { final Enum? assocEnum = _enums.firstWhereOrNull( - (Enum enumDefinition) => enumDefinition.name == type.baseName); + (Enum enumDefinition) => enumDefinition.name == type.baseName, + ); final Class? assocClass = _classes.firstWhereOrNull( - (Class classDefinition) => classDefinition.name == type.baseName); - final AstProxyApi? assocProxyApi = - _apis.whereType().firstWhereOrNull( - (Api apiDefinition) => apiDefinition.name == type.baseName, - ); + (Class classDefinition) => classDefinition.name == type.baseName, + ); + final AstProxyApi? assocProxyApi = _apis + .whereType() + .firstWhereOrNull( + (Api apiDefinition) => apiDefinition.name == type.baseName, + ); if (assocClass != null) { type = type.copyWithClass(assocClass); } else if (assocEnum != null) { @@ -1315,13 +1481,16 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { for (final dart_ast.Expression argument in expression.argumentList.arguments) { if (argument is dart_ast.NamedExpression) { - result[argument.name.label.name] = - _expressionToMap(argument.expression); + result[argument.name.label.name] = _expressionToMap( + argument.expression, + ); } else { - _errors.add(Error( - message: 'expected NamedExpression but found $expression', - lineNumber: calculateLineNumber(source, argument.offset), - )); + _errors.add( + Error( + message: 'expected NamedExpression but found $expression', + lineNumber: calculateLineNumber(source, argument.offset), + ), + ); } } return result; @@ -1339,10 +1508,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (element is dart_ast.Expression) { list.add(_expressionToMap(element)); } else { - _errors.add(Error( - message: 'expected Expression but found $element', - lineNumber: calculateLineNumber(source, element.offset), - )); + _errors.add( + Error( + message: 'expected Expression but found $element', + lineNumber: calculateLineNumber(source, element.offset), + ), + ); } } return list; @@ -1352,19 +1523,23 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (element is dart_ast.Expression) { set.add(_expressionToMap(element)); } else { - _errors.add(Error( - message: 'expected Expression but found $element', - lineNumber: calculateLineNumber(source, element.offset), - )); + _errors.add( + Error( + message: 'expected Expression but found $element', + lineNumber: calculateLineNumber(source, element.offset), + ), + ); } } return set; } else { - _errors.add(Error( - message: - 'unrecognized expression type ${expression.runtimeType} $expression', - lineNumber: calculateLineNumber(source, expression.offset), - )); + _errors.add( + Error( + message: + 'unrecognized expression type ${expression.runtimeType} $expression', + lineNumber: calculateLineNumber(source, expression.offset), + ), + ); return 0; } } @@ -1372,11 +1547,13 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { @override Object? visitImportDirective(dart_ast.ImportDirective node) { if (node.uri.stringValue != 'package:pigeon/pigeon.dart') { - _errors.add(Error( - message: - "Unsupported import ${node.uri}, only imports of 'package:pigeon/pigeon.dart' are supported.", - lineNumber: calculateLineNumber(source, node.offset), - )); + _errors.add( + Error( + message: + "Unsupported import ${node.uri}, only imports of 'package:pigeon/pigeon.dart' are supported.", + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } return null; } @@ -1385,10 +1562,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { Object? visitAnnotation(dart_ast.Annotation node) { if (node.name.name == 'ConfigurePigeon') { if (node.arguments == null) { - _errors.add(Error( - message: 'ConfigurePigeon expects a PigeonOptions() call.', - lineNumber: calculateLineNumber(source, node.offset), - )); + _errors.add( + Error( + message: 'ConfigurePigeon expects a PigeonOptions() call.', + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } final Map pigeonOptionsMap = _expressionToMap(node.arguments!.arguments.first) @@ -1408,14 +1587,18 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (node.metadata.length > 2 || (node.metadata.length > 1 && !_hasMetadata(node.metadata, 'ConfigurePigeon'))) { - _errors.add(Error( + _errors.add( + Error( message: 'API "${node.name.lexeme}" can only have one API annotation but contains: ${node.metadata}', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } if (_hasMetadata(node.metadata, 'HostApi')) { final dart_ast.Annotation hostApi = node.metadata.firstWhere( - (dart_ast.Annotation element) => element.name.name == 'HostApi'); + (dart_ast.Annotation element) => element.name.name == 'HostApi', + ); String? dartHostTestHandler; if (hostApi.arguments != null) { for (final dart_ast.Expression expression @@ -1437,15 +1620,17 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: node.name.lexeme, methods: [], dartHostTestHandler: dartHostTestHandler, - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ); } else if (_hasMetadata(node.metadata, 'FlutterApi')) { _currentApi = AstFlutterApi( name: node.name.lexeme, methods: [], - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ); } else if (_hasMetadata(node.metadata, 'ProxyApi')) { final dart_ast.Annotation proxyApiAnnotation = node.metadata.firstWhere( @@ -1456,8 +1641,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { for (final dart_ast.Expression expression in proxyApiAnnotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { - annotationMap[expression.name.label.name] = - _expressionToMap(expression.expression); + annotationMap[expression.name.label.name] = _expressionToMap( + expression.expression, + ); } } @@ -1487,10 +1673,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (node.implementsClause != null) { for (final dart_ast.NamedType type in node.implementsClause!.interfaces) { - interfaces.add(TypeDeclaration( - baseName: type.name2.lexeme, - isNullable: false, - )); + interfaces.add( + TypeDeclaration(baseName: type.name2.lexeme, isNullable: false), + ); } } @@ -1547,8 +1732,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { interfaces: interfaces, swiftOptions: swiftOptions, kotlinOptions: kotlinOptions, - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ); } else if (_hasMetadata(node.metadata, 'EventChannelApi')) { final dart_ast.Annotation annotation = node.metadata.firstWhere( @@ -1560,8 +1746,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { for (final dart_ast.Expression expression in annotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { - annotationMap[expression.name.label.name] = - _expressionToMap(expression.expression); + annotationMap[expression.name.label.name] = _expressionToMap( + expression.expression, + ); } } @@ -1588,8 +1775,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { methods: [], swiftOptions: swiftOptions, kotlinOptions: kotlinOptions, - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ); } } else { @@ -1598,11 +1786,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { fields: [], superClassName: node.implementsClause?.interfaces.first.name2.toString() ?? - node.extendsClause?.superclass.name2.toString(), + node.extendsClause?.superclass.name2.toString(), isSealed: node.sealedKeyword != null, isSwiftClass: _hasMetadata(node.metadata, 'SwiftClass'), - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ); } @@ -1614,9 +1803,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { List _documentationCommentsParser(List? comments) { const String docCommentPrefix = '///'; return comments - ?.map((Token line) => line.length > docCommentPrefix.length - ? line.toString().substring(docCommentPrefix.length) - : '') + ?.map( + (Token line) => + line.length > docCommentPrefix.length + ? line.toString().substring(docCommentPrefix.length) + : '', + ) .toList() ?? []; } @@ -1704,14 +1896,13 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { parameters.parameters.map(_formalParameterToPigeonParameter).toList(); final bool isAsynchronous = _hasMetadata(node.metadata, 'async'); final bool isStatic = _hasMetadata(node.metadata, 'static'); - final String objcSelector = _findMetadata(node.metadata, 'ObjCSelector') - ?.arguments - ?.arguments - .first + final String objcSelector = + _findMetadata(node.metadata, 'ObjCSelector')?.arguments?.arguments.first .asNullable() ?.value ?? ''; - final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') + final String swiftFunction = + _findMetadata(node.metadata, 'SwiftFunction') ?.arguments ?.arguments .first @@ -1720,15 +1911,15 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ''; final dart_ast.ArgumentList? taskQueueArguments = _findMetadata(node.metadata, 'TaskQueue')?.arguments; - final String? taskQueueTypeName = taskQueueArguments == null - ? null - : _getFirstChildOfType(taskQueueArguments) - ?.expression - .asNullable() - ?.name; + final String? taskQueueTypeName = + taskQueueArguments == null + ? null + : _getFirstChildOfType( + taskQueueArguments, + )?.expression.asNullable()?.name; final TaskQueueType taskQueueType = _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? - TaskQueueType.serial; + TaskQueueType.serial; if (_currentApi != null) { // Methods without named return types aren't supported. @@ -1738,10 +1929,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { Method( name: node.name.lexeme, returnType: TypeDeclaration( - baseName: _getNamedTypeQualifiedName(returnType), - typeArguments: - _typeAnnotationsToTypeArguments(returnType.typeArguments), - isNullable: returnType.question != null), + baseName: _getNamedTypeQualifiedName(returnType), + typeArguments: _typeAnnotationsToTypeArguments( + returnType.typeArguments, + ), + isNullable: returnType.question != null, + ), parameters: arguments, isStatic: isStatic, location: switch (_currentApi!) { @@ -1755,15 +1948,19 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { swiftFunction: swiftFunction, offset: node.offset, taskQueueType: taskQueueType, - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ), ); } else if (_currentClass != null) { - _errors.add(Error( + _errors.add( + Error( message: 'Methods aren\'t supported in Pigeon data classes ("${node.name.lexeme}").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } node.visitChildren(this); return null; @@ -1771,32 +1968,43 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { @override Object? visitEnumDeclaration(dart_ast.EnumDeclaration node) { - _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(), - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), - )); + _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(), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), + ), + ); node.visitChildren(this); return null; } List _typeAnnotationsToTypeArguments( - dart_ast.TypeArgumentList? typeArguments) { + dart_ast.TypeArgumentList? typeArguments, + ) { final List result = []; if (typeArguments != null) { for (final Object x in typeArguments.childEntities) { if (x is dart_ast.NamedType) { - result.add(TypeDeclaration( + result.add( + TypeDeclaration( baseName: _getNamedTypeQualifiedName(x), isNullable: x.question != null, - typeArguments: _typeAnnotationsToTypeArguments(x.typeArguments))); + typeArguments: _typeAnnotationsToTypeArguments(x.typeArguments), + ), + ); } } } @@ -1808,18 +2016,24 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final dart_ast.TypeAnnotation? type = node.fields.type; if (_currentClass != null) { if (node.isStatic) { - _errors.add(Error( + _errors.add( + Error( message: 'Pigeon doesn\'t support static fields ("$node"), consider using enums.', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } else if (type is dart_ast.NamedType) { final _FindInitializer findInitializerVisitor = _FindInitializer(); node.visitChildren(findInitializerVisitor); if (findInitializerVisitor.initializer != null) { - _errors.add(Error( + _errors.add( + Error( message: 'Initialization isn\'t supported for fields in Pigeon data classes ("$node"), just use nullable types with no initializer (example "int? x;").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } else { final dart_ast.TypeArgumentList? typeArguments = type.typeArguments; final String name = node.fields.variables[0].name.lexeme; @@ -1832,22 +2046,29 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: name, offset: node.offset, defaultValue: _currentClassDefaultValues[name], - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ); _currentClass!.fields.add(field); } } else { - _errors.add(Error( + _errors.add( + Error( message: 'Expected a named type but found "$node".', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } } else if (_currentApi is AstProxyApi) { _addProxyApiField(type, node); } else if (_currentApi != null) { - _errors.add(Error( + _errors.add( + Error( message: 'Fields aren\'t supported in Pigeon API classes ("$node").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } node.visitChildren(this); return null; @@ -1859,7 +2080,8 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final dart_ast.FormalParameterList parameters = node.parameters; final List arguments = parameters.parameters.map(_formalParameterToPigeonParameter).toList(); - final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') + final String swiftFunction = + _findMetadata(node.metadata, 'SwiftFunction') ?.arguments ?.arguments .first @@ -1868,31 +2090,40 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ''; (_currentApi as AstProxyApi?)!.constructors.add( - Constructor( - name: node.name?.lexeme ?? '', - parameters: arguments, - swiftFunction: swiftFunction, - offset: node.offset, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), - ), - ); + Constructor( + name: node.name?.lexeme ?? '', + parameters: arguments, + swiftFunction: swiftFunction, + offset: node.offset, + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), + ), + ); } else if (_currentApi != null) { - _errors.add(Error( + _errors.add( + Error( message: 'Constructors aren\'t supported in API classes ("$node").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } else { if (node.body.beginToken.lexeme != ';') { - _errors.add(Error( + _errors.add( + Error( message: 'Constructor bodies aren\'t supported in data classes ("$node").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } else if (node.initializers.isNotEmpty) { - _errors.add(Error( + _errors.add( + Error( message: 'Constructor initializers aren\'t supported in data classes (use "this.fieldName") ("$node").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } else { for (final dart_ast.FormalParameter param in node.parameters.parameters) { @@ -1923,10 +2154,12 @@ 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 String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') + final List parameters = + type.parameters.parameters + .map(_formalParameterToPigeonParameter) + .toList(); + final String swiftFunction = + _findMetadata(node.metadata, 'SwiftFunction') ?.arguments ?.arguments .first @@ -1935,15 +2168,15 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ''; final dart_ast.ArgumentList? taskQueueArguments = _findMetadata(node.metadata, 'TaskQueue')?.arguments; - final String? taskQueueTypeName = taskQueueArguments == null - ? null - : _getFirstChildOfType(taskQueueArguments) - ?.expression - .asNullable() - ?.name; + final String? taskQueueTypeName = + taskQueueArguments == null + ? null + : _getFirstChildOfType( + taskQueueArguments, + )?.expression.asNullable()?.name; final TaskQueueType taskQueueType = _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? - TaskQueueType.serial; + TaskQueueType.serial; // Methods without named return types aren't supported. final dart_ast.TypeAnnotation returnType = type.returnType!; @@ -1954,8 +2187,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: node.fields.variables[0].name.lexeme, returnType: TypeDeclaration( baseName: _getNamedTypeQualifiedName(returnType), - typeArguments: - _typeAnnotationsToTypeArguments(returnType.typeArguments), + typeArguments: _typeAnnotationsToTypeArguments( + returnType.typeArguments, + ), isNullable: returnType.question != null, ), location: ApiLocation.flutter, @@ -1966,38 +2200,40 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { swiftFunction: swiftFunction, offset: node.offset, taskQueueType: taskQueueType, - documentationComments: - _documentationCommentsParser(node.documentationComment?.tokens), + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ), ); } else if (type is dart_ast.NamedType) { final _FindInitializer findInitializerVisitor = _FindInitializer(); node.visitChildren(findInitializerVisitor); if (findInitializerVisitor.initializer != null) { - _errors.add(Error( + _errors.add( + Error( message: 'Initialization isn\'t supported for fields in ProxyApis ("$node"), just use nullable types with no initializer (example "int? x;").', - lineNumber: calculateLineNumber(source, node.offset))); + lineNumber: calculateLineNumber(source, node.offset), + ), + ); } else { final dart_ast.TypeArgumentList? typeArguments = type.typeArguments; (_currentApi as AstProxyApi?)!.fields.add( - ApiField( - type: TypeDeclaration( - baseName: _getNamedTypeQualifiedName(type), - isNullable: type.question != null, - typeArguments: _typeAnnotationsToTypeArguments( - typeArguments, - ), - ), - name: node.fields.variables[0].name.lexeme, - isAttached: _hasMetadata(node.metadata, 'attached') || isStatic, - isStatic: isStatic, - offset: node.offset, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), - ), - ); + ApiField( + type: TypeDeclaration( + baseName: _getNamedTypeQualifiedName(type), + isNullable: type.question != null, + typeArguments: _typeAnnotationsToTypeArguments(typeArguments), + ), + name: node.fields.variables[0].name.lexeme, + isAttached: _hasMetadata(node.metadata, 'attached') || isStatic, + isStatic: isStatic, + offset: node.offset, + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), + ), + ); } } } diff --git a/packages/pigeon/lib/src/swift/swift_generator.dart b/packages/pigeon/lib/src/swift/swift_generator.dart index affc81c3017..fe049e6f9eb 100644 --- a/packages/pigeon/lib/src/swift/swift_generator.dart +++ b/packages/pigeon/lib/src/swift/swift_generator.dart @@ -94,13 +94,13 @@ class InternalSwiftOptions extends InternalOptions { SwiftOptions options, { required this.swiftOut, Iterable? copyrightHeader, - }) : copyrightHeader = options.copyrightHeader ?? copyrightHeader, - fileSpecificClassNameComponent = - options.fileSpecificClassNameComponent ?? - swiftOut.split('/').lastOrNull?.split('.').firstOrNull ?? - '', - errorClassName = options.errorClassName, - includeErrorClass = options.includeErrorClass; + }) : copyrightHeader = options.copyrightHeader ?? copyrightHeader, + fileSpecificClassNameComponent = + options.fileSpecificClassNameComponent ?? + swiftOut.split('/').lastOrNull?.split('.').firstOrNull ?? + '', + errorClassName = options.errorClassName, + includeErrorClass = options.includeErrorClass; /// A copyright header that will get prepended to generated code. final Iterable? copyrightHeader; @@ -233,13 +233,19 @@ class SwiftGenerator extends StructuredGenerator { }) { indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); + indent, + anEnum.documentationComments, + _docCommentSpec, + ); indent.write('enum ${anEnum.name}: Int '); indent.addScoped('{', '}', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( - indent, member.documentationComments, _docCommentSpec); + indent, + member.documentationComments, + _docCommentSpec, + ); indent.writeln('case ${_camelCase(member.name)} = $index'); }); }); @@ -265,28 +271,41 @@ class SwiftGenerator extends StructuredGenerator { indent.nest(1, () { if (customType.type == CustomTypes.customEnum) { indent.writeln( - 'let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)'); - indent.writeScoped('if let enumResultAsInt = enumResultAsInt {', '}', - () { - indent.writeln( - 'return ${customType.name}(rawValue: enumResultAsInt)'); - }); + 'let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)', + ); + indent.writeScoped( + 'if let enumResultAsInt = enumResultAsInt {', + '}', + () { + indent.writeln( + 'return ${customType.name}(rawValue: enumResultAsInt)', + ); + }, + ); indent.writeln('return nil'); } else { indent.writeln( - 'return ${customType.name}.fromList(self.readValue() as! [Any?])'); + 'return ${customType.name}.fromList(self.readValue() as! [Any?])', + ); } }); } final EnumeratedType overflowClass = EnumeratedType( - _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass); + _overflowClassName, + maximumCodecFieldKey, + CustomTypes.customClass, + ); if (root.requiresOverflowClass) { indent.newln(); _writeCodecOverflowUtilities( - generatorOptions, root, indent, enumeratedTypes, - dartPackageName: dartPackageName); + generatorOptions, + root, + indent, + enumeratedTypes, + dartPackageName: dartPackageName, + ); } indent.newln(); @@ -340,7 +359,8 @@ class SwiftGenerator extends StructuredGenerator { : maximumCodecFieldKey; if (customType.enumeration >= maximumCodecFieldKey) { indent.writeln( - 'let wrap = $_overflowClassName(type: ${customType.enumeration - maximumCodecFieldKey}, wrapped: value.$encodeString)'); + 'let wrap = $_overflowClassName(type: ${customType.enumeration - maximumCodecFieldKey}, wrapped: value.$encodeString)', + ); } indent.writeln('super.writeByte($enumeration)'); indent.writeln('super.writeValue($valueString)'); @@ -355,17 +375,20 @@ class SwiftGenerator extends StructuredGenerator { indent.newln(); // Generate ReaderWriter - indent - .write('private class $readerWriterName: FlutterStandardReaderWriter '); + indent.write( + 'private class $readerWriterName: FlutterStandardReaderWriter ', + ); indent.addScoped('{', '}', () { indent.write( - 'override func reader(with data: Data) -> FlutterStandardReader '); + 'override func reader(with data: Data) -> FlutterStandardReader ', + ); indent.addScoped('{', '}', () { indent.writeln('return $readerName(data: data)'); }); indent.newln(); indent.write( - 'override func writer(with data: NSMutableData) -> FlutterStandardWriter '); + 'override func writer(with data: NSMutableData) -> FlutterStandardWriter ', + ); indent.addScoped('{', '}', () { indent.writeln('return $writerName(data: data)'); }); @@ -374,15 +397,18 @@ class SwiftGenerator extends StructuredGenerator { // Generate Codec indent.write( - 'class $codecName: FlutterStandardMessageCodec, @unchecked Sendable '); + 'class $codecName: FlutterStandardMessageCodec, @unchecked Sendable ', + ); indent.addScoped('{', '}', () { indent.writeln( - 'static let shared = $codecName(readerWriter: $readerWriterName())'); + 'static let shared = $codecName(readerWriter: $readerWriterName())', + ); }); indent.newln(); if (root.containsEventChannel) { indent.writeln( - 'var ${_getMethodCodecVarName(generatorOptions)} = FlutterStandardMethodCodec(readerWriter: $readerWriterName());'); + 'var ${_getMethodCodecVarName(generatorOptions)} = FlutterStandardMethodCodec(readerWriter: $readerWriterName());', + ); indent.newln(); } } @@ -394,24 +420,28 @@ class SwiftGenerator extends StructuredGenerator { bool hashable = true, }) { final String privateString = private ? 'private ' : ''; - final String extendsString = classDefinition.superClass != null - ? ': ${classDefinition.superClass!.name}' - : hashable + final String extendsString = + classDefinition.superClass != null + ? ': ${classDefinition.superClass!.name}' + : hashable ? ': Hashable' : ''; if (classDefinition.isSwiftClass) { indent.write( - '${privateString}class ${classDefinition.name}$extendsString '); + '${privateString}class ${classDefinition.name}$extendsString ', + ); } else if (classDefinition.isSealed) { indent.write('protocol ${classDefinition.name} '); } else { indent.write( - '${privateString}struct ${classDefinition.name}$extendsString '); + '${privateString}struct ${classDefinition.name}$extendsString ', + ); } indent.addScoped('{', '', () { - final Iterable fields = - getFieldsInSerializationOrder(classDefinition); + final Iterable fields = getFieldsInSerializationOrder( + classDefinition, + ); if (classDefinition.isSwiftClass) { _writeClassInit(indent, fields.toList()); @@ -419,7 +449,10 @@ class SwiftGenerator extends StructuredGenerator { for (final NamedType field in fields) { addDocumentationComments( - indent, field.documentationComments, _docCommentSpec); + indent, + field.documentationComments, + _docCommentSpec, + ); indent.write('var '); _writeClassField(indent, field, addNil: !classDefinition.isSwiftClass); indent.newln(); @@ -435,17 +468,21 @@ class SwiftGenerator extends StructuredGenerator { required String dartPackageName, }) { final NamedType overflowInt = NamedType( - name: 'type', - type: const TypeDeclaration(baseName: 'Int', isNullable: false)); + name: 'type', + type: const TypeDeclaration(baseName: 'Int', isNullable: false), + ); final NamedType overflowObject = NamedType( - name: 'wrapped', - type: const TypeDeclaration(baseName: 'Object', isNullable: true)); + name: 'wrapped', + type: const TypeDeclaration(baseName: 'Object', isNullable: true), + ); final List overflowFields = [ overflowInt, overflowObject, ]; - final Class overflowClass = - Class(name: _overflowClassName, fields: overflowFields); + final Class overflowClass = Class( + name: _overflowClassName, + fields: overflowFields, + ); indent.newln(); _writeDataClassSignature( indent, @@ -485,16 +522,22 @@ if (wrapped == nil) { '''); indent.writeScoped('switch type {', '}', () { for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) { - indent.writeScoped('case ${i - totalCustomCodecKeysAllowed}:', '', - () { - if (types[i].type == CustomTypes.customClass) { - indent.writeln( - 'return ${types[i].name}.fromList(wrapped as! [Any?]);'); - } else if (types[i].type == CustomTypes.customEnum) { - indent.writeln( - 'return ${types[i].name}(rawValue: wrapped as! Int);'); - } - }, addTrailingNewline: false); + indent.writeScoped( + 'case ${i - totalCustomCodecKeysAllowed}:', + '', + () { + if (types[i].type == CustomTypes.customClass) { + indent.writeln( + 'return ${types[i].name}.fromList(wrapped as! [Any?]);', + ); + } else if (types[i].type == CustomTypes.customEnum) { + indent.writeln( + 'return ${types[i].name}(rawValue: wrapped as! Int);', + ); + } + }, + addTrailingNewline: false, + ); } indent.writeScoped('default: ', '', () { indent.writeln('return nil'); @@ -513,16 +556,20 @@ if (wrapped == nil) { required String dartPackageName, }) { final List generatedComments = [ - ' Generated class from Pigeon that represents data sent in messages.' + ' Generated class from Pigeon that represents data sent in messages.', ]; if (classDefinition.isSealed) { generatedComments.add( - ' This protocol should not be extended by any user class outside of the generated file.'); + ' This protocol should not be extended by any user class outside of the generated file.', + ); } indent.newln(); addDocumentationComments( - indent, classDefinition.documentationComments, _docCommentSpec, - generatorComments: generatedComments); + indent, + classDefinition.documentationComments, + _docCommentSpec, + generatorComments: generatedComments, + ); _writeDataClassSignature(indent, classDefinition); indent.writeScoped('', '}', () { if (classDefinition.isSealed) { @@ -597,8 +644,9 @@ if (wrapped == nil) { // Follow swift-format style, which is to use a trailing comma unless // there is only one element. final String separator = classDefinition.fields.length > 1 ? ',' : ''; - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { indent.writeln('${field.name}$separator'); } }); @@ -614,20 +662,24 @@ if (wrapped == nil) { required String dartPackageName, }) { indent.writeScoped( - 'static func == (lhs: ${classDefinition.name}, rhs: ${classDefinition.name}) -> Bool {', - '}', () { - if (classDefinition.isSwiftClass) { - indent.writeScoped('if (lhs === rhs) {', '}', () { - indent.writeln('return true'); - }); - } - indent.write( - 'return deepEquals${generatorOptions.fileSpecificClassNameComponent}(lhs.toList(), rhs.toList())'); - }); + 'static func == (lhs: ${classDefinition.name}, rhs: ${classDefinition.name}) -> Bool {', + '}', + () { + if (classDefinition.isSwiftClass) { + indent.writeScoped('if (lhs === rhs) {', '}', () { + indent.writeln('return true'); + }); + } + indent.write( + 'return deepEquals${generatorOptions.fileSpecificClassNameComponent}(lhs.toList(), rhs.toList())', + ); + }, + ); indent.writeScoped('func hash(into hasher: inout Hasher) {', '}', () { indent.writeln( - 'deepHash${generatorOptions.fileSpecificClassNameComponent}(value: toList(), hasher: &hasher)'); + 'deepHash${generatorOptions.fileSpecificClassNameComponent}(value: toList(), hasher: &hasher)', + ); }); } @@ -642,11 +694,14 @@ if (wrapped == nil) { final String className = classDefinition.name; indent.writeln('// swift-format-ignore: AlwaysUseLowerCamelCase'); indent.write( - 'static func fromList(_ ${varNamePrefix}list: [Any?]) -> $className? '); + 'static func fromList(_ ${varNamePrefix}list: [Any?]) -> $className? ', + ); indent.addScoped('{', '}', () { - enumerate(getFieldsInSerializationOrder(classDefinition), - (int index, final NamedType field) { + enumerate(getFieldsInSerializationOrder(classDefinition), ( + int index, + final NamedType field, + ) { final String listValue = '${varNamePrefix}list[$index]'; _writeGenericCasting( @@ -661,8 +716,9 @@ if (wrapped == nil) { indent.newln(); indent.write('return '); indent.addScoped('$className(', ')', () { - for (final NamedType field - in getFieldsInSerializationOrder(classDefinition)) { + for (final NamedType field in getFieldsInSerializationOrder( + classDefinition, + )) { final String comma = getFieldsInSerializationOrder(classDefinition).last == field ? '' @@ -672,12 +728,14 @@ if (wrapped == nil) { final String forceUnwrapMapWithNullableEnums = (field.type.baseName == 'Map' && !field.type.isNullable && - field.type.typeArguments - .any((TypeDeclaration type) => type.isEnum)) + field.type.typeArguments.any( + (TypeDeclaration type) => type.isEnum, + )) ? '!' : ''; indent.writeln( - '${field.name}: ${field.name}$forceUnwrapMapWithNullableEnums$comma'); + '${field.name}: ${field.name}$forceUnwrapMapWithNullableEnums$comma', + ); } }); }); @@ -690,13 +748,19 @@ if (wrapped == nil) { Indent indent, { required String dartPackageName, }) { - if (root.apis.any((Api api) => - api is AstHostApi && - api.methods.any((Method it) => it.isAsynchronous))) { + if (root.apis.any( + (Api api) => + api is AstHostApi && + api.methods.any((Method it) => it.isAsynchronous), + )) { indent.newln(); } - super.writeApis(generatorOptions, root, indent, - dartPackageName: dartPackageName); + super.writeApis( + generatorOptions, + root, + indent, + dartPackageName: dartPackageName, + ); } /// Writes the code for a flutter [Api], [api]. @@ -715,24 +779,33 @@ if (wrapped == nil) { required String dartPackageName, }) { const List generatedComments = [ - ' Generated protocol from Pigeon that represents Flutter messages that can be called from Swift.' + ' Generated protocol from Pigeon that represents Flutter messages that can be called from Swift.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedComments); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedComments, + ); indent.addScoped('protocol ${api.name}Protocol {', '}', () { for (final Method func in api.methods) { addDocumentationComments( - indent, func.documentationComments, _docCommentSpec); - indent.writeln(_getMethodSignature( - name: func.name, - parameters: func.parameters, - returnType: func.returnType, - errorTypeName: _getErrorClassName(generatorOptions), - isAsynchronous: true, - swiftFunction: func.swiftFunction, - getParameterName: _getSafeArgumentName, - )); + indent, + func.documentationComments, + _docCommentSpec, + ); + indent.writeln( + _getMethodSignature( + name: func.name, + parameters: func.parameters, + returnType: func.returnType, + errorTypeName: _getErrorClassName(generatorOptions), + isAsynchronous: true, + swiftFunction: func.swiftFunction, + getParameterName: _getSafeArgumentName, + ), + ); } }); @@ -741,11 +814,13 @@ if (wrapped == nil) { indent.writeln('private let binaryMessenger: FlutterBinaryMessenger'); indent.writeln('private let messageChannelSuffix: String'); indent.write( - 'init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") '); + 'init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") ', + ); indent.addScoped('{', '}', () { indent.writeln('self.binaryMessenger = binaryMessenger'); indent.writeln( - r'self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""'); + r'self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""', + ); }); final String codecName = _getMessageCodecName(generatorOptions); indent.write('var codec: $codecName '); @@ -755,7 +830,10 @@ if (wrapped == nil) { for (final Method func in api.methods) { addDocumentationComments( - indent, func.documentationComments, _docCommentSpec); + indent, + func.documentationComments, + _docCommentSpec, + ); _writeFlutterMethod( indent, generatorOptions: generatorOptions, @@ -786,44 +864,59 @@ if (wrapped == nil) { final String apiName = api.name; const List generatedComments = [ - ' Generated protocol from Pigeon that represents a handler of messages from Flutter.' + ' Generated protocol from Pigeon that represents a handler of messages from Flutter.', ]; - addDocumentationComments(indent, api.documentationComments, _docCommentSpec, - generatorComments: generatedComments); + addDocumentationComments( + indent, + api.documentationComments, + _docCommentSpec, + generatorComments: generatedComments, + ); indent.write('protocol $apiName '); indent.addScoped('{', '}', () { for (final Method method in api.methods) { addDocumentationComments( - indent, method.documentationComments, _docCommentSpec); - indent.writeln(_getMethodSignature( - name: method.name, - parameters: method.parameters, - returnType: method.returnType, - errorTypeName: 'Error', - isAsynchronous: method.isAsynchronous, - swiftFunction: method.swiftFunction, - )); + indent, + method.documentationComments, + _docCommentSpec, + ); + indent.writeln( + _getMethodSignature( + name: method.name, + parameters: method.parameters, + returnType: method.returnType, + errorTypeName: 'Error', + isAsynchronous: method.isAsynchronous, + swiftFunction: method.swiftFunction, + ), + ); } }); indent.newln(); indent.writeln( - '$_docCommentPrefix Generated setup class from Pigeon to handle messages through the `binaryMessenger`.'); + '$_docCommentPrefix Generated setup class from Pigeon to handle messages through the `binaryMessenger`.', + ); indent.write('class ${apiName}Setup '); indent.addScoped('{', '}', () { indent.writeln( - 'static var codec: FlutterStandardMessageCodec { ${_getMessageCodecName(generatorOptions)}.shared }'); + 'static var codec: FlutterStandardMessageCodec { ${_getMessageCodecName(generatorOptions)}.shared }', + ); indent.writeln( - '$_docCommentPrefix Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`.'); + '$_docCommentPrefix Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`.', + ); indent.write( - 'static func setUp(binaryMessenger: FlutterBinaryMessenger, api: $apiName?, messageChannelSuffix: String = "") '); + 'static func setUp(binaryMessenger: FlutterBinaryMessenger, api: $apiName?, messageChannelSuffix: String = "") ', + ); indent.addScoped('{', '}', () { indent.writeln( - r'let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""'); + r'let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""', + ); String? serialBackgroundQueue; - if (api.methods.any((Method m) => - m.taskQueueType == TaskQueueType.serialBackgroundThread)) { + if (api.methods.any( + (Method m) => m.taskQueueType == TaskQueueType.serialBackgroundThread, + )) { serialBackgroundQueue = 'taskQueue'; // TODO(stuartmorgan): Remove the ? once macOS supports task queues // and this is no longer an optional protocol method. @@ -880,26 +973,20 @@ if (wrapped == nil) { '${swiftInstanceManagerClassName(generatorOptions)}Api'; final String removeStrongReferenceName = - makeRemoveStrongReferenceChannelName( - dartPackageName, - ); + makeRemoveStrongReferenceChannelName(dartPackageName); indent.writeScoped('private class $instanceManagerApiName {', '}', () { - addDocumentationComments( - indent, - [' The codec used for serializing messages.'], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' The codec used for serializing messages.', + ], _docCommentSpec); indent.writeln( 'var codec: FlutterStandardMessageCodec { ${_getMessageCodecName(generatorOptions)}.shared }', ); indent.newln(); - addDocumentationComments( - indent, - [' Handles sending and receiving messages with Dart.'], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Handles sending and receiving messages with Dart.', + ], _docCommentSpec); indent.writeln('unowned let binaryMessenger: FlutterBinaryMessenger'); indent.newln(); @@ -912,13 +999,9 @@ if (wrapped == nil) { ); indent.newln(); - addDocumentationComments( - indent, - [ - ' Sets up an instance of `$instanceManagerApiName` to handle messages through the `binaryMessenger`.', - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Sets up an instance of `$instanceManagerApiName` to handle messages through the `binaryMessenger`.', + ], _docCommentSpec); indent.writeScoped( 'static func setUpMessageHandlers(binaryMessenger: FlutterBinaryMessenger, instanceManager: ${swiftInstanceManagerClassName(generatorOptions)}?) {', '}', @@ -935,10 +1018,7 @@ if (wrapped == nil) { parameters: [ Parameter( name: 'identifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], returnType: const TypeDeclaration.voidDeclaration(), @@ -972,13 +1052,9 @@ if (wrapped == nil) { ); indent.newln(); - addDocumentationComments( - indent, - [ - ' Sends a message to the Dart `InstanceManager` to remove the strong reference of the instance associated with `identifier`.', - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' Sends a message to the Dart `InstanceManager` to remove the strong reference of the instance associated with `identifier`.', + ], _docCommentSpec); _writeFlutterMethod( indent, generatorOptions: generatorOptions, @@ -987,7 +1063,7 @@ if (wrapped == nil) { Parameter( name: 'identifier', type: const TypeDeclaration(baseName: 'int', isNullable: false), - ) + ), ], returnType: const TypeDeclaration.voidDeclaration(), channelName: removeStrongReferenceName, @@ -1020,9 +1096,7 @@ if (wrapped == nil) { 'private class ${proxyApiReaderWriterName(generatorOptions)}: FlutterStandardReaderWriter {', '}', () { - indent.writeln( - 'unowned let pigeonRegistrar: $registrarName', - ); + indent.writeln('unowned let pigeonRegistrar: $registrarName'); indent.newln(); indent.writeScoped( @@ -1046,8 +1120,7 @@ if (wrapped == nil) { 'override func readValue(ofType type: UInt8) -> Any? {', '}', () { - indent.format( - ''' + indent.format(''' switch type { case $proxyApiCodecInstanceManagerKey: let identifier = self.readValue() @@ -1059,8 +1132,7 @@ if (wrapped == nil) { return instance default: return super.readValue(ofType: type) - }''', - ); + }'''); }, ); }, @@ -1071,9 +1143,7 @@ if (wrapped == nil) { 'private class $filePrefix${classNamePrefix}ProxyApiCodecWriter: ${_getMessageCodecName(generatorOptions)}Writer {', '}', () { - indent.writeln( - 'unowned let pigeonRegistrar: $registrarName', - ); + indent.writeln('unowned let pigeonRegistrar: $registrarName'); indent.newln(); indent.writeScoped( @@ -1086,79 +1156,73 @@ if (wrapped == nil) { ); indent.newln(); - indent.writeScoped( - 'override func writeValue(_ value: Any) {', - '}', - () { - final List nonProxyApiTypes = [ - '[Any]', - 'Bool', - 'Data', - '[AnyHashable: Any]', - 'Double', - 'FlutterStandardTypedData', - 'Int64', - 'String', - ...root.enums.map((Enum anEnum) => anEnum.name), - ]; - final String isBuiltinExpression = nonProxyApiTypes - .map((String swiftType) => 'value is $swiftType') - .join(' || '); - // Non ProxyApi types are checked first to prevent the scenario - // where a client wraps the `NSObject` class which all the - // classes above extend. - indent.writeScoped('if $isBuiltinExpression {', '}', () { - indent.writeln('super.writeValue(value)'); - indent.writeln('return'); - }); - indent.newln(); - - // Sort APIs where edges are an API's super class and interfaces. - // - // This sorts the APIs to have child classes be listed before their parent - // classes. This prevents the scenario where a method might return the super - // class of the actual class, so the incorrect Dart class gets created - // because the 'value is ' was checked first in the codec. For - // example: - // - // class Shape {} - // class Circle extends Shape {} - // - // class SomeClass { - // Shape giveMeAShape() => Circle(); - // } - final List sortedApis = topologicalSort( - allProxyApis, - (AstProxyApi api) { - return [ - if (api.superClass?.associatedProxyApi != null) - api.superClass!.associatedProxyApi!, - ...api.interfaces.map( - (TypeDeclaration interface) => - interface.associatedProxyApi!, - ), - ]; - }, - ); + indent.writeScoped('override func writeValue(_ value: Any) {', '}', () { + final List nonProxyApiTypes = [ + '[Any]', + 'Bool', + 'Data', + '[AnyHashable: Any]', + 'Double', + 'FlutterStandardTypedData', + 'Int64', + 'String', + ...root.enums.map((Enum anEnum) => anEnum.name), + ]; + final String isBuiltinExpression = nonProxyApiTypes + .map((String swiftType) => 'value is $swiftType') + .join(' || '); + // Non ProxyApi types are checked first to prevent the scenario + // where a client wraps the `NSObject` class which all the + // classes above extend. + indent.writeScoped('if $isBuiltinExpression {', '}', () { + indent.writeln('super.writeValue(value)'); + indent.writeln('return'); + }); + indent.newln(); + + // Sort APIs where edges are an API's super class and interfaces. + // + // This sorts the APIs to have child classes be listed before their parent + // classes. This prevents the scenario where a method might return the super + // class of the actual class, so the incorrect Dart class gets created + // because the 'value is ' was checked first in the codec. For + // example: + // + // class Shape {} + // class Circle extends Shape {} + // + // class SomeClass { + // Shape giveMeAShape() => Circle(); + // } + final List sortedApis = topologicalSort( + allProxyApis, + (AstProxyApi api) { + return [ + if (api.superClass?.associatedProxyApi != null) + api.superClass!.associatedProxyApi!, + ...api.interfaces.map( + (TypeDeclaration interface) => + interface.associatedProxyApi!, + ), + ]; + }, + ); - enumerate( - sortedApis, - (int index, AstProxyApi api) { - final TypeDeclaration apiAsTypeDecl = TypeDeclaration( - baseName: api.name, - isNullable: false, - associatedProxyApi: api, - ); - final String? availability = _tryGetAvailabilityAnnotation( - [apiAsTypeDecl], - ); - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition( - [apiAsTypeDecl], - ); - final String className = api.swiftOptions?.name ?? api.name; - indent.format( - ''' + enumerate(sortedApis, (int index, AstProxyApi api) { + final TypeDeclaration apiAsTypeDecl = TypeDeclaration( + baseName: api.name, + isNullable: false, + associatedProxyApi: api, + ); + final String? availability = _tryGetAvailabilityAnnotation( + [apiAsTypeDecl], + ); + final String? unsupportedPlatforms = + _tryGetUnsupportedPlatformsCondition([ + apiAsTypeDecl, + ]); + final String className = api.swiftOptions?.name ?? api.name; + indent.format(''' ${unsupportedPlatforms != null ? '#if $unsupportedPlatforms' : ''} if ${availability != null ? '#$availability, ' : ''}let instance = value as? $className { pigeonRegistrar.apiDelegate.pigeonApi${api.name}(pigeonRegistrar).pigeonNewInstance( @@ -1169,14 +1233,11 @@ if (wrapped == nil) { pigeonRegistrar.instanceManager.identifierWithStrongReference(forInstance: instance as AnyObject)!) return } - ${unsupportedPlatforms != null ? '#endif' : ''}''', - ); - }, - ); - indent.newln(); + ${unsupportedPlatforms != null ? '#endif' : ''}'''); + }); + indent.newln(); - indent.format( - ''' + indent.format(''' if let instance = value as AnyObject?, pigeonRegistrar.instanceManager.containsInstance(instance) { super.writeByte($proxyApiCodecInstanceManagerKey) @@ -1186,36 +1247,28 @@ if (wrapped == nil) { print("Unsupported value: \\(value) of \\(type(of: value))") assert(false, "Unsupported value for $filePrefix${classNamePrefix}ProxyApiCodecWriter") } - ''', - ); - }, - ); + '''); + }); }, ); indent.newln(); - indent.format( - ''' + indent.format(''' init(pigeonRegistrar: $registrarName) { self.pigeonRegistrar = pigeonRegistrar - }''', - ); + }'''); indent.newln(); - indent.format( - ''' + indent.format(''' override func reader(with data: Data) -> FlutterStandardReader { return $filePrefix${classNamePrefix}ProxyApiCodecReader(data: data, pigeonRegistrar: pigeonRegistrar) - }''', - ); + }'''); indent.newln(); - indent.format( - ''' + indent.format(''' override func writer(with data: NSMutableData) -> FlutterStandardWriter { return $filePrefix${classNamePrefix}ProxyApiCodecWriter(data: data, pigeonRegistrar: pigeonRegistrar) - }''', - ); + }'''); }, ); } @@ -1280,52 +1333,55 @@ if (wrapped == nil) { final String swiftApiName = '$hostProxyApiPrefix${api.name}'; indent.writeScoped( - 'final class $swiftApiName: $swiftApiProtocolName {', '}', () { - indent.writeln( - 'unowned let pigeonRegistrar: ${proxyApiRegistrarName(generatorOptions)}', - ); - indent.writeln('let pigeonDelegate: $swiftApiDelegateName'); + 'final class $swiftApiName: $swiftApiProtocolName {', + '}', + () { + indent.writeln( + 'unowned let pigeonRegistrar: ${proxyApiRegistrarName(generatorOptions)}', + ); + indent.writeln('let pigeonDelegate: $swiftApiDelegateName'); - _writeProxyApiInheritedApiMethods(indent, api); + _writeProxyApiInheritedApiMethods(indent, api); - indent.writeScoped( - 'init(pigeonRegistrar: ${proxyApiRegistrarName(generatorOptions)}, delegate: $swiftApiDelegateName) {', - '}', - () { - indent.writeln('self.pigeonRegistrar = pigeonRegistrar'); - indent.writeln('self.pigeonDelegate = delegate'); - }, - ); + indent.writeScoped( + 'init(pigeonRegistrar: ${proxyApiRegistrarName(generatorOptions)}, delegate: $swiftApiDelegateName) {', + '}', + () { + indent.writeln('self.pigeonRegistrar = pigeonRegistrar'); + indent.writeln('self.pigeonDelegate = delegate'); + }, + ); + + if (api.hasAnyHostMessageCalls()) { + _writeProxyApiMessageHandlerMethod( + indent, + api, + generatorOptions: generatorOptions, + apiAsTypeDeclaration: apiAsTypeDeclaration, + swiftApiName: swiftApiName, + dartPackageName: dartPackageName, + ); + indent.newln(); + } - if (api.hasAnyHostMessageCalls()) { - _writeProxyApiMessageHandlerMethod( + _writeProxyApiNewInstanceMethod( indent, api, generatorOptions: generatorOptions, apiAsTypeDeclaration: apiAsTypeDeclaration, - swiftApiName: swiftApiName, + newInstanceMethodName: '${classMemberNamePrefix}newInstance', dartPackageName: dartPackageName, ); - indent.newln(); - } - - _writeProxyApiNewInstanceMethod( - indent, - api, - generatorOptions: generatorOptions, - apiAsTypeDeclaration: apiAsTypeDeclaration, - newInstanceMethodName: '${classMemberNamePrefix}newInstance', - dartPackageName: dartPackageName, - ); - _writeProxyApiFlutterMethods( - indent, - api, - generatorOptions: generatorOptions, - apiAsTypeDeclaration: apiAsTypeDeclaration, - dartPackageName: dartPackageName, - ); - }); + _writeProxyApiFlutterMethods( + indent, + api, + generatorOptions: generatorOptions, + apiAsTypeDeclaration: apiAsTypeDeclaration, + dartPackageName: dartPackageName, + ); + }, + ); } String _castForceUnwrap(String value, TypeDeclaration type) { @@ -1353,7 +1409,8 @@ if (wrapped == nil) { }) { if (type.isNullable) { indent.writeln( - 'let $variableName: $fieldType? = ${_castForceUnwrap(value, type)}'); + 'let $variableName: $fieldType? = ${_castForceUnwrap(value, type)}', + ); } else { indent.writeln('let $variableName = ${_castForceUnwrap(value, type)}'); } @@ -1380,7 +1437,8 @@ if (wrapped == nil) { indent.write('private func wrapError(_ error: Any) -> [Any?] '); indent.addScoped('{', '}', () { indent.write( - 'if let pigeonError = error as? ${_getErrorClassName(generatorOptions)} '); + 'if let pigeonError = error as? ${_getErrorClassName(generatorOptions)} ', + ); indent.addScoped('{', '}', () { indent.write('return '); indent.addScoped('[', ']', () { @@ -1418,14 +1476,19 @@ private func nilOrValue(_ value: Any?) -> T? { } void _writeCreateConnectionError( - InternalSwiftOptions generatorOptions, Indent indent) { + InternalSwiftOptions generatorOptions, + Indent indent, + ) { indent.newln(); indent.writeScoped( - 'private func createConnectionError(withChannelName channelName: String) -> ${_getErrorClassName(generatorOptions)} {', - '}', () { - indent.writeln( - 'return ${_getErrorClassName(generatorOptions)}(code: "channel-error", message: "Unable to establish connection on channel: \'\\(channelName)\'.", details: "")'); - }); + 'private func createConnectionError(withChannelName channelName: String) -> ${_getErrorClassName(generatorOptions)} {', + '}', + () { + indent.writeln( + 'return ${_getErrorClassName(generatorOptions)}(code: "channel-error", message: "Unable to establish connection on channel: \'\\(channelName)\'.", details: "")', + ); + }, + ); } void _writeDeepEquals(InternalSwiftOptions generatorOptions, Indent indent) { @@ -1584,7 +1647,10 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has '''); } addDocumentationComments( - indent, api.documentationComments, _docCommentSpec); + indent, + api.documentationComments, + _docCommentSpec, + ); for (final Method func in api.methods) { indent.format(''' class ${toUpperCamelCase(func.name)}StreamHandler: PigeonEventChannelWrapper<${_swiftTypeForDartType(func.returnType)}> { @@ -1647,35 +1713,44 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } final Iterable enumSafeArgNames = parameters.asMap().entries.map( - (MapEntry e) => - getEnumSafeArgumentExpression(e.key, e.value)); - final String sendArgument = parameters.isEmpty - ? 'nil' - : '[${enumSafeArgNames.join(', ')}] as [Any?]'; + (MapEntry e) => + getEnumSafeArgumentExpression(e.key, e.value), + ); + final String sendArgument = + parameters.isEmpty + ? 'nil' + : '[${enumSafeArgNames.join(', ')}] as [Any?]'; const String channel = 'channel'; indent.writeln('let channelName: String = "$channelName"'); indent.writeln( - 'let $channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger, codec: codec)'); + 'let $channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger, codec: codec)', + ); indent.write('$channel.sendMessage($sendArgument) '); indent.addScoped('{ response in', '}', () { indent.writeScoped( - 'guard let listResponse = response as? [Any?] else {', '}', () { - indent.writeln( - 'completion(.failure(createConnectionError(withChannelName: channelName)))'); - indent.writeln('return'); - }); + 'guard let listResponse = response as? [Any?] else {', + '}', + () { + indent.writeln( + 'completion(.failure(createConnectionError(withChannelName: channelName)))', + ); + indent.writeln('return'); + }, + ); indent.writeScoped('if listResponse.count > 1 {', '} ', () { indent.writeln('let code: String = listResponse[0] as! String'); indent.writeln('let message: String? = nilOrValue(listResponse[1])'); indent.writeln('let details: String? = nilOrValue(listResponse[2])'); indent.writeln( - 'completion(.failure(${_getErrorClassName(generatorOptions)}(code: code, message: message, details: details)))'); + 'completion(.failure(${_getErrorClassName(generatorOptions)}(code: code, message: message, details: details)))', + ); }, addTrailingNewline: false); if (!returnType.isNullable && !returnType.isVoid) { indent.addScoped('else if listResponse[0] == nil {', '} ', () { indent.writeln( - 'completion(.failure(${_getErrorClassName(generatorOptions)}(code: "null-error", message: "Flutter api returned null value for non-null return value.", details: "")))'); + 'completion(.failure(${_getErrorClassName(generatorOptions)}(code: "null-error", message: "Flutter api returned null value for non-null return value.", details: "")))', + ); }, addTrailingNewline: false); } indent.addScoped('else {', '}', () { @@ -1691,11 +1766,13 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has type: returnType, ); // There is a swift bug with unwrapping maps of nullable Enums; - final String enumMapForceUnwrap = returnType.baseName == 'Map' && - returnType.typeArguments - .any((TypeDeclaration type) => type.isEnum) - ? '!' - : ''; + final String enumMapForceUnwrap = + returnType.baseName == 'Map' && + returnType.typeArguments.any( + (TypeDeclaration type) => type.isEnum, + ) + ? '!' + : ''; indent.writeln('completion(.success(result$enumMapForceUnwrap))'); } }); @@ -1714,7 +1791,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has String setHandlerCondition = 'let api = api', List documentationComments = const [], String Function(List safeArgNames, {required String apiVarName})? - onCreateCall, + onCreateCall, }) { final _SwiftFunctionComponents components = _SwiftFunctionComponents( name: name, @@ -1725,7 +1802,8 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has final String varChannelName = '${name}Channel'; addDocumentationComments(indent, documentationComments, _docCommentSpec); - final String baseArgs = 'name: "$channelName", ' + final String baseArgs = + 'name: "$channelName", ' 'binaryMessenger: binaryMessenger, codec: codec'; // The version with taskQueue: is an optional protocol method that isn't // implemented on macOS yet, so the call has to be conditionalized even @@ -1757,30 +1835,36 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has final List methodArgument = []; if (components.arguments.isNotEmpty) { indent.writeln('let args = message as! [Any?]'); - enumerate(components.arguments, - (int index, _SwiftFunctionArgument arg) { + enumerate(components.arguments, ( + int index, + _SwiftFunctionArgument arg, + ) { final String argName = _getSafeArgumentName(index, arg.namedType); final String argIndex = 'args[$index]'; final String fieldType = _swiftTypeForDartType(arg.type); // 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) - ? '!' - : ''; + final String enumMapForceUnwrap = + arg.type.baseName == 'Map' && + arg.type.typeArguments.any( + (TypeDeclaration type) => type.isEnum, + ) + ? '!' + : ''; _writeGenericCasting( - indent: indent, - value: argIndex, - variableName: argName, - fieldType: fieldType, - type: arg.type); + indent: indent, + value: argIndex, + variableName: argName, + fieldType: fieldType, + type: arg.type, + ); if (arg.label == '_') { methodArgument.add('$argName$enumMapForceUnwrap'); } else { - methodArgument - .add('${arg.label ?? arg.name}: $argName$enumMapForceUnwrap'); + methodArgument.add( + '${arg.label ?? arg.name}: $argName$enumMapForceUnwrap', + ); } }); } @@ -1789,9 +1873,10 @@ 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'); @@ -1847,14 +1932,10 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.writeScoped('protocol $delegateName {', '}', () { for (final AstProxyApi api in allProxyApis) { final String hostApiName = '$hostProxyApiPrefix${api.name}'; - addDocumentationComments( - indent, - [ - ' An implementation of [$hostApiName] used to add a new Dart instance of', - ' `${api.name}` to the Dart `InstanceManager` and make calls to Dart.' - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + ' An implementation of [$hostApiName] used to add a new Dart instance of', + ' `${api.name}` to the Dart `InstanceManager` and make calls to Dart.', + ], _docCommentSpec); indent.writeln( 'func pigeonApi${api.name}(_ registrar: ${proxyApiRegistrarName(generatorOptions)}) -> $hostApiName', ); @@ -1873,12 +1954,10 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has final String hostApiName = '$hostProxyApiPrefix${api.name}'; final String swiftApiDelegateName = '${hostProxyApiPrefix}Delegate${api.name}'; - indent.format( - ''' + indent.format(''' func pigeonApi${api.name}(_ registrar: ${proxyApiRegistrarName(generatorOptions)}) -> $hostApiName { return $hostApiName(pigeonRegistrar: registrar, delegate: $swiftApiDelegateName()) - }''', - ); + }'''); } }); indent.newln(); @@ -1888,34 +1967,32 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has '${swiftInstanceManagerClassName(generatorOptions)}Api'; indent.writeScoped( - 'open class ${proxyApiRegistrarName(generatorOptions)} {', '}', () { - indent.writeln('let binaryMessenger: FlutterBinaryMessenger'); - indent.writeln('let apiDelegate: $delegateName'); - indent.writeln( - 'let instanceManager: ${swiftInstanceManagerClassName(generatorOptions)}'); + 'open class ${proxyApiRegistrarName(generatorOptions)} {', + '}', + () { + indent.writeln('let binaryMessenger: FlutterBinaryMessenger'); + indent.writeln('let apiDelegate: $delegateName'); + indent.writeln( + 'let instanceManager: ${swiftInstanceManagerClassName(generatorOptions)}', + ); - addDocumentationComments( - indent, - [' Whether APIs should ignore calling to Dart.'], - _docCommentSpec, - ); - indent.writeln('public var ignoreCallsToDart = false'); + addDocumentationComments(indent, [ + ' Whether APIs should ignore calling to Dart.', + ], _docCommentSpec); + indent.writeln('public var ignoreCallsToDart = false'); - indent.writeln('private var _codec: FlutterStandardMessageCodec?'); - indent.format( - ''' + indent.writeln('private var _codec: FlutterStandardMessageCodec?'); + indent.format(''' var codec: FlutterStandardMessageCodec { if _codec == nil { _codec = FlutterStandardMessageCodec( readerWriter: ${proxyApiReaderWriterName(generatorOptions)}(pigeonRegistrar: self)) } return _codec! - }''', - ); - indent.newln(); + }'''); + indent.newln(); - indent.format( - ''' + indent.format(''' private class InstanceManagerApiFinalizerDelegate: ${instanceManagerFinalizerDelegateName(generatorOptions)} { let api: $instanceManagerApiName @@ -1928,48 +2005,46 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _ in } } - }''', - ); - indent.newln(); + }'''); + indent.newln(); - indent.format( - ''' + indent.format(''' init(binaryMessenger: FlutterBinaryMessenger, apiDelegate: $delegateName) { self.binaryMessenger = binaryMessenger self.apiDelegate = apiDelegate self.instanceManager = ${swiftInstanceManagerClassName(generatorOptions)}( finalizerDelegate: InstanceManagerApiFinalizerDelegate( $instanceManagerApiName(binaryMessenger: binaryMessenger))) - }''', - ); - indent.newln(); + }'''); + indent.newln(); - indent.writeScoped('func setUp() {', '}', () { - indent.writeln( - '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger: binaryMessenger, instanceManager: instanceManager)', - ); - for (final AstProxyApi api in allProxyApis) { - if (api.hasAnyHostMessageCalls()) { - indent.writeln( - '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApi${api.name}(self))', - ); + indent.writeScoped('func setUp() {', '}', () { + indent.writeln( + '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger: binaryMessenger, instanceManager: instanceManager)', + ); + for (final AstProxyApi api in allProxyApis) { + if (api.hasAnyHostMessageCalls()) { + indent.writeln( + '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApi${api.name}(self))', + ); + } } - } - }); + }); - indent.writeScoped('func tearDown() {', '}', () { - indent.writeln( - '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger: binaryMessenger, instanceManager: nil)', - ); - for (final AstProxyApi api in allProxyApis) { - if (api.hasAnyHostMessageCalls()) { - indent.writeln( - '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil)', - ); + indent.writeScoped('func tearDown() {', '}', () { + indent.writeln( + '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger: binaryMessenger, instanceManager: nil)', + ); + for (final AstProxyApi api in allProxyApis) { + if (api.hasAnyHostMessageCalls()) { + indent.writeln( + '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil)', + ); + } } - } - }); - }); + }); + }, + ); } // Writes the delegate method that instantiates a new instance of the Kotlin @@ -1986,8 +2061,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ...constructor.parameters.map((Parameter parameter) => parameter.type), ]; - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition(allReferencedTypes); + final String? unsupportedPlatforms = _tryGetUnsupportedPlatformsCondition( + allReferencedTypes, + ); if (unsupportedPlatforms != null) { indent.writeln('#if $unsupportedPlatforms'); } @@ -1998,16 +2074,18 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _docCommentSpec, ); - final String? availableAnnotation = - _tryGetAvailabilityAnnotation(allReferencedTypes); + final String? availableAnnotation = _tryGetAvailabilityAnnotation( + allReferencedTypes, + ); if (availableAnnotation != null) { indent.writeln('@$availableAnnotation'); } final String methodSignature = _getMethodSignature( - name: constructor.name.isNotEmpty - ? constructor.name - : 'pigeonDefaultConstructor', + name: + constructor.name.isNotEmpty + ? constructor.name + : 'pigeonDefaultConstructor', parameters: [ Parameter( name: 'pigeonApi', @@ -2019,7 +2097,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ...api.unattachedFields.map((ApiField field) { return Parameter(name: field.name, type: field.type); }), - ...constructor.parameters + ...constructor.parameters, ], returnType: apiAsTypeDeclaration, errorTypeName: '', @@ -2044,8 +2122,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has field.type, ]; - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition(allReferencedTypes); + final String? unsupportedPlatforms = _tryGetUnsupportedPlatformsCondition( + allReferencedTypes, + ); if (unsupportedPlatforms != null) { indent.writeln('#if $unsupportedPlatforms'); } @@ -2056,8 +2135,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _docCommentSpec, ); - final String? availableAnnotation = - _tryGetAvailabilityAnnotation(allReferencedTypes); + final String? availableAnnotation = _tryGetAvailabilityAnnotation( + allReferencedTypes, + ); if (availableAnnotation != null) { indent.writeln('@$availableAnnotation'); } @@ -2073,10 +2153,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ), ), if (!field.isStatic) - Parameter( - name: 'pigeonInstance', - type: apiAsTypeDeclaration, - ), + Parameter(name: 'pigeonInstance', type: apiAsTypeDeclaration), ], returnType: field.type, errorTypeName: '', @@ -2101,8 +2178,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has field.type, ]; - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition(allReferencedTypes); + final String? unsupportedPlatforms = _tryGetUnsupportedPlatformsCondition( + allReferencedTypes, + ); if (unsupportedPlatforms != null) { indent.writeln('#if $unsupportedPlatforms'); } @@ -2113,8 +2191,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _docCommentSpec, ); - final String? availableAnnotation = - _tryGetAvailabilityAnnotation(allReferencedTypes); + final String? availableAnnotation = _tryGetAvailabilityAnnotation( + allReferencedTypes, + ); if (availableAnnotation != null) { indent.writeln('@$availableAnnotation'); } @@ -2129,10 +2208,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has isNullable: false, ), ), - Parameter( - name: 'pigeonInstance', - type: apiAsTypeDeclaration, - ), + Parameter(name: 'pigeonInstance', type: apiAsTypeDeclaration), ], returnType: field.type, errorTypeName: '', @@ -2159,8 +2235,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ...method.parameters.map((Parameter p) => p.type), ]; - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition(allReferencedTypes); + final String? unsupportedPlatforms = _tryGetUnsupportedPlatformsCondition( + allReferencedTypes, + ); if (unsupportedPlatforms != null) { indent.writeln('#if $unsupportedPlatforms'); } @@ -2171,8 +2248,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _docCommentSpec, ); - final String? availableAnnotation = - _tryGetAvailabilityAnnotation(allReferencedTypes); + final String? availableAnnotation = _tryGetAvailabilityAnnotation( + allReferencedTypes, + ); if (availableAnnotation != null) { indent.writeln('@$availableAnnotation'); } @@ -2188,10 +2266,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ), ), if (!method.isStatic) - Parameter( - name: 'pigeonInstance', - type: apiAsTypeDeclaration, - ), + Parameter(name: 'pigeonInstance', type: apiAsTypeDeclaration), ...method.parameters, ], returnType: method.returnType, @@ -2215,13 +2290,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ...api.interfaces.map((TypeDeclaration type) => type.baseName), }; for (final String name in inheritedApiNames) { - addDocumentationComments( - indent, - [ - 'An implementation of [$name] used to access callback methods', - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + 'An implementation of [$name] used to access callback methods', + ], _docCommentSpec); indent.writeScoped( 'var pigeonApi$name: $hostProxyApiPrefix$name {', '}', @@ -2249,14 +2320,12 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has 'static func setUpMessageHandlers(binaryMessenger: FlutterBinaryMessenger, api: $swiftApiName?) {', '}', () { - indent.format( - ''' + indent.format(''' let codec: FlutterStandardMessageCodec = api != nil ? FlutterStandardMessageCodec( readerWriter: ${proxyApiReaderWriterName(generatorOptions)}(pigeonRegistrar: api!.pigeonRegistrar)) - : FlutterStandardMessageCodec.sharedInstance()''', - ); + : FlutterStandardMessageCodec.sharedInstance()'''); void writeWithApiCheckIfNecessary( List types, { required String methodName, @@ -2269,8 +2338,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.writeln('#if $unsupportedPlatforms'); } - final String? availableAnnotation = - _tryGetAvailabilityAnnotation(types); + final String? availableAnnotation = _tryGetAvailabilityAnnotation( + types, + ); if (availableAnnotation != null) { indent.writeScoped( 'if #$availableAnnotation {', @@ -2280,8 +2350,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ); indent.writeScoped(' else {', '}', () { final String varChannelName = '${methodName}Channel'; - indent.format( - ''' + indent.format(''' let $varChannelName = FlutterBasicMessageChannel( name: "$channelName", binaryMessenger: binaryMessenger, codec: codec) @@ -2294,8 +2363,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } } else { $varChannelName.setMessageHandler(nil) - }''', - ); + }'''); }); } else { onWrite(); @@ -2307,14 +2375,16 @@ 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( @@ -2355,10 +2425,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ), ), ...api.unattachedFields.map((ApiField field) { - return Parameter( - name: field.name, - type: field.type, - ); + return Parameter(name: field.name, type: field.type); }), ...constructor.parameters, ], @@ -2389,9 +2456,10 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has List methodParameters, { required String apiVarName, }) { - final String instanceArg = field.isStatic - ? '' - : ', pigeonInstance: pigeonInstanceArg'; + final String instanceArg = + field.isStatic + ? '' + : ', pigeonInstance: pigeonInstanceArg'; return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' 'try $apiVarName.pigeonDelegate.${field.name}(pigeonApi: api$instanceArg), ' 'withIdentifier: pigeonIdentifierArg)'; @@ -2416,8 +2484,11 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } for (final Method method in api.hostMethods) { - final String channelName = - makeChannelName(api, method, dartPackageName); + final String channelName = makeChannelName( + api, + method, + dartPackageName, + ); writeWithApiCheckIfNecessary( [ apiAsTypeDeclaration, @@ -2478,19 +2549,16 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has ...api.unattachedFields.map((ApiField field) => field.type), ]; - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition(allReferencedTypes); + final String? unsupportedPlatforms = _tryGetUnsupportedPlatformsCondition( + allReferencedTypes, + ); if (unsupportedPlatforms != null) { indent.writeln('#if $unsupportedPlatforms'); } - addDocumentationComments( - indent, - [ - 'Creates a Dart instance of ${api.name} and attaches it to [pigeonInstance].' - ], - _docCommentSpec, - ); + addDocumentationComments(indent, [ + 'Creates a Dart instance of ${api.name} and attaches it to [pigeonInstance].', + ], _docCommentSpec); final String? availableAnnotation = _tryGetAvailabilityAnnotation( allReferencedTypes, @@ -2509,21 +2577,16 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has errorTypeName: _getErrorClassName(generatorOptions), ); indent.writeScoped('$methodSignature {', '}', () { - indent.writeScoped( - 'if pigeonRegistrar.ignoreCallsToDart {', - '}', - () { - indent.format( - ''' + indent.writeScoped('if pigeonRegistrar.ignoreCallsToDart {', '}', () { + indent.format( + ''' completion( .failure( ${_getErrorClassName(generatorOptions)}( code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: "")))''', - ); - }, - addTrailingNewline: false, - ); + ); + }, addTrailingNewline: false); indent.writeScoped( ' else if pigeonRegistrar.instanceManager.containsInstance(pigeonInstance as AnyObject) {', @@ -2554,16 +2617,11 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has parameters: [ Parameter( name: 'pigeonIdentifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ...api.unattachedFields.map( - (ApiField field) { - return Parameter(name: field.name, type: field.type); - }, + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), + ...api.unattachedFields.map((ApiField field) { + return Parameter(name: field.name, type: field.type); + }), ], returnType: const TypeDeclaration.voidDeclaration(), channelName: makeChannelNameWithStrings( @@ -2606,8 +2664,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has method.returnType, ]; - final String? unsupportedPlatforms = - _tryGetUnsupportedPlatformsCondition(allReferencedTypes); + final String? unsupportedPlatforms = _tryGetUnsupportedPlatformsCondition( + allReferencedTypes, + ); if (unsupportedPlatforms != null) { indent.writeln('#if $unsupportedPlatforms'); } @@ -2618,8 +2677,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _docCommentSpec, ); - final String? availableAnnotation = - _tryGetAvailabilityAnnotation(allReferencedTypes); + final String? availableAnnotation = _tryGetAvailabilityAnnotation( + allReferencedTypes, + ); if (availableAnnotation != null) { indent.writeln('@$availableAnnotation'); } @@ -2639,23 +2699,18 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.write(methodSignature); if (writeBody) { indent.writeScoped(' {', '}', () { - indent.writeScoped( - 'if pigeonRegistrar.ignoreCallsToDart {', - '}', - () { - indent.format( - ''' + indent.writeScoped('if pigeonRegistrar.ignoreCallsToDart {', '}', () { + indent.format(''' completion( .failure( ${_getErrorClassName(generatorOptions)}( code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) - return''', - ); - }, + return'''); + }); + indent.writeln( + 'let binaryMessenger = pigeonRegistrar.binaryMessenger', ); - indent - .writeln('let binaryMessenger = pigeonRegistrar.binaryMessenger'); indent.writeln('let codec = pigeonRegistrar.codec'); _writeFlutterMethodMessageCall( @@ -2680,29 +2735,35 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has void _writePigeonError(InternalSwiftOptions generatorOptions, Indent indent) { indent.newln(); indent.writeln( - '/// Error class for passing custom error details to Dart side.'); + '/// Error class for passing custom error details to Dart side.', + ); indent.writeScoped( - 'final class ${_getErrorClassName(generatorOptions)}: Error {', '}', - () { - indent.writeln('let code: String'); - indent.writeln('let message: String?'); - indent.writeln('let details: Sendable?'); - indent.newln(); - indent.writeScoped( - 'init(code: String, message: String?, details: Sendable?) {', '}', + 'final class ${_getErrorClassName(generatorOptions)}: Error {', + '}', + () { + indent.writeln('let code: String'); + indent.writeln('let message: String?'); + indent.writeln('let details: Sendable?'); + indent.newln(); + indent.writeScoped( + 'init(code: String, message: String?, details: Sendable?) {', + '}', () { - indent.writeln('self.code = code'); - indent.writeln('self.message = message'); - indent.writeln('self.details = details'); - }); - indent.newln(); - indent.writeScoped('var localizedDescription: String {', '}', () { - indent.writeScoped('return', '', () { - indent.writeln( - '"${_getErrorClassName(generatorOptions)}(code: \\(code), message: \\(message ?? ""), details: \\(details ?? "")"'); - }, addTrailingNewline: false); - }); - }); + indent.writeln('self.code = code'); + indent.writeln('self.message = message'); + indent.writeln('self.details = details'); + }, + ); + indent.newln(); + indent.writeScoped('var localizedDescription: String {', '}', () { + indent.writeScoped('return', '', () { + indent.writeln( + '"${_getErrorClassName(generatorOptions)}(code: \\(code), message: \\(message ?? ""), details: \\(details ?? "")"', + ); + }, addTrailingNewline: false); + }); + }, + ); } void _writeProxyApiImports(Indent indent, Iterable apis) { @@ -2723,11 +2784,13 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has // If every ProxyApi that shares an import excludes a platform for // support, surround the import with `#if !os(...) #endif`. final List unsupportedPlatforms = [ - if (!apisOfImports[import]! - .any((AstProxyApi api) => api.swiftOptions?.supportsIos ?? true)) + if (!apisOfImports[import]!.any( + (AstProxyApi api) => api.swiftOptions?.supportsIos ?? true, + )) '!os(iOS)', - if (!apisOfImports[import]! - .any((AstProxyApi api) => api.swiftOptions?.supportsMacos ?? true)) + if (!apisOfImports[import]!.any( + (AstProxyApi api) => api.swiftOptions?.supportsMacos ?? true, + )) '!os(macOS)', ]; @@ -2744,38 +2807,36 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has typedef _VersionRequirement = ({TypeDeclaration type, Version version}); ({_VersionRequirement? ios, _VersionRequirement? macos}) - _findHighestVersionRequirement( - Iterable types, -) { +_findHighestVersionRequirement(Iterable types) { final _VersionRequirement? iosApiRequirement = findHighestApiRequirement( - types, - onGetApiRequirement: (TypeDeclaration type) { - final String? apiRequirement = - type.associatedProxyApi?.swiftOptions?.minIosApi; - if (apiRequirement != null) { - return Version.parse(apiRequirement); - } + types, + onGetApiRequirement: (TypeDeclaration type) { + final String? apiRequirement = + type.associatedProxyApi?.swiftOptions?.minIosApi; + if (apiRequirement != null) { + return Version.parse(apiRequirement); + } - return null; - }, - onCompare: (Version one, Version two) => one.compareTo(two), - ); + return null; + }, + onCompare: (Version one, Version two) => one.compareTo(two), + ); final _VersionRequirement? macosApiRequirement = findHighestApiRequirement( - types, - onGetApiRequirement: (TypeDeclaration type) { - final String? apiRequirement = - type.associatedProxyApi?.swiftOptions?.minMacosApi; - if (apiRequirement != null) { - return Version.parse(apiRequirement); - } + types, + onGetApiRequirement: (TypeDeclaration type) { + final String? apiRequirement = + type.associatedProxyApi?.swiftOptions?.minMacosApi; + if (apiRequirement != null) { + return Version.parse(apiRequirement); + } - return null; - }, - onCompare: (Version one, Version two) => one.compareTo(two), - ); + return null; + }, + onCompare: (Version one, Version two) => one.compareTo(two), + ); return (ios: iosApiRequirement, macos: macosApiRequirement); } @@ -2785,10 +2846,8 @@ typedef _VersionRequirement = ({TypeDeclaration type, Version version}); /// /// Returns `null` if there is not api requirement in [types]. String? _tryGetAvailabilityAnnotation(Iterable types) { - final ({ - _VersionRequirement? ios, - _VersionRequirement? macos - }) versionRequirement = _findHighestVersionRequirement(types); + final ({_VersionRequirement? ios, _VersionRequirement? macos}) + versionRequirement = _findHighestVersionRequirement(types); final List apis = [ if (versionRequirement.ios != null) @@ -2816,8 +2875,9 @@ String? _tryGetUnsupportedPlatformsCondition(Iterable types) { } } - final Iterable allReferencedTypes = - types.expand(addAllRecursive); + final Iterable allReferencedTypes = types.expand( + addAllRecursive, + ); final List unsupportedPlatforms = [ if (!allReferencedTypes.every((TypeDeclaration type) { @@ -2838,7 +2898,8 @@ String? _tryGetUnsupportedPlatformsCondition(Iterable types) { /// Calculates the name of the codec that will be generated for [api]. String _getMessageCodecName(InternalSwiftOptions options) { return toUpperCamelCase( - '${options.fileSpecificClassNameComponent}PigeonCodec'); + '${options.fileSpecificClassNameComponent}PigeonCodec', + ); } /// Calculates the name of the codec that will be generated for [api]. @@ -2860,9 +2921,10 @@ 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); } @@ -2962,15 +3024,21 @@ String _getMethodSignature({ final String returnTypeString = returnType.isVoid ? 'Void' : _nullSafeSwiftTypeForDartType(returnType); - final Iterable types = - parameters.map((NamedType e) => _nullSafeSwiftTypeForDartType(e.type)); - final Iterable labels = indexMap(components.arguments, - (int index, _SwiftFunctionArgument argument) { + final Iterable types = parameters.map( + (NamedType e) => _nullSafeSwiftTypeForDartType(e.type), + ); + final Iterable labels = indexMap(components.arguments, ( + int index, + _SwiftFunctionArgument argument, + ) { return argument.label ?? _getArgumentName(index, argument.namedType); }); final Iterable names = indexMap(parameters, getParameterName); - final String parameterSignature = - map3(types, labels, names, (String type, String label, String name) { + final String parameterSignature = map3(types, labels, names, ( + String type, + String label, + String name, + ) { return '${label != name ? '$label ' : ''}$name: $type'; }).join(', '); @@ -3027,13 +3095,16 @@ 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(), ); } @@ -3041,23 +3112,27 @@ 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/pigeons/configure_pigeon_dart_out.dart b/packages/pigeon/pigeons/configure_pigeon_dart_out.dart index 902163fd3cf..04d3c7d6de6 100644 --- a/packages/pigeon/pigeons/configure_pigeon_dart_out.dart +++ b/packages/pigeon/pigeons/configure_pigeon_dart_out.dart @@ -4,11 +4,13 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'stdout', - javaOut: 'stdout', - dartOptions: DartOptions(), -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'stdout', + javaOut: 'stdout', + dartOptions: DartOptions(), + ), +) @HostApi() abstract class ConfigurePigeonApi { void ping(); diff --git a/packages/pigeon/pigeons/core_tests.dart b/packages/pigeon/pigeons/core_tests.dart index 8a154c8b62d..cf5b8eafbe0 100644 --- a/packages/pigeon/pigeons/core_tests.dart +++ b/packages/pigeon/pigeons/core_tests.dart @@ -4,19 +4,11 @@ import 'package:pigeon/pigeon.dart'; -enum AnEnum { - one, - two, - three, - fortyTwo, - fourHundredTwentyTwo, -} +enum AnEnum { one, two, three, fortyTwo, fourHundredTwentyTwo } // Enums require special logic, having multiple ensures that the logic can be // replicated without collision. -enum AnotherEnum { - justInCase, -} +enum AnotherEnum { justInCase } // This exists to show that unused data classes still generate. class UnusedClass { @@ -386,7 +378,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoClassMap:') @SwiftFunction('echo(classMap:)') Map echoClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNonNullStringMap:') @@ -407,7 +400,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoNonNullClassMap:') @SwiftFunction('echoNonNull(classMap:)') Map echoNonNullClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed class to test nested class serialization and deserialization. @ObjCSelector('echoClassWrapper:') @@ -450,7 +444,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoAllNullableTypesWithoutRecursion:') @SwiftFunction('echo(_:)') AllNullableTypesWithoutRecursion? echoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything); + AllNullableTypesWithoutRecursion? everything, + ); /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. @@ -468,14 +463,21 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('sendMultipleNullableTypesABool:anInt:aString:') @SwiftFunction('sendMultipleNullableTypes(aBool:anInt:aString:)') AllNullableTypes sendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); /// Returns passed in arguments of multiple types. @ObjCSelector('sendMultipleNullableTypesWithoutRecursionABool:anInt:aString:') @SwiftFunction( - 'sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)') + 'sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)', + ) AllNullableTypesWithoutRecursion sendMultipleNullableTypesWithoutRecursion( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); /// Returns passed in int. @ObjCSelector('echoNullableInt:') @@ -521,7 +523,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoNullableClassList:') @SwiftFunction('echoNullable(classList:)') List? echoNullableClassList( - List? classList); + List? classList, + ); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullEnumList:') @@ -532,7 +535,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoNullableNonNullClassList:') @SwiftFunction('echoNullableNonNull(classList:)') List? echoNullableNonNullClassList( - List? classList); + List? classList, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableMap:') @@ -543,7 +547,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoNullableStringMap:') @SwiftFunction('echoNullable(stringMap:)') Map? echoNullableStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableIntMap:') @@ -559,13 +564,15 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoNullableClassMap:') @SwiftFunction('echoNullable(classMap:)') Map? echoNullableClassMap( - Map? classMap); + Map? classMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullStringMap:') @SwiftFunction('echoNullableNonNull(stringMap:)') Map? echoNullableNonNullStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullIntMap:') @@ -581,7 +588,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoNullableNonNullClassMap:') @SwiftFunction('echoNullableNonNull(classMap:)') Map? echoNullableNonNullClassMap( - Map? classMap); + Map? classMap, + ); @ObjCSelector('echoNullableEnum:') @SwiftFunction('echoNullable(_:)') @@ -691,7 +699,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoAsyncClassMap:') @SwiftFunction('echoAsync(classMap:)') Map echoAsyncClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async @@ -728,15 +737,17 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoAsyncNullableAllNullableTypes:') @SwiftFunction('echoAsync(_:)') AllNullableTypes? echoAsyncNullableAllNullableTypes( - AllNullableTypes? everything); + AllNullableTypes? everything, + ); /// Returns the passed object, to test serialization and deserialization. @async @ObjCSelector('echoAsyncNullableAllNullableTypesWithoutRecursion:') @SwiftFunction('echoAsync(_:)') AllNullableTypesWithoutRecursion? - echoAsyncNullableAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything); + echoAsyncNullableAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? everything, + ); /// Returns passed in int asynchronously. @async @@ -791,7 +802,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoAsyncNullableClassList:') @SwiftFunction('echoAsyncNullable(classList:)') List? echoAsyncNullableClassList( - List? classList); + List? classList, + ); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @@ -804,7 +816,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoAsyncNullableStringMap:') @SwiftFunction('echoAsyncNullable(stringMap:)') Map? echoAsyncNullableStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @@ -817,14 +830,16 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('echoAsyncNullableEnumMap:') @SwiftFunction('echoAsyncNullable(enumMap:)') Map? echoAsyncNullableEnumMap( - Map? enumMap); + Map? enumMap, + ); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncNullableClassMap:') @SwiftFunction('echoAsyncNullable(classMap:)') Map? echoAsyncNullableClassMap( - Map? classMap); + Map? classMap, + ); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async @@ -869,29 +884,39 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoAllNullableTypes:') @SwiftFunction('callFlutterEcho(_:)') AllNullableTypes? callFlutterEchoAllNullableTypes( - AllNullableTypes? everything); + AllNullableTypes? everything, + ); @async @ObjCSelector('callFlutterSendMultipleNullableTypesABool:anInt:aString:') @SwiftFunction('callFlutterSendMultipleNullableTypes(aBool:anInt:aString:)') AllNullableTypes callFlutterSendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); @async @ObjCSelector('callFlutterEchoAllNullableTypesWithoutRecursion:') @SwiftFunction('callFlutterEcho(_:)') AllNullableTypesWithoutRecursion? - callFlutterEchoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything); + callFlutterEchoAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? everything, + ); @async @ObjCSelector( - 'callFlutterSendMultipleNullableTypesWithoutRecursionABool:anInt:aString:') + 'callFlutterSendMultipleNullableTypesWithoutRecursionABool:anInt:aString:', + ) @SwiftFunction( - 'callFlutterSendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)') + 'callFlutterSendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)', + ) AllNullableTypesWithoutRecursion - callFlutterSendMultipleNullableTypesWithoutRecursion( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + callFlutterSendMultipleNullableTypesWithoutRecursion( + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); @async @ObjCSelector('callFlutterEchoBool:') @@ -932,7 +957,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoClassList:') @SwiftFunction('callFlutterEcho(classList:)') List callFlutterEchoClassList( - List classList); + List classList, + ); @async @ObjCSelector('callFlutterEchoNonNullEnumList:') @@ -943,7 +969,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNonNullClassList:') @SwiftFunction('callFlutterEchoNonNull(classList:)') List callFlutterEchoNonNullClassList( - List classList); + List classList, + ); @async @ObjCSelector('callFlutterEchoMap:') @@ -954,7 +981,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoStringMap:') @SwiftFunction('callFlutterEcho(stringMap:)') Map callFlutterEchoStringMap( - Map stringMap); + Map stringMap, + ); @async @ObjCSelector('callFlutterEchoIntMap:') @@ -970,13 +998,15 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoClassMap:') @SwiftFunction('callFlutterEcho(classMap:)') Map callFlutterEchoClassMap( - Map classMap); + Map classMap, + ); @async @ObjCSelector('callFlutterEchoNonNullStringMap:') @SwiftFunction('callFlutterEchoNonNull(stringMap:)') Map callFlutterEchoNonNullStringMap( - Map stringMap); + Map stringMap, + ); @async @ObjCSelector('callFlutterEchoNonNullIntMap:') @@ -987,13 +1017,15 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNonNullEnumMap:') @SwiftFunction('callFlutterEchoNonNull(enumMap:)') Map callFlutterEchoNonNullEnumMap( - Map enumMap); + Map enumMap, + ); @async @ObjCSelector('callFlutterEchoNonNullClassMap:') @SwiftFunction('callFlutterEchoNonNull(classMap:)') Map callFlutterEchoNonNullClassMap( - Map classMap); + Map classMap, + ); @async @ObjCSelector('callFlutterEchoEnum:') @@ -1044,7 +1076,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNullableClassList:') @SwiftFunction('callFlutterEchoNullable(classList:)') List? callFlutterEchoNullableClassList( - List? classList); + List? classList, + ); @async @ObjCSelector('callFlutterEchoNullableNonNullEnumList:') @@ -1055,7 +1088,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNullableNonNullClassList:') @SwiftFunction('callFlutterEchoNullableNonNull(classList:)') List? callFlutterEchoNullableNonNullClassList( - List? classList); + List? classList, + ); @async @ObjCSelector('callFlutterEchoNullableMap:') @@ -1066,7 +1100,8 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNullableStringMap:') @SwiftFunction('callFlutterEchoNullable(stringMap:)') Map? callFlutterEchoNullableStringMap( - Map? stringMap); + Map? stringMap, + ); @async @ObjCSelector('callFlutterEchoNullableIntMap:') @@ -1077,19 +1112,22 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNullableEnumMap:') @SwiftFunction('callFlutterEchoNullable(enumMap:)') Map? callFlutterEchoNullableEnumMap( - Map? enumMap); + Map? enumMap, + ); @async @ObjCSelector('callFlutterEchoNullableClassMap:') @SwiftFunction('callFlutterEchoNullable(classMap:)') Map? callFlutterEchoNullableClassMap( - Map? classMap); + Map? classMap, + ); @async @ObjCSelector('callFlutterEchoNullableNonNullStringMap:') @SwiftFunction('callFlutterEchoNullableNonNull(stringMap:)') Map? callFlutterEchoNullableNonNullStringMap( - Map? stringMap); + Map? stringMap, + ); @async @ObjCSelector('callFlutterEchoNullableNonNullIntMap:') @@ -1100,13 +1138,15 @@ abstract class HostIntegrationCoreApi { @ObjCSelector('callFlutterEchoNullableNonNullEnumMap:') @SwiftFunction('callFlutterEchoNullableNonNull(enumMap:)') Map? callFlutterEchoNullableNonNullEnumMap( - Map? enumMap); + Map? enumMap, + ); @async @ObjCSelector('callFlutterEchoNullableNonNullClassMap:') @SwiftFunction('callFlutterEchoNullableNonNull(classMap:)') Map? callFlutterEchoNullableNonNullClassMap( - Map? classMap); + Map? classMap, + ); @async @ObjCSelector('callFlutterEchoNullableEnum:') @@ -1154,22 +1194,30 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('sendMultipleNullableTypesABool:anInt:aString:') @SwiftFunction('sendMultipleNullableTypes(aBool:anInt:aString:)') AllNullableTypes sendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllNullableTypesWithoutRecursion:') @SwiftFunction('echoNullable(_:)') AllNullableTypesWithoutRecursion? echoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything); + AllNullableTypesWithoutRecursion? everything, + ); /// Returns passed in arguments of multiple types. /// /// Tests multiple-arity FlutterApi handling. @ObjCSelector('sendMultipleNullableTypesWithoutRecursionABool:anInt:aString:') @SwiftFunction( - 'sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)') + 'sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)', + ) AllNullableTypesWithoutRecursion sendMultipleNullableTypesWithoutRecursion( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); // ========== Non-nullable argument/return type tests ========== @@ -1247,7 +1295,8 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoClassMap:') @SwiftFunction('echo(classMap:)') Map echoClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNonNullStringMap:') @@ -1268,7 +1317,8 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoNonNullClassMap:') @SwiftFunction('echoNonNull(classMap:)') Map echoNonNullClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoEnum:') @@ -1321,7 +1371,8 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoNullableClassList:') @SwiftFunction('echoNullable(classList:)') List? echoNullableClassList( - List? classList); + List? classList, + ); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullEnumList:') @@ -1332,7 +1383,8 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoNullableNonNullClassList:') @SwiftFunction('echoNullableNonNull(classList:)') List? echoNullableNonNullClassList( - List? classList); + List? classList, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableMap:') @@ -1343,7 +1395,8 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoNullableStringMap:') @SwiftFunction('echoNullable(stringMap:)') Map? echoNullableStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableIntMap:') @@ -1359,13 +1412,15 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoNullableClassMap:') @SwiftFunction('echoNullable(classMap:)') Map? echoNullableClassMap( - Map? classMap); + Map? classMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullStringMap:') @SwiftFunction('echoNullableNonNull(stringMap:)') Map? echoNullableNonNullStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullIntMap:') @@ -1381,7 +1436,8 @@ abstract class FlutterIntegrationCoreApi { @ObjCSelector('echoNullableNonNullClassMap:') @SwiftFunction('echoNullableNonNull(classMap:)') Map? echoNullableNonNullClassMap( - Map? classMap); + Map? classMap, + ); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoNullableEnum:') diff --git a/packages/pigeon/pigeons/enum.dart b/packages/pigeon/pigeons/enum.dart index c8d5f4805b9..e6d07f8a0f2 100644 --- a/packages/pigeon/pigeons/enum.dart +++ b/packages/pigeon/pigeons/enum.dart @@ -4,11 +4,12 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - // This is here to test option merging. - objcOptions: ObjcOptions(prefix: 'ThisShouldntEndUpInTheOutput'), -)) - +@ConfigurePigeon( + PigeonOptions( + // This is here to test option merging. + objcOptions: ObjcOptions(prefix: 'ThisShouldntEndUpInTheOutput'), + ), +) /// This comment is to test enum documentation comments. enum EnumState { /// This comment is to test enum member (Pending) documentation comments. @@ -31,7 +32,6 @@ class DataWithEnum { } @HostApi() - /// This comment is to test api documentation comments. abstract class EnumApi2Host { /// This comment is to test method documentation comments. @@ -39,7 +39,6 @@ abstract class EnumApi2Host { } @FlutterApi() - /// This comment is to test api documentation comments. abstract class EnumApi2Flutter { /// This comment is to test method documentation comments. diff --git a/packages/pigeon/pigeons/event_channel_tests.dart b/packages/pigeon/pigeons/event_channel_tests.dart index e089a60db7e..d530639225b 100644 --- a/packages/pigeon/pigeons/event_channel_tests.dart +++ b/packages/pigeon/pigeons/event_channel_tests.dart @@ -4,19 +4,11 @@ import 'package:pigeon/pigeon.dart'; -enum EventEnum { - one, - two, - three, - fortyTwo, - fourHundredTwentyTwo, -} +enum EventEnum { one, two, three, fortyTwo, fourHundredTwentyTwo } // Enums require special logic, having multiple ensures that the logic can be // replicated without collision. -enum AnotherEventEnum { - justInCase, -} +enum AnotherEventEnum { justInCase } /// A class containing all supported nullable types. @SwiftClass() diff --git a/packages/pigeon/pigeons/event_channel_without_classes_tests.dart b/packages/pigeon/pigeons/event_channel_without_classes_tests.dart index a568f0ae4fa..663e82529d3 100644 --- a/packages/pigeon/pigeons/event_channel_without_classes_tests.dart +++ b/packages/pigeon/pigeons/event_channel_without_classes_tests.dart @@ -7,8 +7,9 @@ import 'package:pigeon/pigeon.dart'; // This file exists to test compilation for multi-file event channel usage. @EventChannelApi( - swiftOptions: SwiftEventChannelOptions(includeSharedClasses: false), - kotlinOptions: KotlinEventChannelOptions(includeSharedClasses: false)) + swiftOptions: SwiftEventChannelOptions(includeSharedClasses: false), + kotlinOptions: KotlinEventChannelOptions(includeSharedClasses: false), +) abstract class EventChannelMethods { int streamIntsAgain(); } diff --git a/packages/pigeon/pigeons/message.dart b/packages/pigeon/pigeons/message.dart index 65ef2ac0e3a..57e2611a152 100644 --- a/packages/pigeon/pigeons/message.dart +++ b/packages/pigeon/pigeons/message.dart @@ -7,16 +7,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - javaOptions: JavaOptions( - className: 'MessagePigeon', - package: 'dev.flutter.aaclarke.pigeon', +@ConfigurePigeon( + PigeonOptions( + javaOptions: JavaOptions( + className: 'MessagePigeon', + package: 'dev.flutter.aaclarke.pigeon', + ), + objcOptions: ObjcOptions(prefix: 'AC'), ), - objcOptions: ObjcOptions( - prefix: 'AC', - ), -)) - +) /// This comment is to test enum documentation comments. /// /// This comment also tests multiple line comments. @@ -24,11 +23,7 @@ import 'package:pigeon/pigeon.dart'; /////////////////////////// /// This comment also tests comments that start with '/' /////////////////////////// -enum MessageRequestState { - pending, - success, - failure, -} +enum MessageRequestState { pending, success, failure } /// This comment is to test class documentation comments. /// @@ -59,7 +54,6 @@ class MessageSearchReply { } @HostApi(dartHostTestHandler: 'TestHostApi') - /// This comment is to test api documentation comments. /// /// This comment also tests multiple line comments. @@ -80,7 +74,6 @@ class MessageNested { } @HostApi(dartHostTestHandler: 'TestNestedApi') - /// This comment is to test api documentation comments. abstract class MessageNestedApi { /// This comment is to test method documentation comments. @@ -90,7 +83,6 @@ abstract class MessageNestedApi { } @FlutterApi() - /// This comment is to test api documentation comments. abstract class MessageFlutterSearchApi { /// This comment is to test method documentation comments. diff --git a/packages/pigeon/pigeons/non_null_fields.dart b/packages/pigeon/pigeons/non_null_fields.dart index f79a262b278..27cef42f350 100644 --- a/packages/pigeon/pigeons/non_null_fields.dart +++ b/packages/pigeon/pigeons/non_null_fields.dart @@ -22,7 +22,12 @@ enum ReplyType { success, error } class NonNullFieldSearchReply { NonNullFieldSearchReply( - this.result, this.error, this.indices, this.extraData, this.type); + this.result, + this.error, + this.indices, + this.extraData, + this.type, + ); String result; String error; List indices; diff --git a/packages/pigeon/pigeons/null_fields.dart b/packages/pigeon/pigeons/null_fields.dart index f9a9804bfa5..9bd409cdead 100644 --- a/packages/pigeon/pigeons/null_fields.dart +++ b/packages/pigeon/pigeons/null_fields.dart @@ -15,10 +15,7 @@ class NullFieldsSearchRequest { int identifier; } -enum NullFieldsSearchReplyType { - success, - failure, -} +enum NullFieldsSearchReplyType { success, failure } class NullFieldsSearchReply { NullFieldsSearchReply( diff --git a/packages/pigeon/pigeons/proxy_api_tests.dart b/packages/pigeon/pigeons/proxy_api_tests.dart index 4d47992ed85..cae5c255b63 100644 --- a/packages/pigeon/pigeons/proxy_api_tests.dart +++ b/packages/pigeon/pigeons/proxy_api_tests.dart @@ -4,11 +4,7 @@ import 'package:pigeon/pigeon.dart'; -enum ProxyApiTestEnum { - one, - two, - three, -} +enum ProxyApiTestEnum { one, two, three } /// The core ProxyApi test class that each supported host language must /// implement in platform_tests integration tests. @@ -115,23 +111,25 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. late List Function(List aList) - flutterEchoProxyApiList; + flutterEchoProxyApiList; /// Returns the passed map, to test serialization and deserialization. late Map Function(Map aMap) - flutterEchoMap; + flutterEchoMap; /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. late Map Function( - Map aMap) flutterEchoProxyApiMap; + Map aMap, + ) + flutterEchoProxyApiMap; /// Returns the passed enum to test serialization and deserialization. late ProxyApiTestEnum Function(ProxyApiTestEnum anEnum) flutterEchoEnum; /// Returns the passed ProxyApi to test serialization and deserialization. late ProxyApiSuperClass Function(ProxyApiSuperClass aProxyApi) - flutterEchoProxyApi; + flutterEchoProxyApi; // ========== Nullable argument/return type tests ========== @@ -155,15 +153,15 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map, to test serialization and deserialization. late Map? Function(Map? aMap)? - flutterEchoNullableMap; + flutterEchoNullableMap; /// Returns the passed enum to test serialization and deserialization. late ProxyApiTestEnum? Function(ProxyApiTestEnum? anEnum)? - flutterEchoNullableEnum; + flutterEchoNullableEnum; /// Returns the passed ProxyApi to test serialization and deserialization. late ProxyApiSuperClass? Function(ProxyApiSuperClass? aProxyApi)? - flutterEchoNullableProxyApi; + flutterEchoNullableProxyApi; // ========== Async tests ========== // These are minimal since async FlutterApi only changes Dart generation. @@ -217,9 +215,7 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. - List echoProxyApiList( - List aList, - ); + List echoProxyApiList(List aList); /// Returns the passed map, to test serialization and deserialization. Map echoMap(Map aMap); @@ -403,14 +399,16 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass @async List callFlutterEchoProxyApiList( - List aList); + List aList, + ); @async Map callFlutterEchoMap(Map aMap); @async Map callFlutterEchoProxyApiMap( - Map aMap); + Map aMap, + ); @async ProxyApiTestEnum callFlutterEchoEnum(ProxyApiTestEnum anEnum); diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml index ee2866b2b95..a902a642fd8 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Pigeon test harness for alternate plugin languages. publish_to: 'none' environment: - sdk: ^3.6.0 + sdk: ^3.7.0 dependencies: alternate_language_test_plugin: diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml b/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml index 14ece47a315..06058dd0028 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml @@ -4,8 +4,8 @@ version: 0.0.1 publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/example_app.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/example_app.dart index 31075ae532f..3a52e57154e 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/example_app.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/example_app.dart @@ -54,12 +54,8 @@ class _ExampleAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Pigeon integration tests'), - ), - body: Center( - child: Text(status), - ), + appBar: AppBar(title: const Text('Pigeon integration tests')), + body: Center(child: Text(status)), ), ); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart index 48b495dd6a3..5fb7c630a74 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart @@ -52,117 +52,130 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(api.noop(), completes); }); - testWidgets('all datatypes serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('all datatypes serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAllTypes(genericAllTypes); expect(echoObject, genericAllTypes); }); - testWidgets('all nullable datatypes serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('all nullable datatypes serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypes? echoObject = - await api.echoAllNullableTypes(recursiveAllNullableTypes); + final AllNullableTypes? echoObject = await api.echoAllNullableTypes( + recursiveAllNullableTypes, + ); expect(echoObject, recursiveAllNullableTypes); }); - testWidgets('all null datatypes serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('all null datatypes serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes allTypesNull = AllNullableTypes(); - final AllNullableTypes? echoNullFilledClass = - await api.echoAllNullableTypes(allTypesNull); + final AllNullableTypes? echoNullFilledClass = await api + .echoAllNullableTypes(allTypesNull); expect(allTypesNull, echoNullFilledClass); }); - testWidgets('Classes with list of null serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + testWidgets( + 'Classes with list of null serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypes listTypes = - AllNullableTypes(list: ['String', null]); + final AllNullableTypes listTypes = AllNullableTypes( + list: ['String', null], + ); - final AllNullableTypes? echoNullFilledClass = - await api.echoAllNullableTypes(listTypes); + final AllNullableTypes? echoNullFilledClass = await api + .echoAllNullableTypes(listTypes); - expect(listTypes, echoNullFilledClass); - }); + expect(listTypes, echoNullFilledClass); + }, + ); - testWidgets('Classes with map of null serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + testWidgets( + 'Classes with map of null serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypes listTypes = AllNullableTypes( - map: {'String': 'string', 'null': null}); + final AllNullableTypes listTypes = AllNullableTypes( + map: {'String': 'string', 'null': null}, + ); - final AllNullableTypes? echoNullFilledClass = - await api.echoAllNullableTypes(listTypes); + final AllNullableTypes? echoNullFilledClass = await api + .echoAllNullableTypes(listTypes); - expect(listTypes, echoNullFilledClass); - }); + expect(listTypes, echoNullFilledClass); + }, + ); testWidgets( - 'all nullable datatypes without recursion serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'all nullable datatypes without recursion serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion? echoObject = - await api.echoAllNullableTypesWithoutRecursion( - genericAllNullableTypesWithoutRecursion); + final AllNullableTypesWithoutRecursion? echoObject = await api + .echoAllNullableTypesWithoutRecursion( + genericAllNullableTypesWithoutRecursion, + ); - expect(echoObject, genericAllNullableTypesWithoutRecursion); - }); + expect(echoObject, genericAllNullableTypesWithoutRecursion); + }, + ); testWidgets( - 'all null datatypes without recursion serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'all null datatypes without recursion serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion allTypesNull = - AllNullableTypesWithoutRecursion(); + final AllNullableTypesWithoutRecursion allTypesNull = + AllNullableTypesWithoutRecursion(); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = - await api.echoAllNullableTypesWithoutRecursion(allTypesNull); - expect(allTypesNull, echoNullFilledClass); - }); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAllNullableTypesWithoutRecursion(allTypesNull); + expect(allTypesNull, echoNullFilledClass); + }, + ); testWidgets( - 'Classes without recursion with list of null serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'Classes without recursion with list of null serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion listTypes = - AllNullableTypesWithoutRecursion( - list: ['String', null], - ); + final AllNullableTypesWithoutRecursion listTypes = + AllNullableTypesWithoutRecursion(list: ['String', null]); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = - await api.echoAllNullableTypesWithoutRecursion(listTypes); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAllNullableTypesWithoutRecursion(listTypes); - expect(listTypes, echoNullFilledClass); - }); + expect(listTypes, echoNullFilledClass); + }, + ); testWidgets( - 'Classes without recursion with map of null serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'Classes without recursion with map of null serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion listTypes = - AllNullableTypesWithoutRecursion( - map: {'String': 'string', 'null': null}, - ); + final AllNullableTypesWithoutRecursion listTypes = + AllNullableTypesWithoutRecursion( + map: {'String': 'string', 'null': null}, + ); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = - await api.echoAllNullableTypesWithoutRecursion(listTypes); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAllNullableTypesWithoutRecursion(listTypes); - expect(listTypes, echoNullFilledClass); - }); + expect(listTypes, echoNullFilledClass); + }, + ); testWidgets('errors are returned correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); @@ -172,8 +185,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('errors are returned from void methods correctly', - (WidgetTester _) async { + testWidgets('errors are returned from void methods correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { @@ -181,124 +195,146 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('flutter errors are returned correctly', - (WidgetTester _) async { + testWidgets('flutter errors are returned correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect( - () => api.throwFlutterError(), - throwsA((dynamic e) => + () => api.throwFlutterError(), + throwsA( + (dynamic e) => e is PlatformException && e.code == 'code' && e.message == 'message' && - e.details == 'details')); + e.details == 'details', + ), + ); }); testWidgets('nested objects can be sent correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); - final String? receivedString = - await api.extractNestedNullableString(classWrapper); + final String? receivedString = await api.extractNestedNullableString( + classWrapper, + ); expect(receivedString, classWrapper.allNullableTypes.aNullableString); }); - testWidgets('nested objects can be received correctly', - (WidgetTester _) async { + testWidgets('nested objects can be received correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = 'Some string'; - final AllClassesWrapper receivedObject = - await api.createNestedNullableString(sentString); + final AllClassesWrapper receivedObject = await api + .createNestedNullableString(sentString); expect(receivedObject.allNullableTypes.aNullableString, sentString); }); - testWidgets('nested classes can serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nested classes can serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); - final AllClassesWrapper receivedClassWrapper = - await api.echoClassWrapper(classWrapper); + final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper( + classWrapper, + ); expect(classWrapper, receivedClassWrapper); }); - testWidgets('nested null classes can serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nested null classes can serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); classWrapper.allTypes = null; - final AllClassesWrapper receivedClassWrapper = - await api.echoClassWrapper(classWrapper); + final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper( + classWrapper, + ); expect(classWrapper, receivedClassWrapper); }); testWidgets( - 'Arguments of multiple types serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; - const int aNullableInt = regularInt; - - final AllNullableTypes echoObject = await api.sendMultipleNullableTypes( - aNullableBool, aNullableInt, aNullableString); - expect(echoObject.aNullableInt, aNullableInt); - expect(echoObject.aNullableBool, aNullableBool); - expect(echoObject.aNullableString, aNullableString); - }); + 'Arguments of multiple types serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + const String aNullableString = 'this is a String'; + const bool aNullableBool = false; + const int aNullableInt = regularInt; + + final AllNullableTypes echoObject = await api.sendMultipleNullableTypes( + aNullableBool, + aNullableInt, + aNullableString, + ); + expect(echoObject.aNullableInt, aNullableInt); + expect(echoObject.aNullableBool, aNullableBool); + expect(echoObject.aNullableString, aNullableString); + }, + ); testWidgets( - 'Arguments of multiple null types serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final AllNullableTypes echoNullFilledClass = - await api.sendMultipleNullableTypes(null, null, null); - expect(echoNullFilledClass.aNullableInt, null); - expect(echoNullFilledClass.aNullableBool, null); - expect(echoNullFilledClass.aNullableString, null); - }); + 'Arguments of multiple null types serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final AllNullableTypes echoNullFilledClass = await api + .sendMultipleNullableTypes(null, null, null); + expect(echoNullFilledClass.aNullableInt, null); + expect(echoNullFilledClass.aNullableBool, null); + expect(echoNullFilledClass.aNullableString, null); + }, + ); testWidgets( - 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; - const int aNullableInt = regularInt; - - final AllNullableTypesWithoutRecursion echoObject = - await api.sendMultipleNullableTypesWithoutRecursion( - aNullableBool, aNullableInt, aNullableString); - expect(echoObject.aNullableInt, aNullableInt); - expect(echoObject.aNullableBool, aNullableBool); - expect(echoObject.aNullableString, aNullableString); - }); + 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + const String aNullableString = 'this is a String'; + const bool aNullableBool = false; + const int aNullableInt = regularInt; + + final AllNullableTypesWithoutRecursion echoObject = await api + .sendMultipleNullableTypesWithoutRecursion( + aNullableBool, + aNullableInt, + aNullableString, + ); + expect(echoObject.aNullableInt, aNullableInt); + expect(echoObject.aNullableBool, aNullableBool); + expect(echoObject.aNullableString, aNullableString); + }, + ); testWidgets( - 'Arguments of multiple null types serialize and deserialize correctly (WithoutRecursion)', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final AllNullableTypesWithoutRecursion echoNullFilledClass = - await api.sendMultipleNullableTypesWithoutRecursion(null, null, null); - expect(echoNullFilledClass.aNullableInt, null); - expect(echoNullFilledClass.aNullableBool, null); - expect(echoNullFilledClass.aNullableString, null); - }); - - testWidgets('Int serialize and deserialize correctly', - (WidgetTester _) async { + 'Arguments of multiple null types serialize and deserialize correctly (WithoutRecursion)', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final AllNullableTypesWithoutRecursion echoNullFilledClass = await api + .sendMultipleNullableTypesWithoutRecursion(null, null, null); + expect(echoNullFilledClass.aNullableInt, null); + expect(echoNullFilledClass.aNullableBool, null); + expect(echoNullFilledClass.aNullableString, null); + }, + ); + + testWidgets('Int serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int receivedInt = await api.echoInt(sentInt); expect(receivedInt, sentInt); }); - testWidgets('Int64 serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Int64 serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -306,8 +342,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Doubles serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Doubles serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; @@ -315,8 +352,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedDouble, sentDouble); }); - testWidgets('booleans serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('booleans serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentBool in [true, false]) { @@ -325,16 +363,18 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('strings serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('strings serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = 'default'; final String receivedString = await api.echoString(sentString); expect(receivedString, sentString); }); - testWidgets('Uint8List serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Uint8List serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List data = [ 102, @@ -346,16 +386,18 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { 116, 119, 111, - 0 + 0, ]; final Uint8List sentUint8List = Uint8List.fromList(data); - final Uint8List receivedUint8List = - await api.echoUint8List(sentUint8List); + final Uint8List receivedUint8List = await api.echoUint8List( + sentUint8List, + ); expect(receivedUint8List, sentUint8List); }); - testWidgets('generic Objects serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('generic Objects serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoObject(sentString); @@ -367,129 +409,152 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List echoObject = await api.echoList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List echoObject = await api.echoEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.echoClassList(allNullableTypesList); + final List echoObject = await api.echoClassList( + allNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('NonNull enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.echoNonNullEnumList(nonNullEnumList); + final List echoObject = await api.echoNonNullEnumList( + nonNullEnumList, + ); expect(listEquals(echoObject, nonNullEnumList), true); }); - testWidgets('NonNull class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.echoNonNullClassList(nonNullAllNullableTypesList); + final List echoObject = await api.echoNonNullClassList( + nonNullAllNullableTypesList, + ); for (final (int index, AllNullableTypes value) in echoObject.indexed) { expect(value, nonNullAllNullableTypesList[index]); } }); - testWidgets('maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map echoObject = await api.echoMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoStringMap(stringMap); + final Map echoObject = await api.echoStringMap( + stringMap, + ); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map echoObject = await api.echoIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map echoObject = await api.echoEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoClassMap(allNullableTypesMap); + final Map echoObject = await api.echoClassMap( + allNullableTypesMap, + ); for (final MapEntry entry in echoObject.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('NonNull string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoNonNullStringMap(nonNullStringMap); + final Map echoObject = await api.echoNonNullStringMap( + nonNullStringMap, + ); expect(mapEquals(echoObject, nonNullStringMap), true); }); - testWidgets('NonNull int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoNonNullIntMap(nonNullIntMap); + final Map echoObject = await api.echoNonNullIntMap( + nonNullIntMap, + ); expect(mapEquals(echoObject, nonNullIntMap), true); }); - testWidgets('NonNull enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoNonNullEnumMap(nonNullEnumMap); + final Map echoObject = await api.echoNonNullEnumMap( + nonNullEnumMap, + ); expect(mapEquals(echoObject, nonNullEnumMap), true); }); - testWidgets('NonNull class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoNonNullClassMap(nonNullAllNullableTypesMap); + final Map echoObject = await api + .echoNonNullClassMap(nonNullAllNullableTypesMap); for (final MapEntry entry in echoObject.entries) { expect(entry.value, nonNullAllNullableTypesMap[entry.key]); } }); - testWidgets('enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.two; @@ -497,8 +562,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedEnum, sentEnum); }); - testWidgets('enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; @@ -506,8 +572,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedEnum, sentEnum); }); - testWidgets('multi word enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('multi word enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; @@ -536,8 +603,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 3.15; - final double receivedDouble = - await api.echoOptionalDefaultDouble(sentDouble); + final double receivedDouble = await api.echoOptionalDefaultDouble( + sentDouble, + ); expect(receivedDouble, sentDouble); }); @@ -553,13 +621,15 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); // This string corresponds with the default value of this method. const String sentString = 'notDefault'; - final String receivedString = - await api.echoNamedDefaultString(aString: sentString); + final String receivedString = await api.echoNamedDefaultString( + aString: sentString, + ); expect(receivedString, sentString); }); - testWidgets('Nullable Int serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Nullable Int serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = regularInt; @@ -567,8 +637,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Nullable Int64 serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Nullable Int64 serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -576,16 +647,18 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Null Ints serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Null Ints serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? receivedNullInt = await api.echoNullableInt(null); expect(receivedNullInt, null); }); - testWidgets('Nullable Doubles serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Nullable Doubles serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; @@ -593,16 +666,18 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedDouble, sentDouble); }); - testWidgets('Null Doubles serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Null Doubles serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final double? receivedNullDouble = await api.echoNullableDouble(null); expect(receivedNullDouble, null); }); - testWidgets('Nullable booleans serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Nullable booleans serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool? sentBool in [true, false]) { @@ -611,8 +686,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('Null booleans serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Null booleans serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const bool? sentBool = null; @@ -620,24 +696,27 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedBool, sentBool); }); - testWidgets('Nullable strings serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Nullable strings serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = "I'm a computer"; final String? receivedString = await api.echoNullableString(sentString); expect(receivedString, sentString); }); - testWidgets('Null strings serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Null strings serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? receivedNullString = await api.echoNullableString(null); expect(receivedNullString, null); }); - testWidgets('Nullable Uint8List serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Nullable Uint8List serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List data = [ 102, @@ -649,128 +728,148 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { 116, 119, 111, - 0 + 0, ]; final Uint8List sentUint8List = Uint8List.fromList(data); - final Uint8List? receivedUint8List = - await api.echoNullableUint8List(sentUint8List); + final Uint8List? receivedUint8List = await api.echoNullableUint8List( + sentUint8List, + ); expect(receivedUint8List, sentUint8List); }); - testWidgets('Null Uint8List serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Null Uint8List serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Uint8List? receivedNullUint8List = - await api.echoNullableUint8List(null); + final Uint8List? receivedNullUint8List = await api.echoNullableUint8List( + null, + ); expect(receivedNullUint8List, null); }); - testWidgets('generic nullable Objects serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const Object sentString = "I'm a computer"; - final Object? receivedString = await api.echoNullableObject(sentString); - expect(receivedString, sentString); + testWidgets( + 'generic nullable Objects serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + const Object sentString = "I'm a computer"; + final Object? receivedString = await api.echoNullableObject(sentString); + expect(receivedString, sentString); - // Echo a second type as well to ensure the handling is generic. - const Object sentInt = regularInt; - final Object? receivedInt = await api.echoNullableObject(sentInt); - expect(receivedInt, sentInt); - }); + // Echo a second type as well to ensure the handling is generic. + const Object sentInt = regularInt; + final Object? receivedInt = await api.echoNullableObject(sentInt); + expect(receivedInt, sentInt); + }, + ); - testWidgets('Null generic Objects serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Null generic Objects serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Object? receivedNullObject = await api.echoNullableObject(null); expect(receivedNullObject, null); }); - testWidgets('nullable lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('nullable enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.echoNullableEnumList(enumList); + final List? echoObject = await api.echoNullableEnumList( + enumList, + ); expect(listEquals(echoObject, enumList), true); }); - testWidgets('nullable lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.echoNullableClassList(allNullableTypesList); + final List? echoObject = await api + .echoNullableClassList(allNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, allNullableTypesList[index]); } }); testWidgets( - 'nullable NonNull enum lists serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'nullable NonNull enum lists serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.echoNullableNonNullEnumList(nonNullEnumList); - expect(listEquals(echoObject, nonNullEnumList), true); - }); + final List? echoObject = await api.echoNullableNonNullEnumList( + nonNullEnumList, + ); + expect(listEquals(echoObject, nonNullEnumList), true); + }, + ); - testWidgets('nullable NonNull lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable NonNull lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.echoNullableClassList(nonNullAllNullableTypesList); + final List? echoObject = await api + .echoNullableClassList(nonNullAllNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, nonNullAllNullableTypesList[index]); } }); - testWidgets('nullable maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('nullable string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableStringMap(stringMap); + final Map? echoObject = await api.echoNullableStringMap( + stringMap, + ); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('nullable int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('nullable enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableEnumMap(enumMap); + final Map? echoObject = await api.echoNullableEnumMap( + enumMap, + ); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('nullable class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableClassMap(allNullableTypesMap); + final Map? echoObject = await api + .echoNullableClassMap(allNullableTypesMap); for (final MapEntry entry in echoObject!.entries) { expect(entry.value, allNullableTypesMap[entry.key]); @@ -778,45 +877,52 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets( - 'nullable NonNull string maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableNonNullStringMap(nonNullStringMap); - expect(mapEquals(echoObject, nonNullStringMap), true); - }); - - testWidgets('nullable NonNull int maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableNonNullIntMap(nonNullIntMap); - expect(mapEquals(echoObject, nonNullIntMap), true); - }); + 'nullable NonNull string maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .echoNullableNonNullStringMap(nonNullStringMap); + expect(mapEquals(echoObject, nonNullStringMap), true); + }, + ); testWidgets( - 'nullable NonNull enum maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableNonNullEnumMap(nonNullEnumMap); - expect(mapEquals(echoObject, nonNullEnumMap), true); - }); + 'nullable NonNull int maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api.echoNullableNonNullIntMap( + nonNullIntMap, + ); + expect(mapEquals(echoObject, nonNullIntMap), true); + }, + ); testWidgets( - 'nullable NonNull class maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableNonNullClassMap(nonNullAllNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { - expect(entry.value, nonNullAllNullableTypesMap[entry.key]); - } - }); + 'nullable NonNull enum maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .echoNullableNonNullEnumMap(nonNullEnumMap); + expect(mapEquals(echoObject, nonNullEnumMap), true); + }, + ); - testWidgets('nullable enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets( + 'nullable NonNull class maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .echoNullableNonNullClassMap(nonNullAllNullableTypesMap); + for (final MapEntry entry + in echoObject!.entries) { + expect(entry.value, nonNullAllNullableTypesMap[entry.key]); + } + }, + ); + + testWidgets('nullable enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -824,8 +930,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('nullable enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; @@ -833,50 +940,58 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('multi word nullable enums serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + testWidgets( + 'multi word nullable enums serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; - final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); - expect(echoEnum, sentEnum); - }); + const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; + final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); + expect(echoEnum, sentEnum); + }, + ); - testWidgets('null lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableList(null); expect(listEquals(echoObject, null), true); }); - testWidgets('null maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoNullableStringMap(null); + final Map? echoObject = await api.echoNullableStringMap( + null, + ); expect(mapEquals(echoObject, null), true); }); - testWidgets('null int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableIntMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; @@ -884,8 +999,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('null enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; @@ -893,8 +1009,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null classes serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null classes serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api.echoAllNullableTypes(null); @@ -920,8 +1037,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('named nullable parameter', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = "I'm a computer"; - final String? receivedString = - await api.echoNamedNullableString(aNullableString: sentString); + final String? receivedString = await api.echoNamedNullableString( + aNullableString: sentString, + ); expect(receivedString, sentString); }); @@ -940,8 +1058,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(api.noopAsync(), completes); }); - testWidgets('async errors are returned from non void methods correctly', - (WidgetTester _) async { + testWidgets('async errors are returned from non void methods correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { @@ -949,8 +1068,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('async errors are returned from void methods correctly', - (WidgetTester _) async { + testWidgets('async errors are returned from void methods correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { @@ -959,21 +1079,26 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets( - 'async flutter errors are returned from non void methods correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'async flutter errors are returned from non void methods correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - expect( + expect( () => api.throwAsyncFlutterError(), - throwsA((dynamic e) => - e is PlatformException && - e.code == 'code' && - e.message == 'message' && - e.details == 'details')); - }); + throwsA( + (dynamic e) => + e is PlatformException && + e.code == 'code' && + e.message == 'message' && + e.details == 'details', + ), + ); + }, + ); - testWidgets('all datatypes async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('all datatypes async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAsyncAllTypes(genericAllTypes); @@ -982,54 +1107,61 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets( - 'all nullable async datatypes serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'all nullable async datatypes serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypes? echoObject = await api - .echoAsyncNullableAllNullableTypes(recursiveAllNullableTypes); + final AllNullableTypes? echoObject = await api + .echoAsyncNullableAllNullableTypes(recursiveAllNullableTypes); - expect(echoObject, recursiveAllNullableTypes); - }); + expect(echoObject, recursiveAllNullableTypes); + }, + ); - testWidgets('all null datatypes async serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + testWidgets( + 'all null datatypes async serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypes allTypesNull = AllNullableTypes(); + final AllNullableTypes allTypesNull = AllNullableTypes(); - final AllNullableTypes? echoNullFilledClass = - await api.echoAsyncNullableAllNullableTypes(allTypesNull); - expect(echoNullFilledClass, allTypesNull); - }); + final AllNullableTypes? echoNullFilledClass = await api + .echoAsyncNullableAllNullableTypes(allTypesNull); + expect(echoNullFilledClass, allTypesNull); + }, + ); testWidgets( - 'all nullable async datatypes without recursion serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'all nullable async datatypes without recursion serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion? echoObject = - await api.echoAsyncNullableAllNullableTypesWithoutRecursion( - genericAllNullableTypesWithoutRecursion); + final AllNullableTypesWithoutRecursion? echoObject = await api + .echoAsyncNullableAllNullableTypesWithoutRecursion( + genericAllNullableTypesWithoutRecursion, + ); - expect(echoObject, genericAllNullableTypesWithoutRecursion); - }); + expect(echoObject, genericAllNullableTypesWithoutRecursion); + }, + ); testWidgets( - 'all null datatypes without recursion async serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'all null datatypes without recursion async serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion allTypesNull = - AllNullableTypesWithoutRecursion(); + final AllNullableTypesWithoutRecursion allTypesNull = + AllNullableTypesWithoutRecursion(); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api - .echoAsyncNullableAllNullableTypesWithoutRecursion(allTypesNull); - expect(echoNullFilledClass, allTypesNull); - }); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAsyncNullableAllNullableTypesWithoutRecursion(allTypesNull); + expect(echoNullFilledClass, allTypesNull); + }, + ); - testWidgets('Int async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Int async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = regularInt; @@ -1037,8 +1169,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Int64 async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Int64 async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -1046,8 +1179,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Doubles async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Doubles async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; @@ -1055,8 +1189,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedDouble, sentDouble); }); - testWidgets('booleans async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('booleans async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentBool in [true, false]) { @@ -1065,8 +1200,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('strings async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('strings async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = 'Hello, asynchronously!'; @@ -1075,8 +1211,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('Uint8List async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Uint8List async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List data = [ 102, @@ -1088,16 +1225,18 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { 116, 119, 111, - 0 + 0, ]; final Uint8List sentUint8List = Uint8List.fromList(data); - final Uint8List receivedUint8List = - await api.echoAsyncUint8List(sentUint8List); + final Uint8List receivedUint8List = await api.echoAsyncUint8List( + sentUint8List, + ); expect(receivedUint8List, sentUint8List); }); - testWidgets('generic Objects async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('generic Objects async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoAsyncObject(sentString); @@ -1109,76 +1248,88 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.echoAsyncClassList(allNullableTypesList); + final List echoObject = await api.echoAsyncClassList( + allNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoAsyncStringMap(stringMap); + final Map echoObject = await api.echoAsyncStringMap( + stringMap, + ); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoAsyncEnumMap(enumMap); + final Map echoObject = await api.echoAsyncEnumMap( + enumMap, + ); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.echoAsyncClassMap(allNullableTypesMap); + final Map echoObject = await api + .echoAsyncClassMap(allNullableTypesMap); for (final MapEntry entry in echoObject.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -1186,8 +1337,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; @@ -1195,8 +1347,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('multi word enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('multi word enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; @@ -1204,8 +1357,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable Int async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable Int async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = regularInt; @@ -1213,8 +1367,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('nullable Int64 async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable Int64 async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -1222,18 +1377,21 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('nullable Doubles async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable Doubles async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; - final double? receivedDouble = - await api.echoAsyncNullableDouble(sentDouble); + final double? receivedDouble = await api.echoAsyncNullableDouble( + sentDouble, + ); expect(receivedDouble, sentDouble); }); - testWidgets('nullable booleans async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable booleans async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentBool in [true, false]) { @@ -1242,8 +1400,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('nullable strings async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable strings async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = 'Hello, asynchronously!'; @@ -1252,115 +1411,131 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('nullable Uint8List async serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0 - ]; - final Uint8List sentUint8List = Uint8List.fromList(data); - final Uint8List? receivedUint8List = - await api.echoAsyncNullableUint8List(sentUint8List); - expect(receivedUint8List, sentUint8List); - }); - testWidgets( - 'nullable generic Objects async serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const Object sentString = "I'm a computer"; - final Object? receivedString = - await api.echoAsyncNullableObject(sentString); - expect(receivedString, sentString); + 'nullable Uint8List async serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final List data = [ + 102, + 111, + 114, + 116, + 121, + 45, + 116, + 119, + 111, + 0, + ]; + final Uint8List sentUint8List = Uint8List.fromList(data); + final Uint8List? receivedUint8List = await api + .echoAsyncNullableUint8List(sentUint8List); + expect(receivedUint8List, sentUint8List); + }, + ); - // Echo a second type as well to ensure the handling is generic. - const Object sentInt = regularInt; - final Object? receivedInt = await api.echoAsyncNullableObject(sentInt); - expect(receivedInt, sentInt); - }); - - testWidgets('nullable lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets( + 'nullable generic Objects async serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + const Object sentString = "I'm a computer"; + final Object? receivedString = await api.echoAsyncNullableObject( + sentString, + ); + expect(receivedString, sentString); + + // Echo a second type as well to ensure the handling is generic. + const Object sentInt = regularInt; + final Object? receivedInt = await api.echoAsyncNullableObject(sentInt); + expect(receivedInt, sentInt); + }, + ); + + testWidgets('nullable lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('nullable enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.echoAsyncNullableEnumList(enumList); + final List? echoObject = await api.echoAsyncNullableEnumList( + enumList, + ); expect(listEquals(echoObject, enumList), true); }); - testWidgets('nullable class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.echoAsyncNullableClassList(allNullableTypesList); + final List? echoObject = await api + .echoAsyncNullableClassList(allNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('nullable maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableMap(map); + final Map? echoObject = await api.echoAsyncNullableMap( + map, + ); expect(mapEquals(echoObject, map), true); }); - testWidgets('nullable string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableStringMap(stringMap); + final Map? echoObject = await api + .echoAsyncNullableStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('nullable int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableIntMap(intMap); + final Map? echoObject = await api.echoAsyncNullableIntMap( + intMap, + ); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('nullable enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableEnumMap(enumMap); + final Map? echoObject = await api + .echoAsyncNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('nullable class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableClassMap(allNullableTypesMap); + final Map? echoObject = await api + .echoAsyncNullableClassMap(allNullableTypesMap); for (final MapEntry entry in echoObject!.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('nullable enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -1368,18 +1543,21 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('nullable enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; - final AnotherEnum? echoEnum = - await api.echoAnotherAsyncNullableEnum(sentEnum); + final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum( + sentEnum, + ); expect(echoEnum, sentEnum); }); - testWidgets('nullable enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; @@ -1387,92 +1565,106 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null Ints async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null Ints async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? receivedInt = await api.echoAsyncNullableInt(null); expect(receivedInt, null); }); - testWidgets('null Doubles async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null Doubles async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final double? receivedDouble = await api.echoAsyncNullableDouble(null); expect(receivedDouble, null); }); - testWidgets('null booleans async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null booleans async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final bool? receivedBool = await api.echoAsyncNullableBool(null); expect(receivedBool, null); }); - testWidgets('null strings async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null strings async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? echoObject = await api.echoAsyncNullableString(null); expect(echoObject, null); }); - testWidgets('null Uint8List async serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null Uint8List async serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Uint8List? receivedUint8List = - await api.echoAsyncNullableUint8List(null); + final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List( + null, + ); expect(receivedUint8List, null); }); testWidgets( - 'null generic Objects async serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Object? receivedString = await api.echoAsyncNullableObject(null); - expect(receivedString, null); - }); + 'null generic Objects async serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Object? receivedString = await api.echoAsyncNullableObject(null); + expect(receivedString, null); + }, + ); - testWidgets('null lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableList(null); expect(listEquals(echoObject, null), true); }); - testWidgets('null maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableMap(null); + final Map? echoObject = await api.echoAsyncNullableMap( + null, + ); expect(mapEquals(echoObject, null), true); }); - testWidgets('null string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableStringMap(null); + final Map? echoObject = await api + .echoAsyncNullableStringMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.echoAsyncNullableIntMap(null); + final Map? echoObject = await api.echoAsyncNullableIntMap( + null, + ); expect(mapEquals(echoObject, null), true); }); - testWidgets('null enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; @@ -1480,24 +1672,29 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; - final AnotherEnum? echoEnum = - await api.echoAnotherAsyncNullableEnum(null); + final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum( + null, + ); expect(echoEnum, sentEnum); }); }); group('Host API with suffix', () { - testWidgets('echo string succeeds with suffix with multiple instances', - (_) async { - final HostSmallApi apiWithSuffixOne = - HostSmallApi(messageChannelSuffix: 'suffixOne'); - final HostSmallApi apiWithSuffixTwo = - HostSmallApi(messageChannelSuffix: 'suffixTwo'); + testWidgets('echo string succeeds with suffix with multiple instances', ( + _, + ) async { + final HostSmallApi apiWithSuffixOne = HostSmallApi( + messageChannelSuffix: 'suffixOne', + ); + final HostSmallApi apiWithSuffixTwo = HostSmallApi( + messageChannelSuffix: 'suffixTwo', + ); const String sentString = "I'm a computer"; final String echoStringOne = await apiWithSuffixOne.echo(sentString); final String echoStringTwo = await apiWithSuffixTwo.echo(sentString); @@ -1505,14 +1702,17 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(sentString, echoStringTwo); }); - testWidgets('multiple instances will have different method channel names', - (_) async { + testWidgets('multiple instances will have different method channel names', ( + _, + ) async { // The only way to get the channel name back is to throw an exception. // These APIs have no corresponding APIs on the host platforms. - final HostSmallApi apiWithSuffixOne = - HostSmallApi(messageChannelSuffix: 'suffixWithNoHost'); - final HostSmallApi apiWithSuffixTwo = - HostSmallApi(messageChannelSuffix: 'suffixWithoutHost'); + final HostSmallApi apiWithSuffixOne = HostSmallApi( + messageChannelSuffix: 'suffixWithNoHost', + ); + final HostSmallApi apiWithSuffixTwo = HostSmallApi( + messageChannelSuffix: 'suffixWithoutHost', + ); const String sentString = "I'm a computer"; try { await apiWithSuffixOne.echo(sentString); @@ -1542,8 +1742,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(api.callFlutterNoop(), completes); }); - testWidgets('errors are returned from non void methods correctly', - (WidgetTester _) async { + testWidgets('errors are returned from non void methods correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { @@ -1551,8 +1752,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('errors are returned from void methods correctly', - (WidgetTester _) async { + testWidgets('errors are returned from void methods correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { @@ -1560,75 +1762,91 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('all datatypes serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('all datatypes serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final AllTypes echoObject = - await api.callFlutterEchoAllTypes(genericAllTypes); + final AllTypes echoObject = await api.callFlutterEchoAllTypes( + genericAllTypes, + ); expect(echoObject, genericAllTypes); }); testWidgets( - 'Arguments of multiple types serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; - const int aNullableInt = regularInt; - - final AllNullableTypes compositeObject = - await api.callFlutterSendMultipleNullableTypes( - aNullableBool, aNullableInt, aNullableString); - expect(compositeObject.aNullableInt, aNullableInt); - expect(compositeObject.aNullableBool, aNullableBool); - expect(compositeObject.aNullableString, aNullableString); - }); + 'Arguments of multiple types serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + const String aNullableString = 'this is a String'; + const bool aNullableBool = false; + const int aNullableInt = regularInt; + + final AllNullableTypes compositeObject = await api + .callFlutterSendMultipleNullableTypes( + aNullableBool, + aNullableInt, + aNullableString, + ); + expect(compositeObject.aNullableInt, aNullableInt); + expect(compositeObject.aNullableBool, aNullableBool); + expect(compositeObject.aNullableString, aNullableString); + }, + ); testWidgets( - 'Arguments of multiple null types serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final AllNullableTypes compositeObject = - await api.callFlutterSendMultipleNullableTypes(null, null, null); - expect(compositeObject.aNullableInt, null); - expect(compositeObject.aNullableBool, null); - expect(compositeObject.aNullableString, null); - }); + 'Arguments of multiple null types serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final AllNullableTypes compositeObject = await api + .callFlutterSendMultipleNullableTypes(null, null, null); + expect(compositeObject.aNullableInt, null); + expect(compositeObject.aNullableBool, null); + expect(compositeObject.aNullableString, null); + }, + ); testWidgets( - 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; - const int aNullableInt = regularInt; - - final AllNullableTypesWithoutRecursion compositeObject = - await api.callFlutterSendMultipleNullableTypesWithoutRecursion( - aNullableBool, aNullableInt, aNullableString); - expect(compositeObject.aNullableInt, aNullableInt); - expect(compositeObject.aNullableBool, aNullableBool); - expect(compositeObject.aNullableString, aNullableString); - }); + 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + const String aNullableString = 'this is a String'; + const bool aNullableBool = false; + const int aNullableInt = regularInt; + + final AllNullableTypesWithoutRecursion compositeObject = await api + .callFlutterSendMultipleNullableTypesWithoutRecursion( + aNullableBool, + aNullableInt, + aNullableString, + ); + expect(compositeObject.aNullableInt, aNullableInt); + expect(compositeObject.aNullableBool, aNullableBool); + expect(compositeObject.aNullableString, aNullableString); + }, + ); testWidgets( - 'Arguments of multiple null types serialize and deserialize correctly (WithoutRecursion)', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final AllNullableTypesWithoutRecursion compositeObject = - await api.callFlutterSendMultipleNullableTypesWithoutRecursion( - null, null, null); - expect(compositeObject.aNullableInt, null); - expect(compositeObject.aNullableBool, null); - expect(compositeObject.aNullableString, null); - }); - - testWidgets('booleans serialize and deserialize correctly', - (WidgetTester _) async { + 'Arguments of multiple null types serialize and deserialize correctly (WithoutRecursion)', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final AllNullableTypesWithoutRecursion compositeObject = await api + .callFlutterSendMultipleNullableTypesWithoutRecursion( + null, + null, + null, + ); + expect(compositeObject.aNullableInt, null); + expect(compositeObject.aNullableBool, null); + expect(compositeObject.aNullableString, null); + }, + ); + + testWidgets('booleans serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentObject in [true, false]) { @@ -1637,8 +1855,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('ints serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('ints serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentObject = regularInt; @@ -1646,8 +1865,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('doubles serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('doubles serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentObject = 2.0694; @@ -1655,8 +1875,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('strings serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('strings serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = 'Hello Dart!'; @@ -1664,8 +1885,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('Uint8Lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('Uint8Lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List data = [ @@ -1678,53 +1900,61 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { 116, 119, 111, - 0 + 0, ]; final Uint8List sentObject = Uint8List.fromList(data); - final Uint8List echoObject = - await api.callFlutterEchoUint8List(sentObject); + final Uint8List echoObject = await api.callFlutterEchoUint8List( + sentObject, + ); expect(echoObject, sentObject); }); - testWidgets('lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List echoObject = await api.callFlutterEchoList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.callFlutterEchoEnumList(enumList); + final List echoObject = await api.callFlutterEchoEnumList( + enumList, + ); expect(listEquals(echoObject, enumList), true); }); - testWidgets('class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.callFlutterEchoClassList(allNullableTypesList); + final List echoObject = await api + .callFlutterEchoClassList(allNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('NonNull enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List echoObject = - await api.callFlutterEchoNonNullEnumList(nonNullEnumList); + final List echoObject = await api.callFlutterEchoNonNullEnumList( + nonNullEnumList, + ); expect(listEquals(echoObject, nonNullEnumList), true); }); - testWidgets('NonNull class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List echoObject = await api @@ -1734,85 +1964,99 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoMap(map); + final Map echoObject = await api.callFlutterEchoMap( + map, + ); expect(mapEquals(echoObject, map), true); }); - testWidgets('string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoStringMap(stringMap); + final Map echoObject = await api + .callFlutterEchoStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoIntMap(intMap); + final Map echoObject = await api.callFlutterEchoIntMap( + intMap, + ); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoEnumMap(enumMap); + final Map echoObject = await api.callFlutterEchoEnumMap( + enumMap, + ); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoClassMap(allNullableTypesMap); + final Map echoObject = await api + .callFlutterEchoClassMap(allNullableTypesMap); for (final MapEntry entry in echoObject.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('NonNull string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoNonNullStringMap(nonNullStringMap); + final Map echoObject = await api + .callFlutterEchoNonNullStringMap(nonNullStringMap); expect(mapEquals(echoObject, nonNullStringMap), true); }); - testWidgets('NonNull int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoNonNullIntMap(nonNullIntMap); + final Map echoObject = await api.callFlutterEchoNonNullIntMap( + nonNullIntMap, + ); expect(mapEquals(echoObject, nonNullIntMap), true); }); - testWidgets('NonNull enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoNonNullEnumMap(nonNullEnumMap); + final Map echoObject = await api + .callFlutterEchoNonNullEnumMap(nonNullEnumMap); expect(mapEquals(echoObject, nonNullEnumMap), true); }); - testWidgets('NonNull class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('NonNull class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map echoObject = - await api.callFlutterEchoNonNullClassMap(nonNullAllNullableTypesMap); + final Map echoObject = await api + .callFlutterEchoNonNullClassMap(nonNullAllNullableTypesMap); for (final MapEntry entry in echoObject.entries) { expect(entry.value, nonNullAllNullableTypesMap[entry.key]); } }); - testWidgets('enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -1820,18 +2064,21 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; - final AnotherEnum echoEnum = - await api.callFlutterEchoAnotherEnum(sentEnum); + final AnotherEnum echoEnum = await api.callFlutterEchoAnotherEnum( + sentEnum, + ); expect(echoEnum, sentEnum); }); - testWidgets('multi word enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('multi word enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; @@ -1839,29 +2086,34 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable booleans serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable booleans serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool? sentObject in [true, false]) { - final bool? echoObject = - await api.callFlutterEchoNullableBool(sentObject); + final bool? echoObject = await api.callFlutterEchoNullableBool( + sentObject, + ); expect(echoObject, sentObject); } }); - testWidgets('null booleans serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null booleans serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const bool? sentObject = null; - final bool? echoObject = - await api.callFlutterEchoNullableBool(sentObject); + final bool? echoObject = await api.callFlutterEchoNullableBool( + sentObject, + ); expect(echoObject, sentObject); }); - testWidgets('nullable ints serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable ints serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentObject = regularInt; @@ -1869,8 +2121,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('nullable big ints serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable big ints serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentObject = biggerThanBigInt; @@ -1878,52 +2131,60 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('null ints serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null ints serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? echoObject = await api.callFlutterEchoNullableInt(null); expect(echoObject, null); }); - testWidgets('nullable doubles serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable doubles serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentObject = 2.0694; - final double? echoObject = - await api.callFlutterEchoNullableDouble(sentObject); + final double? echoObject = await api.callFlutterEchoNullableDouble( + sentObject, + ); expect(echoObject, sentObject); }); - testWidgets('null doubles serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null doubles serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final double? echoObject = await api.callFlutterEchoNullableDouble(null); expect(echoObject, null); }); - testWidgets('nullable strings serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable strings serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = "I'm a computer"; - final String? echoObject = - await api.callFlutterEchoNullableString(sentObject); + final String? echoObject = await api.callFlutterEchoNullableString( + sentObject, + ); expect(echoObject, sentObject); }); - testWidgets('null strings serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null strings serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? echoObject = await api.callFlutterEchoNullableString(null); expect(echoObject, null); }); - testWidgets('nullable Uint8Lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable Uint8Lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List data = [ 102, @@ -1935,129 +2196,149 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { 116, 119, 111, - 0 + 0, ]; final Uint8List sentObject = Uint8List.fromList(data); - final Uint8List? echoObject = - await api.callFlutterEchoNullableUint8List(sentObject); + final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List( + sentObject, + ); expect(echoObject, sentObject); }); - testWidgets('null Uint8Lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null Uint8Lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Uint8List? echoObject = - await api.callFlutterEchoNullableUint8List(null); + final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List( + null, + ); expect(echoObject, null); }); - testWidgets('nullable lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.callFlutterEchoNullableList(list); + final List? echoObject = await api.callFlutterEchoNullableList( + list, + ); expect(listEquals(echoObject, list), true); }); - testWidgets('nullable enum lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.callFlutterEchoNullableEnumList(enumList); + final List? echoObject = await api + .callFlutterEchoNullableEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('nullable class lists serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable class lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.callFlutterEchoNullableClassList(allNullableTypesList); + final List? echoObject = await api + .callFlutterEchoNullableClassList(allNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, allNullableTypesList[index]); } }); testWidgets( - 'nullable NonNull enum lists serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + 'nullable NonNull enum lists serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List? echoObject = - await api.callFlutterEchoNullableNonNullEnumList(nonNullEnumList); - expect(listEquals(echoObject, nonNullEnumList), true); - }); + final List? echoObject = await api + .callFlutterEchoNullableNonNullEnumList(nonNullEnumList); + expect(listEquals(echoObject, nonNullEnumList), true); + }, + ); testWidgets( - 'nullable NonNull class lists serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final List? echoObject = await api - .callFlutterEchoNullableNonNullClassList(nonNullAllNullableTypesList); - for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { - expect(value, nonNullAllNullableTypesList[index]); - } - }); - - testWidgets('null lists serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final List? echoObject = - await api.callFlutterEchoNullableList(null); + 'nullable NonNull class lists serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final List? echoObject = await api + .callFlutterEchoNullableNonNullClassList( + nonNullAllNullableTypesList, + ); + for (final (int index, AllNullableTypes? value) + in echoObject!.indexed) { + expect(value, nonNullAllNullableTypesList[index]); + } + }, + ); + + testWidgets('null lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final List? echoObject = await api.callFlutterEchoNullableList( + null, + ); expect(listEquals(echoObject, null), true); }); - testWidgets('nullable maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableMap(map); + final Map? echoObject = await api + .callFlutterEchoNullableMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('null maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableMap(null); + final Map? echoObject = await api + .callFlutterEchoNullableMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('nullable string maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableStringMap(stringMap); + final Map? echoObject = await api + .callFlutterEchoNullableStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('nullable int maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableIntMap(intMap); + final Map? echoObject = await api + .callFlutterEchoNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('nullable enum maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableEnumMap(enumMap); + final Map? echoObject = await api + .callFlutterEchoNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('nullable class maps serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable class maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableClassMap(allNullableTypesMap); + final Map? echoObject = await api + .callFlutterEchoNullableClassMap(allNullableTypesMap); for (final MapEntry entry in echoObject!.entries) { expect(entry.value, allNullableTypesMap[entry.key]); @@ -2065,54 +2346,61 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets( - 'nullable NonNull string maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableNonNullStringMap(nonNullStringMap); - expect(mapEquals(echoObject, nonNullStringMap), true); - }); - - testWidgets('nullable NonNull int maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableNonNullIntMap(nonNullIntMap); - expect(mapEquals(echoObject, nonNullIntMap), true); - }); + 'nullable NonNull string maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .callFlutterEchoNullableNonNullStringMap(nonNullStringMap); + expect(mapEquals(echoObject, nonNullStringMap), true); + }, + ); testWidgets( - 'nullable NonNull enum maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = - await api.callFlutterEchoNullableNonNullEnumMap(nonNullEnumMap); - expect(mapEquals(echoObject, nonNullEnumMap), true); - }); + 'nullable NonNull int maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .callFlutterEchoNullableNonNullIntMap(nonNullIntMap); + expect(mapEquals(echoObject, nonNullIntMap), true); + }, + ); testWidgets( - 'nullable NonNull class maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableNonNullClassMap(nonNullAllNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { - expect(entry.value, nonNullAllNullableTypesMap[entry.key]); - } - }); + 'nullable NonNull enum maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .callFlutterEchoNullableNonNullEnumMap(nonNullEnumMap); + expect(mapEquals(echoObject, nonNullEnumMap), true); + }, + ); - testWidgets('null maps serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - - final Map? echoObject = - await api.callFlutterEchoNullableIntMap(null); + testWidgets( + 'nullable NonNull class maps serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .callFlutterEchoNullableNonNullClassMap(nonNullAllNullableTypesMap); + for (final MapEntry entry + in echoObject!.entries) { + expect(entry.value, nonNullAllNullableTypesMap[entry.key]); + } + }, + ); + + testWidgets('null maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + + final Map? echoObject = await api + .callFlutterEchoNullableIntMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('nullable enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('nullable enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -2120,27 +2408,33 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('nullable enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; - final AnotherEnum? echoEnum = - await api.callFlutterEchoAnotherNullableEnum(sentEnum); + final AnotherEnum? echoEnum = await api + .callFlutterEchoAnotherNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); - testWidgets('multi word nullable enums serialize and deserialize correctly', - (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + testWidgets( + 'multi word nullable enums serialize and deserialize correctly', + (WidgetTester _) async { + final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; - final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); - expect(echoEnum, sentEnum); - }); + const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; + final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum( + sentEnum, + ); + expect(echoEnum, sentEnum); + }, + ); - testWidgets('null enums serialize and deserialize correctly', - (WidgetTester _) async { + testWidgets('null enums serialize and deserialize correctly', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; @@ -2148,13 +2442,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null enums serialize and deserialize correctly (again)', - (WidgetTester _) async { + testWidgets('null enums serialize and deserialize correctly (again)', ( + WidgetTester _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; - final AnotherEnum? echoEnum = - await api.callFlutterEchoAnotherNullableEnum(sentEnum); + final AnotherEnum? echoEnum = await api + .callFlutterEchoAnotherNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); }); @@ -2221,14 +2516,12 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { await expectLater( () => api.throwFlutterError(), - throwsA( - (dynamic e) { - return e is PlatformException && - e.code == 'code' && - e.message == 'message' && - e.details == 'details'; - }, - ), + throwsA((dynamic e) { + return e is PlatformException && + e.code == 'code' && + e.message == 'message' && + e.details == 'details'; + }), ); }); @@ -2386,10 +2679,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(await api.echoNullableProxyApi(null), null); final ProxyApiSuperClass proxyApi = ProxyApiSuperClass(); - expect( - await api.echoNullableProxyApi(proxyApi), - proxyApi, - ); + expect(await api.echoNullableProxyApi(proxyApi), proxyApi); }); testWidgets('noopAsync', (_) async { @@ -2485,14 +2775,12 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { await expectLater( () => api.throwAsyncFlutterError(), - throwsA( - (dynamic e) { - return e is PlatformException && - e.code == 'code' && - e.message == 'message' && - e.details == 'details'; - }, - ), + throwsA((dynamic e) { + return e is PlatformException && + e.code == 'code' && + e.message == 'message' && + e.details == 'details'; + }), ); }); @@ -2523,10 +2811,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoAsyncNullableUint8List', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); expect(await api.echoAsyncNullableUint8List(null), null); - expect( - await api.echoAsyncNullableUint8List(Uint8List(0)), - Uint8List(0), - ); + expect(await api.echoAsyncNullableUint8List(Uint8List(0)), Uint8List(0)); }); testWidgets('echoAsyncNullableObject', (_) async { @@ -2692,22 +2977,20 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoMap: (_, Map aMap) => aMap, ); - final Map value = { - 'a String': 4, - }; + final Map value = {'a String': 4}; expect(await api.callFlutterEchoMap(value), value); }); testWidgets('callFlutterEchoProxyApiMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass( - flutterEchoProxyApiMap: (_, Map aMap) => - aMap, + flutterEchoProxyApiMap: + (_, Map aMap) => aMap, ); final Map value = { - 'a String': _createGenericProxyApiTestClass(), - }; + 'a String': _createGenericProxyApiTestClass(), + }; expect(await api.callFlutterEchoProxyApiMap(value), value); }); @@ -2804,8 +3087,8 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('callFlutterEchoNullableProxyApi', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass( - flutterEchoNullableProxyApi: (_, ProxyApiSuperClass? aProxyApi) => - aProxyApi, + flutterEchoNullableProxyApi: + (_, ProxyApiSuperClass? aProxyApi) => aProxyApi, ); expect(await api.callFlutterEchoNullableProxyApi(null), null); @@ -2848,12 +3131,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { ); }); - testWidgets('echo string succeeds with suffix with multiple instances', - (_) async { + testWidgets('echo string succeeds with suffix with multiple instances', ( + _, + ) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = "I'm a computer"; - final String echoObject = - await api.callFlutterSmallApiEchoString(sentObject); + final String echoObject = await api.callFlutterSmallApiEchoString( + sentObject, + ); expect(echoObject, sentObject); }); }); @@ -2881,7 +3166,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { // background is not supported. final bool taskQueuesSupported = defaultTargetPlatform == TargetPlatform.android || - defaultTargetPlatform == TargetPlatform.iOS; + defaultTargetPlatform == TargetPlatform.iOS; expect(await api.taskQueueIsBackgroundThread(), taskQueuesSupported); }); @@ -2889,74 +3174,90 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { const List eventChannelSupported = [ TargetGenerator.kotlin, - TargetGenerator.swift + TargetGenerator.swift, ]; - testWidgets('event channel sends continuous ints', (_) async { - final Stream events = streamInts(); - final List listEvents = await events.toList(); - for (final int value in listEvents) { - expect(listEvents[value], value); - } - }, skip: !eventChannelSupported.contains(targetGenerator)); - - testWidgets('event channel handles extended sealed classes', (_) async { - final Completer completer = Completer(); - int count = 0; - final Stream events = streamEvents(); - events.listen((PlatformEvent event) { - switch (event) { - case IntEvent(): - expect(event.value, 1); - expect(count, 0); - count++; - case StringEvent(): - expect(event.value, 'string'); - expect(count, 1); - count++; - case BoolEvent(): - expect(event.value, false); - expect(count, 2); - count++; - case DoubleEvent(): - expect(event.value, 3.14); - expect(count, 3); - count++; - case ObjectsEvent(): - expect(event.value, true); - expect(count, 4); - count++; - case EnumEvent(): - expect(event.value, EventEnum.fortyTwo); - expect(count, 5); - count++; - case ClassEvent(): - expect(event.value.aNullableInt, 0); - expect(count, 6); - count++; - completer.complete(); + testWidgets( + 'event channel sends continuous ints', + (_) async { + final Stream events = streamInts(); + final List listEvents = await events.toList(); + for (final int value in listEvents) { + expect(listEvents[value], value); } - }); - await completer.future; - }, skip: !eventChannelSupported.contains(targetGenerator)); - - testWidgets('event channels handle multiple instances', (_) async { - final Completer completer1 = Completer(); - final Completer completer2 = Completer(); - final Stream events1 = streamConsistentNumbers(instanceName: '1'); - final Stream events2 = streamConsistentNumbers(instanceName: '2'); - - events1.listen((int event) { - expect(event, 1); - }).onDone(() => completer1.complete()); + }, + skip: !eventChannelSupported.contains(targetGenerator), + ); - events2.listen((int event) { - expect(event, 2); - }).onDone(() => completer2.complete()); + testWidgets( + 'event channel handles extended sealed classes', + (_) async { + final Completer completer = Completer(); + int count = 0; + final Stream events = streamEvents(); + events.listen((PlatformEvent event) { + switch (event) { + case IntEvent(): + expect(event.value, 1); + expect(count, 0); + count++; + case StringEvent(): + expect(event.value, 'string'); + expect(count, 1); + count++; + case BoolEvent(): + expect(event.value, false); + expect(count, 2); + count++; + case DoubleEvent(): + expect(event.value, 3.14); + expect(count, 3); + count++; + case ObjectsEvent(): + expect(event.value, true); + expect(count, 4); + count++; + case EnumEvent(): + expect(event.value, EventEnum.fortyTwo); + expect(count, 5); + count++; + case ClassEvent(): + expect(event.value.aNullableInt, 0); + expect(count, 6); + count++; + completer.complete(); + } + }); + await completer.future; + }, + skip: !eventChannelSupported.contains(targetGenerator), + ); - await completer1.future; - await completer2.future; - }, skip: !eventChannelSupported.contains(targetGenerator)); + testWidgets( + 'event channels handle multiple instances', + (_) async { + final Completer completer1 = Completer(); + final Completer completer2 = Completer(); + final Stream events1 = streamConsistentNumbers(instanceName: '1'); + final Stream events2 = streamConsistentNumbers(instanceName: '2'); + + events1 + .listen((int event) { + expect(event, 1); + }) + .onDone(() => completer1.complete()); + + events2 + .listen((int event) { + expect(event, 2); + }) + .onDone(() => completer2.complete()); + + await completer1.future; + await completer2.future; + }, + skip: !eventChannelSupported.contains(targetGenerator), + ); } class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @@ -2972,7 +3273,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override AllNullableTypesWithoutRecursion? echoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything) { + AllNullableTypesWithoutRecursion? everything, + ) { return everything; } @@ -2991,20 +3293,28 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override AllNullableTypes sendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString) { + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ) { return AllNullableTypes( - aNullableBool: aNullableBool, - aNullableInt: aNullableInt, - aNullableString: aNullableString); + aNullableBool: aNullableBool, + aNullableInt: aNullableInt, + aNullableString: aNullableString, + ); } @override AllNullableTypesWithoutRecursion sendMultipleNullableTypesWithoutRecursion( - bool? aNullableBool, int? aNullableInt, String? aNullableString) { + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ) { return AllNullableTypesWithoutRecursion( - aNullableBool: aNullableBool, - aNullableInt: aNullableInt, - aNullableString: aNullableString); + aNullableBool: aNullableBool, + aNullableInt: aNullableInt, + aNullableString: aNullableString, + ); } @override @@ -3038,7 +3348,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override List echoNonNullClassList( - List classList) { + List classList, + ) { return classList; } @@ -3057,7 +3368,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override Map echoClassMap( - Map classMap) { + Map classMap, + ) { return classMap; } @@ -3074,7 +3386,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override Map echoNonNullClassMap( - Map classMap) { + Map classMap, + ) { return classMap; } @@ -3101,7 +3414,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override List? echoNullableClassList( - List? classList) { + List? classList, + ) { return classList; } @@ -3112,7 +3426,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override List? echoNullableNonNullClassList( - List? classList) { + List? classList, + ) { return classList; } @@ -3121,7 +3436,8 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override Map? echoNullableStringMap( - Map? stringMap) { + Map? stringMap, + ) { return stringMap; } @@ -3135,13 +3451,15 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override Map? echoNullableClassMap( - Map? classMap) { + Map? classMap, + ) { return classMap; } @override Map? echoNullableNonNullStringMap( - Map? stringMap) { + Map? stringMap, + ) { return stringMap; } @@ -3152,13 +3470,15 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override Map? echoNullableNonNullEnumMap( - Map? enumMap) { + Map? enumMap, + ) { return enumMap; } @override Map? echoNullableNonNullClassMap( - Map? classMap) { + Map? classMap, + ) { return classMap; } @@ -3198,94 +3518,71 @@ class _SmallFlutterApi implements FlutterSmallApi { ProxyApiTestClass _createGenericProxyApiTestClass({ void Function(ProxyApiTestClass instance)? flutterNoop, Object? Function(ProxyApiTestClass instance)? flutterThrowError, - void Function( - ProxyApiTestClass instance, - )? flutterThrowErrorFromVoid, - bool Function( - ProxyApiTestClass instance, - bool aBool, - )? flutterEchoBool, - int Function( - ProxyApiTestClass instance, - int anInt, - )? flutterEchoInt, - double Function( - ProxyApiTestClass instance, - double aDouble, - )? flutterEchoDouble, - String Function( - ProxyApiTestClass instance, - String aString, - )? flutterEchoString, - Uint8List Function( - ProxyApiTestClass instance, - Uint8List aList, - )? flutterEchoUint8List, - List Function( - ProxyApiTestClass instance, - List aList, - )? flutterEchoList, + void Function(ProxyApiTestClass instance)? flutterThrowErrorFromVoid, + bool Function(ProxyApiTestClass instance, bool aBool)? flutterEchoBool, + int Function(ProxyApiTestClass instance, int anInt)? flutterEchoInt, + double Function(ProxyApiTestClass instance, double aDouble)? + flutterEchoDouble, + String Function(ProxyApiTestClass instance, String aString)? + flutterEchoString, + Uint8List Function(ProxyApiTestClass instance, Uint8List aList)? + flutterEchoUint8List, + List Function(ProxyApiTestClass instance, List aList)? + flutterEchoList, List Function( ProxyApiTestClass instance, List aList, - )? flutterEchoProxyApiList, + )? + flutterEchoProxyApiList, Map Function( ProxyApiTestClass instance, Map aMap, - )? flutterEchoMap, + )? + flutterEchoMap, Map Function( ProxyApiTestClass instance, Map aMap, - )? flutterEchoProxyApiMap, + )? + flutterEchoProxyApiMap, ProxyApiTestEnum Function( ProxyApiTestClass instance, ProxyApiTestEnum anEnum, - )? flutterEchoEnum, + )? + flutterEchoEnum, ProxyApiSuperClass Function( ProxyApiTestClass instance, ProxyApiSuperClass aProxyApi, - )? flutterEchoProxyApi, - bool? Function( - ProxyApiTestClass instance, - bool? aBool, - )? flutterEchoNullableBool, - int? Function( - ProxyApiTestClass instance, - int? anInt, - )? flutterEchoNullableInt, - double? Function( - ProxyApiTestClass instance, - double? aDouble, - )? flutterEchoNullableDouble, - String? Function( - ProxyApiTestClass instance, - String? aString, - )? flutterEchoNullableString, - Uint8List? Function( - ProxyApiTestClass instance, - Uint8List? aList, - )? flutterEchoNullableUint8List, - List? Function( - ProxyApiTestClass instance, - List? aList, - )? flutterEchoNullableList, + )? + flutterEchoProxyApi, + bool? Function(ProxyApiTestClass instance, bool? aBool)? + flutterEchoNullableBool, + int? Function(ProxyApiTestClass instance, int? anInt)? flutterEchoNullableInt, + double? Function(ProxyApiTestClass instance, double? aDouble)? + flutterEchoNullableDouble, + String? Function(ProxyApiTestClass instance, String? aString)? + flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass instance, Uint8List? aList)? + flutterEchoNullableUint8List, + List? Function(ProxyApiTestClass instance, List? aList)? + flutterEchoNullableList, Map? Function( ProxyApiTestClass instance, Map? aMap, - )? flutterEchoNullableMap, + )? + flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum, + )? + flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi, + )? + flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass instance)? flutterNoopAsync, - Future Function( - ProxyApiTestClass instance, - String aString, - )? flutterEchoAsyncString, + Future Function(ProxyApiTestClass instance, String aString)? + flutterEchoAsyncString, }) { return ProxyApiTestClass( aBool: true, diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart index 2b6cb135625..871abf69bd6 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart @@ -44,11 +44,12 @@ class BackgroundApi2Host { /// Constructor for [BackgroundApi2Host]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - BackgroundApi2Host( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + BackgroundApi2Host({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -60,14 +61,15 @@ class BackgroundApi2Host { 'dev.flutter.pigeon.pigeon_integration_tests.BackgroundApi2Host.add$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [ + [x, y], + ], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([ - [x, y] - ]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart index 12a5e53c620..e43420ff751 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -33,41 +36,32 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } -enum AnEnum { - one, - two, - three, - fortyTwo, - fourHundredTwentyTwo, -} +enum AnEnum { one, two, three, fortyTwo, fourHundredTwentyTwo } -enum AnotherEnum { - justInCase, -} +enum AnotherEnum { justInCase } class UnusedClass { - UnusedClass({ - this.aField, - }); + UnusedClass({this.aField}); Object? aField; List _toList() { - return [ - aField, - ]; + return [aField]; } Object encode() { @@ -76,9 +70,7 @@ class UnusedClass { static UnusedClass decode(Object result) { result as List; - return UnusedClass( - aField: result[0], - ); + return UnusedClass(aField: result[0]); } @override @@ -255,8 +247,9 @@ class AllTypes { objectMap: (result[25] as Map?)!.cast(), listMap: (result[26] as Map?)!.cast>(), - mapMap: (result[27] as Map?)! - .cast>(), + mapMap: + (result[27] as Map?)! + .cast>(), ); } @@ -451,10 +444,12 @@ class AllNullableTypes { (result[27] as Map?)?.cast(), listMap: (result[28] as Map?)?.cast?>(), - mapMap: (result[29] as Map?) - ?.cast?>(), - recursiveClassMap: (result[30] as Map?) - ?.cast(), + mapMap: + (result[29] as Map?) + ?.cast?>(), + recursiveClassMap: + (result[30] as Map?) + ?.cast(), ); } @@ -636,8 +631,9 @@ class AllNullableTypesWithoutRecursion { (result[25] as Map?)?.cast(), listMap: (result[26] as Map?)?.cast?>(), - mapMap: (result[27] as Map?) - ?.cast?>(), + mapMap: + (result[27] as Map?) + ?.cast?>(), ); } @@ -713,11 +709,13 @@ class AllClassesWrapper { result[1] as AllNullableTypesWithoutRecursion?, allTypes: result[2] as AllTypes?, classList: (result[3] as List?)!.cast(), - nullableClassList: (result[4] as List?) - ?.cast(), + nullableClassList: + (result[4] as List?) + ?.cast(), classMap: (result[5] as Map?)!.cast(), - nullableClassMap: (result[6] as Map?) - ?.cast(), + nullableClassMap: + (result[6] as Map?) + ?.cast(), ); } @@ -740,16 +738,12 @@ class AllClassesWrapper { /// A data class containing a List, used in unit tests. class TestMessage { - TestMessage({ - this.testList, - }); + TestMessage({this.testList}); List? testList; List _toList() { - return [ - testList, - ]; + return [testList]; } Object encode() { @@ -758,9 +752,7 @@ class TestMessage { static TestMessage decode(Object result) { result as List; - return TestMessage( - testList: result[0] as List?, - ); + return TestMessage(testList: result[0] as List?); } @override @@ -849,11 +841,12 @@ class HostIntegrationCoreApi { /// Constructor for [HostIntegrationCoreApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - HostIntegrationCoreApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + HostIntegrationCoreApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -867,10 +860,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noop$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -893,12 +886,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -925,10 +919,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwError$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -951,10 +945,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwErrorFromVoid$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -977,10 +971,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwFlutterError$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1003,12 +997,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1035,12 +1030,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1067,12 +1063,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1099,12 +1096,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1131,12 +1129,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoUint8List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1163,12 +1162,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoObject$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1195,12 +1195,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1227,12 +1228,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1255,17 +1257,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. Future> echoClassList( - List classList) async { + List classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1293,12 +1297,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1321,17 +1326,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. Future> echoNonNullClassList( - List classList) async { + List classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1359,12 +1366,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [map], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([map]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1388,17 +1396,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future> echoStringMap( - Map stringMap) async { + Map stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1426,12 +1436,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1455,17 +1466,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future> echoEnumMap( - Map enumMap) async { + Map enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1489,17 +1502,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future> echoClassMap( - Map classMap) async { + Map classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1523,17 +1538,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullStringMap( - Map stringMap) async { + Map stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1561,12 +1578,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1590,17 +1608,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullEnumMap( - Map enumMap) async { + Map enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1624,17 +1644,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullClassMap( - Map classMap) async { + Map classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1662,12 +1684,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassWrapper$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [wrapper], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([wrapper]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1694,12 +1717,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1726,12 +1750,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anotherEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anotherEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1758,12 +1783,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedDefaultString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1790,12 +1816,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalDefaultDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1822,12 +1849,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoRequiredInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1850,17 +1878,19 @@ class HostIntegrationCoreApi { /// Returns the passed object, to test serialization and deserialization. Future echoAllNullableTypes( - AllNullableTypes? everything) async { + AllNullableTypes? everything, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1878,18 +1908,20 @@ class HostIntegrationCoreApi { /// Returns the passed object, to test serialization and deserialization. Future - echoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything) async { + echoAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? everything, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1912,12 +1944,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.extractNestedNullableString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [wrapper], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([wrapper]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1936,17 +1969,19 @@ class HostIntegrationCoreApi { /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. Future createNestedNullableString( - String? nullableString) async { + String? nullableString, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.createNestedNullableString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [nullableString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([nullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1969,17 +2004,21 @@ class HostIntegrationCoreApi { /// Returns passed in arguments of multiple types. Future sendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString) async { + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.sendMultipleNullableTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableBool, aNullableInt, aNullableString], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([aNullableBool, aNullableInt, aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2002,18 +2041,22 @@ class HostIntegrationCoreApi { /// Returns passed in arguments of multiple types. Future - sendMultipleNullableTypesWithoutRecursion(bool? aNullableBool, - int? aNullableInt, String? aNullableString) async { + sendMultipleNullableTypesWithoutRecursion( + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableBool, aNullableInt, aNullableString], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([aNullableBool, aNullableInt, aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2040,12 +2083,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2067,12 +2111,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2094,12 +2139,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2121,12 +2167,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2144,17 +2191,19 @@ class HostIntegrationCoreApi { /// Returns the passed in Uint8List. Future echoNullableUint8List( - Uint8List? aNullableUint8List) async { + Uint8List? aNullableUint8List, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableUint8List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2176,12 +2225,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableObject$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2203,12 +2253,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2230,12 +2281,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2253,17 +2305,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableClassList( - List? classList) async { + List? classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2282,17 +2336,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableNonNullEnumList( - List? enumList) async { + List? enumList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2310,17 +2366,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableNonNullClassList( - List? classList) async { + List? classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2339,17 +2397,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableMap( - Map? map) async { + Map? map, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [map], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([map]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2368,17 +2428,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableStringMap( - Map? stringMap) async { + Map? stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2401,12 +2463,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2425,17 +2488,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableEnumMap( - Map? enumMap) async { + Map? enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2454,17 +2519,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableClassMap( - Map? classMap) async { + Map? classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2483,17 +2550,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullStringMap( - Map? stringMap) async { + Map? stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2512,17 +2581,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullIntMap( - Map? intMap) async { + Map? intMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2541,17 +2612,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullEnumMap( - Map? enumMap) async { + Map? enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2570,17 +2643,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullClassMap( - Map? classMap) async { + Map? classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2602,12 +2677,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2628,12 +2704,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherNullableEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anotherEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anotherEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2655,12 +2732,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalNullableInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2682,12 +2760,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedNullableString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2710,10 +2789,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noopAsync$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -2736,12 +2815,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2768,12 +2848,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2800,12 +2881,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2832,12 +2914,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2864,12 +2947,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncUint8List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2896,12 +2980,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncObject$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2928,12 +3013,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2960,12 +3046,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2988,17 +3075,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test asynchronous serialization and deserialization. Future> echoAsyncClassList( - List classList) async { + List classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3026,12 +3115,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [map], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([map]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3055,17 +3145,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncStringMap( - Map stringMap) async { + Map stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3093,12 +3185,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3122,17 +3215,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncEnumMap( - Map enumMap) async { + Map enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3156,17 +3251,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncClassMap( - Map classMap) async { + Map classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3194,12 +3291,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3226,12 +3324,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherAsyncEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anotherEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anotherEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3258,10 +3357,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncError$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3284,10 +3383,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncErrorFromVoid$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3310,10 +3409,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncFlutterError$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3336,12 +3435,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncAllTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3364,17 +3464,19 @@ class HostIntegrationCoreApi { /// Returns the passed object, to test serialization and deserialization. Future echoAsyncNullableAllNullableTypes( - AllNullableTypes? everything) async { + AllNullableTypes? everything, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3392,18 +3494,20 @@ class HostIntegrationCoreApi { /// Returns the passed object, to test serialization and deserialization. Future - echoAsyncNullableAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything) async { + echoAsyncNullableAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? everything, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3425,12 +3529,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3452,12 +3557,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3479,12 +3585,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3506,12 +3613,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3533,12 +3641,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableUint8List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3560,12 +3669,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableObject$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3587,12 +3697,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3610,17 +3721,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableEnumList( - List? enumList) async { + List? enumList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3638,17 +3751,19 @@ class HostIntegrationCoreApi { /// Returns the passed list, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableClassList( - List? classList) async { + List? classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3667,17 +3782,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableMap( - Map? map) async { + Map? map, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [map], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([map]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3696,17 +3813,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableStringMap( - Map? stringMap) async { + Map? stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3725,17 +3844,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableIntMap( - Map? intMap) async { + Map? intMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3754,17 +3875,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableEnumMap( - Map? enumMap) async { + Map? enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3783,17 +3906,19 @@ class HostIntegrationCoreApi { /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableClassMap( - Map? classMap) async { + Map? classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3816,12 +3941,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3839,17 +3965,19 @@ class HostIntegrationCoreApi { /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAnotherAsyncNullableEnum( - AnotherEnum? anotherEnum) async { + AnotherEnum? anotherEnum, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherAsyncNullableEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anotherEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anotherEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3872,10 +4000,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.defaultIsMainThread$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3904,10 +4032,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.taskQueueIsBackgroundThread$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3934,10 +4062,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterNoop$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3959,10 +4087,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowError$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3984,10 +4112,10 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowErrorFromVoid$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4009,12 +4137,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4036,17 +4165,19 @@ class HostIntegrationCoreApi { } Future callFlutterEchoAllNullableTypes( - AllNullableTypes? everything) async { + AllNullableTypes? everything, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4063,17 +4194,21 @@ class HostIntegrationCoreApi { } Future callFlutterSendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString) async { + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSendMultipleNullableTypes$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableBool, aNullableInt, aNullableString], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([aNullableBool, aNullableInt, aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4095,18 +4230,20 @@ class HostIntegrationCoreApi { } Future - callFlutterEchoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything) async { + callFlutterEchoAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? everything, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [everything], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([everything]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4123,18 +4260,22 @@ class HostIntegrationCoreApi { } Future - callFlutterSendMultipleNullableTypesWithoutRecursion(bool? aNullableBool, - int? aNullableInt, String? aNullableString) async { + callFlutterSendMultipleNullableTypesWithoutRecursion( + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSendMultipleNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aNullableBool, aNullableInt, aNullableString], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([aNullableBool, aNullableInt, aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4160,12 +4301,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4191,12 +4333,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4222,12 +4365,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4253,12 +4397,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4284,12 +4429,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoUint8List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4315,12 +4461,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4346,12 +4493,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4373,17 +4521,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoClassList( - List classList) async { + List classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4406,17 +4556,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoNonNullEnumList( - List enumList) async { + List enumList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4438,17 +4590,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoNonNullClassList( - List classList) async { + List classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4471,17 +4625,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoMap( - Map map) async { + Map map, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [map], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([map]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4504,17 +4660,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoStringMap( - Map stringMap) async { + Map stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4541,12 +4699,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4569,17 +4728,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoEnumMap( - Map enumMap) async { + Map enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4602,17 +4763,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoClassMap( - Map classMap) async { + Map classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4635,17 +4798,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoNonNullStringMap( - Map stringMap) async { + Map stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4668,17 +4833,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoNonNullIntMap( - Map intMap) async { + Map intMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4701,17 +4868,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoNonNullEnumMap( - Map enumMap) async { + Map enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4734,17 +4903,19 @@ class HostIntegrationCoreApi { } Future> callFlutterEchoNonNullClassMap( - Map classMap) async { + Map classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4771,12 +4942,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4798,17 +4970,19 @@ class HostIntegrationCoreApi { } Future callFlutterEchoAnotherEnum( - AnotherEnum anotherEnum) async { + AnotherEnum anotherEnum, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAnotherEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anotherEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anotherEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4834,12 +5008,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4860,12 +5035,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4886,12 +5062,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4912,12 +5089,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4938,12 +5116,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableUint8List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4960,17 +5139,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableList( - List? list) async { + List? list, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [list], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([list]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4987,17 +5168,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableEnumList( - List? enumList) async { + List? enumList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5014,17 +5197,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableClassList( - List? classList) async { + List? classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5042,17 +5227,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableNonNullEnumList( - List? enumList) async { + List? enumList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullEnumList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5069,17 +5256,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableNonNullClassList( - List? classList) async { + List? classList, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullClassList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5097,17 +5286,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableMap( - Map? map) async { + Map? map, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [map], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([map]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5125,17 +5316,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableStringMap( - Map? stringMap) async { + Map? stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5153,17 +5346,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableIntMap( - Map? intMap) async { + Map? intMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5181,17 +5376,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableEnumMap( - Map? enumMap) async { + Map? enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5209,17 +5406,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableClassMap( - Map? classMap) async { + Map? classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5237,17 +5436,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableNonNullStringMap( - Map? stringMap) async { + Map? stringMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullStringMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stringMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([stringMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5265,17 +5466,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableNonNullIntMap( - Map? intMap) async { + Map? intMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [intMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([intMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5293,17 +5496,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableNonNullEnumMap( - Map? enumMap) async { + Map? enumMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullEnumMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enumMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enumMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5321,17 +5526,19 @@ class HostIntegrationCoreApi { } Future?> callFlutterEchoNullableNonNullClassMap( - Map? classMap) async { + Map? classMap, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullClassMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [classMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([classMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5353,12 +5560,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5375,17 +5583,19 @@ class HostIntegrationCoreApi { } Future callFlutterEchoAnotherNullableEnum( - AnotherEnum? anotherEnum) async { + AnotherEnum? anotherEnum, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAnotherNullableEnum$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [anotherEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([anotherEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5406,12 +5616,13 @@ class HostIntegrationCoreApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSmallApiEchoString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5458,17 +5669,24 @@ abstract class FlutterIntegrationCoreApi { /// /// Tests multiple-arity FlutterApi handling. AllNullableTypes sendMultipleNullableTypes( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); /// Returns the passed object, to test serialization and deserialization. AllNullableTypesWithoutRecursion? echoAllNullableTypesWithoutRecursion( - AllNullableTypesWithoutRecursion? everything); + AllNullableTypesWithoutRecursion? everything, + ); /// Returns passed in arguments of multiple types. /// /// Tests multiple-arity FlutterApi handling. AllNullableTypesWithoutRecursion sendMultipleNullableTypesWithoutRecursion( - bool? aNullableBool, int? aNullableInt, String? aNullableString); + bool? aNullableBool, + int? aNullableInt, + String? aNullableString, + ); /// Returns the passed boolean, to test serialization and deserialization. bool echoBool(bool aBool); @@ -5514,7 +5732,8 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Map echoClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed map, to test serialization and deserialization. Map echoNonNullStringMap(Map stringMap); @@ -5527,7 +5746,8 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Map echoNonNullClassMap( - Map classMap); + Map classMap, + ); /// Returns the passed enum to test serialization and deserialization. AnEnum echoEnum(AnEnum anEnum); @@ -5558,21 +5778,24 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. List? echoNullableClassList( - List? classList); + List? classList, + ); /// Returns the passed list, to test serialization and deserialization. List? echoNullableNonNullEnumList(List? enumList); /// Returns the passed list, to test serialization and deserialization. List? echoNullableNonNullClassList( - List? classList); + List? classList, + ); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableMap(Map? map); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableIntMap(Map? intMap); @@ -5582,11 +5805,13 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Map? echoNullableClassMap( - Map? classMap); + Map? classMap, + ); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableNonNullStringMap( - Map? stringMap); + Map? stringMap, + ); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableNonNullIntMap(Map? intMap); @@ -5596,7 +5821,8 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. Map? echoNullableNonNullClassMap( - Map? classMap); + Map? classMap, + ); /// Returns the passed enum to test serialization and deserialization. AnEnum? echoNullableEnum(AnEnum? anEnum); @@ -5619,12 +5845,12 @@ abstract class FlutterIntegrationCoreApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -5636,18 +5862,19 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -5659,18 +5886,19 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -5682,28 +5910,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes was null.', + ); final List args = (message as List?)!; final AllTypes? arg_everything = (args[0] as AllTypes?); - assert(arg_everything != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes was null, expected non-null AllTypes.'); + assert( + arg_everything != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes was null, expected non-null AllTypes.', + ); try { final AllTypes output = api.echoAllTypes(arg_everything!); return wrapResponse(result: output); @@ -5711,147 +5944,171 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes was null.', + ); final List args = (message as List?)!; final AllNullableTypes? arg_everything = (args[0] as AllNullableTypes?); try { - final AllNullableTypes? output = - api.echoAllNullableTypes(arg_everything); + final AllNullableTypes? output = api.echoAllNullableTypes( + arg_everything, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes was null.', + ); final List args = (message as List?)!; final bool? arg_aNullableBool = (args[0] as bool?); final int? arg_aNullableInt = (args[1] as int?); final String? arg_aNullableString = (args[2] as String?); try { final AllNullableTypes output = api.sendMultipleNullableTypes( - arg_aNullableBool, arg_aNullableInt, arg_aNullableString); + arg_aNullableBool, + arg_aNullableInt, + arg_aNullableString, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypesWithoutRecursion$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypesWithoutRecursion$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypesWithoutRecursion was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypesWithoutRecursion was null.', + ); final List args = (message as List?)!; final AllNullableTypesWithoutRecursion? arg_everything = (args[0] as AllNullableTypesWithoutRecursion?); try { - final AllNullableTypesWithoutRecursion? output = - api.echoAllNullableTypesWithoutRecursion(arg_everything); + final AllNullableTypesWithoutRecursion? output = api + .echoAllNullableTypesWithoutRecursion(arg_everything); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion was null.', + ); final List args = (message as List?)!; final bool? arg_aNullableBool = (args[0] as bool?); final int? arg_aNullableInt = (args[1] as int?); final String? arg_aNullableString = (args[2] as String?); try { - final AllNullableTypesWithoutRecursion output = - api.sendMultipleNullableTypesWithoutRecursion( - arg_aNullableBool, arg_aNullableInt, arg_aNullableString); + final AllNullableTypesWithoutRecursion output = api + .sendMultipleNullableTypesWithoutRecursion( + arg_aNullableBool, + arg_aNullableInt, + arg_aNullableString, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool was null.', + ); final List args = (message as List?)!; final bool? arg_aBool = (args[0] as bool?); - assert(arg_aBool != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool was null, expected non-null bool.'); + assert( + arg_aBool != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool was null, expected non-null bool.', + ); try { final bool output = api.echoBool(arg_aBool!); return wrapResponse(result: output); @@ -5859,28 +6116,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt was null.', + ); final List args = (message as List?)!; final int? arg_anInt = (args[0] as int?); - assert(arg_anInt != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt was null, expected non-null int.'); + assert( + arg_anInt != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt was null, expected non-null int.', + ); try { final int output = api.echoInt(arg_anInt!); return wrapResponse(result: output); @@ -5888,28 +6150,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble was null.', + ); final List args = (message as List?)!; final double? arg_aDouble = (args[0] as double?); - assert(arg_aDouble != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble was null, expected non-null double.'); + assert( + arg_aDouble != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble was null, expected non-null double.', + ); try { final double output = api.echoDouble(arg_aDouble!); return wrapResponse(result: output); @@ -5917,28 +6184,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString was null.', + ); final List args = (message as List?)!; final String? arg_aString = (args[0] as String?); - assert(arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString was null, expected non-null String.'); + assert( + arg_aString != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString was null, expected non-null String.', + ); try { final String output = api.echoString(arg_aString!); return wrapResponse(result: output); @@ -5946,28 +6218,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List was null.', + ); final List args = (message as List?)!; final Uint8List? arg_list = (args[0] as Uint8List?); - assert(arg_list != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List was null, expected non-null Uint8List.'); + assert( + arg_list != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List was null, expected non-null Uint8List.', + ); try { final Uint8List output = api.echoUint8List(arg_list!); return wrapResponse(result: output); @@ -5975,29 +6252,34 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList was null.', + ); final List args = (message as List?)!; final List? arg_list = (args[0] as List?)?.cast(); - assert(arg_list != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList was null, expected non-null List.'); + assert( + arg_list != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList was null, expected non-null List.', + ); try { final List output = api.echoList(arg_list!); return wrapResponse(result: output); @@ -6005,29 +6287,34 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList was null.', + ); final List args = (message as List?)!; final List? arg_enumList = (args[0] as List?)?.cast(); - assert(arg_enumList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList was null, expected non-null List.'); + assert( + arg_enumList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList was null, expected non-null List.', + ); try { final List output = api.echoEnumList(arg_enumList!); return wrapResponse(result: output); @@ -6035,60 +6322,71 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList was null.', + ); final List args = (message as List?)!; final List? arg_classList = (args[0] as List?)?.cast(); - assert(arg_classList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList was null, expected non-null List.'); + assert( + arg_classList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList was null, expected non-null List.', + ); try { - final List output = - api.echoClassList(arg_classList!); + final List output = api.echoClassList( + arg_classList!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList was null.', + ); final List args = (message as List?)!; final List? arg_enumList = (args[0] as List?)?.cast(); - assert(arg_enumList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList was null, expected non-null List.'); + assert( + arg_enumList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList was null, expected non-null List.', + ); try { final List output = api.echoNonNullEnumList(arg_enumList!); return wrapResponse(result: output); @@ -6096,60 +6394,71 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList was null.', + ); final List args = (message as List?)!; final List? arg_classList = (args[0] as List?)?.cast(); - assert(arg_classList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList was null, expected non-null List.'); + assert( + arg_classList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList was null, expected non-null List.', + ); try { - final List output = - api.echoNonNullClassList(arg_classList!); + final List output = api.echoNonNullClassList( + arg_classList!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap was null.', + ); final List args = (message as List?)!; final Map? arg_map = (args[0] as Map?)?.cast(); - assert(arg_map != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap was null, expected non-null Map.'); + assert( + arg_map != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap was null, expected non-null Map.', + ); try { final Map output = api.echoMap(arg_map!); return wrapResponse(result: output); @@ -6157,60 +6466,71 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap was null.', + ); final List args = (message as List?)!; final Map? arg_stringMap = (args[0] as Map?)?.cast(); - assert(arg_stringMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap was null, expected non-null Map.'); + assert( + arg_stringMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap was null, expected non-null Map.', + ); try { - final Map output = - api.echoStringMap(arg_stringMap!); + final Map output = api.echoStringMap( + arg_stringMap!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap was null.', + ); final List args = (message as List?)!; final Map? arg_intMap = (args[0] as Map?)?.cast(); - assert(arg_intMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap was null, expected non-null Map.'); + assert( + arg_intMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap was null, expected non-null Map.', + ); try { final Map output = api.echoIntMap(arg_intMap!); return wrapResponse(result: output); @@ -6218,29 +6538,34 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap was null.', + ); final List args = (message as List?)!; final Map? arg_enumMap = (args[0] as Map?)?.cast(); - assert(arg_enumMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap was null, expected non-null Map.'); + assert( + arg_enumMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap was null, expected non-null Map.', + ); try { final Map output = api.echoEnumMap(arg_enumMap!); return wrapResponse(result: output); @@ -6248,92 +6573,109 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap was null.', + ); final List args = (message as List?)!; final Map? arg_classMap = (args[0] as Map?) ?.cast(); - assert(arg_classMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap was null, expected non-null Map.'); + assert( + arg_classMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap was null, expected non-null Map.', + ); try { - final Map output = - api.echoClassMap(arg_classMap!); + final Map output = api.echoClassMap( + arg_classMap!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap was null.', + ); final List args = (message as List?)!; final Map? arg_stringMap = (args[0] as Map?)?.cast(); - assert(arg_stringMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap was null, expected non-null Map.'); + assert( + arg_stringMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap was null, expected non-null Map.', + ); try { - final Map output = - api.echoNonNullStringMap(arg_stringMap!); + final Map output = api.echoNonNullStringMap( + arg_stringMap!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap was null.', + ); final List args = (message as List?)!; final Map? arg_intMap = (args[0] as Map?)?.cast(); - assert(arg_intMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap was null, expected non-null Map.'); + assert( + arg_intMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap was null, expected non-null Map.', + ); try { final Map output = api.echoNonNullIntMap(arg_intMap!); return wrapResponse(result: output); @@ -6341,91 +6683,108 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap was null.', + ); final List args = (message as List?)!; final Map? arg_enumMap = (args[0] as Map?)?.cast(); - assert(arg_enumMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap was null, expected non-null Map.'); + assert( + arg_enumMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap was null, expected non-null Map.', + ); try { - final Map output = - api.echoNonNullEnumMap(arg_enumMap!); + final Map output = api.echoNonNullEnumMap( + arg_enumMap!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap was null.', + ); final List args = (message as List?)!; final Map? arg_classMap = (args[0] as Map?) ?.cast(); - assert(arg_classMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap was null, expected non-null Map.'); + assert( + arg_classMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap was null, expected non-null Map.', + ); try { - final Map output = - api.echoNonNullClassMap(arg_classMap!); + final Map output = api.echoNonNullClassMap( + arg_classMap!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum was null.', + ); final List args = (message as List?)!; final AnEnum? arg_anEnum = (args[0] as AnEnum?); - assert(arg_anEnum != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum was null, expected non-null AnEnum.'); + assert( + arg_anEnum != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum was null, expected non-null AnEnum.', + ); try { final AnEnum output = api.echoEnum(arg_anEnum!); return wrapResponse(result: output); @@ -6433,28 +6792,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum was null.', + ); final List args = (message as List?)!; final AnotherEnum? arg_anotherEnum = (args[0] as AnotherEnum?); - assert(arg_anotherEnum != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum was null, expected non-null AnotherEnum.'); + assert( + arg_anotherEnum != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum was null, expected non-null AnotherEnum.', + ); try { final AnotherEnum output = api.echoAnotherEnum(arg_anotherEnum!); return wrapResponse(result: output); @@ -6462,24 +6826,27 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool was null.', + ); final List args = (message as List?)!; final bool? arg_aBool = (args[0] as bool?); try { @@ -6489,24 +6856,27 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt was null.', + ); final List args = (message as List?)!; final int? arg_anInt = (args[0] as int?); try { @@ -6516,24 +6886,27 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble was null.', + ); final List args = (message as List?)!; final double? arg_aDouble = (args[0] as double?); try { @@ -6543,24 +6916,27 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString was null.', + ); final List args = (message as List?)!; final String? arg_aString = (args[0] as String?); try { @@ -6570,24 +6946,27 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List was null.', + ); final List args = (message as List?)!; final Uint8List? arg_list = (args[0] as Uint8List?); try { @@ -6597,24 +6976,27 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList was null.', + ); final List args = (message as List?)!; final List? arg_list = (args[0] as List?)?.cast(); @@ -6625,140 +7007,158 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumList was null.', + ); final List args = (message as List?)!; final List? arg_enumList = (args[0] as List?)?.cast(); try { - final List? output = - api.echoNullableEnumList(arg_enumList); + final List? output = api.echoNullableEnumList( + arg_enumList, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassList was null.', + ); final List args = (message as List?)!; final List? arg_classList = (args[0] as List?)?.cast(); try { - final List? output = - api.echoNullableClassList(arg_classList); + final List? output = api.echoNullableClassList( + arg_classList, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumList was null.', + ); final List args = (message as List?)!; final List? arg_enumList = (args[0] as List?)?.cast(); try { - final List? output = - api.echoNullableNonNullEnumList(arg_enumList); + final List? output = api.echoNullableNonNullEnumList( + arg_enumList, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassList was null.', + ); final List args = (message as List?)!; final List? arg_classList = (args[0] as List?)?.cast(); try { - final List? output = - api.echoNullableNonNullClassList(arg_classList); + final List? output = api + .echoNullableNonNullClassList(arg_classList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap was null.', + ); final List args = (message as List?)!; final Map? arg_map = (args[0] as Map?)?.cast(); @@ -6769,53 +7169,60 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableStringMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableStringMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableStringMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableStringMap was null.', + ); final List args = (message as List?)!; final Map? arg_stringMap = (args[0] as Map?)?.cast(); try { - final Map? output = - api.echoNullableStringMap(arg_stringMap); + final Map? output = api.echoNullableStringMap( + arg_stringMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableIntMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableIntMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableIntMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableIntMap was null.', + ); final List args = (message as List?)!; final Map? arg_intMap = (args[0] as Map?)?.cast(); @@ -6826,200 +7233,224 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumMap was null.', + ); final List args = (message as List?)!; final Map? arg_enumMap = (args[0] as Map?)?.cast(); try { - final Map? output = - api.echoNullableEnumMap(arg_enumMap); + final Map? output = api.echoNullableEnumMap( + arg_enumMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassMap was null.', + ); final List args = (message as List?)!; final Map? arg_classMap = (args[0] as Map?) ?.cast(); try { - final Map? output = - api.echoNullableClassMap(arg_classMap); + final Map? output = api + .echoNullableClassMap(arg_classMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullStringMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullStringMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullStringMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullStringMap was null.', + ); final List args = (message as List?)!; final Map? arg_stringMap = (args[0] as Map?)?.cast(); try { - final Map? output = - api.echoNullableNonNullStringMap(arg_stringMap); + final Map? output = api + .echoNullableNonNullStringMap(arg_stringMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullIntMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullIntMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullIntMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullIntMap was null.', + ); final List args = (message as List?)!; final Map? arg_intMap = (args[0] as Map?)?.cast(); try { - final Map? output = - api.echoNullableNonNullIntMap(arg_intMap); + final Map? output = api.echoNullableNonNullIntMap( + arg_intMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumMap was null.', + ); final List args = (message as List?)!; final Map? arg_enumMap = (args[0] as Map?)?.cast(); try { - final Map? output = - api.echoNullableNonNullEnumMap(arg_enumMap); + final Map? output = api.echoNullableNonNullEnumMap( + arg_enumMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassMap was null.', + ); final List args = (message as List?)!; final Map? arg_classMap = (args[0] as Map?) ?.cast(); try { - final Map? output = - api.echoNullableNonNullClassMap(arg_classMap); + final Map? output = api + .echoNullableNonNullClassMap(arg_classMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum was null.', + ); final List args = (message as List?)!; final AnEnum? arg_anEnum = (args[0] as AnEnum?); try { @@ -7029,46 +7460,51 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherNullableEnum$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherNullableEnum$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherNullableEnum was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherNullableEnum was null.', + ); final List args = (message as List?)!; final AnotherEnum? arg_anotherEnum = (args[0] as AnotherEnum?); try { - final AnotherEnum? output = - api.echoAnotherNullableEnum(arg_anotherEnum); + final AnotherEnum? output = api.echoAnotherNullableEnum( + arg_anotherEnum, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -7080,28 +7516,33 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString was null.', + ); final List args = (message as List?)!; final String? arg_aString = (args[0] as String?); - assert(arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString was null, expected non-null String.'); + assert( + arg_aString != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString was null, expected non-null String.', + ); try { final String output = await api.echoAsyncString(arg_aString!); return wrapResponse(result: output); @@ -7109,7 +7550,8 @@ abstract class FlutterIntegrationCoreApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7122,11 +7564,12 @@ class HostTrivialApi { /// Constructor for [HostTrivialApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - HostTrivialApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + HostTrivialApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -7138,10 +7581,10 @@ class HostTrivialApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -7164,11 +7607,12 @@ class HostSmallApi { /// Constructor for [HostSmallApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - HostSmallApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + HostSmallApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -7180,12 +7624,13 @@ class HostSmallApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7211,10 +7656,10 @@ class HostSmallApi { 'dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -7248,22 +7693,26 @@ abstract class FlutterSmallApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList was null.', + ); final List args = (message as List?)!; final TestMessage? arg_msg = (args[0] as TestMessage?); - assert(arg_msg != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList was null, expected non-null TestMessage.'); + assert( + arg_msg != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList was null, expected non-null TestMessage.', + ); try { final TestMessage output = api.echoWrappedList(arg_msg!); return wrapResponse(result: output); @@ -7271,28 +7720,33 @@ abstract class FlutterSmallApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString was null.', + ); final List args = (message as List?)!; final String? arg_aString = (args[0] as String?); - assert(arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString was null, expected non-null String.'); + assert( + arg_aString != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString was null, expected non-null String.', + ); try { final String output = api.echoString(arg_aString!); return wrapResponse(result: output); @@ -7300,7 +7754,8 @@ abstract class FlutterSmallApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart index e22b2f372e6..c370d9aeda5 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -33,14 +36,17 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -62,17 +68,13 @@ enum EnumState { /// This comment is to test class documentation comments. class DataWithEnum { - DataWithEnum({ - this.state, - }); + DataWithEnum({this.state}); /// This comment is to test field documentation comments. EnumState? state; List _toList() { - return [ - state, - ]; + return [state]; } Object encode() { @@ -81,9 +83,7 @@ class DataWithEnum { static DataWithEnum decode(Object result) { result as List; - return DataWithEnum( - state: result[0] as EnumState?, - ); + return DataWithEnum(state: result[0] as EnumState?); } @override @@ -140,11 +140,12 @@ class EnumApi2Host { /// Constructor for [EnumApi2Host]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - EnumApi2Host( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + EnumApi2Host({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -157,12 +158,13 @@ class EnumApi2Host { 'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Host.echo$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [data], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([data]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -199,22 +201,26 @@ abstract class EnumApi2Flutter { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null.', + ); final List args = (message as List?)!; final DataWithEnum? arg_data = (args[0] as DataWithEnum?); - assert(arg_data != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null, expected non-null DataWithEnum.'); + assert( + arg_data != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null, expected non-null DataWithEnum.', + ); try { final DataWithEnum output = api.echo(arg_data!); return wrapResponse(result: output); @@ -222,7 +228,8 @@ abstract class EnumApi2Flutter { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart index cc803f595e2..f2e2c5d86a8 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart @@ -15,29 +15,24 @@ import 'package:flutter/services.dart'; bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } -enum EventEnum { - one, - two, - three, - fortyTwo, - fourHundredTwentyTwo, -} +enum EventEnum { one, two, three, fortyTwo, fourHundredTwentyTwo } -enum AnotherEventEnum { - justInCase, -} +enum AnotherEventEnum { justInCase } /// A class containing all supported nullable types. class EventAllNullableTypes { @@ -208,16 +203,19 @@ class EventAllNullableTypes { stringMap: (result[24] as Map?)?.cast(), intMap: (result[25] as Map?)?.cast(), - enumMap: (result[26] as Map?) - ?.cast(), + enumMap: + (result[26] as Map?) + ?.cast(), objectMap: (result[27] as Map?)?.cast(), listMap: (result[28] as Map?)?.cast?>(), - mapMap: (result[29] as Map?) - ?.cast?>(), - recursiveClassMap: (result[30] as Map?) - ?.cast(), + mapMap: + (result[29] as Map?) + ?.cast?>(), + recursiveClassMap: + (result[30] as Map?) + ?.cast(), ); } @@ -241,16 +239,12 @@ class EventAllNullableTypes { sealed class PlatformEvent {} class IntEvent extends PlatformEvent { - IntEvent({ - required this.value, - }); + IntEvent({required this.value}); int value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -259,9 +253,7 @@ class IntEvent extends PlatformEvent { static IntEvent decode(Object result) { result as List; - return IntEvent( - value: result[0]! as int, - ); + return IntEvent(value: result[0]! as int); } @override @@ -282,16 +274,12 @@ class IntEvent extends PlatformEvent { } class StringEvent extends PlatformEvent { - StringEvent({ - required this.value, - }); + StringEvent({required this.value}); String value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -300,9 +288,7 @@ class StringEvent extends PlatformEvent { static StringEvent decode(Object result) { result as List; - return StringEvent( - value: result[0]! as String, - ); + return StringEvent(value: result[0]! as String); } @override @@ -323,16 +309,12 @@ class StringEvent extends PlatformEvent { } class BoolEvent extends PlatformEvent { - BoolEvent({ - required this.value, - }); + BoolEvent({required this.value}); bool value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -341,9 +323,7 @@ class BoolEvent extends PlatformEvent { static BoolEvent decode(Object result) { result as List; - return BoolEvent( - value: result[0]! as bool, - ); + return BoolEvent(value: result[0]! as bool); } @override @@ -364,16 +344,12 @@ class BoolEvent extends PlatformEvent { } class DoubleEvent extends PlatformEvent { - DoubleEvent({ - required this.value, - }); + DoubleEvent({required this.value}); double value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -382,9 +358,7 @@ class DoubleEvent extends PlatformEvent { static DoubleEvent decode(Object result) { result as List; - return DoubleEvent( - value: result[0]! as double, - ); + return DoubleEvent(value: result[0]! as double); } @override @@ -405,16 +379,12 @@ class DoubleEvent extends PlatformEvent { } class ObjectsEvent extends PlatformEvent { - ObjectsEvent({ - required this.value, - }); + ObjectsEvent({required this.value}); Object value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -423,9 +393,7 @@ class ObjectsEvent extends PlatformEvent { static ObjectsEvent decode(Object result) { result as List; - return ObjectsEvent( - value: result[0]!, - ); + return ObjectsEvent(value: result[0]!); } @override @@ -446,16 +414,12 @@ class ObjectsEvent extends PlatformEvent { } class EnumEvent extends PlatformEvent { - EnumEvent({ - required this.value, - }); + EnumEvent({required this.value}); EventEnum value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -464,9 +428,7 @@ class EnumEvent extends PlatformEvent { static EnumEvent decode(Object result) { result as List; - return EnumEvent( - value: result[0]! as EventEnum, - ); + return EnumEvent(value: result[0]! as EventEnum); } @override @@ -487,16 +449,12 @@ class EnumEvent extends PlatformEvent { } class ClassEvent extends PlatformEvent { - ClassEvent({ - required this.value, - }); + ClassEvent({required this.value}); EventAllNullableTypes value; List _toList() { - return [ - value, - ]; + return [value]; } Object encode() { @@ -505,9 +463,7 @@ class ClassEvent extends PlatformEvent { static ClassEvent decode(Object result) { result as List; - return ClassEvent( - value: result[0]! as EventAllNullableTypes, - ); + return ClassEvent(value: result[0]! as EventAllNullableTypes); } @override @@ -600,16 +556,18 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = - StandardMethodCodec(_PigeonCodec()); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( + _PigeonCodec(), +); Stream streamInts({String instanceName = ''}) { if (instanceName.isNotEmpty) { instanceName = '.$instanceName'; } final EventChannel streamIntsChannel = EventChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamInts$instanceName', - pigeonMethodCodec); + 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamInts$instanceName', + pigeonMethodCodec, + ); return streamIntsChannel.receiveBroadcastStream().map((dynamic event) { return event as int; }); @@ -620,8 +578,9 @@ Stream streamEvents({String instanceName = ''}) { instanceName = '.$instanceName'; } final EventChannel streamEventsChannel = EventChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamEvents$instanceName', - pigeonMethodCodec); + 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamEvents$instanceName', + pigeonMethodCodec, + ); return streamEventsChannel.receiveBroadcastStream().map((dynamic event) { return event as PlatformEvent; }); @@ -632,11 +591,12 @@ Stream streamConsistentNumbers({String instanceName = ''}) { instanceName = '.$instanceName'; } final EventChannel streamConsistentNumbersChannel = EventChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamConsistentNumbers$instanceName', - pigeonMethodCodec); - return streamConsistentNumbersChannel - .receiveBroadcastStream() - .map((dynamic event) { + 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamConsistentNumbers$instanceName', + pigeonMethodCodec, + ); + return streamConsistentNumbersChannel.receiveBroadcastStream().map(( + dynamic event, + ) { return event as int; }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart index 4c6b0307cf5..b376cf23569 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart @@ -33,16 +33,18 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = - StandardMethodCodec(_PigeonCodec()); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( + _PigeonCodec(), +); Stream streamIntsAgain({String instanceName = ''}) { if (instanceName.isNotEmpty) { instanceName = '.$instanceName'; } final EventChannel streamIntsAgainChannel = EventChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamIntsAgain$instanceName', - pigeonMethodCodec); + 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamIntsAgain$instanceName', + pigeonMethodCodec, + ); return streamIntsAgainChannel.receiveBroadcastStream().map((dynamic event) { return event as int; }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart index 318ca3fd057..b41d8082c29 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart @@ -22,29 +22,28 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } class FlutterSearchRequest { - FlutterSearchRequest({ - this.query, - }); + FlutterSearchRequest({this.query}); String? query; List _toList() { - return [ - query, - ]; + return [query]; } Object encode() { @@ -53,9 +52,7 @@ class FlutterSearchRequest { static FlutterSearchRequest decode(Object result) { result as List; - return FlutterSearchRequest( - query: result[0] as String?, - ); + return FlutterSearchRequest(query: result[0] as String?); } @override @@ -76,20 +73,14 @@ class FlutterSearchRequest { } class FlutterSearchReply { - FlutterSearchReply({ - this.result, - this.error, - }); + FlutterSearchReply({this.result, this.error}); String? result; String? error; List _toList() { - return [ - result, - error, - ]; + return [result, error]; } Object encode() { @@ -122,16 +113,12 @@ class FlutterSearchReply { } class FlutterSearchRequests { - FlutterSearchRequests({ - this.requests, - }); + FlutterSearchRequests({this.requests}); List? requests; List _toList() { - return [ - requests, - ]; + return [requests]; } Object encode() { @@ -140,9 +127,7 @@ class FlutterSearchRequests { static FlutterSearchRequests decode(Object result) { result as List; - return FlutterSearchRequests( - requests: result[0] as List?, - ); + return FlutterSearchRequests(requests: result[0] as List?); } @override @@ -163,16 +148,12 @@ class FlutterSearchRequests { } class FlutterSearchReplies { - FlutterSearchReplies({ - this.replies, - }); + FlutterSearchReplies({this.replies}); List? replies; List _toList() { - return [ - replies, - ]; + return [replies]; } Object encode() { @@ -181,9 +162,7 @@ class FlutterSearchReplies { static FlutterSearchReplies decode(Object result) { result as List; - return FlutterSearchReplies( - replies: result[0] as List?, - ); + return FlutterSearchReplies(replies: result[0] as List?); } @override @@ -249,9 +228,9 @@ class Api { /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. Api({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -263,12 +242,13 @@ class Api { 'dev.flutter.pigeon.pigeon_integration_tests.Api.search$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [request], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([request]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -294,12 +274,13 @@ class Api { 'dev.flutter.pigeon.pigeon_integration_tests.Api.doSearches$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [request], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([request]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -325,12 +306,13 @@ class Api { 'dev.flutter.pigeon.pigeon_integration_tests.Api.echo$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [requests], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([requests]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -356,12 +338,13 @@ class Api { 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart index 8e67ae2a4d1..738731c94b0 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -33,14 +36,17 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -52,21 +58,13 @@ bool _deepEquals(Object? a, Object? b) { /// //////////////////////// /// This comment also tests comments that start with '/' /// //////////////////////// -enum MessageRequestState { - pending, - success, - failure, -} +enum MessageRequestState { pending, success, failure } /// This comment is to test class documentation comments. /// /// This comment also tests multiple line comments. class MessageSearchRequest { - MessageSearchRequest({ - this.query, - this.anInt, - this.aBool, - }); + MessageSearchRequest({this.query, this.anInt, this.aBool}); /// This comment is to test field documentation comments. String? query; @@ -78,11 +76,7 @@ class MessageSearchRequest { bool? aBool; List _toList() { - return [ - query, - anInt, - aBool, - ]; + return [query, anInt, aBool]; } Object encode() { @@ -117,11 +111,7 @@ class MessageSearchRequest { /// This comment is to test class documentation comments. class MessageSearchReply { - MessageSearchReply({ - this.result, - this.error, - this.state, - }); + MessageSearchReply({this.result, this.error, this.state}); /// This comment is to test field documentation comments. /// @@ -135,11 +125,7 @@ class MessageSearchReply { MessageRequestState? state; List _toList() { - return [ - result, - error, - state, - ]; + return [result, error, state]; } Object encode() { @@ -174,17 +160,13 @@ class MessageSearchReply { /// This comment is to test class documentation comments. class MessageNested { - MessageNested({ - this.request, - }); + MessageNested({this.request}); /// This comment is to test field documentation comments. MessageSearchRequest? request; List _toList() { - return [ - request, - ]; + return [request]; } Object encode() { @@ -193,9 +175,7 @@ class MessageNested { static MessageNested decode(Object result) { result as List; - return MessageNested( - request: result[0] as MessageSearchRequest?, - ); + return MessageNested(request: result[0] as MessageSearchRequest?); } @override @@ -264,11 +244,12 @@ class MessageApi { /// Constructor for [MessageApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MessageApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + MessageApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -283,10 +264,10 @@ class MessageApi { 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -309,12 +290,13 @@ class MessageApi { 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [request], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([request]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -341,11 +323,12 @@ class MessageNestedApi { /// Constructor for [MessageNestedApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MessageNestedApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + MessageNestedApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -360,12 +343,13 @@ class MessageNestedApi { 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [nested], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([nested]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -402,23 +386,27 @@ abstract class MessageFlutterSearchApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null.', + ); final List args = (message as List?)!; final MessageSearchRequest? arg_request = (args[0] as MessageSearchRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null, expected non-null MessageSearchRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null, expected non-null MessageSearchRequest.', + ); try { final MessageSearchReply output = api.search(arg_request!); return wrapResponse(result: output); @@ -426,7 +414,8 @@ abstract class MessageFlutterSearchApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart index 7ac4cf0f932..4330b5f0143 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -55,11 +58,12 @@ class MultipleArityHostApi { /// Constructor for [MultipleArityHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MultipleArityHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + MultipleArityHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -71,12 +75,13 @@ class MultipleArityHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [x, y], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([x, y]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -111,25 +116,31 @@ abstract class MultipleArityFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null.', + ); final List args = (message as List?)!; final int? arg_x = (args[0] as int?); - assert(arg_x != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.'); + assert( + arg_x != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.', + ); final int? arg_y = (args[1] as int?); - assert(arg_y != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.'); + assert( + arg_y != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.', + ); try { final int output = api.subtract(arg_x!, arg_y!); return wrapResponse(result: output); @@ -137,7 +148,8 @@ abstract class MultipleArityFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart index 1aead0d1607..71bf12a06a3 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -33,34 +36,30 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } -enum ReplyType { - success, - error, -} +enum ReplyType { success, error } class NonNullFieldSearchRequest { - NonNullFieldSearchRequest({ - required this.query, - }); + NonNullFieldSearchRequest({required this.query}); String query; List _toList() { - return [ - query, - ]; + return [query]; } Object encode() { @@ -69,9 +68,7 @@ class NonNullFieldSearchRequest { static NonNullFieldSearchRequest decode(Object result) { result as List; - return NonNullFieldSearchRequest( - query: result[0]! as String, - ); + return NonNullFieldSearchRequest(query: result[0]! as String); } @override @@ -93,20 +90,14 @@ class NonNullFieldSearchRequest { } class ExtraData { - ExtraData({ - required this.detailA, - required this.detailB, - }); + ExtraData({required this.detailA, required this.detailB}); String detailA; String detailB; List _toList() { - return [ - detailA, - detailB, - ]; + return [detailA, detailB]; } Object encode() { @@ -158,13 +149,7 @@ class NonNullFieldSearchReply { ReplyType type; List _toList() { - return [ - result, - error, - indices, - extraData, - type, - ]; + return [result, error, indices, extraData, type]; } Object encode() { @@ -245,11 +230,12 @@ class NonNullFieldHostApi { /// Constructor for [NonNullFieldHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NonNullFieldHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + NonNullFieldHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -257,17 +243,19 @@ class NonNullFieldHostApi { final String pigeonVar_messageChannelSuffix; Future search( - NonNullFieldSearchRequest nested) async { + NonNullFieldSearchRequest nested, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldHostApi.search$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [nested], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([nested]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -302,23 +290,27 @@ abstract class NonNullFieldFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null.', + ); final List args = (message as List?)!; final NonNullFieldSearchRequest? arg_request = (args[0] as NonNullFieldSearchRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null, expected non-null NonNullFieldSearchRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null, expected non-null NonNullFieldSearchRequest.', + ); try { final NonNullFieldSearchReply output = api.search(arg_request!); return wrapResponse(result: output); @@ -326,7 +318,8 @@ abstract class NonNullFieldFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart index ce9fd9ca82e..d08a04eaf4e 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -33,38 +36,32 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } -enum NullFieldsSearchReplyType { - success, - failure, -} +enum NullFieldsSearchReplyType { success, failure } class NullFieldsSearchRequest { - NullFieldsSearchRequest({ - this.query, - required this.identifier, - }); + NullFieldsSearchRequest({this.query, required this.identifier}); String? query; int identifier; List _toList() { - return [ - query, - identifier, - ]; + return [query, identifier]; } Object encode() { @@ -116,13 +113,7 @@ class NullFieldsSearchReply { NullFieldsSearchReplyType? type; List _toList() { - return [ - result, - error, - indices, - request, - type, - ]; + return [result, error, indices, request, type]; } Object encode() { @@ -198,11 +189,12 @@ class NullFieldsHostApi { /// Constructor for [NullFieldsHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullFieldsHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + NullFieldsHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -214,12 +206,13 @@ class NullFieldsHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsHostApi.search$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [nested], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([nested]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -254,23 +247,27 @@ abstract class NullFieldsFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null.', + ); final List args = (message as List?)!; final NullFieldsSearchRequest? arg_request = (args[0] as NullFieldsSearchRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null, expected non-null NullFieldsSearchRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null, expected non-null NullFieldsSearchRequest.', + ); try { final NullFieldsSearchReply output = api.search(arg_request!); return wrapResponse(result: output); @@ -278,7 +275,8 @@ abstract class NullFieldsFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart index c17bddc3027..8028756bfa9 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -55,11 +58,12 @@ class NullableReturnHostApi { /// Constructor for [NullableReturnHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableReturnHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + NullableReturnHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -71,10 +75,10 @@ class NullableReturnHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -105,12 +109,12 @@ abstract class NullableReturnFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -122,7 +126,8 @@ abstract class NullableReturnFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -134,11 +139,12 @@ class NullableArgHostApi { /// Constructor for [NullableArgHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableArgHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + NullableArgHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -150,12 +156,13 @@ class NullableArgHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [x], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([x]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -190,18 +197,20 @@ abstract class NullableArgFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit was null.', + ); final List args = (message as List?)!; final int? arg_x = (args[0] as int?); try { @@ -211,7 +220,8 @@ abstract class NullableArgFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -223,11 +233,12 @@ class NullableCollectionReturnHostApi { /// Constructor for [NullableCollectionReturnHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableCollectionReturnHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + NullableCollectionReturnHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -239,10 +250,10 @@ class NullableCollectionReturnHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -273,12 +284,12 @@ abstract class NullableCollectionReturnFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -290,7 +301,8 @@ abstract class NullableCollectionReturnFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -302,11 +314,12 @@ class NullableCollectionArgHostApi { /// Constructor for [NullableCollectionArgHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableCollectionArgHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + NullableCollectionArgHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -318,12 +331,13 @@ class NullableCollectionArgHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [x], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([x]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -358,18 +372,20 @@ abstract class NullableCollectionArgFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit was null.', + ); final List args = (message as List?)!; final List? arg_x = (args[0] as List?)?.cast(); @@ -380,7 +396,8 @@ abstract class NullableCollectionArgFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart index 62eb4c85b5f..bcef1911e6f 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart @@ -19,8 +19,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -55,11 +58,12 @@ class PrimitiveHostApi { /// Constructor for [PrimitiveHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - PrimitiveHostApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + PrimitiveHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -71,12 +75,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -102,12 +107,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -133,12 +139,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -164,12 +171,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -195,12 +203,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -226,12 +235,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -257,12 +267,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt32List$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -288,12 +299,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -319,12 +331,13 @@ class PrimitiveHostApi { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -376,22 +389,26 @@ abstract class PrimitiveFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null.', + ); final List args = (message as List?)!; final int? arg_value = (args[0] as int?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null, expected non-null int.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null, expected non-null int.', + ); try { final int output = api.anInt(arg_value!); return wrapResponse(result: output); @@ -399,28 +416,33 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null.', + ); final List args = (message as List?)!; final bool? arg_value = (args[0] as bool?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null, expected non-null bool.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null, expected non-null bool.', + ); try { final bool output = api.aBool(arg_value!); return wrapResponse(result: output); @@ -428,28 +450,33 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null.', + ); final List args = (message as List?)!; final String? arg_value = (args[0] as String?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null, expected non-null String.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null, expected non-null String.', + ); try { final String output = api.aString(arg_value!); return wrapResponse(result: output); @@ -457,28 +484,33 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null.', + ); final List args = (message as List?)!; final double? arg_value = (args[0] as double?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null, expected non-null double.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null, expected non-null double.', + ); try { final double output = api.aDouble(arg_value!); return wrapResponse(result: output); @@ -486,29 +518,34 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null.', + ); final List args = (message as List?)!; final Map? arg_value = (args[0] as Map?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null, expected non-null Map.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null, expected non-null Map.', + ); try { final Map output = api.aMap(arg_value!); return wrapResponse(result: output); @@ -516,28 +553,33 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null.', + ); final List args = (message as List?)!; final List? arg_value = (args[0] as List?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null, expected non-null List.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null, expected non-null List.', + ); try { final List output = api.aList(arg_value!); return wrapResponse(result: output); @@ -545,28 +587,33 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null.', + ); final List args = (message as List?)!; final Int32List? arg_value = (args[0] as Int32List?); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null, expected non-null Int32List.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null, expected non-null Int32List.', + ); try { final Int32List output = api.anInt32List(arg_value!); return wrapResponse(result: output); @@ -574,29 +621,34 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null.', + ); final List args = (message as List?)!; final List? arg_value = (args[0] as List?)?.cast(); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null, expected non-null List.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null, expected non-null List.', + ); try { final List output = api.aBoolList(arg_value!); return wrapResponse(result: output); @@ -604,29 +656,34 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null.', + ); final List args = (message as List?)!; final Map? arg_value = (args[0] as Map?)?.cast(); - assert(arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null, expected non-null Map.'); + assert( + arg_value != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null, expected non-null Map.', + ); try { final Map output = api.aStringIntMap(arg_value!); return wrapResponse(result: output); @@ -634,7 +691,8 @@ abstract class PrimitiveFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart index fd7d5a450f2..790ff650bc2 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart @@ -22,8 +22,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -53,54 +56,54 @@ class PigeonOverrides { required Map aMap, required ProxyApiTestEnum anEnum, required ProxyApiSuperClass aProxyApi, - required bool Function( - ProxyApiTestClass pigeon_instance, - bool aBool, - ) flutterEchoBool, - required int Function( - ProxyApiTestClass pigeon_instance, - int anInt, - ) flutterEchoInt, - required double Function( - ProxyApiTestClass pigeon_instance, - double aDouble, - ) flutterEchoDouble, - required String Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) flutterEchoString, + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) + flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) + flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) + flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) + flutterEchoString, required Uint8List Function( ProxyApiTestClass pigeon_instance, Uint8List aList, - ) flutterEchoUint8List, + ) + flutterEchoUint8List, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoList, + ) + flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoProxyApiList, + ) + flutterEchoProxyApiList, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoMap, + ) + flutterEchoMap, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoProxyApiMap, + ) + flutterEchoProxyApiMap, required ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, - ) flutterEchoEnum, + ) + flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, - ) flutterEchoProxyApi, + ) + flutterEchoProxyApi, required Future Function( ProxyApiTestClass pigeon_instance, String aString, - ) flutterEchoAsyncString, + ) + flutterEchoAsyncString, required bool boolParam, required int intParam, required double doubleParam, @@ -123,42 +126,36 @@ class PigeonOverrides { void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - bool? Function( - ProxyApiTestClass pigeon_instance, - bool? aBool, - )? flutterEchoNullableBool, - int? Function( - ProxyApiTestClass pigeon_instance, - int? anInt, - )? flutterEchoNullableInt, - double? Function( - ProxyApiTestClass pigeon_instance, - double? aDouble, - )? flutterEchoNullableDouble, - String? Function( - ProxyApiTestClass pigeon_instance, - String? aString, - )? flutterEchoNullableString, - Uint8List? Function( - ProxyApiTestClass pigeon_instance, - Uint8List? aList, - )? flutterEchoNullableUint8List, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? + flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? + flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? + flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? + flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? + flutterEchoNullableUint8List, List? Function( ProxyApiTestClass pigeon_instance, List? aList, - )? flutterEchoNullableList, + )? + flutterEchoNullableList, Map? Function( ProxyApiTestClass pigeon_instance, Map? aMap, - )? flutterEchoNullableMap, + )? + flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum, + )? + flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi, + )? + flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, bool? nullableBoolParam, int? nullableIntParam, @@ -169,7 +166,8 @@ class PigeonOverrides { Map? nullableMapParam, ProxyApiTestEnum? nullableEnumParam, ProxyApiSuperClass? nullableProxyApiParam, - })? proxyApiTestClass_new; + })? + proxyApiTestClass_new; /// Overrides [ProxyApiTestClass.namedConstructor]. static ProxyApiTestClass Function({ @@ -182,54 +180,54 @@ class PigeonOverrides { required Map aMap, required ProxyApiTestEnum anEnum, required ProxyApiSuperClass aProxyApi, - required bool Function( - ProxyApiTestClass pigeon_instance, - bool aBool, - ) flutterEchoBool, - required int Function( - ProxyApiTestClass pigeon_instance, - int anInt, - ) flutterEchoInt, - required double Function( - ProxyApiTestClass pigeon_instance, - double aDouble, - ) flutterEchoDouble, - required String Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) flutterEchoString, + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) + flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) + flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) + flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) + flutterEchoString, required Uint8List Function( ProxyApiTestClass pigeon_instance, Uint8List aList, - ) flutterEchoUint8List, + ) + flutterEchoUint8List, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoList, + ) + flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoProxyApiList, + ) + flutterEchoProxyApiList, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoMap, + ) + flutterEchoMap, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoProxyApiMap, + ) + flutterEchoProxyApiMap, required ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, - ) flutterEchoEnum, + ) + flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, - ) flutterEchoProxyApi, + ) + flutterEchoProxyApi, required Future Function( ProxyApiTestClass pigeon_instance, String aString, - ) flutterEchoAsyncString, + ) + flutterEchoAsyncString, bool? aNullableBool, int? aNullableInt, double? aNullableDouble, @@ -243,44 +241,39 @@ class PigeonOverrides { void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - bool? Function( - ProxyApiTestClass pigeon_instance, - bool? aBool, - )? flutterEchoNullableBool, - int? Function( - ProxyApiTestClass pigeon_instance, - int? anInt, - )? flutterEchoNullableInt, - double? Function( - ProxyApiTestClass pigeon_instance, - double? aDouble, - )? flutterEchoNullableDouble, - String? Function( - ProxyApiTestClass pigeon_instance, - String? aString, - )? flutterEchoNullableString, - Uint8List? Function( - ProxyApiTestClass pigeon_instance, - Uint8List? aList, - )? flutterEchoNullableUint8List, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? + flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? + flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? + flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? + flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? + flutterEchoNullableUint8List, List? Function( ProxyApiTestClass pigeon_instance, List? aList, - )? flutterEchoNullableList, + )? + flutterEchoNullableList, Map? Function( ProxyApiTestClass pigeon_instance, Map? aMap, - )? flutterEchoNullableMap, + )? + flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum, + )? + flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi, + )? + flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, - })? proxyApiTestClass_namedConstructor; + })? + proxyApiTestClass_namedConstructor; /// Overrides [ProxyApiSuperClass.new]. static ProxyApiSuperClass Function()? proxyApiSuperClass_new; @@ -325,7 +318,7 @@ abstract class PigeonInternalProxyApiBaseClass { this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -396,7 +389,7 @@ class PigeonInstanceManager { // HashMap). final Expando _identifiers = Expando(); final Map> - _weakInstances = >{}; + _weakInstances = >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -421,15 +414,20 @@ class PigeonInstanceManager { }, ); _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager); + instanceManager: instanceManager, + ); ProxyApiTestClass.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ProxyApiSuperClass.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ProxyApiInterface.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ClassWithApiRequirement.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); return instanceManager; } @@ -446,8 +444,9 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = - WeakReference(instance); + _weakInstances[identifier] = WeakReference( + instance, + ); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -509,7 +508,8 @@ class PigeonInstanceManager { /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. T? getInstanceWithWeakReference( - int identifier) { + int identifier, + ) { final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; @@ -544,7 +544,9 @@ class PigeonInstanceManager { /// Throws assertion error if the instance or its identifier has already been /// added. void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, int identifier) { + PigeonInternalProxyApiBaseClass instance, + int identifier, + ) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -573,7 +575,7 @@ class PigeonInstanceManager { class _PigeonInternalInstanceManagerApi { /// Constructor for [_PigeonInternalInstanceManagerApi]. _PigeonInternalInstanceManagerApi({BinaryMessenger? binaryMessenger}) - : pigeonVar_binaryMessenger = binaryMessenger; + : pigeonVar_binaryMessenger = binaryMessenger; final BinaryMessenger? pigeonVar_binaryMessenger; @@ -585,31 +587,37 @@ class _PigeonInternalInstanceManagerApi { PigeonInstanceManager? instanceManager, }) { { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference was null.', + ); final List args = (message as List?)!; final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.'); + assert( + arg_identifier != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', + ); try { - (instanceManager ?? PigeonInstanceManager.instance) - .remove(arg_identifier!); + (instanceManager ?? PigeonInstanceManager.instance).remove( + arg_identifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -621,12 +629,13 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [identifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([identifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -650,10 +659,10 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.clear'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -688,19 +697,16 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager - .getInstanceWithWeakReference(readValue(buffer)! as int); + return instanceManager.getInstanceWithWeakReference( + readValue(buffer)! as int, + ); default: return super.readValueOfType(type, buffer); } } } -enum ProxyApiTestEnum { - one, - two, - three, -} +enum ProxyApiTestEnum { one, two, three } class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); @@ -758,91 +764,85 @@ class ProxyApiTestClass extends ProxyApiSuperClass void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - required bool Function( - ProxyApiTestClass pigeon_instance, - bool aBool, - ) flutterEchoBool, - required int Function( - ProxyApiTestClass pigeon_instance, - int anInt, - ) flutterEchoInt, - required double Function( - ProxyApiTestClass pigeon_instance, - double aDouble, - ) flutterEchoDouble, - required String Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) flutterEchoString, + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) + flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) + flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) + flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) + flutterEchoString, required Uint8List Function( ProxyApiTestClass pigeon_instance, Uint8List aList, - ) flutterEchoUint8List, + ) + flutterEchoUint8List, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoList, + ) + flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoProxyApiList, + ) + flutterEchoProxyApiList, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoMap, + ) + flutterEchoMap, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoProxyApiMap, + ) + flutterEchoProxyApiMap, required ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, - ) flutterEchoEnum, + ) + flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, - ) flutterEchoProxyApi, - bool? Function( - ProxyApiTestClass pigeon_instance, - bool? aBool, - )? flutterEchoNullableBool, - int? Function( - ProxyApiTestClass pigeon_instance, - int? anInt, - )? flutterEchoNullableInt, - double? Function( - ProxyApiTestClass pigeon_instance, - double? aDouble, - )? flutterEchoNullableDouble, - String? Function( - ProxyApiTestClass pigeon_instance, - String? aString, - )? flutterEchoNullableString, - Uint8List? Function( - ProxyApiTestClass pigeon_instance, - Uint8List? aList, - )? flutterEchoNullableUint8List, + ) + flutterEchoProxyApi, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? + flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? + flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? + flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? + flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? + flutterEchoNullableUint8List, List? Function( ProxyApiTestClass pigeon_instance, List? aList, - )? flutterEchoNullableList, + )? + flutterEchoNullableList, Map? Function( ProxyApiTestClass pigeon_instance, Map? aMap, - )? flutterEchoNullableMap, + )? + flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum, + )? + flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi, + )? + flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, required Future Function( ProxyApiTestClass pigeon_instance, String aString, - ) flutterEchoAsyncString, + ) + flutterEchoAsyncString, required bool boolParam, required int intParam, required double doubleParam, @@ -1063,8 +1063,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass ProxyApiTestEnum? nullableEnumParam, ProxyApiSuperClass? nullableProxyApiParam, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1072,50 +1072,50 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([ - pigeonVar_instanceIdentifier, - aBool, - anInt, - aDouble, - aString, - aUint8List, - aList, - aMap, - anEnum, - aProxyApi, - aNullableBool, - aNullableInt, - aNullableDouble, - aNullableString, - aNullableUint8List, - aNullableList, - aNullableMap, - aNullableEnum, - aNullableProxyApi, - boolParam, - intParam, - doubleParam, - stringParam, - aUint8ListParam, - listParam, - mapParam, - enumParam, - proxyApiParam, - nullableBoolParam, - nullableIntParam, - nullableDoubleParam, - nullableStringParam, - nullableUint8ListParam, - nullableListParam, - nullableMapParam, - nullableEnumParam, - nullableProxyApiParam - ]); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + aBool, + anInt, + aDouble, + aString, + aUint8List, + aList, + aMap, + anEnum, + aProxyApi, + aNullableBool, + aNullableInt, + aNullableDouble, + aNullableString, + aNullableUint8List, + aNullableList, + aNullableMap, + aNullableEnum, + aNullableProxyApi, + boolParam, + intParam, + doubleParam, + stringParam, + aUint8ListParam, + listParam, + mapParam, + enumParam, + proxyApiParam, + nullableBoolParam, + nullableIntParam, + nullableDoubleParam, + nullableStringParam, + nullableUint8ListParam, + nullableListParam, + nullableMapParam, + nullableEnumParam, + nullableProxyApiParam, + ]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1158,91 +1158,85 @@ class ProxyApiTestClass extends ProxyApiSuperClass void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - required bool Function( - ProxyApiTestClass pigeon_instance, - bool aBool, - ) flutterEchoBool, - required int Function( - ProxyApiTestClass pigeon_instance, - int anInt, - ) flutterEchoInt, - required double Function( - ProxyApiTestClass pigeon_instance, - double aDouble, - ) flutterEchoDouble, - required String Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) flutterEchoString, + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) + flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) + flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) + flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) + flutterEchoString, required Uint8List Function( ProxyApiTestClass pigeon_instance, Uint8List aList, - ) flutterEchoUint8List, + ) + flutterEchoUint8List, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoList, + ) + flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoProxyApiList, + ) + flutterEchoProxyApiList, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoMap, + ) + flutterEchoMap, required Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoProxyApiMap, + ) + flutterEchoProxyApiMap, required ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, - ) flutterEchoEnum, + ) + flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, - ) flutterEchoProxyApi, - bool? Function( - ProxyApiTestClass pigeon_instance, - bool? aBool, - )? flutterEchoNullableBool, - int? Function( - ProxyApiTestClass pigeon_instance, - int? anInt, - )? flutterEchoNullableInt, - double? Function( - ProxyApiTestClass pigeon_instance, - double? aDouble, - )? flutterEchoNullableDouble, - String? Function( - ProxyApiTestClass pigeon_instance, - String? aString, - )? flutterEchoNullableString, - Uint8List? Function( - ProxyApiTestClass pigeon_instance, - Uint8List? aList, - )? flutterEchoNullableUint8List, + ) + flutterEchoProxyApi, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? + flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? + flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? + flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? + flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? + flutterEchoNullableUint8List, List? Function( ProxyApiTestClass pigeon_instance, List? aList, - )? flutterEchoNullableList, + )? + flutterEchoNullableList, Map? Function( ProxyApiTestClass pigeon_instance, Map? aMap, - )? flutterEchoNullableMap, + )? + flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum, + )? + flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi, + )? + flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, required Future Function( ProxyApiTestClass pigeon_instance, String aString, - ) flutterEchoAsyncString, + ) + flutterEchoAsyncString, }) { if (PigeonOverrides.proxyApiTestClass_namedConstructor != null) { return PigeonOverrides.proxyApiTestClass_namedConstructor!( @@ -1391,8 +1385,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass this.flutterNoopAsync, required this.flutterEchoAsyncString, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1400,32 +1394,32 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.namedConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([ - pigeonVar_instanceIdentifier, - aBool, - anInt, - aDouble, - aString, - aUint8List, - aList, - aMap, - anEnum, - aProxyApi, - aNullableBool, - aNullableInt, - aNullableDouble, - aNullableString, - aNullableUint8List, - aNullableList, - aNullableMap, - aNullableEnum, - aNullableProxyApi - ]); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + aBool, + anInt, + aDouble, + aString, + aUint8List, + aList, + aMap, + anEnum, + aProxyApi, + aNullableBool, + aNullableInt, + aNullableDouble, + aNullableString, + aNullableUint8List, + aNullableList, + aNullableMap, + aNullableEnum, + aNullableProxyApi, + ]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1498,8 +1492,9 @@ class ProxyApiTestClass extends ProxyApiSuperClass }) : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecProxyApiTestClass = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecProxyApiTestClass = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); final bool aBool; @@ -1600,7 +1595,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final void Function(ProxyApiTestClass pigeon_instance)? - flutterThrowErrorFromVoid; + flutterThrowErrorFromVoid; /// Returns the passed boolean, to test serialization and deserialization. /// @@ -1621,10 +1616,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final bool Function( - ProxyApiTestClass pigeon_instance, - bool aBool, - ) flutterEchoBool; + final bool Function(ProxyApiTestClass pigeon_instance, bool aBool) + flutterEchoBool; /// Returns the passed int, to test serialization and deserialization. /// @@ -1645,10 +1638,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final int Function( - ProxyApiTestClass pigeon_instance, - int anInt, - ) flutterEchoInt; + final int Function(ProxyApiTestClass pigeon_instance, int anInt) + flutterEchoInt; /// Returns the passed double, to test serialization and deserialization. /// @@ -1669,10 +1660,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final double Function( - ProxyApiTestClass pigeon_instance, - double aDouble, - ) flutterEchoDouble; + final double Function(ProxyApiTestClass pigeon_instance, double aDouble) + flutterEchoDouble; /// Returns the passed string, to test serialization and deserialization. /// @@ -1693,10 +1682,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final String Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) flutterEchoString; + final String Function(ProxyApiTestClass pigeon_instance, String aString) + flutterEchoString; /// Returns the passed byte list, to test serialization and deserialization. /// @@ -1717,10 +1704,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Uint8List Function( - ProxyApiTestClass pigeon_instance, - Uint8List aList, - ) flutterEchoUint8List; + final Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) + flutterEchoUint8List; /// Returns the passed list, to test serialization and deserialization. /// @@ -1744,7 +1729,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoList; + ) + flutterEchoList; /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. @@ -1769,7 +1755,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final List Function( ProxyApiTestClass pigeon_instance, List aList, - ) flutterEchoProxyApiList; + ) + flutterEchoProxyApiList; /// Returns the passed map, to test serialization and deserialization. /// @@ -1793,7 +1780,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoMap; + ) + flutterEchoMap; /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. @@ -1818,7 +1806,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - ) flutterEchoProxyApiMap; + ) + flutterEchoProxyApiMap; /// Returns the passed enum to test serialization and deserialization. /// @@ -1842,7 +1831,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, - ) flutterEchoEnum; + ) + flutterEchoEnum; /// Returns the passed ProxyApi to test serialization and deserialization. /// @@ -1866,7 +1856,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, - ) flutterEchoProxyApi; + ) + flutterEchoProxyApi; /// Returns the passed boolean, to test serialization and deserialization. /// @@ -1887,10 +1878,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final bool? Function( - ProxyApiTestClass pigeon_instance, - bool? aBool, - )? flutterEchoNullableBool; + final bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? + flutterEchoNullableBool; /// Returns the passed int, to test serialization and deserialization. /// @@ -1911,10 +1900,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final int? Function( - ProxyApiTestClass pigeon_instance, - int? anInt, - )? flutterEchoNullableInt; + final int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? + flutterEchoNullableInt; /// Returns the passed double, to test serialization and deserialization. /// @@ -1935,10 +1922,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final double? Function( - ProxyApiTestClass pigeon_instance, - double? aDouble, - )? flutterEchoNullableDouble; + final double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? + flutterEchoNullableDouble; /// Returns the passed string, to test serialization and deserialization. /// @@ -1959,10 +1944,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final String? Function( - ProxyApiTestClass pigeon_instance, - String? aString, - )? flutterEchoNullableString; + final String? Function(ProxyApiTestClass pigeon_instance, String? aString)? + flutterEchoNullableString; /// Returns the passed byte list, to test serialization and deserialization. /// @@ -1986,7 +1969,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Uint8List? Function( ProxyApiTestClass pigeon_instance, Uint8List? aList, - )? flutterEchoNullableUint8List; + )? + flutterEchoNullableUint8List; /// Returns the passed list, to test serialization and deserialization. /// @@ -2010,7 +1994,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final List? Function( ProxyApiTestClass pigeon_instance, List? aList, - )? flutterEchoNullableList; + )? + flutterEchoNullableList; /// Returns the passed map, to test serialization and deserialization. /// @@ -2034,7 +2019,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Map? Function( ProxyApiTestClass pigeon_instance, Map? aMap, - )? flutterEchoNullableMap; + )? + flutterEchoNullableMap; /// Returns the passed enum to test serialization and deserialization. /// @@ -2058,7 +2044,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum; + )? + flutterEchoNullableEnum; /// Returns the passed ProxyApi to test serialization and deserialization. /// @@ -2082,7 +2069,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi; + )? + flutterEchoNullableProxyApi; /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. @@ -2105,7 +2093,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Future Function(ProxyApiTestClass pigeon_instance)? - flutterNoopAsync; + flutterNoopAsync; /// Returns the passed in generic Object asynchronously. /// @@ -2129,7 +2117,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Future Function( ProxyApiTestClass pigeon_instance, String aString, - ) flutterEchoAsyncString; + ) + flutterEchoAsyncString; @override final void Function(ProxyApiInterface pigeon_instance)? anInterfaceMethod; @@ -2150,179 +2139,182 @@ class ProxyApiTestClass extends ProxyApiSuperClass void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - bool Function( - ProxyApiTestClass pigeon_instance, - bool aBool, - )? flutterEchoBool, - int Function( - ProxyApiTestClass pigeon_instance, - int anInt, - )? flutterEchoInt, - double Function( - ProxyApiTestClass pigeon_instance, - double aDouble, - )? flutterEchoDouble, - String Function( - ProxyApiTestClass pigeon_instance, - String aString, - )? flutterEchoString, - Uint8List Function( - ProxyApiTestClass pigeon_instance, - Uint8List aList, - )? flutterEchoUint8List, + bool Function(ProxyApiTestClass pigeon_instance, bool aBool)? + flutterEchoBool, + int Function(ProxyApiTestClass pigeon_instance, int anInt)? flutterEchoInt, + double Function(ProxyApiTestClass pigeon_instance, double aDouble)? + flutterEchoDouble, + String Function(ProxyApiTestClass pigeon_instance, String aString)? + flutterEchoString, + Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList)? + flutterEchoUint8List, List Function( ProxyApiTestClass pigeon_instance, List aList, - )? flutterEchoList, + )? + flutterEchoList, List Function( ProxyApiTestClass pigeon_instance, List aList, - )? flutterEchoProxyApiList, + )? + flutterEchoProxyApiList, Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - )? flutterEchoMap, + )? + flutterEchoMap, Map Function( ProxyApiTestClass pigeon_instance, Map aMap, - )? flutterEchoProxyApiMap, + )? + flutterEchoProxyApiMap, ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, - )? flutterEchoEnum, + )? + flutterEchoEnum, ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, - )? flutterEchoProxyApi, - bool? Function( - ProxyApiTestClass pigeon_instance, - bool? aBool, - )? flutterEchoNullableBool, - int? Function( - ProxyApiTestClass pigeon_instance, - int? anInt, - )? flutterEchoNullableInt, - double? Function( - ProxyApiTestClass pigeon_instance, - double? aDouble, - )? flutterEchoNullableDouble, - String? Function( - ProxyApiTestClass pigeon_instance, - String? aString, - )? flutterEchoNullableString, - Uint8List? Function( - ProxyApiTestClass pigeon_instance, - Uint8List? aList, - )? flutterEchoNullableUint8List, + )? + flutterEchoProxyApi, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? + flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? + flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? + flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? + flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? + flutterEchoNullableUint8List, List? Function( ProxyApiTestClass pigeon_instance, List? aList, - )? flutterEchoNullableList, + )? + flutterEchoNullableList, Map? Function( ProxyApiTestClass pigeon_instance, Map? aMap, - )? flutterEchoNullableMap, + )? + flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, - )? flutterEchoNullableEnum, + )? + flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, - )? flutterEchoNullableProxyApi, + )? + flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, - Future Function( - ProxyApiTestClass pigeon_instance, - String aString, - )? flutterEchoAsyncString, + Future Function(ProxyApiTestClass pigeon_instance, String aString)? + flutterEchoAsyncString, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null, expected non-null ProxyApiTestClass.', + ); try { - (flutterNoop ?? arg_pigeon_instance!.flutterNoop) - ?.call(arg_pigeon_instance!); + (flutterNoop ?? arg_pigeon_instance!.flutterNoop)?.call( + arg_pigeon_instance!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null, expected non-null ProxyApiTestClass.', + ); try { - final Object? output = - (flutterThrowError ?? arg_pigeon_instance!.flutterThrowError) - ?.call(arg_pigeon_instance!); + final Object? output = (flutterThrowError ?? + arg_pigeon_instance!.flutterThrowError) + ?.call(arg_pigeon_instance!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null, expected non-null ProxyApiTestClass.', + ); try { (flutterThrowErrorFromVoid ?? arg_pigeon_instance!.flutterThrowErrorFromVoid) @@ -2332,177 +2324,212 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null ProxyApiTestClass.', + ); final bool? arg_aBool = (args[1] as bool?); - assert(arg_aBool != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null bool.'); + assert( + arg_aBool != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null bool.', + ); try { - final bool output = - (flutterEchoBool ?? arg_pigeon_instance!.flutterEchoBool) - .call(arg_pigeon_instance!, arg_aBool!); + final bool output = (flutterEchoBool ?? + arg_pigeon_instance!.flutterEchoBool) + .call(arg_pigeon_instance!, arg_aBool!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null ProxyApiTestClass.', + ); final int? arg_anInt = (args[1] as int?); - assert(arg_anInt != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null int.'); + assert( + arg_anInt != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null int.', + ); try { - final int output = - (flutterEchoInt ?? arg_pigeon_instance!.flutterEchoInt) - .call(arg_pigeon_instance!, arg_anInt!); + final int output = (flutterEchoInt ?? + arg_pigeon_instance!.flutterEchoInt) + .call(arg_pigeon_instance!, arg_anInt!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null ProxyApiTestClass.', + ); final double? arg_aDouble = (args[1] as double?); - assert(arg_aDouble != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null double.'); + assert( + arg_aDouble != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null double.', + ); try { - final double output = - (flutterEchoDouble ?? arg_pigeon_instance!.flutterEchoDouble) - .call(arg_pigeon_instance!, arg_aDouble!); + final double output = (flutterEchoDouble ?? + arg_pigeon_instance!.flutterEchoDouble) + .call(arg_pigeon_instance!, arg_aDouble!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null ProxyApiTestClass.', + ); final String? arg_aString = (args[1] as String?); - assert(arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null String.'); + assert( + arg_aString != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null String.', + ); try { - final String output = - (flutterEchoString ?? arg_pigeon_instance!.flutterEchoString) - .call(arg_pigeon_instance!, arg_aString!); + final String output = (flutterEchoString ?? + arg_pigeon_instance!.flutterEchoString) + .call(arg_pigeon_instance!, arg_aString!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null ProxyApiTestClass.', + ); final Uint8List? arg_aList = (args[1] as Uint8List?); - assert(arg_aList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null Uint8List.'); + assert( + arg_aList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null Uint8List.', + ); try { final Uint8List output = (flutterEchoUint8List ?? arg_pigeon_instance!.flutterEchoUint8List) @@ -2512,71 +2539,85 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null ProxyApiTestClass.', + ); final List? arg_aList = (args[1] as List?)?.cast(); - assert(arg_aList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null List.'); + assert( + arg_aList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null List.', + ); try { - final List output = - (flutterEchoList ?? arg_pigeon_instance!.flutterEchoList) - .call(arg_pigeon_instance!, arg_aList!); + final List output = (flutterEchoList ?? + arg_pigeon_instance!.flutterEchoList) + .call(arg_pigeon_instance!, arg_aList!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null ProxyApiTestClass.', + ); final List? arg_aList = (args[1] as List?)?.cast(); - assert(arg_aList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null List.'); + assert( + arg_aList != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null List.', + ); try { final List output = (flutterEchoProxyApiList ?? arg_pigeon_instance!.flutterEchoProxyApiList) @@ -2586,72 +2627,86 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null ProxyApiTestClass.', + ); final Map? arg_aMap = (args[1] as Map?)?.cast(); - assert(arg_aMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null Map.'); + assert( + arg_aMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null Map.', + ); try { - final Map output = - (flutterEchoMap ?? arg_pigeon_instance!.flutterEchoMap) - .call(arg_pigeon_instance!, arg_aMap!); + final Map output = (flutterEchoMap ?? + arg_pigeon_instance!.flutterEchoMap) + .call(arg_pigeon_instance!, arg_aMap!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null ProxyApiTestClass.', + ); final Map? arg_aMap = (args[1] as Map?) ?.cast(); - assert(arg_aMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null Map.'); + assert( + arg_aMap != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null Map.', + ); try { final Map output = (flutterEchoProxyApiMap ?? @@ -2662,70 +2717,84 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestClass.', + ); final ProxyApiTestEnum? arg_anEnum = (args[1] as ProxyApiTestEnum?); - assert(arg_anEnum != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestEnum.'); + assert( + arg_anEnum != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestEnum.', + ); try { - final ProxyApiTestEnum output = - (flutterEchoEnum ?? arg_pigeon_instance!.flutterEchoEnum) - .call(arg_pigeon_instance!, arg_anEnum!); + final ProxyApiTestEnum output = (flutterEchoEnum ?? + arg_pigeon_instance!.flutterEchoEnum) + .call(arg_pigeon_instance!, arg_anEnum!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiTestClass.', + ); final ProxyApiSuperClass? arg_aProxyApi = (args[1] as ProxyApiSuperClass?); - assert(arg_aProxyApi != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiSuperClass.'); + assert( + arg_aProxyApi != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiSuperClass.', + ); try { final ProxyApiSuperClass output = (flutterEchoProxyApi ?? arg_pigeon_instance!.flutterEchoProxyApi) @@ -2735,30 +2804,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null, expected non-null ProxyApiTestClass.', + ); final bool? arg_aBool = (args[1] as bool?); try { final bool? output = (flutterEchoNullableBool ?? @@ -2769,30 +2843,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null, expected non-null ProxyApiTestClass.', + ); final int? arg_anInt = (args[1] as int?); try { final int? output = (flutterEchoNullableInt ?? @@ -2803,30 +2882,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null, expected non-null ProxyApiTestClass.', + ); final double? arg_aDouble = (args[1] as double?); try { final double? output = (flutterEchoNullableDouble ?? @@ -2837,30 +2921,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null, expected non-null ProxyApiTestClass.', + ); final String? arg_aString = (args[1] as String?); try { final String? output = (flutterEchoNullableString ?? @@ -2871,30 +2960,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null, expected non-null ProxyApiTestClass.', + ); final Uint8List? arg_aList = (args[1] as Uint8List?); try { final Uint8List? output = (flutterEchoNullableUint8List ?? @@ -2905,30 +2999,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null, expected non-null ProxyApiTestClass.', + ); final List? arg_aList = (args[1] as List?)?.cast(); try { @@ -2940,30 +3039,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null, expected non-null ProxyApiTestClass.', + ); final Map? arg_aMap = (args[1] as Map?)?.cast(); try { @@ -2975,30 +3079,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null, expected non-null ProxyApiTestClass.', + ); final ProxyApiTestEnum? arg_anEnum = (args[1] as ProxyApiTestEnum?); try { final ProxyApiTestEnum? output = (flutterEchoNullableEnum ?? @@ -3009,30 +3118,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null, expected non-null ProxyApiTestClass.', + ); final ProxyApiSuperClass? arg_aProxyApi = (args[1] as ProxyApiSuperClass?); try { @@ -3044,30 +3158,35 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null, expected non-null ProxyApiTestClass.', + ); try { await (flutterNoopAsync ?? arg_pigeon_instance!.flutterNoopAsync) ?.call(arg_pigeon_instance!); @@ -3076,33 +3195,40 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null.', + ); final List args = (message as List?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null ProxyApiTestClass.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null ProxyApiTestClass.', + ); final String? arg_aString = (args[1] as String?); - assert(arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null String.'); + assert( + arg_aString != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null String.', + ); try { final String output = await (flutterEchoAsyncString ?? arg_pigeon_instance!.flutterEchoAsyncString) @@ -3112,7 +3238,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3122,25 +3249,26 @@ class ProxyApiTestClass extends ProxyApiSuperClass ProxyApiSuperClass pigeonVar_attachedField() { final ProxyApiSuperClass pigeonVar_instance = ProxyApiSuperClass.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ); + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(pigeonVar_instance); () async { const String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.attachedField'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3172,12 +3300,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAttachedField'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3205,12 +3334,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noop'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3235,12 +3365,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3265,12 +3396,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwErrorFromVoid'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3295,12 +3427,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwFlutterError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3325,12 +3458,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoInt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3360,12 +3494,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoDouble'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3395,12 +3530,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoBool'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3430,12 +3566,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3465,12 +3602,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoUint8List'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3500,12 +3638,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoObject'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3535,12 +3674,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3564,7 +3704,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. Future> echoProxyApiList( - List aList) async { + List aList, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3572,12 +3713,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3608,12 +3750,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3638,7 +3781,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. Future> echoProxyApiMap( - Map aMap) async { + Map aMap, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3646,12 +3790,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3682,12 +3827,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoEnum'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3717,12 +3863,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApi'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aProxyApi], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aProxyApi]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3752,12 +3899,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableInt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3782,12 +3930,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableDouble'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3812,12 +3961,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableBool'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3842,12 +3992,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3865,7 +4016,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in Uint8List. Future echoNullableUint8List( - Uint8List? aNullableUint8List) async { + Uint8List? aNullableUint8List, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3873,12 +4025,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableUint8List'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3903,12 +4056,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableObject'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3933,12 +4087,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3956,7 +4111,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableMap( - Map? aNullableMap) async { + Map? aNullableMap, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3964,12 +4120,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3987,7 +4144,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future echoNullableEnum( - ProxyApiTestEnum? aNullableEnum) async { + ProxyApiTestEnum? aNullableEnum, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3995,12 +4153,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableEnum'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4018,7 +4177,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed ProxyApi to test serialization and deserialization. Future echoNullableProxyApi( - ProxyApiSuperClass? aNullableProxyApi) async { + ProxyApiSuperClass? aNullableProxyApi, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4026,12 +4186,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableProxyApi'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aNullableProxyApi], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aNullableProxyApi]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4057,12 +4218,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noopAsync'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4087,12 +4249,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncInt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4122,12 +4285,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncDouble'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4157,12 +4321,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncBool'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4192,12 +4357,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4227,12 +4393,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncUint8List'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4262,12 +4429,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncObject'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4297,12 +4465,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4332,12 +4501,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4368,12 +4538,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncEnum'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4403,12 +4574,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4433,12 +4605,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncErrorFromVoid'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4463,12 +4636,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncFlutterError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4493,12 +4667,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableInt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4523,12 +4698,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableDouble'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4553,12 +4729,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableBool'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4583,12 +4760,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4613,12 +4791,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableUint8List'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4643,12 +4822,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableObject'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anObject], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anObject]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4673,12 +4853,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4696,7 +4877,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableMap( - Map? aMap) async { + Map? aMap, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4704,12 +4886,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4728,7 +4911,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAsyncNullableEnum( - ProxyApiTestEnum? anEnum) async { + ProxyApiTestEnum? anEnum, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4736,12 +4920,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableEnum'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4766,16 +4951,17 @@ class ProxyApiTestClass extends ProxyApiSuperClass } final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticNoop'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4802,18 +4988,20 @@ class ProxyApiTestClass extends ProxyApiSuperClass } final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoStaticString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4843,16 +5031,17 @@ class ProxyApiTestClass extends ProxyApiSuperClass } final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAsyncNoop'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4877,12 +5066,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoop'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4906,12 +5096,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4935,12 +5126,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowErrorFromVoid'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4964,12 +5156,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoBool'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4998,12 +5191,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoInt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5032,12 +5226,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoDouble'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5066,12 +5261,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5100,12 +5296,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoUint8List'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5134,12 +5331,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5161,7 +5359,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future> callFlutterEchoProxyApiList( - List aList) async { + List aList, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5169,12 +5368,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5197,7 +5397,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future> callFlutterEchoMap( - Map aMap) async { + Map aMap, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5205,12 +5406,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5233,7 +5435,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future> callFlutterEchoProxyApiMap( - Map aMap) async { + Map aMap, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5241,12 +5444,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5276,12 +5480,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoEnum'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5303,7 +5508,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoProxyApi( - ProxyApiSuperClass aProxyApi) async { + ProxyApiSuperClass aProxyApi, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5311,12 +5517,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApi'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aProxyApi], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aProxyApi]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5345,12 +5552,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableBool'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aBool], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aBool]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5374,12 +5582,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableInt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anInt], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anInt]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5403,12 +5612,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableDouble'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aDouble], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aDouble]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5432,12 +5642,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5454,7 +5665,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableUint8List( - Uint8List? aUint8List) async { + Uint8List? aUint8List, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5462,12 +5674,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableUint8List'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aUint8List], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aUint8List]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5484,7 +5697,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future?> callFlutterEchoNullableList( - List? aList) async { + List? aList, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5492,12 +5706,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableList'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5514,7 +5729,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future?> callFlutterEchoNullableMap( - Map? aMap) async { + Map? aMap, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5522,12 +5738,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableMap'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aMap], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aMap]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5545,7 +5762,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableEnum( - ProxyApiTestEnum? anEnum) async { + ProxyApiTestEnum? anEnum, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5553,12 +5771,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableEnum'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, anEnum], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, anEnum]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5575,7 +5794,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableProxyApi( - ProxyApiSuperClass? aProxyApi) async { + ProxyApiSuperClass? aProxyApi, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5583,12 +5803,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableProxyApi'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aProxyApi], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aProxyApi]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5612,12 +5833,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoopAsync'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5641,12 +5863,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoAsyncString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, aString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, aString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5740,8 +5963,8 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiSuperClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5749,12 +5972,13 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -5783,8 +6007,9 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecProxyApiSuperClass = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecProxyApiSuperClass = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5794,41 +6019,47 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ProxyApiSuperClass.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ProxyApiSuperClass.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5843,12 +6074,13 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.aSuperMethod'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5916,73 +6148,85 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ProxyApiInterface.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ProxyApiInterface.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null.', + ); final List args = (message as List?)!; final ProxyApiInterface? arg_pigeon_instance = (args[0] as ProxyApiInterface?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null, expected non-null ProxyApiInterface.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null, expected non-null ProxyApiInterface.', + ); try { - (anInterfaceMethod ?? arg_pigeon_instance!.anInterfaceMethod) - ?.call(arg_pigeon_instance!); + (anInterfaceMethod ?? arg_pigeon_instance!.anInterfaceMethod)?.call( + arg_pigeon_instance!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6018,8 +6262,8 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecClassWithApiRequirement; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6027,12 +6271,13 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -6061,8 +6306,9 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecClassWithApiRequirement = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecClassWithApiRequirement = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -6072,41 +6318,47 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ClassWithApiRequirement.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ClassWithApiRequirement.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6121,12 +6373,13 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.aMethod'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart index 23e0e2229c4..1df440bd306 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart @@ -12,40 +12,15 @@ const int biggerThanBigInt = 3000000000; const int regularInt = 42; const double doublePi = 3.14159; -final List nonNullList = [ - 'Thing 1', - 2, - true, - 3.14, -]; +final List nonNullList = ['Thing 1', 2, true, 3.14]; -final List nonNullStringList = [ - 'Thing 1', - '2', - 'true', - '3.14', -]; +final List nonNullStringList = ['Thing 1', '2', 'true', '3.14']; -final List nonNullIntList = [ - 1, - 2, - 3, - 4, -]; +final List nonNullIntList = [1, 2, 3, 4]; -final List nonNullDoubleList = [ - 1, - 2.99999, - 3, - 3.14, -]; +final List nonNullDoubleList = [1, 2.99999, 3, 3.14]; -final List nonNullBoolList = [ - true, - false, - true, - false, -]; +final List nonNullBoolList = [true, false, true, false]; final List nonNullEnumList = [ AnEnum.one, @@ -78,12 +53,7 @@ final Map nonNullStringMap = { 'd': 'false', }; -final Map nonNullIntMap = { - 0: 0, - 1: 1, - 2: 3, - 4: -1, -}; +final Map nonNullIntMap = {0: 0, 1: 1, 2: 3, 4: -1}; final Map nonNullDoubleMap = { 0.0: 0, @@ -92,11 +62,7 @@ final Map nonNullDoubleMap = { -.4: -0.2, }; -final Map nonNullBoolMap = { - 0: true, - 1: false, - 2: true, -}; +final Map nonNullBoolMap = {0: true, 1: false, 2: true}; final Map nonNullEnumMap = { AnEnum.one: AnEnum.one, @@ -132,13 +98,7 @@ final List> nonNullMapList = >[ nonNullEnumMap, ]; -final List list = [ - 'Thing 1', - 2, - true, - 3.14, - null, -]; +final List list = ['Thing 1', 2, true, 3.14, null]; final List stringList = [ 'Thing 1', @@ -148,29 +108,11 @@ final List stringList = [ null, ]; -final List intList = [ - 1, - 2, - 3, - 4, - null, -]; +final List intList = [1, 2, 3, 4, null]; -final List doubleList = [ - 1, - 2.99999, - 3, - 3.14, - null, -]; +final List doubleList = [1, 2.99999, 3, 3.14, null]; -final List boolList = [ - true, - false, - true, - false, - null, -]; +final List boolList = [true, false, true, false, null]; final List enumList = [ AnEnum.one, @@ -178,7 +120,7 @@ final List enumList = [ AnEnum.three, AnEnum.fortyTwo, AnEnum.fourHundredTwentyTwo, - null + null, ]; final List?> listList = ?>[ @@ -188,7 +130,7 @@ final List?> listList = ?>[ doubleList, boolList, enumList, - null + null, ]; final Map map = { @@ -196,7 +138,7 @@ final Map map = { 'b': 2.0, 'c': 'three', 'd': false, - 'e': null + 'e': null, }; final Map stringMap = { @@ -205,23 +147,17 @@ final Map stringMap = { 'c': 'three', 'd': 'false', 'e': 'null', - 'f': null + 'f': null, }; -final Map intMap = { - 0: 0, - 1: 1, - 2: 3, - 4: -1, - 5: null, -}; +final Map intMap = {0: 0, 1: 1, 2: 3, 4: -1, 5: null}; final Map doubleMap = { 0.0: 0, 1.1: 2.0, 3: 0.3, -.4: -0.2, - 1111111111111111.11111111111111111111111111111111111111111111: null + 1111111111111111.11111111111111111111111111111111111111111111: null, }; final Map boolMap = { @@ -246,7 +182,7 @@ final Map?> listMap = ?>{ 4: intList, 5: boolList, 6: enumList, - 7: null + 7: null, }; final Map?> mapMap = ?>{ @@ -256,7 +192,7 @@ final Map?> mapMap = ?>{ 4: intMap, 5: boolMap, 6: enumMap, - 7: null + 7: null, }; final List?> mapList = ?>[ @@ -266,55 +202,54 @@ final List?> mapList = ?>[ intMap, boolMap, enumMap, - null + null, ]; final AllNullableTypesWithoutRecursion genericAllNullableTypesWithoutRecursion = AllNullableTypesWithoutRecursion( - aNullableBool: true, - aNullableInt: regularInt, - aNullableInt64: biggerThanBigInt, - aNullableDouble: doublePi, - aNullableString: 'Hello host!', - aNullableByteArray: Uint8List.fromList([1, 2, 3]), - aNullable4ByteArray: Int32List.fromList([4, 5, 6]), - aNullable8ByteArray: Int64List.fromList([7, 8, 9]), - aNullableFloatArray: Float64List.fromList([2.71828, doublePi]), - aNullableEnum: AnEnum.fourHundredTwentyTwo, - aNullableObject: 0, - list: list, - stringList: stringList, - intList: intList, - doubleList: doubleList, - boolList: boolList, - enumList: enumList, - objectList: list, - listList: listList, - mapList: mapList, - map: map, - stringMap: stringMap, - intMap: intMap, - enumMap: enumMap, - objectMap: map, - listMap: listMap, - mapMap: mapMap, -); + aNullableBool: true, + aNullableInt: regularInt, + aNullableInt64: biggerThanBigInt, + aNullableDouble: doublePi, + aNullableString: 'Hello host!', + aNullableByteArray: Uint8List.fromList([1, 2, 3]), + aNullable4ByteArray: Int32List.fromList([4, 5, 6]), + aNullable8ByteArray: Int64List.fromList([7, 8, 9]), + aNullableFloatArray: Float64List.fromList([2.71828, doublePi]), + aNullableEnum: AnEnum.fourHundredTwentyTwo, + aNullableObject: 0, + list: list, + stringList: stringList, + intList: intList, + doubleList: doubleList, + boolList: boolList, + enumList: enumList, + objectList: list, + listList: listList, + mapList: mapList, + map: map, + stringMap: stringMap, + intMap: intMap, + enumMap: enumMap, + objectMap: map, + listMap: listMap, + mapMap: mapMap, + ); final List - allNullableTypesWithoutRecursionClassList = - [ +allNullableTypesWithoutRecursionClassList = [ genericAllNullableTypesWithoutRecursion, AllNullableTypesWithoutRecursion(), null, ]; final Map - allNullableTypesWithoutRecursionClassMap = +allNullableTypesWithoutRecursionClassMap = { - 0: genericAllNullableTypesWithoutRecursion, - 1: AllNullableTypesWithoutRecursion(), - 2: null, -}; + 0: genericAllNullableTypesWithoutRecursion, + 1: AllNullableTypesWithoutRecursion(), + 2: null, + }; final AllTypes genericAllTypes = AllTypes( aBool: true, @@ -348,10 +283,7 @@ final AllTypes genericAllTypes = AllTypes( mapMap: nonNullMapMap, ); -final List allTypesClassList = [ - genericAllTypes, - null, -]; +final List allTypesClassList = [genericAllTypes, null]; final Map allTypesClassMap = { 0: genericAllTypes, @@ -394,10 +326,7 @@ final List nonNullAllNullableTypesList = [ ]; final Map nonNullAllNullableTypesMap = - { - 0: genericAllNullableTypes, - 1: AllNullableTypes(), -}; + {0: genericAllNullableTypes, 1: AllNullableTypes()}; final List allNullableTypesList = [ genericAllNullableTypes, @@ -407,10 +336,10 @@ final List allNullableTypesList = [ final Map allNullableTypesMap = { - 0: genericAllNullableTypes, - 1: AllNullableTypes(), - 2: null, -}; + 0: genericAllNullableTypes, + 1: AllNullableTypes(), + 2: null, + }; final AllNullableTypes recursiveAllNullableTypes = AllNullableTypes( aNullableBool: true, diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml b/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml index 0568aef5d31..234f018c1dc 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml @@ -4,8 +4,8 @@ version: 0.0.1 publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: build_runner: ^2.1.10 diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart index 0ecb40962c1..ac63ccc2385 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart @@ -51,51 +51,52 @@ void main() { final Map correctMap = { 'a': 1, 'b': 2, - 'c': 'three' + 'c': 'three', }; final Map matchingMap = {...correctMap}; final Map differentKeyMap = { 'a': 1, 'b': 2, - 'd': 'three' + 'd': 'three', }; final Map differentValueMap = { 'a': 1, 'b': 2, - 'c': 'five' + 'c': 'five', }; final Map correctListInMap = { 'a': 1, 'b': 2, - 'c': correctList + 'c': correctList, }; final Map matchingListInMap = { 'a': 1, 'b': 2, - 'c': matchingList + 'c': matchingList, }; final Map differentListInMap = { 'a': 1, 'b': 2, - 'c': differentList + 'c': differentList, }; final List correctMapInList = ['a', 2, correctMap]; final List matchingMapInList = ['a', 2, matchingMap]; final List differentKeyMapInList = [ 'a', 2, - differentKeyMap + differentKeyMap, ]; final List differentValueMapInList = [ 'a', 2, - differentValueMap + differentValueMap, ]; test('equality method correctly checks deep equality', () { final AllNullableTypes generic = genericAllNullableTypes; - final AllNullableTypes identical = - AllNullableTypes.decode(generic.encode()); + final AllNullableTypes identical = AllNullableTypes.decode( + generic.encode(), + ); expect(identical, generic); }); @@ -105,106 +106,133 @@ void main() { expect(allNull == generic, false); }); - test('equality method correctly identifies non-matching lists in classes', - () { - final AllNullableTypes withList = AllNullableTypes(list: correctList); - final AllNullableTypes withDifferentList = - AllNullableTypes(list: differentList); - expect(withList == withDifferentList, false); - }); + test( + 'equality method correctly identifies non-matching lists in classes', + () { + final AllNullableTypes withList = AllNullableTypes(list: correctList); + final AllNullableTypes withDifferentList = AllNullableTypes( + list: differentList, + ); + expect(withList == withDifferentList, false); + }, + ); test( - 'equality method correctly identifies matching -but unique- lists in classes', - () { - final AllNullableTypes withList = AllNullableTypes(list: correctList); - final AllNullableTypes withDifferentList = - AllNullableTypes(list: matchingList); - expect(withList, withDifferentList); - }); + 'equality method correctly identifies matching -but unique- lists in classes', + () { + final AllNullableTypes withList = AllNullableTypes(list: correctList); + final AllNullableTypes withDifferentList = AllNullableTypes( + list: matchingList, + ); + expect(withList, withDifferentList); + }, + ); test( - 'equality method correctly identifies non-matching keys in maps in classes', - () { - final AllNullableTypes withMap = AllNullableTypes(map: correctMap); - final AllNullableTypes withDifferentMap = - AllNullableTypes(map: differentKeyMap); - expect(withMap == withDifferentMap, false); - }); + 'equality method correctly identifies non-matching keys in maps in classes', + () { + final AllNullableTypes withMap = AllNullableTypes(map: correctMap); + final AllNullableTypes withDifferentMap = AllNullableTypes( + map: differentKeyMap, + ); + expect(withMap == withDifferentMap, false); + }, + ); test( - 'equality method correctly identifies non-matching values in maps in classes', - () { - final AllNullableTypes withMap = AllNullableTypes(map: correctMap); - final AllNullableTypes withDifferentMap = - AllNullableTypes(map: differentValueMap); - expect(withMap == withDifferentMap, false); - }); + 'equality method correctly identifies non-matching values in maps in classes', + () { + final AllNullableTypes withMap = AllNullableTypes(map: correctMap); + final AllNullableTypes withDifferentMap = AllNullableTypes( + map: differentValueMap, + ); + expect(withMap == withDifferentMap, false); + }, + ); test( - 'equality method correctly identifies matching -but unique- maps in classes', - () { - final AllNullableTypes withMap = AllNullableTypes(map: correctMap); - final AllNullableTypes withDifferentMap = - AllNullableTypes(map: matchingMap); - expect(withMap, withDifferentMap); - }); + 'equality method correctly identifies matching -but unique- maps in classes', + () { + final AllNullableTypes withMap = AllNullableTypes(map: correctMap); + final AllNullableTypes withDifferentMap = AllNullableTypes( + map: matchingMap, + ); + expect(withMap, withDifferentMap); + }, + ); test( - 'equality method correctly identifies non-matching lists nested in maps in classes', - () { - final AllNullableTypes withListInMap = - AllNullableTypes(map: correctListInMap); - final AllNullableTypes withDifferentListInMap = - AllNullableTypes(map: differentListInMap); - expect(withListInMap == withDifferentListInMap, false); - }); + 'equality method correctly identifies non-matching lists nested in maps in classes', + () { + final AllNullableTypes withListInMap = AllNullableTypes( + map: correctListInMap, + ); + final AllNullableTypes withDifferentListInMap = AllNullableTypes( + map: differentListInMap, + ); + expect(withListInMap == withDifferentListInMap, false); + }, + ); test( - 'equality method correctly identifies matching -but unique- lists nested in maps in classes', - () { - final AllNullableTypes withListInMap = - AllNullableTypes(map: correctListInMap); - final AllNullableTypes withDifferentListInMap = - AllNullableTypes(map: matchingListInMap); - expect(withListInMap, withDifferentListInMap); - }); + 'equality method correctly identifies matching -but unique- lists nested in maps in classes', + () { + final AllNullableTypes withListInMap = AllNullableTypes( + map: correctListInMap, + ); + final AllNullableTypes withDifferentListInMap = AllNullableTypes( + map: matchingListInMap, + ); + expect(withListInMap, withDifferentListInMap); + }, + ); test( - 'equality method correctly identifies non-matching keys in maps nested in lists in classes', - () { - final AllNullableTypes withMapInList = - AllNullableTypes(list: correctMapInList); - final AllNullableTypes withDifferentMapInList = - AllNullableTypes(list: differentKeyMapInList); - expect(withMapInList == withDifferentMapInList, false); - }); + 'equality method correctly identifies non-matching keys in maps nested in lists in classes', + () { + final AllNullableTypes withMapInList = AllNullableTypes( + list: correctMapInList, + ); + final AllNullableTypes withDifferentMapInList = AllNullableTypes( + list: differentKeyMapInList, + ); + expect(withMapInList == withDifferentMapInList, false); + }, + ); test( - 'equality method correctly identifies non-matching values in maps nested in lists in classes', - () { - final AllNullableTypes withMapInList = - AllNullableTypes(list: correctMapInList); - final AllNullableTypes withDifferentMapInList = - AllNullableTypes(list: differentValueMapInList); - expect(withMapInList == withDifferentMapInList, false); - }); + 'equality method correctly identifies non-matching values in maps nested in lists in classes', + () { + final AllNullableTypes withMapInList = AllNullableTypes( + list: correctMapInList, + ); + final AllNullableTypes withDifferentMapInList = AllNullableTypes( + list: differentValueMapInList, + ); + expect(withMapInList == withDifferentMapInList, false); + }, + ); test( - 'equality method correctly identifies matching -but unique- maps nested in lists in classes', - () { - final AllNullableTypes withMapInList = - AllNullableTypes(list: correctMapInList); - final AllNullableTypes withDifferentMapInList = - AllNullableTypes(list: matchingMapInList); - expect(withMapInList, withDifferentMapInList); - }); + 'equality method correctly identifies matching -but unique- maps nested in lists in classes', + () { + final AllNullableTypes withMapInList = AllNullableTypes( + list: correctMapInList, + ); + final AllNullableTypes withDifferentMapInList = AllNullableTypes( + list: matchingMapInList, + ); + expect(withMapInList, withDifferentMapInList); + }, + ); }); test('simple', () async { final MessageNestedApi api = MessageNestedApi(); final MockNested mock = MockNested(); TestNestedApi.setUp(mock); - final MessageSearchReply reply = - await api.search(MessageNested()..request = null); + final MessageSearchReply reply = await api.search( + MessageNested()..request = null, + ); expect(mock.didCall, true); expect(reply.result, null); }); @@ -213,8 +241,9 @@ void main() { final MessageApi api = MessageApi(); final Mock mock = Mock(); TestHostApi.setUp(mock); - final MessageSearchReply reply = - await api.search(MessageSearchRequest()..query = 'foo'); + final MessageSearchReply reply = await api.search( + MessageSearchRequest()..query = 'foo', + ); expect(mock.log, ['search']); expect(reply.result, 'foo'); }); @@ -227,34 +256,32 @@ void main() { expect(mock.log, ['initialize']); }); - test( - 'calling methods with null', - () async { - final Mock mock = Mock(); - TestHostApi.setUp(mock); + test('calling methods with null', () async { + final Mock mock = Mock(); + TestHostApi.setUp(mock); + expect( + await const BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize', + StandardMessageCodec(), + ).send([null]), + isEmpty, + ); + try { + await const BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', + StandardMessageCodec(), + ).send([null]) + as List?; + expect(true, isFalse); // should not reach here + } catch (error) { + expect(error, isAssertionError); expect( - await const BasicMessageChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize', - StandardMessageCodec(), - ).send([null]), - isEmpty, + error.toString(), + contains( + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.', + ), ); - try { - await const BasicMessageChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', - StandardMessageCodec(), - ).send([null]) as List?; - expect(true, isFalse); // should not reach here - } catch (error) { - expect(error, isAssertionError); - expect( - error.toString(), - contains( - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.', - ), - ); - } - expect(mock.log, ['initialize']); - }, - ); + } + expect(mock.log, ['initialize']); + }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart index 2582ed27a02..96557573dc1 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart @@ -11,8 +11,9 @@ import 'package:shared_test_plugin_code/src/generated/proxy_api_tests.gen.dart'; void main() { group('InstanceManager', () { test('addHostCreatedInstance', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -28,8 +29,9 @@ void main() { }); test('addHostCreatedInstance prevents already used objects and ids', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -52,8 +54,9 @@ void main() { }); test('addFlutterCreatedInstance', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -63,18 +66,16 @@ void main() { final int? instanceId = instanceManager.getIdentifier(object); expect(instanceId, isNotNull); - expect( - instanceManager.getInstanceWithWeakReference(instanceId!), - object, - ); + expect(instanceManager.getInstanceWithWeakReference(instanceId!), object); }); test('removeWeakReference', () { int? weakInstanceId; - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (int instanceId) { - weakInstanceId = instanceId; - }); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (int instanceId) { + weakInstanceId = instanceId; + }, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -91,8 +92,9 @@ void main() { }); test('removeWeakReference removes only weak reference', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -101,15 +103,15 @@ void main() { instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.removeWeakReference(object), 0); - final CopyableObject copy = instanceManager.getInstanceWithWeakReference( - 0, - )!; + final CopyableObject copy = + instanceManager.getInstanceWithWeakReference(0)!; expect(identical(object, copy), isFalse); }); test('remove', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -122,8 +124,9 @@ void main() { }); test('remove throws AssertionError if weak reference still exists', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -134,8 +137,9 @@ void main() { }); test('getInstance can add a new weak reference', () { - final PigeonInstanceManager instanceManager = - PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, @@ -145,60 +149,64 @@ void main() { instanceManager.removeWeakReference(object); final CopyableObject newWeakCopy = - instanceManager.getInstanceWithWeakReference( - 0, - )!; + instanceManager.getInstanceWithWeakReference(0)!; expect(identical(object, newWeakCopy), isFalse); }); - test('addDartCreatedInstance should add finalizer to original object', - () async { - bool weakReferencedRemovedCalled = false; - final PigeonInstanceManager instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) { - weakReferencedRemovedCalled = true; - }, - ); + test( + 'addDartCreatedInstance should add finalizer to original object', + () async { + bool weakReferencedRemovedCalled = false; + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) { + weakReferencedRemovedCalled = true; + }, + ); - CopyableObject? object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + CopyableObject? object = CopyableObject( + pigeon_instanceManager: instanceManager, + ); - instanceManager.addDartCreatedInstance(object); + instanceManager.addDartCreatedInstance(object); - object = null; - await forceGC(fullGcCycles: 2); + object = null; + await forceGC(fullGcCycles: 2); - expect(weakReferencedRemovedCalled, isTrue); - }); + expect(weakReferencedRemovedCalled, isTrue); + }, + ); - test('addHostCreatedInstance should not add finalizer to original object', - () async { - bool weakReferencedRemovedCalled = false; - final PigeonInstanceManager instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) { - weakReferencedRemovedCalled = true; - }, - ); + test( + 'addHostCreatedInstance should not add finalizer to original object', + () async { + bool weakReferencedRemovedCalled = false; + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) { + weakReferencedRemovedCalled = true; + }, + ); - CopyableObject? object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + CopyableObject? object = CopyableObject( + pigeon_instanceManager: instanceManager, + ); - instanceManager.addHostCreatedInstance(object, 0); + instanceManager.addHostCreatedInstance(object, 0); - object = null; - await forceGC(fullGcCycles: 2); + object = null; + await forceGC(fullGcCycles: 2); - expect(weakReferencedRemovedCalled, isFalse); - }); + expect(weakReferencedRemovedCalled, isFalse); + }, + ); testWidgets( 'instantiating default InstanceManager does not make a message call', (WidgetTester tester) async { bool messageCallMade = false; TestDefaultBinaryMessengerBinding - .instance.defaultBinaryMessenger.allMessagesHandler = (_, __, ___) { + .instance + .defaultBinaryMessenger + .allMessagesHandler = (_, __, ___) { messageCallMade = true; return null; }; @@ -216,7 +224,9 @@ void main() { (WidgetTester tester) async { bool messageCallMade = false; TestDefaultBinaryMessengerBinding - .instance.defaultBinaryMessenger.allMessagesHandler = (_, __, ___) { + .instance + .defaultBinaryMessenger + .allMessagesHandler = (_, __, ___) { messageCallMade = true; return null; }; @@ -224,8 +234,9 @@ void main() { final PigeonInstanceManager instanceManager = PigeonInstanceManager.instance; - final int identifier = - instanceManager.addDartCreatedInstance(CopyableObject()); + final int identifier = instanceManager.addDartCreatedInstance( + CopyableObject(), + ); instanceManager.onWeakReferenceRemoved(identifier); expect(messageCallMade, isFalse); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart index 64063f84786..4b1cff77e3f 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart @@ -14,21 +14,27 @@ import 'multiple_arity_test.mocks.dart'; void main() { test('multiple arity', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - when(mockMessenger.send( - 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract', - any)) - .thenAnswer((Invocation realInvocation) async { - final Object input = MultipleArityHostApi.pigeonChannelCodec - .decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; + when( + mockMessenger.send( + 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract', + any, + ), + ).thenAnswer((Invocation realInvocation) async { + final Object input = + MultipleArityHostApi.pigeonChannelCodec.decodeMessage( + realInvocation.positionalArguments[1] as ByteData?, + )!; final List args = input as List; final int x = (args[0] as int?)!; final int y = (args[1] as int?)!; - return MultipleArityHostApi.pigeonChannelCodec - .encodeMessage([x - y]); + return MultipleArityHostApi.pigeonChannelCodec.encodeMessage([ + x - y, + ]); }); - final MultipleArityHostApi api = - MultipleArityHostApi(binaryMessenger: mockMessenger); + final MultipleArityHostApi api = MultipleArityHostApi( + binaryMessenger: mockMessenger, + ); final int result = await api.subtract(30, 10); expect(result, 20); }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart index bca236c840a..f9a491abcc5 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart @@ -7,8 +7,9 @@ import 'package:shared_test_plugin_code/src/generated/non_null_fields.gen.dart'; void main() { test('test constructor', () { - final NonNullFieldSearchRequest request = - NonNullFieldSearchRequest(query: 'what?'); + final NonNullFieldSearchRequest request = NonNullFieldSearchRequest( + query: 'what?', + ); expect(request.query, 'what?'); }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart index 5192bebc3f1..ba9db65361f 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart @@ -7,8 +7,10 @@ import 'package:shared_test_plugin_code/src/generated/null_fields.gen.dart'; void main() { test('test constructor with values', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest(query: 'query', identifier: 1); + final NullFieldsSearchRequest request = NullFieldsSearchRequest( + query: 'query', + identifier: 1, + ); final NullFieldsSearchReply reply = NullFieldsSearchReply( result: 'result', @@ -26,8 +28,9 @@ void main() { }); test('test request constructor with nulls', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest(identifier: 1); + final NullFieldsSearchRequest request = NullFieldsSearchRequest( + identifier: 1, + ); expect(request.query, isNull); }); @@ -43,37 +46,31 @@ void main() { }); test('test request decode with values', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest.decode([ - 'query', - 1, - ]); + final NullFieldsSearchRequest request = NullFieldsSearchRequest.decode( + ['query', 1], + ); expect(request.query, 'query'); }); test('test request decode with null', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest.decode([ - null, - 1, - ]); + final NullFieldsSearchRequest request = NullFieldsSearchRequest.decode( + [null, 1], + ); expect(request.query, isNull); }); test('test reply decode with values', () { - final NullFieldsSearchReply reply = - NullFieldsSearchReply.decode(NullFieldsSearchReply( - result: 'result', - error: 'error', - indices: [1, 2, 3], - request: NullFieldsSearchRequest( - query: 'query', - identifier: 1, - ), - type: NullFieldsSearchReplyType.success, - ).encode()); + final NullFieldsSearchReply reply = NullFieldsSearchReply.decode( + NullFieldsSearchReply( + result: 'result', + error: 'error', + indices: [1, 2, 3], + request: NullFieldsSearchRequest(query: 'query', identifier: 1), + type: NullFieldsSearchReplyType.success, + ).encode(), + ); expect(reply.result, 'result'); expect(reply.error, 'error'); @@ -99,28 +96,27 @@ void main() { }); test('test request encode with values', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest(query: 'query', identifier: 1); + final NullFieldsSearchRequest request = NullFieldsSearchRequest( + query: 'query', + identifier: 1, + ); - expect(request.encode(), [ - 'query', - 1, - ]); + expect(request.encode(), ['query', 1]); }); test('test request encode with null', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest(identifier: 1); + final NullFieldsSearchRequest request = NullFieldsSearchRequest( + identifier: 1, + ); - expect(request.encode(), [ - null, - 1, - ]); + expect(request.encode(), [null, 1]); }); test('test reply encode with values', () { - final NullFieldsSearchRequest request = - NullFieldsSearchRequest(query: 'query', identifier: 1); + final NullFieldsSearchRequest request = NullFieldsSearchRequest( + query: 'query', + identifier: 1, + ); final NullFieldsSearchReply reply = NullFieldsSearchReply( result: 'result', error: 'error', @@ -141,12 +137,6 @@ void main() { test('test reply encode with nulls', () { final NullFieldsSearchReply reply = NullFieldsSearchReply(); - expect(reply.encode(), [ - null, - null, - null, - null, - null, - ]); + expect(reply.encode(), [null, null, null, null, null]); }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart index 0514371264c..0b84e8ab363 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart @@ -26,9 +26,10 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('with values filled', () { - final FlutterSearchReply reply = FlutterSearchReply() - ..result = 'foo' - ..error = 'bar'; + final FlutterSearchReply reply = + FlutterSearchReply() + ..result = 'foo' + ..error = 'bar'; final List encoded = reply.encode() as List; final FlutterSearchReply decoded = FlutterSearchReply.decode(encoded); expect(reply.result, decoded.result); @@ -36,9 +37,10 @@ void main() { }); test('with null value', () { - final FlutterSearchReply reply = FlutterSearchReply() - ..result = 'foo' - ..error = null; + final FlutterSearchReply reply = + FlutterSearchReply() + ..result = 'foo' + ..error = null; final List encoded = reply.encode() as List; final FlutterSearchReply decoded = FlutterSearchReply.decode(encoded); expect(reply.result, decoded.result); @@ -52,9 +54,12 @@ void main() { final Completer completer = Completer(); completer.complete(Api.pigeonChannelCodec.encodeMessage([reply])); final Future sendResult = completer.future; - when(mockMessenger.send( - 'dev.flutter.pigeon.pigeon_integration_tests.Api.search', any)) - .thenAnswer((Invocation realInvocation) => sendResult); + when( + mockMessenger.send( + 'dev.flutter.pigeon.pigeon_integration_tests.Api.search', + any, + ), + ).thenAnswer((Invocation realInvocation) => sendResult); final Api api = Api(binaryMessenger: mockMessenger); final FlutterSearchReply readReply = await api.search(request); expect(readReply, isNotNull); @@ -63,8 +68,8 @@ void main() { test('send/receive list classes', () async { final FlutterSearchRequest request = FlutterSearchRequest()..query = 'hey'; - final FlutterSearchRequests requests = FlutterSearchRequests() - ..requests = [request]; + final FlutterSearchRequests requests = + FlutterSearchRequests()..requests = [request]; final BinaryMessenger mockMessenger = MockBinaryMessenger(); echoOneArgument( mockMessenger, @@ -93,25 +98,30 @@ void main() { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const String channel = 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt'; - when(mockMessenger.send(channel, any)) - .thenAnswer((Invocation realInvocation) async { + when(mockMessenger.send(channel, any)).thenAnswer(( + Invocation realInvocation, + ) async { return Api.pigeonChannelCodec.encodeMessage([null]); }); final Api api = Api(binaryMessenger: mockMessenger); - expect(() async => api.anInt(1), - throwsA(const TypeMatcher())); + expect( + () async => api.anInt(1), + throwsA(const TypeMatcher()), + ); }); test('send null parameter', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const String channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit'; - when(mockMessenger.send(channel, any)) - .thenAnswer((Invocation realInvocation) async { + when(mockMessenger.send(channel, any)).thenAnswer(( + Invocation realInvocation, + ) async { return Api.pigeonChannelCodec.encodeMessage([123]); }); - final NullableArgHostApi api = - NullableArgHostApi(binaryMessenger: mockMessenger); + final NullableArgHostApi api = NullableArgHostApi( + binaryMessenger: mockMessenger, + ); expect(await api.doit(null), 123); }); @@ -119,14 +129,16 @@ void main() { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const String channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit'; - when(mockMessenger.send(channel, any)) - .thenAnswer((Invocation realInvocation) async { + when(mockMessenger.send(channel, any)).thenAnswer(( + Invocation realInvocation, + ) async { return Api.pigeonChannelCodec.encodeMessage([ - ['123'] + ['123'], ]); }); - final NullableCollectionArgHostApi api = - NullableCollectionArgHostApi(binaryMessenger: mockMessenger); + final NullableCollectionArgHostApi api = NullableCollectionArgHostApi( + binaryMessenger: mockMessenger, + ); expect(await api.doit(null), ['123']); }); @@ -144,8 +156,9 @@ void main() { (ByteData? data) { resultCompleter.complete( (NullableArgFlutterApi.pigeonChannelCodec.decodeMessage(data)! - as List) - .first! as int, + as List) + .first! + as int, ); }, ); @@ -166,13 +179,17 @@ void main() { final Completer> resultCompleter = Completer>(); binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit', - NullableCollectionArgFlutterApi.pigeonChannelCodec - .encodeMessage([null]), + NullableCollectionArgFlutterApi.pigeonChannelCodec.encodeMessage( + [null], + ), (ByteData? data) { resultCompleter.complete( - ((NullableCollectionArgFlutterApi.pigeonChannelCodec - .decodeMessage(data)! as List) - .first! as List) + ((NullableCollectionArgFlutterApi.pigeonChannelCodec.decodeMessage( + data, + )! + as List) + .first! + as List) .cast(), ); }, @@ -188,13 +205,16 @@ void main() { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const String channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit'; - when(mockMessenger.send(channel, any)) - .thenAnswer((Invocation realInvocation) async { - return NullableReturnHostApi.pigeonChannelCodec - .encodeMessage([null]); + when(mockMessenger.send(channel, any)).thenAnswer(( + Invocation realInvocation, + ) async { + return NullableReturnHostApi.pigeonChannelCodec.encodeMessage([ + null, + ]); }); - final NullableReturnHostApi api = - NullableReturnHostApi(binaryMessenger: mockMessenger); + final NullableReturnHostApi api = NullableReturnHostApi( + binaryMessenger: mockMessenger, + ); expect(await api.doit(), null); }); @@ -202,13 +222,16 @@ void main() { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const String channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit'; - when(mockMessenger.send(channel, any)) - .thenAnswer((Invocation realInvocation) async { - return NullableCollectionReturnHostApi.pigeonChannelCodec - .encodeMessage([null]); + when(mockMessenger.send(channel, any)).thenAnswer(( + Invocation realInvocation, + ) async { + return NullableCollectionReturnHostApi.pigeonChannelCodec.encodeMessage( + [null], + ); }); - final NullableCollectionReturnHostApi api = - NullableCollectionReturnHostApi(binaryMessenger: mockMessenger); + final NullableCollectionReturnHostApi api = NullableCollectionReturnHostApi( + binaryMessenger: mockMessenger, + ); expect(await api.doit(), null); }); @@ -220,13 +243,15 @@ void main() { NullableReturnFlutterApi.setUp(mockFlutterApi); final Completer resultCompleter = Completer(); - unawaited(binding.defaultBinaryMessenger.handlePlatformMessage( - 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit', - NullableReturnFlutterApi.pigeonChannelCodec.encodeMessage([]), - (ByteData? data) { - resultCompleter.complete(null); - }, - )); + unawaited( + binding.defaultBinaryMessenger.handlePlatformMessage( + 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit', + NullableReturnFlutterApi.pigeonChannelCodec.encodeMessage([]), + (ByteData? data) { + resultCompleter.complete(null); + }, + ), + ); expect(resultCompleter.future, completion(null)); @@ -243,14 +268,17 @@ void main() { final Completer?> resultCompleter = Completer?>(); - unawaited(binding.defaultBinaryMessenger.handlePlatformMessage( - 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit', - NullableCollectionReturnFlutterApi.pigeonChannelCodec - .encodeMessage([]), - (ByteData? data) { - resultCompleter.complete(null); - }, - )); + unawaited( + binding.defaultBinaryMessenger.handlePlatformMessage( + 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit', + NullableCollectionReturnFlutterApi.pigeonChannelCodec.encodeMessage( + [], + ), + (ByteData? data) { + resultCompleter.complete(null); + }, + ), + ); expect(resultCompleter.future, completion(null)); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart index 7adf512ec5f..a257781fcfc 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart @@ -20,8 +20,9 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt', PrimitiveHostApi.pigeonChannelCodec, ); - final PrimitiveHostApi api = - PrimitiveHostApi(binaryMessenger: mockMessenger); + final PrimitiveHostApi api = PrimitiveHostApi( + binaryMessenger: mockMessenger, + ); final int result = await api.anInt(1); expect(result, 1); }); @@ -33,8 +34,9 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList', PrimitiveHostApi.pigeonChannelCodec, ); - final PrimitiveHostApi api = - PrimitiveHostApi(binaryMessenger: mockMessenger); + final PrimitiveHostApi api = PrimitiveHostApi( + binaryMessenger: mockMessenger, + ); final List result = await api.aBoolList([true]); expect(result[0], true); }); @@ -43,15 +45,19 @@ void main() { final BinaryMessenger mockMessenger = MockBinaryMessenger(); final PrimitiveFlutterApi api = MockPrimitiveFlutterApi(); when(api.aBoolList([true, false])).thenReturn([]); - when(mockMessenger.setMessageHandler( - 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList', - any)) - .thenAnswer((Invocation realInvocation) { + when( + mockMessenger.setMessageHandler( + 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList', + any, + ), + ).thenAnswer((Invocation realInvocation) { final MessageHandler? handler = realInvocation.positionalArguments[1] as MessageHandler?; - handler!(PrimitiveFlutterApi.pigeonChannelCodec.encodeMessage([ - [true, false] - ])); + handler!( + PrimitiveFlutterApi.pigeonChannelCodec.encodeMessage([ + [true, false], + ]), + ); }); PrimitiveFlutterApi.setUp(api, binaryMessenger: mockMessenger); verify(api.aBoolList([true, false])); @@ -64,10 +70,12 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap', PrimitiveHostApi.pigeonChannelCodec, ); - final PrimitiveHostApi api = - PrimitiveHostApi(binaryMessenger: mockMessenger); - final Map result = - await api.aStringIntMap({'hello': 1}); + final PrimitiveHostApi api = PrimitiveHostApi( + binaryMessenger: mockMessenger, + ); + final Map result = await api.aStringIntMap({ + 'hello': 1, + }); expect(result['hello'], 1); }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart index d3a1967d11b..b6acb9db83e 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart @@ -40,10 +40,7 @@ void main() { () => ProxyApiSuperClass.pigeon_detached(); PigeonOverrides.pigeon_reset(); - expect( - PigeonOverrides.proxyApiSuperClass_new, - isNull, - ); + expect(PigeonOverrides.proxyApiSuperClass_new, isNull); }); test('pigeon_reset sets attached field overrides to null', () { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart index 62f67720232..0b71e764953 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart @@ -80,62 +80,76 @@ abstract class TestHostApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - try { - api.initialize(); - return wrapResponse(empty: true); - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + api.initialize(); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null.'); - final List args = (message as List?)!; - final MessageSearchRequest? arg_request = - (args[0] as MessageSearchRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.'); - try { - final MessageSearchReply output = api.search(arg_request!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null.', + ); + final List args = (message as List?)!; + final MessageSearchRequest? arg_request = + (args[0] as MessageSearchRequest?); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.', + ); + try { + final MessageSearchReply output = api.search(arg_request!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } @@ -160,35 +174,44 @@ abstract class TestNestedApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null.'); - final List args = (message as List?)!; - final MessageNested? arg_nested = (args[0] as MessageNested?); - assert(arg_nested != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null, expected non-null MessageNested.'); - try { - final MessageSearchReply output = api.search(arg_nested!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null.', + ); + final List args = (message as List?)!; + final MessageNested? arg_nested = (args[0] as MessageNested?); + assert( + arg_nested != null, + 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null, expected non-null MessageNested.', + ); + try { + final MessageSearchReply output = api.search(arg_nested!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart index 44b196e4801..905620be976 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart @@ -10,10 +10,13 @@ void echoOneArgument( String channel, MessageCodec codec, ) { - when(mockMessenger.send(channel, any)) - .thenAnswer((Invocation realInvocation) async { - final Object input = codec - .decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; + when(mockMessenger.send(channel, any)).thenAnswer(( + Invocation realInvocation, + ) async { + final Object input = + codec.decodeMessage( + realInvocation.positionalArguments[1] as ByteData?, + )!; final List args = input as List; return codec.encodeMessage([args[0]!]); }); diff --git a/packages/pigeon/platform_tests/test_plugin/example/pubspec.yaml b/packages/pigeon/platform_tests/test_plugin/example/pubspec.yaml index f7e294d720c..e63f596204d 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/pubspec.yaml +++ b/packages/pigeon/platform_tests/test_plugin/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Pigeon test harness for primary plugin languages. publish_to: 'none' environment: - sdk: ^3.6.0 + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/pigeon/platform_tests/test_plugin/pubspec.yaml b/packages/pigeon/platform_tests/test_plugin/pubspec.yaml index f50e5da3cd1..13121627204 100644 --- a/packages/pigeon/platform_tests/test_plugin/pubspec.yaml +++ b/packages/pigeon/platform_tests/test_plugin/pubspec.yaml @@ -4,8 +4,8 @@ version: 0.0.1 publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/pigeon/pubspec.yaml b/packages/pigeon/pubspec.yaml index 12b7bc4c241..3197a83dd4e 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.0.1 # This must match the version in lib/src/generator_tools.dart environment: - sdk: ^3.6.0 + sdk: ^3.7.0 dependencies: analyzer: ">=6.0.0 <8.0.0" diff --git a/packages/pigeon/test/ast_generator_test.dart b/packages/pigeon/test/ast_generator_test.dart index 21ebf09d5b8..3143b275980 100644 --- a/packages/pigeon/test/ast_generator_test.dart +++ b/packages/pigeon/test/ast_generator_test.dart @@ -12,11 +12,9 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'dataType1', - isNullable: true, - ), - name: 'field1'), + type: const TypeDeclaration(baseName: 'dataType1', isNullable: true), + name: 'field1', + ), ], ); final Root root = Root( diff --git a/packages/pigeon/test/cpp_generator_test.dart b/packages/pigeon/test/cpp_generator_test.dart index 7fd45fe6db0..f4f3061b3e3 100644 --- a/packages/pigeon/test/cpp_generator_test.dart +++ b/packages/pigeon/test/cpp_generator_test.dart @@ -10,12 +10,15 @@ import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); final Enum emptyEnum = Enum( name: 'enumName', @@ -24,56 +27,73 @@ final Enum emptyEnum = Enum( void main() { test('gen one api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'input', ), - name: 'input') + ], + location: ApiLocation.host, + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), ], - location: ApiLocation.host, - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output') - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect(code, contains('class Input')); expect(code, contains('class Output')); @@ -85,88 +105,118 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect(code, contains('Input::Input()')); expect(code, contains('Output::Output')); expect( - code, - contains(RegExp(r'void Api::SetUp\(\s*' - r'flutter::BinaryMessenger\* binary_messenger,\s*' - r'Api\* api\s*\)'))); + code, + contains( + RegExp( + r'void Api::SetUp\(\s*' + r'flutter::BinaryMessenger\* binary_messenger,\s*' + r'Api\* api\s*\)', + ), + ), + ); } }); test('naming follows style', () { - final Enum anEnum = Enum(name: 'AnEnum', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'fortyTwo'), - ]); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Enum anEnum = Enum( + name: 'AnEnum', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'fortyTwo'), + ], + ); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'someInput', ), - name: 'someInput') + ], + location: ApiLocation.host, + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), ], - location: ApiLocation.host, - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'inputField') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'outputField'), - NamedType( - type: TypeDeclaration( - baseName: anEnum.name, - isNullable: false, - associatedEnum: anEnum, - ), - name: 'code', - ) - ]) - ], enums: [ - anEnum - ]); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'inputField', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'outputField', + ), + NamedType( + type: TypeDeclaration( + baseName: anEnum.name, + isNullable: false, + associatedEnum: anEnum, + ), + name: 'code', + ), + ], + ), + ], + enums: [anEnum], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); // Method name and argument names should be adjusted. expect(code, contains(' DoSomething(const Input& some_input)')); @@ -187,12 +237,19 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect(code, contains('encodable_some_input')); expect(code, contains('Output::output_field()')); @@ -201,32 +258,46 @@ void main() { }); test('FlutterError fields are private with public accessors', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: 'someInput', ), - name: 'someInput') + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -236,42 +307,49 @@ void main() { final String code = sink.toString(); expect( - code.split('\n'), - containsAllInOrder([ - contains('class FlutterError {'), - contains(' public:'), - contains(' const std::string& code() const { return code_; }'), - contains( - ' const std::string& message() const { return message_; }'), - contains( - ' const flutter::EncodableValue& details() const { return details_; }'), - contains(' private:'), - contains(' std::string code_;'), - contains(' std::string message_;'), - contains(' flutter::EncodableValue details_;'), - ])); + code.split('\n'), + containsAllInOrder([ + contains('class FlutterError {'), + contains(' public:'), + contains(' const std::string& code() const { return code_; }'), + contains(' const std::string& message() const { return message_; }'), + contains( + ' const flutter::EncodableValue& details() const { return details_; }', + ), + contains(' private:'), + contains(' std::string code_;'), + contains(' std::string message_;'), + contains(' flutter::EncodableValue details_;'), + ]), + ); } }); test('Error field is private with public accessors', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: const TypeDeclaration( baseName: 'int', isNullable: false, ), - name: 'someInput') - ], - returnType: - const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) + name: 'someInput', + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + ), ], classes: [], enums: [], @@ -282,77 +360,98 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect( - code.split('\n'), - containsAllInOrder([ - contains('class ErrorOr {'), - contains(' public:'), - contains(' bool has_error() const {'), - contains(' const T& value() const {'), - contains(' const FlutterError& error() const {'), - contains(' private:'), - contains(' std::variant v_;'), - ])); + code.split('\n'), + containsAllInOrder([ + contains('class ErrorOr {'), + contains(' public:'), + contains(' bool has_error() const {'), + contains(' const T& value() const {'), + contains(' const FlutterError& error() const {'), + contains(' private:'), + contains(' std::variant v_;'), + ]), + ); } }); test('Spaces before {', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'input', ), - name: 'input') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output') - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -368,10 +467,13 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -385,32 +487,46 @@ void main() { }); test('include blocks follow style', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'String', + isNullable: true, + ), + name: 'input', ), - name: 'input') + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -418,7 +534,9 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, contains(''' + expect( + code, + contains(''' #include #include #include @@ -427,19 +545,21 @@ void main() { #include #include #include -''')); +'''), + ); } { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - headerIncludePath: 'a_header.h', - cppHeaderOut: '', - cppSourceOut: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + headerIncludePath: 'a_header.h', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -447,7 +567,9 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, contains(''' + expect( + code, + contains(''' #include "a_header.h" #include @@ -458,40 +580,53 @@ void main() { #include #include #include -''')); +'''), + ); } }); test('namespaces follows style', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'String', + isNullable: true, + ), + name: 'input', ), - name: 'input') + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - namespace: 'foo', - headerIncludePath: '', - cppHeaderOut: '', - cppSourceOut: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + namespace: 'foo', + headerIncludePath: '', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -507,13 +642,14 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - namespace: 'foo', - headerIncludePath: '', - cppHeaderOut: '', - cppSourceOut: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + namespace: 'foo', + headerIncludePath: '', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -527,69 +663,79 @@ void main() { }); test('data classes handle nullable fields', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'someInput', ), - name: 'someInput') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Nested', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), - name: 'nestedValue'), - ]), - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), - name: 'nullableBool'), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'nullableInt'), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'nullableString'), - NamedType( - type: TypeDeclaration( - baseName: 'Nested', - isNullable: true, - associatedClass: emptyClass, - ), - name: 'nullableNested'), - ]), - ], enums: []); - { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); + ), + ], + classes: [ + Class( + name: 'Nested', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'nestedValue', + ), + ], + ), + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'nullableBool', + ), + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'nullableInt', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'nullableString', + ), + NamedType( + type: TypeDeclaration( + baseName: 'Nested', + isNullable: true, + associatedClass: emptyClass, + ), + name: 'nullableNested', + ), + ], + ), + ], + enums: [], + ); + { + final StringBuffer sink = StringBuffer(); + const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -602,9 +748,9 @@ void main() { expect(code, contains('Nested();')); // There should be a convenience constructor. expect( - code, - contains( - RegExp(r'explicit Nested\(\s*const bool\* nested_value\s*\)'))); + code, + contains(RegExp(r'explicit Nested\(\s*const bool\* nested_value\s*\)')), + ); // Getters should return const pointers. expect(code, contains('const bool* nullable_bool()')); @@ -616,18 +762,24 @@ void main() { expect(code, contains('void set_nullable_int(const int64_t* value_arg)')); // Strings should be string_view rather than string as an argument. expect( - code, - contains( - 'void set_nullable_string(const std::string_view* value_arg)')); + code, + contains('void set_nullable_string(const std::string_view* value_arg)'), + ); expect( - code, contains('void set_nullable_nested(const Nested* value_arg)')); + code, + contains('void set_nullable_nested(const Nested* value_arg)'), + ); // Setters should have non-null-style variants. expect(code, contains('void set_nullable_bool(bool value_arg)')); expect(code, contains('void set_nullable_int(int64_t value_arg)')); - expect(code, - contains('void set_nullable_string(std::string_view value_arg)')); expect( - code, contains('void set_nullable_nested(const Nested& value_arg)')); + code, + contains('void set_nullable_string(std::string_view value_arg)'), + ); + expect( + code, + contains('void set_nullable_nested(const Nested& value_arg)'), + ); // Most instance variables should be std::optionals. expect(code, contains('std::optional nullable_bool_')); expect(code, contains('std::optional nullable_int_')); @@ -640,10 +792,13 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -656,123 +811,164 @@ void main() { expect(code, contains('Nested::Nested() {}')); // There should be a convenience constructor. expect( - code, - contains(RegExp(r'Nested::Nested\(\s*const bool\* nested_value\s*\)' - r'\s*:\s*nested_value_\(nested_value \? ' - r'std::optional\(\*nested_value\) : std::nullopt\)\s*{}'))); + code, + contains( + RegExp( + r'Nested::Nested\(\s*const bool\* nested_value\s*\)' + r'\s*:\s*nested_value_\(nested_value \? ' + r'std::optional\(\*nested_value\) : std::nullopt\)\s*{}', + ), + ), + ); // Getters extract optionals. - expect(code, - contains('return nullable_bool_ ? &(*nullable_bool_) : nullptr;')); - expect(code, - contains('return nullable_int_ ? &(*nullable_int_) : nullptr;')); expect( - code, - contains( - 'return nullable_string_ ? &(*nullable_string_) : nullptr;')); + code, + contains('return nullable_bool_ ? &(*nullable_bool_) : nullptr;'), + ); + expect( + code, + contains('return nullable_int_ ? &(*nullable_int_) : nullptr;'), + ); + expect( + code, + contains('return nullable_string_ ? &(*nullable_string_) : nullptr;'), + ); expect(code, contains('return nullable_nested_.get();')); // Setters convert to optionals. expect( - code, - contains('nullable_bool_ = value_arg ? ' - 'std::optional(*value_arg) : std::nullopt;')); + code, + contains( + 'nullable_bool_ = value_arg ? ' + 'std::optional(*value_arg) : std::nullopt;', + ), + ); expect( - code, - contains('nullable_int_ = value_arg ? ' - 'std::optional(*value_arg) : std::nullopt;')); + code, + contains( + 'nullable_int_ = value_arg ? ' + 'std::optional(*value_arg) : std::nullopt;', + ), + ); expect( - code, - contains('nullable_string_ = value_arg ? ' - 'std::optional(*value_arg) : std::nullopt;')); + code, + contains( + 'nullable_string_ = value_arg ? ' + 'std::optional(*value_arg) : std::nullopt;', + ), + ); expect( - code, - contains( - 'nullable_nested_ = value_arg ? std::make_unique(*value_arg) : nullptr;')); + code, + contains( + 'nullable_nested_ = value_arg ? std::make_unique(*value_arg) : nullptr;', + ), + ); // Serialization handles optionals. expect( - code, - contains('nullable_bool_ ? EncodableValue(*nullable_bool_) ' - ': EncodableValue()')); + code, + contains( + 'nullable_bool_ ? EncodableValue(*nullable_bool_) ' + ': EncodableValue()', + ), + ); expect( - code, - contains( - 'nullable_nested_ ? CustomEncodableValue(*nullable_nested_) : EncodableValue())')); + code, + contains( + 'nullable_nested_ ? CustomEncodableValue(*nullable_nested_) : EncodableValue())', + ), + ); // Serialization should use push_back, not initializer lists, to avoid // copies. expect(code, contains('list.reserve(4)')); expect( - code, - contains('list.push_back(nullable_bool_ ? ' - 'EncodableValue(*nullable_bool_) : ' - 'EncodableValue())')); + code, + contains( + 'list.push_back(nullable_bool_ ? ' + 'EncodableValue(*nullable_bool_) : ' + 'EncodableValue())', + ), + ); } }); test('data classes handle non-nullable fields', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'someInput', ), - name: 'someInput') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Nested', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'nestedValue', + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Nested', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'nestedValue'), - ]), - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'nonNullableBool'), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - name: 'nonNullableInt'), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - name: 'nonNullableString'), - NamedType( - type: TypeDeclaration( - baseName: 'Nested', - isNullable: false, - associatedClass: emptyClass, - ), - name: 'nonNullableNested'), - ]), - ], enums: []); + ), + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'nonNullableBool', + ), + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'nonNullableInt', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: 'nonNullableString', + ), + NamedType( + type: TypeDeclaration( + baseName: 'Nested', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'nonNullableNested', + ), + ], + ), + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -784,8 +980,10 @@ void main() { // There should not be a default constructor. expect(code, isNot(contains('Nested();'))); // There should be a convenience constructor. - expect(code, - contains(RegExp(r'explicit Nested\(\s*bool nested_value\s*\)'))); + expect( + code, + contains(RegExp(r'explicit Nested\(\s*bool nested_value\s*\)')), + ); // POD getters should return copies references. expect(code, contains('bool non_nullable_bool()')); @@ -797,11 +995,15 @@ void main() { expect(code, contains('void set_non_nullable_bool(bool value_arg)')); expect(code, contains('void set_non_nullable_int(int64_t value_arg)')); // Strings should be string_view as an argument. - expect(code, - contains('void set_non_nullable_string(std::string_view value_arg)')); + expect( + code, + contains('void set_non_nullable_string(std::string_view value_arg)'), + ); // Other non-POD setters should take const references. - expect(code, - contains('void set_non_nullable_nested(const Nested& value_arg)')); + expect( + code, + contains('void set_non_nullable_nested(const Nested& value_arg)'), + ); // Instance variables should be plain types. expect(code, contains('bool non_nullable_bool_;')); expect(code, contains('int64_t non_nullable_int_;')); @@ -814,10 +1016,13 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -830,9 +1035,14 @@ void main() { expect(code, isNot(contains('Nested::Nested() {}'))); // There should be a convenience constructor. expect( - code, - contains(RegExp(r'Nested::Nested\(\s*bool nested_value\s*\)' - r'\s*:\s*nested_value_\(nested_value\)\s*{}'))); + code, + contains( + RegExp( + r'Nested::Nested\(\s*bool nested_value\s*\)' + r'\s*:\s*nested_value_\(nested_value\)\s*{}', + ), + ), + ); // Getters just return the value. expect(code, contains('return non_nullable_bool_;')); @@ -846,9 +1056,9 @@ void main() { expect(code, contains('non_nullable_string_ = value_arg;')); // Unless it's a custom class. expect( - code, - contains( - 'non_nullable_nested_ = std::make_unique(value_arg);')); + code, + contains('non_nullable_nested_ = std::make_unique(value_arg);'), + ); // Serialization uses the value directly. expect(code, contains('EncodableValue(non_nullable_bool_)')); expect(code, contains('CustomEncodableValue(*non_nullable_nested_)')); @@ -857,106 +1067,108 @@ void main() { // copies. expect(code, contains('list.reserve(4)')); expect( - code, - contains( - 'list.push_back(CustomEncodableValue(*non_nullable_nested_))')); + code, + contains('list.push_back(CustomEncodableValue(*non_nullable_nested_))'), + ); } }); test('host nullable return types map correctly', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'returnNullableBool', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), - ), - Method( - name: 'returnNullableInt', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - ), - Method( - name: 'returnNullableString', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - ), - Method( - name: 'returnNullableList', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration( - baseName: 'String', + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'returnNullableBool', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'bool', isNullable: true, - ) - ], - isNullable: true, - ), - ), - Method( - name: 'returnNullableMap', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration( - baseName: 'String', + ), + ), + Method( + name: 'returnNullableInt', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'int', isNullable: true, ), - TypeDeclaration( + ), + Method( + name: 'returnNullableString', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( baseName: 'String', isNullable: true, - ) - ], - isNullable: true, - ), + ), + ), + Method( + name: 'returnNullableList', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + ], + isNullable: true, + ), + ), + Method( + name: 'returnNullableMap', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'String', isNullable: true), + ], + isNullable: true, + ), + ), + Method( + name: 'returnNullableDataClass', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'ReturnData', + isNullable: true, + associatedClass: emptyClass, + ), + ), + ], ), - Method( - name: 'returnNullableDataClass', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'ReturnData', - isNullable: true, - associatedClass: emptyClass, - ), + ], + classes: [ + Class( + name: 'ReturnData', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), + ], ), - ]) - ], classes: [ - Class(name: 'ReturnData', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -965,122 +1177,134 @@ void main() { ); final String code = sink.toString(); expect( - code, contains('ErrorOr> ReturnNullableBool()')); - expect(code, - contains('ErrorOr> ReturnNullableInt()')); + code, + contains('ErrorOr> ReturnNullableBool()'), + ); expect( - code, - contains( - 'ErrorOr> ReturnNullableString()')); + code, + contains('ErrorOr> ReturnNullableInt()'), + ); expect( - code, - contains( - 'ErrorOr> ReturnNullableList()')); + code, + contains('ErrorOr> ReturnNullableString()'), + ); expect( - code, - contains( - 'ErrorOr> ReturnNullableMap()')); + code, + contains( + 'ErrorOr> ReturnNullableList()', + ), + ); expect( - code, - contains( - 'ErrorOr> ReturnNullableDataClass()')); + code, + contains( + 'ErrorOr> ReturnNullableMap()', + ), + ); + expect( + code, + contains( + 'ErrorOr> ReturnNullableDataClass()', + ), + ); } }); test('host non-nullable return types map correctly', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'returnBool', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - ), - Method( - name: 'returnInt', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - Method( - name: 'returnString', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - ), - Method( - name: 'returnList', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration( - baseName: 'String', - isNullable: true, - ) - ], - isNullable: false, - ), - ), - Method( - name: 'returnMap', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'returnBool', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'bool', + isNullable: false, ), - TypeDeclaration( - baseName: 'String', - isNullable: true, - ) - ], - isNullable: false, - ), - ), - Method( - name: 'returnDataClass', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'ReturnData', - isNullable: false, - associatedClass: emptyClass, - ), + ), + Method( + name: 'returnInt', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Method( + name: 'returnString', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + ), + Method( + name: 'returnList', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + ], + isNullable: false, + ), + ), + Method( + name: 'returnMap', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'String', isNullable: true), + ], + isNullable: false, + ), + ), + Method( + name: 'returnDataClass', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'ReturnData', + isNullable: false, + associatedClass: emptyClass, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'ReturnData', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), + ], ), - ]) - ], classes: [ - Class(name: 'ReturnData', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1098,85 +1322,103 @@ void main() { }); test('host nullable arguments map correctly', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - )), - Parameter( - name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - Parameter( - name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - )), - Parameter( - name: 'aList', - type: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration(baseName: 'Object', isNullable: true) - ], - isNullable: true, - )), - Parameter( - name: 'aMap', - type: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'Object', isNullable: true), - ], - isNullable: true, - )), - Parameter( - name: 'anObject', - type: TypeDeclaration( - baseName: 'ParameterObject', - isNullable: true, - associatedClass: emptyClass, - )), - Parameter( - name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: true, - )), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'aBool', + type: const TypeDeclaration( + baseName: 'bool', + isNullable: true, + ), + ), + Parameter( + name: 'anInt', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + Parameter( + name: 'aString', + type: const TypeDeclaration( + baseName: 'String', + isNullable: true, + ), + ), + Parameter( + name: 'aList', + type: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: true, + ), + ), + Parameter( + name: 'aMap', + type: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: true, + ), + ), + Parameter( + name: 'anObject', + type: TypeDeclaration( + baseName: 'ParameterObject', + isNullable: true, + associatedClass: emptyClass, + ), + ), + Parameter( + name: 'aGenericObject', + type: const TypeDeclaration( + baseName: 'Object', + isNullable: true, + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'ParameterObject', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ), - ]) - ], classes: [ - Class(name: 'ParameterObject', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ), + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1185,25 +1427,33 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains(RegExp(r'DoSomething\(\s*' - r'const bool\* a_bool,\s*' - r'const int64_t\* an_int,\s*' - r'const std::string\* a_string,\s*' - r'const flutter::EncodableList\* a_list,\s*' - r'const flutter::EncodableMap\* a_map,\s*' - r'const ParameterObject\* an_object,\s*' - r'const flutter::EncodableValue\* a_generic_object\s*\)'))); + code, + contains( + RegExp( + r'DoSomething\(\s*' + r'const bool\* a_bool,\s*' + r'const int64_t\* an_int,\s*' + r'const std::string\* a_string,\s*' + r'const flutter::EncodableList\* a_list,\s*' + r'const flutter::EncodableMap\* a_map,\s*' + r'const ParameterObject\* an_object,\s*' + r'const flutter::EncodableValue\* a_generic_object\s*\)', + ), + ), + ); } { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1216,123 +1466,157 @@ void main() { // EncodableValue will not match the queried type, so get_if will return // nullptr). expect( - code, - contains( - 'const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);')); + code, + contains( + 'const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);', + ), + ); expect( - code, - contains( - 'const auto* a_string_arg = std::get_if(&encodable_a_string_arg);')); + code, + contains( + 'const auto* a_string_arg = std::get_if(&encodable_a_string_arg);', + ), + ); expect( - code, - contains( - 'const auto* a_list_arg = std::get_if(&encodable_a_list_arg);')); + code, + contains( + 'const auto* a_list_arg = std::get_if(&encodable_a_list_arg);', + ), + ); expect( - code, - contains( - 'const auto* a_map_arg = std::get_if(&encodable_a_map_arg);')); + code, + contains( + 'const auto* a_map_arg = std::get_if(&encodable_a_map_arg);', + ), + ); expect( - code, - contains( - 'const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);')); + code, + contains( + 'const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);', + ), + ); expect( - code, - contains( - 'const auto* an_int_arg = std::get_if(&encodable_an_int_arg);')); + code, + contains( + 'const auto* an_int_arg = std::get_if(&encodable_an_int_arg);', + ), + ); // Custom class types require an extra layer of extraction. expect( - code, - contains( - 'const auto* an_object_arg = encodable_an_object_arg.IsNull() ? nullptr : &(std::any_cast(std::get(encodable_an_object_arg)));')); + code, + contains( + 'const auto* an_object_arg = encodable_an_object_arg.IsNull() ? nullptr : &(std::any_cast(std::get(encodable_an_object_arg)));', + ), + ); // "Object" requires no extraction at all since it has to use // EncodableValue directly. expect( - code, - contains( - 'const auto* a_generic_object_arg = &encodable_a_generic_object_arg;')); + code, + contains( + 'const auto* a_generic_object_arg = &encodable_a_generic_object_arg;', + ), + ); } }); test('host non-nullable arguments map correctly', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - )), - Parameter( - name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - )), - Parameter( - name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - )), - Parameter( - name: 'aList', - type: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration(baseName: 'Object', isNullable: true) - ], - isNullable: false, - )), - Parameter( - name: 'aMap', - type: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'Object', isNullable: true), - ], - isNullable: false, - )), - Parameter( - name: 'anObject', - type: TypeDeclaration( - baseName: 'ParameterObject', - isNullable: false, - associatedClass: emptyClass, - )), - Parameter( - name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: false, - )), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'aBool', + type: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + ), + Parameter( + name: 'anInt', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Parameter( + name: 'aString', + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + ), + Parameter( + name: 'aList', + type: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: false, + ), + ), + Parameter( + name: 'aMap', + type: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: false, + ), + ), + Parameter( + name: 'anObject', + type: TypeDeclaration( + baseName: 'ParameterObject', + isNullable: false, + associatedClass: emptyClass, + ), + ), + Parameter( + name: 'aGenericObject', + type: const TypeDeclaration( + baseName: 'Object', + isNullable: false, + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ), - ]) - ], classes: [ - Class(name: 'ParameterObject', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ), + ], + classes: [ + Class( + name: 'ParameterObject', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), + ], + ), + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1341,25 +1625,33 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains(RegExp(r'DoSomething\(\s*' - r'bool a_bool,\s*' - r'int64_t an_int,\s*' - r'const std::string& a_string,\s*' - r'const flutter::EncodableList& a_list,\s*' - r'const flutter::EncodableMap& a_map,\s*' - r'const ParameterObject& an_object,\s*' - r'const flutter::EncodableValue& a_generic_object\s*\)'))); + code, + contains( + RegExp( + r'DoSomething\(\s*' + r'bool a_bool,\s*' + r'int64_t an_int,\s*' + r'const std::string& a_string,\s*' + r'const flutter::EncodableList& a_list,\s*' + r'const flutter::EncodableMap& a_map,\s*' + r'const ParameterObject& an_object,\s*' + r'const flutter::EncodableValue& a_generic_object\s*\)', + ), + ), + ); } { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1370,125 +1662,156 @@ void main() { // Most types should extract references. Since the type is non-nullable, // there's only one possible type. expect( - code, - contains( - 'const auto& a_bool_arg = std::get(encodable_a_bool_arg);')); + code, + contains( + 'const auto& a_bool_arg = std::get(encodable_a_bool_arg);', + ), + ); expect( - code, - contains( - 'const auto& a_string_arg = std::get(encodable_a_string_arg);')); + code, + contains( + 'const auto& a_string_arg = std::get(encodable_a_string_arg);', + ), + ); expect( - code, - contains( - 'const auto& a_list_arg = std::get(encodable_a_list_arg);')); + code, + contains( + 'const auto& a_list_arg = std::get(encodable_a_list_arg);', + ), + ); expect( - code, - contains( - 'const auto& a_map_arg = std::get(encodable_a_map_arg);')); + code, + contains( + 'const auto& a_map_arg = std::get(encodable_a_map_arg);', + ), + ); // Ints use a copy since there are two possible reference types, but // the parameter always needs an int64_t. expect( - code, - contains( - 'const int64_t an_int_arg = encodable_an_int_arg.LongValue();', - )); + code, + contains( + 'const int64_t an_int_arg = encodable_an_int_arg.LongValue();', + ), + ); // Custom class types require an extra layer of extraction. expect( - code, - contains( - 'const auto& an_object_arg = std::any_cast(std::get(encodable_an_object_arg));')); + code, + contains( + 'const auto& an_object_arg = std::any_cast(std::get(encodable_an_object_arg));', + ), + ); // "Object" requires no extraction at all since it has to use // EncodableValue directly. expect( - code, - contains( - 'const auto& a_generic_object_arg = encodable_a_generic_object_arg;')); + code, + contains( + 'const auto& a_generic_object_arg = encodable_a_generic_object_arg;', + ), + ); } }); test('flutter nullable arguments map correctly', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - )), - Parameter( - name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - Parameter( - name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - )), - Parameter( - name: 'aList', - type: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration(baseName: 'Object', isNullable: true) - ], - isNullable: true, - )), - Parameter( - name: 'aMap', - type: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'Object', isNullable: true), - ], - isNullable: true, - )), - Parameter( - name: 'anObject', - type: TypeDeclaration( - baseName: 'ParameterObject', - isNullable: true, - associatedClass: emptyClass, - )), - Parameter( - name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: true, - )), + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'aBool', + type: const TypeDeclaration( + baseName: 'bool', + isNullable: true, + ), + ), + Parameter( + name: 'anInt', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + Parameter( + name: 'aString', + type: const TypeDeclaration( + baseName: 'String', + isNullable: true, + ), + ), + Parameter( + name: 'aList', + type: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: true, + ), + ), + Parameter( + name: 'aMap', + type: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: true, + ), + ), + Parameter( + name: 'anObject', + type: TypeDeclaration( + baseName: 'ParameterObject', + isNullable: true, + associatedClass: emptyClass, + ), + ), + Parameter( + name: 'aGenericObject', + type: const TypeDeclaration( + baseName: 'Object', + isNullable: true, + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'bool', + isNullable: true, + ), + ), ], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), ), - ]) - ], classes: [ - Class(name: 'ParameterObject', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ], + classes: [ + Class( + name: 'ParameterObject', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), + ], + ), + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1504,33 +1827,45 @@ void main() { // `std::optional`s; that may be more ergonomic, but the perf implications // would need to be considered. expect( - code, - contains(RegExp(r'DoSomething\(\s*' - r'const bool\* a_bool,\s*' - r'const int64_t\* an_int,\s*' - // Nullable strings use std::string* rather than std::string_view* - // since there's no implicit conversion for pointer types. - r'const std::string\* a_string,\s*' - r'const flutter::EncodableList\* a_list,\s*' - r'const flutter::EncodableMap\* a_map,\s*' - r'const ParameterObject\* an_object,\s*' - r'const flutter::EncodableValue\* a_generic_object,'))); + code, + contains( + RegExp( + r'DoSomething\(\s*' + r'const bool\* a_bool,\s*' + r'const int64_t\* an_int,\s*' + // Nullable strings use std::string* rather than std::string_view* + // since there's no implicit conversion for pointer types. + r'const std::string\* a_string,\s*' + r'const flutter::EncodableList\* a_list,\s*' + r'const flutter::EncodableMap\* a_map,\s*' + r'const ParameterObject\* an_object,\s*' + r'const flutter::EncodableValue\* a_generic_object,', + ), + ), + ); // The callback should pass a pointer as well. expect( - code, - contains( - RegExp(r'std::function&& on_success,\s*' - r'std::function&& on_error\)'))); + code, + contains( + RegExp( + r'std::function&& on_success,\s*' + r'std::function&& on_error\)', + ), + ), + ); } { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1541,116 +1876,138 @@ void main() { // All types pass nulls values when the pointer is null. // Standard types are wrapped an EncodableValues. expect( - code, - contains( - 'a_bool_arg ? EncodableValue(*a_bool_arg) : EncodableValue()')); + code, + contains('a_bool_arg ? EncodableValue(*a_bool_arg) : EncodableValue()'), + ); expect( - code, - contains( - 'an_int_arg ? EncodableValue(*an_int_arg) : EncodableValue()')); + code, + contains('an_int_arg ? EncodableValue(*an_int_arg) : EncodableValue()'), + ); expect( - code, - contains( - 'a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue()')); + code, + contains( + 'a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue()', + ), + ); expect( - code, - contains( - 'a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue()')); + code, + contains('a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue()'), + ); expect( - code, - contains( - 'a_map_arg ? EncodableValue(*a_map_arg) : EncodableValue()')); + code, + contains('a_map_arg ? EncodableValue(*a_map_arg) : EncodableValue()'), + ); // Class types use ToEncodableList. expect( - code, - contains( - 'an_object_arg ? CustomEncodableValue(*an_object_arg) : EncodableValue()')); + code, + contains( + 'an_object_arg ? CustomEncodableValue(*an_object_arg) : EncodableValue()', + ), + ); } }); test('flutter non-nullable arguments map correctly', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - )), - Parameter( - name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - )), - Parameter( - name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - )), - Parameter( - name: 'aList', - type: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration(baseName: 'Object', isNullable: true) - ], - isNullable: false, - )), - Parameter( - name: 'aMap', - type: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'Object', isNullable: true), - ], - isNullable: false, - )), - Parameter( - name: 'anObject', - type: TypeDeclaration( - baseName: 'ParameterObject', - isNullable: false, - associatedClass: emptyClass, - )), - Parameter( - name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: false, - )), + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'aBool', + type: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + ), + Parameter( + name: 'anInt', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Parameter( + name: 'aString', + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + ), + Parameter( + name: 'aList', + type: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: false, + ), + ), + Parameter( + name: 'aMap', + type: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: false, + ), + ), + Parameter( + name: 'anObject', + type: TypeDeclaration( + baseName: 'ParameterObject', + isNullable: false, + associatedClass: emptyClass, + ), + ), + Parameter( + name: 'aGenericObject', + type: const TypeDeclaration( + baseName: 'Object', + isNullable: false, + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'ParameterObject', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), ], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), ), - ]) - ], classes: [ - Class(name: 'ParameterObject', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1659,33 +2016,46 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains(RegExp(r'DoSomething\(\s*' - r'bool a_bool,\s*' - r'int64_t an_int,\s*' - // Non-nullable strings use std::string for consistency with - // nullable strings. - r'const std::string& a_string,\s*' - // Non-POD types use const references. - r'const flutter::EncodableList& a_list,\s*' - r'const flutter::EncodableMap& a_map,\s*' - r'const ParameterObject& an_object,\s*' - r'const flutter::EncodableValue& a_generic_object,\s*'))); + code, + contains( + RegExp( + r'DoSomething\(\s*' + r'bool a_bool,\s*' + r'int64_t an_int,\s*' + // Non-nullable strings use std::string for consistency with + // nullable strings. + r'const std::string& a_string,\s*' + // Non-POD types use const references. + r'const flutter::EncodableList& a_list,\s*' + r'const flutter::EncodableMap& a_map,\s*' + r'const ParameterObject& an_object,\s*' + r'const flutter::EncodableValue& a_generic_object,\s*', + ), + ), + ); // The callback should pass a value. expect( - code, - contains(RegExp(r'std::function&& on_success,\s*' - r'std::function&& on_error\s*\)'))); + code, + contains( + RegExp( + r'std::function&& on_success,\s*' + r'std::function&& on_error\s*\)', + ), + ), + ); } { final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1705,32 +2075,43 @@ void main() { }); test('host API argument extraction uses references', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'anArg', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - )), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'anArg', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), ), - ]) - ], classes: [], enums: []); + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1741,15 +2122,19 @@ void main() { // A bare 'auto' here would create a copy, not a reference, which is // inefficient. expect( - code, contains('const auto& args = std::get(message);')); + code, + contains('const auto& args = std::get(message);'), + ); expect(code, contains('const auto& encodable_an_arg_arg = args.at(0);')); }); test('enum argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( + AstHostApi( + name: 'Bar', + methods: [ + Method( name: 'bar', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), @@ -1761,22 +2146,31 @@ void main() { isNullable: false, associatedEnum: emptyEnum, ), - ) - ]) - ]) + ), + ], + ), + ], + ), ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), ], ); final List errors = validateCpp( - const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - root); + const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + root, + ); expect(errors.length, 1); }); @@ -1814,9 +2208,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -1824,15 +2218,17 @@ void main() { documentationComments: [comments[count++]], fields: [ NamedType( - documentationComments: [comments[count++]], - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), - name: 'field1'), + documentationComments: [comments[count++]], + type: const TypeDeclaration( + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ), ], @@ -1841,7 +2237,7 @@ void main() { name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -1857,13 +2253,13 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - headerIncludePath: 'foo', - cppHeaderOut: '', - cppSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + headerIncludePath: 'foo', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1878,54 +2274,67 @@ void main() { }); test('creates custom codecs', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output') - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1937,78 +2346,95 @@ void main() { }); test('Does not send unwrapped EncodableLists', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - )), - Parameter( - name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - )), - Parameter( - name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - )), - Parameter( - name: 'aList', - type: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration(baseName: 'Object', isNullable: true) - ], - isNullable: false, - )), - Parameter( - name: 'aMap', - type: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'Object', isNullable: true), - ], - isNullable: false, - )), - Parameter( - name: 'anObject', - type: TypeDeclaration( - baseName: 'ParameterObject', - isNullable: false, - associatedClass: emptyClass, - )), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'aBool', + type: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + ), + Parameter( + name: 'anInt', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Parameter( + name: 'aString', + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + ), + Parameter( + name: 'aList', + type: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: false, + ), + ), + Parameter( + name: 'aMap', + type: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + isNullable: false, + ), + ), + Parameter( + name: 'anObject', + type: TypeDeclaration( + baseName: 'ParameterObject', + isNullable: false, + associatedClass: emptyClass, + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'ParameterObject', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ), - ]) - ], classes: [ - Class(name: 'ParameterObject', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]), - ], enums: []); + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2021,64 +2447,83 @@ void main() { }); test('does not keep unowned references in async handlers', () { - final Root root = Root(apis: [ - AstHostApi(name: 'HostApi', methods: [ - Method( - name: 'noop', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true, - ), - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'HostApi', + methods: [ + Method( + name: 'noop', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, + ), + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration( + baseName: 'double', + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: - const TypeDeclaration(baseName: 'double', isNullable: false), - isAsynchronous: true, - ), - ]), - AstFlutterApi(name: 'FlutterApi', methods: [ - Method( - name: 'noop', - location: ApiLocation.flutter, - parameters: [], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true, - ), - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, + ), + AstFlutterApi( + name: 'FlutterApi', + methods: [ + Method( + name: 'noop', + location: ApiLocation.flutter, + parameters: [], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, + ), + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: - const TypeDeclaration(baseName: 'bool', isNullable: false), - isAsynchronous: true, ), - ]) - ], classes: [], enums: []); + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2115,9 +2560,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], @@ -2127,10 +2572,13 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2139,9 +2587,11 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '"Unable to establish connection on channel: \'" + channel_name + "\'."')); + code, + contains( + '"Unable to establish connection on channel: \'" + channel_name + "\'."', + ), + ); expect(code, contains('on_error(CreateConnectionError(channel_name));')); }); @@ -2164,9 +2614,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], @@ -2175,10 +2625,13 @@ void main() { const CppGenerator generator = CppGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), - ); + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2187,9 +2640,11 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec());')); + code, + contains( + 'BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec());', + ), + ); expect(code, contains('channel.Send')); }); } diff --git a/packages/pigeon/test/dart/proxy_api_test.dart b/packages/pigeon/test/dart/proxy_api_test.dart index d1bc8761065..9c69d64666f 100644 --- a/packages/pigeon/test/dart/proxy_api_test.dart +++ b/packages/pigeon/test/dart/proxy_api_test.dart @@ -11,63 +11,72 @@ const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { group('ProxyApi', () { test('one api', () { - final Root root = Root(apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor(name: 'name', parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [ + Constructor( + name: 'name', + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'Input', + isNullable: false, + ), + name: 'input', + ), + ], ), - name: 'input', - ), - ]), - ], fields: [ - ApiField( - name: 'someField', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ) - ], methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'Input', + ], + fields: [ + ApiField( + name: 'someField', + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ), + ], + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'Input', + isNullable: false, + ), + name: 'input', + ), + ], + returnType: const TypeDeclaration( + baseName: 'String', isNullable: false, ), - name: 'input', - ) - ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - ), - Method( - name: 'doSomethingElse', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'Input', + ), + Method( + name: 'doSomethingElse', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'Input', + isNullable: false, + ), + name: 'input', + ), + ], + returnType: const TypeDeclaration( + baseName: 'String', isNullable: false, ), - name: 'input', - ) + isRequired: false, + ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - isRequired: false, ), - ]) - ], classes: [], enums: []); + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -84,15 +93,14 @@ void main() { expect(code, contains(r'class _PigeonInternalInstanceManagerApi')); // Base Api class - expect( - code, - contains(r'abstract class PigeonInternalProxyApiBaseClass'), - ); + expect(code, contains(r'abstract class PigeonInternalProxyApiBaseClass')); // Codec and class expect(code, contains('class _PigeonInternalProxyApiBaseCodec')); expect( - code, contains(r'class Api extends PigeonInternalProxyApiBaseClass')); + code, + contains(r'class Api extends PigeonInternalProxyApiBaseClass'), + ); // Constructors expect( @@ -107,12 +115,7 @@ void main() { r'Api.pigeon_name({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, required this.someField, this.doSomethingElse, required Input input, })', ), ); - expect( - code, - contains( - r'Api.pigeon_detached', - ), - ); + expect(code, contains(r'Api.pigeon_detached')); // Field expect(code, contains('final int someField;')); @@ -134,14 +137,18 @@ void main() { }); test('InstanceManagerApi', () { - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - ) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -157,9 +164,7 @@ void main() { expect( code, - contains( - 'Future removeStrongReference(int identifier)', - ), + contains('Future removeStrongReference(int identifier)'), ); expect( code, @@ -185,14 +190,18 @@ void main() { group('ProxyApi base class', () { test('class name', () { - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - ) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -210,14 +219,18 @@ void main() { }); test('InstanceManager field', () { - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - ) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -247,20 +260,24 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - superClass: TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + superClass: TypeDeclaration( + baseName: 'Api2', + isNullable: false, + associatedProxyApi: api2, + ), ), - ), - api2, - ], classes: [], enums: []); + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -287,22 +304,26 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, - ) - }, - ), - api2, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: 'Api2', + isNullable: false, + associatedProxyApi: api2, + ), + }, + ), + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -333,28 +354,32 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, - ), - TypeDeclaration( - baseName: 'Api3', - isNullable: false, - associatedProxyApi: api2, - ), - }, - ), - api2, - api3, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: 'Api2', + isNullable: false, + associatedProxyApi: api2, + ), + TypeDeclaration( + baseName: 'Api3', + isNullable: false, + associatedProxyApi: api2, + ), + }, + ), + api2, + api3, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -393,22 +418,26 @@ void main() { ), ], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, - ) - }, - ), - api2, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: 'Api2', + isNullable: false, + associatedProxyApi: api2, + ), + }, + ), + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -441,12 +470,14 @@ void main() { test('empty name and no params constructor', () { final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: '', - parameters: [], - ) - ], fields: [], methods: []), + AstProxyApi( + name: 'Api', + constructors: [ + Constructor(name: '', parameters: []), + ], + fields: [], + methods: [], + ), ], classes: [], enums: [], @@ -503,57 +534,62 @@ void main() { ); final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: 'name', - parameters: [ - Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', + AstProxyApi( + name: 'Api', + constructors: [ + Constructor( + name: 'name', + parameters: [ + Parameter( + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + name: 'validType', ), - name: 'validType', - ), - Parameter( - type: TypeDeclaration( - isNullable: false, - baseName: 'AnEnum', - associatedEnum: anEnum, + Parameter( + type: TypeDeclaration( + isNullable: false, + baseName: 'AnEnum', + associatedEnum: anEnum, + ), + name: 'enumType', ), - name: 'enumType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', + Parameter( + type: const TypeDeclaration( + isNullable: false, + baseName: 'Api2', + ), + name: 'proxyApiType', ), - name: 'proxyApiType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', + Parameter( + type: const TypeDeclaration( + isNullable: true, + baseName: 'int', + ), + name: 'nullableValidType', ), - name: 'nullableValidType', - ), - Parameter( - type: TypeDeclaration( - isNullable: true, - baseName: 'AnEnum', - associatedEnum: anEnum, + Parameter( + type: TypeDeclaration( + isNullable: true, + baseName: 'AnEnum', + associatedEnum: anEnum, + ), + name: 'nullableEnumType', ), - name: 'nullableEnumType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', + Parameter( + type: const TypeDeclaration( + isNullable: true, + baseName: 'Api2', + ), + name: 'nullableProxyApiType', ), - name: 'nullableProxyApiType', - ), - ], - ) - ], fields: [], methods: []), + ], + ), + ], + fields: [], + methods: [], + ), AstProxyApi( name: 'Api2', constructors: [], @@ -624,10 +660,7 @@ void main() { AstProxyApi( name: 'Api', constructors: [ - Constructor( - name: 'name', - parameters: [], - ) + Constructor(name: 'name', parameters: []), ], fields: [ ApiField( @@ -733,30 +766,12 @@ void main() { r'nullableValidType, nullableEnumType, nullableProxyApiType ])', ), ); - expect( - code, - contains(r'final int validType;'), - ); - expect( - code, - contains(r'final AnEnum enumType;'), - ); - expect( - code, - contains(r'final Api2 proxyApiType;'), - ); - expect( - code, - contains(r'final int? nullableValidType;'), - ); - expect( - code, - contains(r'final AnEnum? nullableEnumType;'), - ); - expect( - code, - contains(r'final Api2? nullableProxyApiType;'), - ); + expect(code, contains(r'final int validType;')); + expect(code, contains(r'final AnEnum enumType;')); + expect(code, contains(r'final Api2 proxyApiType;')); + expect(code, contains(r'final int? nullableValidType;')); + expect(code, contains(r'final AnEnum? nullableEnumType;')); + expect(code, contains(r'final Api2? nullableProxyApiType;')); }); test('attached field', () { @@ -845,11 +860,15 @@ void main() { final String code = sink.toString(); expect(code, contains('class Api')); expect( - code, - contains( - r'static Api2 get aField => PigeonOverrides.api_aField ?? _aField;')); + code, + contains( + r'static Api2 get aField => PigeonOverrides.api_aField ?? _aField;', + ), + ); expect( - code, contains(r'static final Api2 _aField = pigeonVar_aField();')); + code, + contains(r'static final Api2 _aField = pigeonVar_aField();'), + ); expect(code, contains(r'static Api2 pigeonVar_aField()')); }); }); @@ -999,10 +1018,7 @@ void main() { r'PigeonInstanceManager? pigeon_instanceManager, })', ), ); - expect( - collapsedCode, - contains(r'pigeonVar_channel.send(null)'), - ); + expect(collapsedCode, contains(r'pigeonVar_channel.send(null)')); expect(code, contains('await pigeonVar_sendFuture')); }); }); @@ -1013,8 +1029,9 @@ void main() { name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root(apis: [ - AstProxyApi( + final Root root = Root( + apis: [ + AstProxyApi( name: 'Api', constructors: [], fields: [], @@ -1071,10 +1088,12 @@ void main() { ], returnType: const TypeDeclaration.voidDeclaration(), ), - ]) - ], classes: [], enums: [ - anEnum - ]); + ], + ), + ], + classes: [], + enums: [anEnum], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -1098,10 +1117,11 @@ void main() { expect( collapsedCode, contains( - r'void Function( Api pigeon_instance, int validType, AnEnum enumType, ' - r'Api2 proxyApiType, int? nullableValidType, ' - r'AnEnum? nullableEnumType, Api2? nullableProxyApiType, )? ' - r'doSomething'), + r'void Function( Api pigeon_instance, int validType, AnEnum enumType, ' + r'Api2 proxyApiType, int? nullableValidType, ' + r'AnEnum? nullableEnumType, Api2? nullableProxyApiType, )? ' + r'doSomething', + ), ); expect( code, @@ -1113,9 +1133,7 @@ void main() { ); expect( code, - contains( - r'final AnEnum? arg_enumType = (args[2] as AnEnum?);', - ), + contains(r'final AnEnum? arg_enumType = (args[2] as AnEnum?);'), ); expect( code, diff --git a/packages/pigeon/test/dart_generator_test.dart b/packages/pigeon/test/dart_generator_test.dart index 857fece3394..5577c6358fa 100644 --- a/packages/pigeon/test/dart_generator_test.dart +++ b/packages/pigeon/test/dart_generator_test.dart @@ -12,12 +12,15 @@ import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); final Enum emptyEnum = Enum( name: 'enumName', @@ -30,12 +33,13 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'dataType1', - isNullable: true, - associatedClass: emptyClass, - ), - name: 'field1'), + type: TypeDeclaration( + baseName: 'dataType1', + isNullable: true, + associatedClass: emptyClass, + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -59,10 +63,7 @@ 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: [], @@ -84,45 +85,55 @@ void main() { }); test('gen one host api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'input', ), - name: 'input') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -137,25 +148,41 @@ void main() { }); test('host multiple args', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -177,25 +204,41 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -207,39 +250,44 @@ void main() { final String code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('int add(int x, int y)')); - expect(code, - contains('final List args = (message as List?)!')); + expect( + code, + contains('final List args = (message as List?)!'), + ); expect(code, contains('final int? arg_x = (args[0] as int?)')); expect(code, contains('final int? arg_y = (args[1] as int?)')); expect(code, contains('final int output = api.add(arg_x!, arg_y!)')); }); test('nested class', () { - final Root root = Root(apis: [], classes: [ - Class( - name: 'Input', - fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ], - ), - Class( - name: 'Nested', - fields: [ - NamedType( + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Nested', + fields: [ + NamedType( type: TypeDeclaration( baseName: 'Input', isNullable: true, associatedClass: emptyClass, ), - name: 'nested') - ], - ) - ], enums: []); + name: 'nested', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -249,46 +297,42 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect( - code, - contains( - 'nested,', - ), - ); - expect( - code, - contains( - 'nested: result[0] as Input?', - ), - ); + expect(code, contains('nested,')); + expect(code, contains('nested: result[0] as Input?')); }); test('nested non-nullable class', () { - final Root root = Root(apis: [], classes: [ - Class( - name: 'Input', - fields: [ - NamedType( + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: false, ), - name: 'input') - ], - ), - Class( - name: 'Nested', - fields: [ - NamedType( + name: 'input', + ), + ], + ), + Class( + name: 'Nested', + fields: [ + NamedType( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), - name: 'nested') - ], - ) - ], enums: []); + name: 'nested', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -298,60 +342,60 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect( - code, - contains( - 'nested,', - ), - ); - expect( - code, - contains( - 'nested: result[0]! as Input', - ), - ); + expect(code, contains('nested,')); + expect(code, contains('nested: result[0]! as Input')); }); test('flutterApi', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'input', ), - name: 'input') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -367,33 +411,42 @@ void main() { }); test('host void', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -408,33 +461,42 @@ void main() { }); test('flutter void return', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -452,29 +514,37 @@ void main() { }); test('flutter void argument', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -489,46 +559,58 @@ void main() { }); test('flutter enum argument with enum class', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'EnumClass', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'EnumClass', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'enumClass', ), - name: 'enumClass') + ], + returnType: TypeDeclaration( + baseName: 'EnumClass', + isNullable: false, + associatedClass: emptyClass, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'EnumClass', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'EnumClass', fields: [ - NamedType( - type: TypeDeclaration( - baseName: 'Enum', - isNullable: true, - associatedEnum: emptyEnum, + ), + ], + classes: [ + Class( + name: 'EnumClass', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Enum', + isNullable: true, + associatedEnum: emptyEnum, + ), + name: 'enum1', ), - name: 'enum1') - ]), - ], enums: [ - Enum( - name: 'Enum', - members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ], - ) - ]); + ], + ), + ], + enums: [ + Enum( + name: 'Enum', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -540,34 +622,48 @@ void main() { final String code = sink.toString(); expect(code, contains('return value == null ? null : Enum.values[value];')); expect(code, contains('writeValue(buffer, value.index);')); - expect(code, - contains('final EnumClass? arg_enumClass = (args[0] as EnumClass?);')); + expect( + code, + contains('final EnumClass? arg_enumClass = (args[0] as EnumClass?);'), + ); expect(code, contains('EnumClass doSomething(EnumClass enumClass);')); }); test('primitive enum host', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( - name: 'bar', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Bar', + methods: [ + Method( + name: 'bar', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', isNullable: true, associatedEnum: emptyEnum, - )) - ]) - ]) - ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) - ]); + ), + ), + ], + ), + ], + ), + ], + classes: [], + enums: [ + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -587,46 +683,58 @@ void main() { }); test('flutter non-nullable enum argument with enum class', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'EnumClass', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'EnumClass', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'EnumClass', + isNullable: false, + associatedClass: emptyClass, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'EnumClass', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Enum', + isNullable: false, + associatedEnum: emptyEnum, + ), + name: 'enum1', + ), + ], + ), + ], + enums: [ + Enum( + name: 'Enum', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), ], - returnType: TypeDeclaration( - baseName: 'EnumClass', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'EnumClass', fields: [ - NamedType( - type: TypeDeclaration( - baseName: 'Enum', - isNullable: false, - associatedEnum: emptyEnum, - ), - name: 'enum1') - ]), - ], enums: [ - Enum( - name: 'Enum', - members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ], - ) - ]); + ), + ], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -642,29 +750,37 @@ void main() { }); test('host void argument', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -681,59 +797,71 @@ void main() { }); test('mock Dart handler', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', dartHostTestHandler: 'ApiMock', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + dartHostTestHandler: 'ApiMock', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - ), - Method( - name: 'voidReturner', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + ), + Method( + name: 'voidReturner', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer mainCodeSink = StringBuffer(); final StringBuffer testCodeSink = StringBuffer(); const DartGenerator generator = DartGenerator(); @@ -753,10 +881,7 @@ void main() { const DartGenerator testGenerator = DartGenerator(); testGenerator.generateTest( - const InternalDartOptions( - dartOut: "fo'o.dart", - testOut: 'test.dart', - ), + const InternalDartOptions(dartOut: "fo'o.dart", testOut: 'test.dart'), root, testCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -772,46 +897,56 @@ void main() { }); test('gen one async Flutter Api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: 'input', ), - name: 'input') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -823,47 +958,59 @@ void main() { final String code = sink.toString(); expect(code, contains('abstract class Api')); expect(code, contains('Future doSomething(Input input);')); - expect(code, - contains('final Output output = await api.doSomething(arg_input!);')); + expect( + code, + contains('final Output output = await api.doSomething(arg_input!);'), + ); }); test('gen one async Flutter Api with void return', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') - ], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -879,46 +1026,56 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -933,30 +1090,38 @@ void main() { }); test('async host void argument', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + isAsynchronous: true, ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -993,13 +1158,15 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'List', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -1025,14 +1192,16 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -1056,22 +1225,28 @@ void main() { test('host generics argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1091,22 +1266,28 @@ void main() { test('flutter generics argument with void return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1126,18 +1307,23 @@ void main() { test('host generics return', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -1153,35 +1339,44 @@ void main() { final String code = sink.toString(); expect(code, contains('Future> doit(')); expect( - code, - contains( - 'return (pigeonVar_replyList[0] as List?)!.cast();')); + code, + contains( + 'return (pigeonVar_replyList[0] as List?)!.cast();', + ), + ); }); test('flutter generics argument non void return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'foo') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'foo', + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1197,25 +1392,31 @@ void main() { final String code = sink.toString(); expect(code, contains('List doit(')); expect( - code, - contains( - 'final List? arg_foo = (args[0] as List?)?.cast()')); + code, + contains( + 'final List? arg_foo = (args[0] as List?)?.cast()', + ), + ); expect(code, contains('final List output = api.doit(arg_foo!)')); }); test('return nullable host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -1236,18 +1437,23 @@ void main() { test('return nullable collection host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -1263,16 +1469,20 @@ void main() { final String code = sink.toString(); expect(code, contains('Future?> doit()')); expect( - code, - contains( - 'return (pigeonVar_replyList[0] as List?)?.cast();')); + code, + contains( + 'return (pigeonVar_replyList[0] as List?)?.cast();', + ), + ); }); test('return nullable async host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( @@ -1280,8 +1490,10 @@ void main() { isNullable: true, ), parameters: [], - isAsynchronous: true) - ]) + isAsynchronous: true, + ), + ], + ), ], classes: [], enums: [], @@ -1302,16 +1514,20 @@ void main() { test('return nullable flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -1332,8 +1548,10 @@ void main() { test('return nullable async flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( @@ -1341,8 +1559,10 @@ void main() { isNullable: true, ), parameters: [], - isAsynchronous: true) - ]) + isAsynchronous: true, + ), + ], + ), ], classes: [], enums: [], @@ -1363,16 +1583,20 @@ void main() { test('platform error for return nil on nonnull', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: false, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -1387,28 +1611,33 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'Host platform returned null value for non-null return value.')); + code, + contains('Host platform returned null value for non-null return value.'), + ); }); test('nullable argument host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1428,20 +1657,25 @@ void main() { test('nullable argument flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1461,22 +1695,27 @@ void main() { test('named argument flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - isNamed: true, - isPositional: false), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + isNamed: true, + isPositional: false, + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1506,8 +1745,11 @@ void main() { pubspecFile.writeAsStringSync(''' name: foobar '''); - final Root root = - Root(classes: [], apis: [], enums: []); + final Root root = Root( + classes: [], + apis: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator testGenerator = DartGenerator(); testGenerator.generateTest( @@ -1522,7 +1764,9 @@ name: foobar ); final String code = sink.toString(); expect( - code, contains("import 'package:$outputPackageName/foo/bar.dart';")); + code, + contains("import 'package:$outputPackageName/foo/bar.dart';"), + ); } finally { tempDir.deleteSync(recursive: true); } @@ -1562,9 +1806,9 @@ name: foobar ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -1572,15 +1816,17 @@ name: foobar documentationComments: [comments[count++]], fields: [ NamedType( - documentationComments: [comments[count++]], - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), - name: 'field1'), + documentationComments: [comments[count++]], + type: const TypeDeclaration( + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ), ], @@ -1589,7 +1835,7 @@ name: foobar name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -1617,46 +1863,56 @@ name: foobar }); test('creates custom codecs', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: emptyClass, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: emptyClass, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: emptyClass, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( @@ -1673,23 +1929,26 @@ name: foobar final Root root = Root( apis: [ AstHostApi( - name: 'Api', - dartHostTestHandler: 'ApiMock', - methods: [ - Method( - name: 'doit', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Enum', - isNullable: false, - associatedEnum: emptyEnum, - ), - name: 'anEnum') - ]) - ]) + name: 'Api', + dartHostTestHandler: 'ApiMock', + methods: [ + Method( + name: 'doit', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Enum', + isNullable: false, + associatedEnum: emptyEnum, + ), + name: 'anEnum', + ), + ], + ), + ], + ), ], classes: [], enums: [ @@ -1699,17 +1958,14 @@ name: foobar EnumMember(name: 'one'), EnumMember(name: 'two'), ], - ) + ), ], ); final StringBuffer sink = StringBuffer(); const DartGenerator testGenerator = DartGenerator(); testGenerator.generateTest( - const InternalDartOptions( - dartOut: 'code.dart', - testOut: 'test.dart', - ), + const InternalDartOptions(dartOut: 'code.dart', testOut: 'test.dart'), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -1718,23 +1974,30 @@ name: foobar final String testCode = sink.toString(); expect(testCode, contains('final Enum? arg_anEnum = (args[0] as Enum?);')); - expect(testCode, - contains('return value == null ? null : Enum.values[value];')); + expect( + testCode, + contains('return value == null ? null : Enum.values[value];'), + ); expect(testCode, contains('writeValue(buffer, value.index);')); }); test('connection error contains channel name', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'method', - location: ApiLocation.host, - parameters: [], - returnType: - const TypeDeclaration(baseName: 'Output', isNullable: false), - ) - ]) + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'method', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'Output', + isNullable: false, + ), + ), + ], + ), ], classes: [], enums: [], @@ -1750,27 +2013,32 @@ name: foobar ); final String code = sink.toString(); expect( - code, contains('throw _createConnectionError(pigeonVar_channelName);')); + code, + contains('throw _createConnectionError(pigeonVar_channelName);'), + ); expect( - code, - contains( - '\'Unable to establish connection on channel: "\$channelName".\'')); + code, + contains( + '\'Unable to establish connection on channel: "\$channelName".\'', + ), + ); }); test('generate wrapResponse if is generating tests', () { final Root root = Root( apis: [ AstHostApi( - name: 'Api', - dartHostTestHandler: 'ApiMock', - methods: [ - Method( - name: 'foo', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [], - ) - ]) + name: 'Api', + dartHostTestHandler: 'ApiMock', + methods: [ + Method( + name: 'foo', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -1779,9 +2047,7 @@ name: foobar final StringBuffer mainCodeSink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( - const InternalDartOptions( - testOut: 'test.dart', - ), + const InternalDartOptions(testOut: 'test.dart'), root, mainCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -1793,16 +2059,20 @@ name: foobar test('writes custom int codec without custom types', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], diff --git a/packages/pigeon/test/functional_test.dart b/packages/pigeon/test/functional_test.dart index 62ee434a6b0..f32980dc3fd 100644 --- a/packages/pigeon/test/functional_test.dart +++ b/packages/pigeon/test/functional_test.dart @@ -9,8 +9,10 @@ void main() { test('indexMap', () { final List items = ['a', 'b', 'c']; final List result = - indexMap(items, (int index, String value) => value + index.toString()) - .toList(); + indexMap( + items, + (int index, String value) => value + index.toString(), + ).toList(); expect(result[0], 'a0'); expect(result[1], 'b1'); expect(result[2], 'c2'); @@ -44,13 +46,18 @@ void main() { test('map2 unequal', () { expect( - () => map2([], [1, 2, 3], (int x, int y) => x * y).toList(), - throwsArgumentError); + () => map2([], [1, 2, 3], (int x, int y) => x * y).toList(), + throwsArgumentError, + ); }); 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); @@ -58,9 +65,15 @@ void main() { test('map3 unequal', () { expect( - () => map3([], [1, 2, 3], [], - (int x, int y, int z) => x * y * z).toList(), - throwsArgumentError); + () => + map3( + [], + [1, 2, 3], + [], + (int x, int y, int z) => x * y * z, + ).toList(), + throwsArgumentError, + ); }); test('wholeNumbers', () { final List result = wholeNumbers.take(3).toList(); diff --git a/packages/pigeon/test/generator_tools_test.dart b/packages/pigeon/test/generator_tools_test.dart index 34286260aab..5f0aafc66e7 100644 --- a/packages/pigeon/test/generator_tools_test.dart +++ b/packages/pigeon/test/generator_tools_test.dart @@ -37,21 +37,21 @@ bool _equalMaps(Map x, Map y) { return true; } -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); void main() { test('test merge maps', () { final Map source = { '1': '1', - '2': { - '1': '1', - '3': '3', - }, + '2': {'1': '1', '3': '3'}, '3': '3', // not modified }; final Map modification = { @@ -62,45 +62,50 @@ void main() { }; final Map expected = { '1': '2', - '2': { - '1': '1', - '2': '2', - '3': '3', - }, + '2': {'1': '1', '2': '2', '3': '3'}, '3': '3', }; expect(_equalMaps(expected, mergeMaps(source, modification)), isTrue); }); test('get codec types from all classes and enums', () { - final Root root = Root(classes: [ - Class(name: 'name', fields: [ - NamedType( - name: 'name', - type: const TypeDeclaration( - baseName: 'name', - isNullable: true, - )) - ]) - ], apis: [], enums: [ - Enum(name: 'enum', members: [ - EnumMember(name: 'enumMember'), - ]) - ]); + final Root root = Root( + classes: [ + Class( + name: 'name', + fields: [ + NamedType( + name: 'name', + type: const TypeDeclaration(baseName: 'name', isNullable: true), + ), + ], + ), + ], + apis: [], + enums: [ + Enum( + name: 'enum', + members: [EnumMember(name: 'enumMember')], + ), + ], + ); final List types = getEnumeratedTypes(root).toList(); expect(types.length, 2); }); test('getEnumeratedTypes:ed type arguments', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'foo', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: TypeDeclaration( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'foo', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: TypeDeclaration( isNullable: false, baseName: 'List', typeArguments: [ @@ -108,134 +113,170 @@ void main() { baseName: 'Foo', isNullable: true, associatedClass: emptyClass, - ) - ])), + ), + ], + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Foo', fields: [ - NamedType( - name: 'bar', - type: TypeDeclaration( - baseName: 'Bar', - isNullable: true, - associatedClass: emptyClass, - )), - ]), - Class(name: 'Bar', fields: [ - NamedType( - name: 'value', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )) - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Foo', + fields: [ + NamedType( + name: 'bar', + type: TypeDeclaration( + baseName: 'Bar', + isNullable: true, + associatedClass: emptyClass, + ), + ), + ], + ), + Class( + name: 'Bar', + fields: [ + NamedType( + name: 'value', + type: const TypeDeclaration(baseName: 'int', isNullable: true), + ), + ], + ), + ], + enums: [], + ); final List classes = getEnumeratedTypes(root).toList(); expect(classes.length, 2); expect( - classes.where((EnumeratedType element) => element.name == 'Foo').length, - 1); + classes.where((EnumeratedType element) => element.name == 'Foo').length, + 1, + ); expect( - classes.where((EnumeratedType element) => element.name == 'Bar').length, - 1); + classes.where((EnumeratedType element) => element.name == 'Bar').length, + 1, + ); }); test('getEnumeratedTypes: Object', () { - final Root root = Root(apis: [ - AstFlutterApi( - name: 'Api1', - methods: [ - Method( - name: 'foo', - location: ApiLocation.flutter, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api1', + methods: [ + Method( + name: 'foo', + location: ApiLocation.flutter, + parameters: [ + Parameter( name: 'x', type: const TypeDeclaration( - isNullable: false, - baseName: 'List', - typeArguments: [ - TypeDeclaration(baseName: 'Object', isNullable: true) - ])), - ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ], - ), - ], classes: [ - Class(name: 'Foo', fields: [ - NamedType( - name: 'bar', - type: const TypeDeclaration(baseName: 'int', isNullable: true)), - ]), - ], enums: []); + isNullable: false, + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Foo', + fields: [ + NamedType( + name: 'bar', + type: const TypeDeclaration(baseName: 'int', isNullable: true), + ), + ], + ), + ], + enums: [], + ); final List classes = getEnumeratedTypes(root).toList(); expect(classes.length, 1); expect( - classes.where((EnumeratedType element) => element.name == 'Foo').length, - 1); + classes.where((EnumeratedType element) => element.name == 'Foo').length, + 1, + ); }); test('getEnumeratedTypes:ue entries', () { - final Root root = Root(apis: [ - AstFlutterApi( - name: 'Api1', - methods: [ - Method( - name: 'foo', - location: ApiLocation.flutter, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api1', + methods: [ + Method( + name: 'foo', + location: ApiLocation.flutter, + parameters: [ + Parameter( name: 'x', type: TypeDeclaration( isNullable: false, baseName: 'Foo', associatedClass: emptyClass, - )), - ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ], - ), - AstHostApi( - name: 'Api2', - methods: [ - Method( - name: 'foo', - location: ApiLocation.host, - parameters: [ - Parameter( + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + AstHostApi( + name: 'Api2', + methods: [ + Method( + name: 'foo', + location: ApiLocation.host, + parameters: [ + Parameter( name: 'x', type: TypeDeclaration( isNullable: false, baseName: 'Foo', associatedClass: emptyClass, - )), - ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ], - ) - ], classes: [ - Class(name: 'Foo', fields: [ - NamedType( - name: 'bar', - type: const TypeDeclaration(baseName: 'int', isNullable: true)), - ]), - ], enums: []); + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Foo', + fields: [ + NamedType( + name: 'bar', + type: const TypeDeclaration(baseName: 'int', isNullable: true), + ), + ], + ), + ], + enums: [], + ); final List classes = getEnumeratedTypes(root).toList(); expect(classes.length, 1); expect( - classes.where((EnumeratedType element) => element.name == 'Foo').length, - 1); + classes.where((EnumeratedType element) => element.name == 'Foo').length, + 1, + ); }); test('deduces package name successfully', () { - final String? dartPackageName = - deducePackageName('./pigeons/core_tests.dart'); + final String? dartPackageName = deducePackageName( + './pigeons/core_tests.dart', + ); expect(dartPackageName, 'pigeon'); }); @@ -354,39 +395,52 @@ void main() { }); test( - 'recursiveFindAllInterfacesApis throws error if api recursively implements itself', - () { - final AstProxyApi a = AstProxyApi( - name: 'A', - methods: [], - constructors: [], - fields: [], - ); - final AstProxyApi b = AstProxyApi( - name: 'B', - methods: [], - constructors: [], - fields: [], - ); - final AstProxyApi c = AstProxyApi( - name: 'C', - methods: [], - constructors: [], - fields: [], - ); + 'recursiveFindAllInterfacesApis throws error if api recursively implements itself', + () { + final AstProxyApi a = AstProxyApi( + name: 'A', + methods: [], + constructors: [], + fields: [], + ); + final AstProxyApi b = AstProxyApi( + name: 'B', + methods: [], + constructors: [], + fields: [], + ); + final AstProxyApi c = AstProxyApi( + name: 'C', + methods: [], + constructors: [], + fields: [], + ); - a.interfaces = { - TypeDeclaration(baseName: 'B', isNullable: false, associatedProxyApi: b), - }; - b.interfaces = { - TypeDeclaration(baseName: 'C', isNullable: false, associatedProxyApi: c), - }; - c.interfaces = { - TypeDeclaration(baseName: 'A', isNullable: false, associatedProxyApi: a), - }; + a.interfaces = { + TypeDeclaration( + baseName: 'B', + isNullable: false, + associatedProxyApi: b, + ), + }; + b.interfaces = { + TypeDeclaration( + baseName: 'C', + isNullable: false, + associatedProxyApi: c, + ), + }; + c.interfaces = { + TypeDeclaration( + baseName: 'A', + isNullable: false, + associatedProxyApi: a, + ), + }; - expect(() => a.apisOfInterfaces(), throwsArgumentError); - }); + expect(() => a.apisOfInterfaces(), throwsArgumentError); + }, + ); test('findHighestApiRequirement', () { final TypeDeclaration typeWithoutMinApi = TypeDeclaration( @@ -424,22 +478,22 @@ void main() { final ({TypeDeclaration type, int version})? result = findHighestApiRequirement( - [ - typeWithoutMinApi, - typeWithMinApi, - typeWithHighestMinApi, - ], - onGetApiRequirement: (TypeDeclaration type) { - if (type == typeWithMinApi) { - return 1; - } else if (type == typeWithHighestMinApi) { - return 2; - } + [ + typeWithoutMinApi, + typeWithMinApi, + typeWithHighestMinApi, + ], + onGetApiRequirement: (TypeDeclaration type) { + if (type == typeWithMinApi) { + return 1; + } else if (type == typeWithHighestMinApi) { + return 2; + } - return null; - }, - onCompare: (int one, int two) => one.compareTo(two), - ); + return null; + }, + onCompare: (int one, int two) => one.compareTo(two), + ); expect(result?.type, typeWithHighestMinApi); expect(result?.version, 2); @@ -449,13 +503,11 @@ void main() { final StringBuffer buffer = StringBuffer(); final Indent indent = Indent(buffer); - indent.format( - ''' + indent.format(''' void myMethod() { print('hello'); - }''', - ); + }'''); expect(buffer.toString(), ''' void myMethod() { diff --git a/packages/pigeon/test/gobject_generator_test.dart b/packages/pigeon/test/gobject_generator_test.dart index 103fe3d138c..10d13d79447 100644 --- a/packages/pigeon/test/gobject_generator_test.dart +++ b/packages/pigeon/test/gobject_generator_test.dart @@ -11,98 +11,121 @@ const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { test('gen one api', () { - final Class inputClass = Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ]); - final Class outputClass = Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output') - ]); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: inputClass, + final Class inputClass = Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ); + final Class outputClass = Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: inputClass, + ), + name: 'input', ), - name: 'input') + ], + location: ApiLocation.host, + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: outputClass, + ), + ), ], - location: ApiLocation.host, - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: outputClass, - ), - ) - ]) - ], classes: [ - inputClass, - outputClass - ], enums: []); + ), + ], + classes: [inputClass, outputClass], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect( - code, - contains( - 'G_DECLARE_FINAL_TYPE(TestPackageInput, test_package_input, TEST_PACKAGE, INPUT, GObject)')); + code, + contains( + 'G_DECLARE_FINAL_TYPE(TestPackageInput, test_package_input, TEST_PACKAGE, INPUT, GObject)', + ), + ); expect( - code, - contains( - 'G_DECLARE_FINAL_TYPE(TestPackageOutput, test_package_output, TEST_PACKAGE, OUTPUT, GObject)')); + code, + contains( + 'G_DECLARE_FINAL_TYPE(TestPackageOutput, test_package_output, TEST_PACKAGE, OUTPUT, GObject)', + ), + ); } { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect( - code, - contains( - 'static void test_package_input_init(TestPackageInput* self) {')); + code, + contains( + 'static void test_package_input_init(TestPackageInput* self) {', + ), + ); expect( - code, - contains( - 'static void test_package_output_init(TestPackageOutput* self) {')); + code, + contains( + 'static void test_package_output_init(TestPackageOutput* self) {', + ), + ); expect( - code, - contains( - 'static void test_package_api_init(TestPackageApi* self) {')); + code, + contains('static void test_package_api_init(TestPackageApi* self) {'), + ); // See https://github.com/flutter/flutter/issues/153083. If a private type // is ever needed, this should be updated to ensure that any type declared // in the implementation file has a corresponding _IS_ call in the file. @@ -111,155 +134,187 @@ void main() { }); test('naming follows style', () { - final Class inputClass = Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'inputField') - ]); - final Class outputClass = Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'outputField') - ]); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: inputClass, + final Class inputClass = Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'inputField', + ), + ], + ); + final Class outputClass = Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'outputField', + ), + ], + ); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: inputClass, + ), + name: 'someInput', ), - name: 'someInput') + ], + location: ApiLocation.host, + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: outputClass, + ), + ), ], - location: ApiLocation.host, - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: outputClass, - ), - ) - ]) - ], classes: [ - inputClass, - outputClass - ], enums: []); + ), + ], + classes: [inputClass, outputClass], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect( - code, - contains( - ' TestPackageApiDoSomethingResponse* (*do_something)(TestPackageInput* some_input, gpointer user_data);')); + code, + contains( + ' TestPackageApiDoSomethingResponse* (*do_something)(TestPackageInput* some_input, gpointer user_data);', + ), + ); expect( - code, - contains( - 'gboolean test_package_input_get_input_field(TestPackageInput* object);')); + code, + contains( + 'gboolean test_package_input_get_input_field(TestPackageInput* object);', + ), + ); expect( - code, - contains( - 'gboolean test_package_output_get_output_field(TestPackageOutput* object);')); + code, + contains( + 'gboolean test_package_output_get_output_field(TestPackageOutput* object);', + ), + ); } { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, ); - generator.generate(generatorOptions, root, sink, - dartPackageName: DEFAULT_PACKAGE_NAME); final String code = sink.toString(); expect( - code, - contains( - 'gboolean test_package_input_get_input_field(TestPackageInput* self) {')); + code, + contains( + 'gboolean test_package_input_get_input_field(TestPackageInput* self) {', + ), + ); expect( - code, - contains( - 'gboolean test_package_output_get_output_field(TestPackageOutput* self) {')); + code, + contains( + 'gboolean test_package_output_get_output_field(TestPackageOutput* self) {', + ), + ); } }); test('Spaces before {', () { - final Class inputClass = Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ]); - final Class outputClass = Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output') - ]); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: inputClass, + final Class inputClass = Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ); + final Class outputClass = Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: inputClass, + ), + name: 'input', ), - name: 'input') + ], + returnType: TypeDeclaration( + baseName: 'Output', + isNullable: false, + associatedClass: outputClass, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - isNullable: false, - associatedClass: outputClass, - ), - ) - ]) - ], classes: [ - inputClass, - outputClass - ], enums: []); + ), + ], + classes: [inputClass, outputClass], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -275,13 +330,13 @@ void main() { const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -295,35 +350,46 @@ void main() { }); test('include blocks follow style', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'String', + isNullable: true, + ), + name: 'input', ), - name: 'input') + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -331,22 +397,25 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, contains(''' + expect( + code, + contains(''' #include -''')); +'''), + ); } { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: 'a_header.h', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: 'a_header.h', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -354,81 +423,88 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, contains(''' + expect( + code, + contains(''' #include "a_header.h" -''')); +'''), + ); } }); test('data classes handle non-nullable fields', () { - final Class nestedClass = Class(name: 'Nested', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'nestedValue'), - ]); - final Class inputClass = Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'nonNullableBool'), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - name: 'nonNullableInt'), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - name: 'nonNullableString'), - NamedType( + final Class nestedClass = Class( + name: 'Nested', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'nestedValue', + ), + ], + ); + final Class inputClass = Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'nonNullableBool', + ), + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'nonNullableInt', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: false), + name: 'nonNullableString', + ), + NamedType( type: TypeDeclaration( baseName: 'Nested', isNullable: false, associatedClass: nestedClass, ), - name: 'nonNullableNested'), - ]); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - isNullable: false, - associatedClass: inputClass, + name: 'nonNullableNested', + ), + ], + ); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + isNullable: false, + associatedClass: inputClass, + ), + name: 'someInput', ), - name: 'someInput') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - nestedClass, - inputClass - ], enums: []); + ), + ], + classes: [nestedClass, inputClass], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -438,22 +514,24 @@ void main() { final String code = sink.toString(); expect( - code, - contains( - 'TestPackageNested* test_package_nested_new(gboolean nested_value);')); + code, + contains( + 'TestPackageNested* test_package_nested_new(gboolean nested_value);', + ), + ); } { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -463,110 +541,109 @@ void main() { final String code = sink.toString(); expect( - code, - contains( - 'TestPackageNested* test_package_nested_new(gboolean nested_value) {')); + code, + contains( + 'TestPackageNested* test_package_nested_new(gboolean nested_value) {', + ), + ); } }); test('host non-nullable return types map correctly', () { - final Class returnDataClass = Class(name: 'ReturnData', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'returnBool', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - ), - Method( - name: 'returnInt', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - Method( - name: 'returnString', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - ), - Method( - name: 'returnList', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration( - baseName: 'String', - isNullable: true, - ) - ], - isNullable: false, - ), + final Class returnDataClass = Class( + name: 'ReturnData', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', ), - Method( - name: 'returnMap', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration( - baseName: 'Map', - typeArguments: [ - TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'returnBool', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + ), + Method( + name: 'returnInt', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, ), - TypeDeclaration( + ), + Method( + name: 'returnString', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( baseName: 'String', - isNullable: true, - ) - ], - isNullable: false, - ), - ), - Method( - name: 'returnDataClass', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'ReturnData', - isNullable: false, - associatedClass: returnDataClass, - ), + isNullable: false, + ), + ), + Method( + name: 'returnList', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + ], + isNullable: false, + ), + ), + Method( + name: 'returnMap', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration( + baseName: 'Map', + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'String', isNullable: true), + ], + isNullable: false, + ), + ), + Method( + name: 'returnDataClass', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'ReturnData', + isNullable: false, + associatedClass: returnDataClass, + ), + ), + ], ), - ]) - ], classes: [ - returnDataClass - ], enums: []); + ], + classes: [returnDataClass], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -575,128 +652,154 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - ' TestPackageApiReturnBoolResponse* (*return_bool)(gpointer user_data);')); + code, + contains( + ' TestPackageApiReturnBoolResponse* (*return_bool)(gpointer user_data);', + ), + ); expect( - code, - contains( - ' TestPackageApiReturnIntResponse* (*return_int)(gpointer user_data);')); + code, + contains( + ' TestPackageApiReturnIntResponse* (*return_int)(gpointer user_data);', + ), + ); expect( - code, - contains( - ' TestPackageApiReturnStringResponse* (*return_string)(gpointer user_data);')); + code, + contains( + ' TestPackageApiReturnStringResponse* (*return_string)(gpointer user_data);', + ), + ); expect( - code, - contains( - ' TestPackageApiReturnListResponse* (*return_list)(gpointer user_data);')); + code, + contains( + ' TestPackageApiReturnListResponse* (*return_list)(gpointer user_data);', + ), + ); expect( - code, - contains( - ' TestPackageApiReturnMapResponse* (*return_map)(gpointer user_data);')); + code, + contains( + ' TestPackageApiReturnMapResponse* (*return_map)(gpointer user_data);', + ), + ); expect( - code, - contains( - ' TestPackageApiReturnDataClassResponse* (*return_data_class)(gpointer user_data);')); + code, + contains( + ' TestPackageApiReturnDataClassResponse* (*return_data_class)(gpointer user_data);', + ), + ); } }); test('host non-nullable arguments map correctly', () { - final Class parameterObjectClass = - Class(name: 'ParameterObject', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aValue'), - ]); + final Class parameterObjectClass = Class( + name: 'ParameterObject', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aValue', + ), + ], + ); final Class objectClass = Class(name: 'Object', fields: []); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - )), - Parameter( - name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - )), - Parameter( - name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - )), - Parameter( - name: 'aList', - type: TypeDeclaration( - baseName: 'List', - typeArguments: [ - TypeDeclaration( - baseName: 'Object', - isNullable: true, - associatedClass: objectClass, - ) - ], - isNullable: false, - )), - Parameter( - name: 'aMap', - type: TypeDeclaration( - baseName: 'Map', - typeArguments: [ - const TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration( - baseName: 'Object', - isNullable: true, - associatedClass: objectClass, - ), - ], - isNullable: false, - )), - Parameter( - name: 'anObject', - type: TypeDeclaration( - baseName: 'ParameterObject', - isNullable: false, - associatedClass: parameterObjectClass, - )), - Parameter( - name: 'aGenericObject', - type: TypeDeclaration( - baseName: 'Object', - isNullable: false, - associatedClass: objectClass, - )), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'aBool', + type: const TypeDeclaration( + baseName: 'bool', + isNullable: false, + ), + ), + Parameter( + name: 'anInt', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Parameter( + name: 'aString', + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + ), + Parameter( + name: 'aList', + type: TypeDeclaration( + baseName: 'List', + typeArguments: [ + TypeDeclaration( + baseName: 'Object', + isNullable: true, + associatedClass: objectClass, + ), + ], + isNullable: false, + ), + ), + Parameter( + name: 'aMap', + type: TypeDeclaration( + baseName: 'Map', + typeArguments: [ + const TypeDeclaration( + baseName: 'String', + isNullable: true, + ), + TypeDeclaration( + baseName: 'Object', + isNullable: true, + associatedClass: objectClass, + ), + ], + isNullable: false, + ), + ), + Parameter( + name: 'anObject', + type: TypeDeclaration( + baseName: 'ParameterObject', + isNullable: false, + associatedClass: parameterObjectClass, + ), + ), + Parameter( + name: 'aGenericObject', + type: TypeDeclaration( + baseName: 'Object', + isNullable: false, + associatedClass: objectClass, + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), ), - ]) - ], classes: [ - parameterObjectClass, - objectClass - ], enums: []); + ], + classes: [parameterObjectClass, objectClass], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -705,22 +808,24 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - ' TestPackageApiDoSomethingResponse* (*do_something)(gboolean a_bool, int64_t an_int, const gchar* a_string, FlValue* a_list, FlValue* a_map, TestPackageParameterObject* an_object, TestPackageObject* a_generic_object, gpointer user_data);')); + code, + contains( + ' TestPackageApiDoSomethingResponse* (*do_something)(gboolean a_bool, int64_t an_int, const gchar* a_string, FlValue* a_list, FlValue* a_map, TestPackageParameterObject* an_object, TestPackageObject* a_generic_object, gpointer user_data);', + ), + ); } { final StringBuffer sink = StringBuffer(); const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -729,9 +834,11 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - ' g_autoptr(TestPackageApiDoSomethingResponse) response = self->vtable->do_something(a_bool, an_int, a_string, a_list, a_map, an_object, a_generic_object, self->user_data);')); + code, + contains( + ' g_autoptr(TestPackageApiDoSomethingResponse) response = self->vtable->do_something(a_bool, an_int, a_string, a_list, a_map, an_object, a_generic_object, self->user_data);', + ), + ); } }); @@ -769,9 +876,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -779,15 +886,17 @@ void main() { documentationComments: [comments[count++]], fields: [ NamedType( - documentationComments: [comments[count++]], - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), - name: 'field1'), + documentationComments: [comments[count++]], + type: const TypeDeclaration( + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ), ], @@ -796,7 +905,7 @@ void main() { name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -812,13 +921,13 @@ void main() { const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: 'foo', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: 'foo', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -833,12 +942,15 @@ void main() { }); test('generates custom class id constants', () { - final Class parameterObjectClass = - Class(name: 'ParameterObject', fields: [ - NamedType( + final Class parameterObjectClass = Class( + name: 'ParameterObject', + fields: [ + NamedType( type: const TypeDeclaration(baseName: 'bool', isNullable: false), - name: 'aValue'), - ]); + name: 'aValue', + ), + ], + ); final Class objectClass = Class(name: 'Object', fields: []); final Enum anEnum = Enum( name: 'enum', @@ -846,33 +958,38 @@ void main() { ); final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( name: 'anObject', type: TypeDeclaration( baseName: 'ParameterObject', isNullable: false, associatedClass: parameterObjectClass, - )), - Parameter( + ), + ), + Parameter( name: 'aGenericObject', type: TypeDeclaration( baseName: 'Object', isNullable: false, associatedClass: objectClass, - )), - ], - returnType: TypeDeclaration( - baseName: 'anObject', - isNullable: false, - associatedClass: parameterObjectClass, + ), + ), + ], + returnType: TypeDeclaration( + baseName: 'anObject', + isNullable: false, + associatedClass: parameterObjectClass, + ), ), - ), - ]) + ], + ), ], classes: [parameterObjectClass, objectClass], enums: [anEnum], @@ -882,13 +999,13 @@ void main() { const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -897,8 +1014,10 @@ void main() { ); final String code = sink.toString(); expect(code, contains('extern const int test_packageenum_type_id;')); - expect(code, - contains('extern const int test_package_parameter_object_type_id;')); + expect( + code, + contains('extern const int test_package_parameter_object_type_id;'), + ); expect(code, contains('extern const int test_package_object_type_id;')); } { @@ -906,13 +1025,13 @@ void main() { const GObjectGenerator generator = GObjectGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -922,8 +1041,10 @@ void main() { final String code = sink.toString(); expect(code, contains('const int test_packageenum_type_id = 129;')); - expect(code, - contains('const int test_package_parameter_object_type_id = 130;')); + expect( + code, + contains('const int test_package_parameter_object_type_id = 130;'), + ); expect(code, contains('const int test_package_object_type_id = 131;')); } }); diff --git a/packages/pigeon/test/java_generator_test.dart b/packages/pigeon/test/java_generator_test.dart index 8ac76b14c71..fb4a05473ad 100644 --- a/packages/pigeon/test/java_generator_test.dart +++ b/packages/pigeon/test/java_generator_test.dart @@ -9,12 +9,15 @@ import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); final Enum emptyEnum = Enum( name: 'enumName', @@ -27,11 +30,9 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'field1'), + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), ], ); final Root root = Root( @@ -40,8 +41,10 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -72,8 +75,10 @@ void main() { enums: [anEnum], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -96,11 +101,9 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'field1') + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), ], ); final Root root = Root( @@ -110,7 +113,10 @@ void main() { ); final StringBuffer sink = StringBuffer(); const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', package: 'com.google.foobar', javaOut: ''); + className: 'Messages', + package: 'com.google.foobar', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -125,51 +131,59 @@ void main() { test('gen one host api', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), ), - ) - ]) + ], + ), ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output') - ]) + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), ], enums: [], containsHostApi: true, ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -182,77 +196,90 @@ void main() { expect(code, matches('Output.*doSomething.*Input')); expect(code, contains('channel.setMessageHandler(null)')); expect( - code, - contains( - 'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer)')); + code, + contains( + 'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer)', + ), + ); expect( - code, - contains( - 'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value)')); + code, + contains( + 'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value)', + ), + ); expect( - code, - contains(RegExp( - r'@NonNull\s*protected static ArrayList wrapError\(@NonNull Throwable exception\)'))); + code, + contains( + RegExp( + r'@NonNull\s*protected static ArrayList wrapError\(@NonNull Throwable exception\)', + ), + ), + ); expect(code, isNot(contains('ArrayList '))); }); test('all the simple datatypes header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'aBool', ), - name: 'aBool'), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'aInt', ), - name: 'aInt'), - NamedType( - type: const TypeDeclaration( - baseName: 'double', - isNullable: true, + NamedType( + type: const TypeDeclaration(baseName: 'double', isNullable: true), + name: 'aDouble', ), - name: 'aDouble'), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'aString', ), - name: 'aString'), - NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Uint8List', + isNullable: true, + ), + name: 'aUint8List', ), - name: 'aUint8List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Int32List', + isNullable: true, + ), + name: 'aInt32List', ), - name: 'aInt32List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Int64List', + isNullable: true, + ), + name: 'aInt64List', ), - name: 'aInt64List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Float64List', + isNullable: true, + ), + name: 'aFloat64List', ), - name: 'aFloat64List'), - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -272,48 +299,60 @@ void main() { }); test('gen one flutter api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -327,36 +366,47 @@ void main() { }); test('gen host void api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -370,36 +420,47 @@ void main() { }); test('gen flutter void return api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -409,39 +470,51 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'public void doSomething(@NonNull Input arg0Arg, @NonNull VoidResult result)')); + code, + contains( + 'public void doSomething(@NonNull Input arg0Arg, @NonNull VoidResult result)', + ), + ); expect(code, contains('result.success();')); }); test('gen host void argument api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -455,32 +528,42 @@ void main() { }); test('gen flutter void argument api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -489,25 +572,34 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - contains('public void doSomething(@NonNull Result result)')); + expect( + code, + contains('public void doSomething(@NonNull Result result)'), + ); expect(code, contains(RegExp(r'channel.send\(\s*null'))); }); test('gen list', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'List', isNullable: true), + name: 'field1', ), - name: 'field1') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -521,19 +613,26 @@ void main() { }); test('gen map', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'Map', isNullable: true), + name: 'field1', ), - name: 'field1') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -551,23 +650,22 @@ void main() { name: 'Outer', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: true, - ), - name: 'nested') + type: TypeDeclaration( + baseName: 'Nested', + associatedClass: emptyClass, + isNullable: true, + ), + name: 'nested', + ), ], ); final Class nestedClass = Class( name: 'Nested', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'data') + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'data', + ), ], ); final Root root = Root( @@ -576,8 +674,10 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -594,49 +694,61 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: 'arg', ), - name: 'arg') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -649,57 +761,71 @@ void main() { expect(code, contains('public interface Result {')); expect(code, contains('void error(@NonNull Throwable error);')); expect( - code, - contains( - 'void doSomething(@NonNull Input arg, @NonNull Result result);')); + code, + contains( + 'void doSomething(@NonNull Input arg, @NonNull Result result);', + ), + ); expect(code, contains('api.doSomething(argArg, resultCallback);')); expect(code, contains('channel.setMessageHandler(null)')); }); test('gen one async Flutter Api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -725,12 +851,13 @@ void main() { name: 'EnumClass', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), - name: 'enum1'), + type: TypeDeclaration( + baseName: 'Enum1', + associatedEnum: emptyEnum, + isNullable: true, + ), + name: 'enum1', + ), ], ); final Root root = Root( @@ -739,8 +866,10 @@ void main() { enums: [anEnum], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -762,32 +891,45 @@ void main() { }); test('primitive enum host', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( - name: 'bar', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( - name: 'foo', - type: TypeDeclaration( - baseName: 'Foo', - isNullable: true, - associatedEnum: emptyEnum, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Bar', + methods: [ + Method( + name: 'bar', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( + name: 'foo', + type: TypeDeclaration( + baseName: 'Foo', + isNullable: true, + associatedEnum: emptyEnum, + ), ), - ) - ]) - ]) - ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) - ]); + ], + ), + ], + ), + ], + classes: [], + enums: [ + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -798,13 +940,17 @@ void main() { final String code = sink.toString(); expect(code, contains('public enum Foo')); expect( - code, - contains( - 'return value == null ? null : Foo.values()[((Long) value).intValue()];')); + code, + contains( + 'return value == null ? null : Foo.values()[((Long) value).intValue()];', + ), + ); expect( - code, - contains( - 'writeValue(stream, value == null ? null : ((Foo) value).index);')); + code, + contains( + 'writeValue(stream, value == null ? null : ((Foo) value).index);', + ), + ); expect(code, contains('Foo fooArg = (Foo) args.get(0);')); }); @@ -836,13 +982,15 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'List', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -851,8 +999,10 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -870,14 +1020,16 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'String', isNullable: true), - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'String', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -886,8 +1038,10 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -903,29 +1057,37 @@ void main() { test('host generics argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -940,29 +1102,37 @@ void main() { test('flutter generics argument', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -977,25 +1147,32 @@ void main() { test('host generics return', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1011,25 +1188,32 @@ void main() { test('flutter generics return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1039,29 +1223,39 @@ void main() { ); final String code = sink.toString(); expect( - code, contains('public void doit(@NonNull Result> result)')); + code, + contains('public void doit(@NonNull Result> result)'), + ); expect(code, contains('List output = (List) listReply.get(0)')); }); test('flutter int return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, - returnType: - const TypeDeclaration(baseName: 'int', isNullable: false), + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), parameters: [], - isAsynchronous: true) - ]) + isAsynchronous: true, + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1075,28 +1269,46 @@ void main() { }); test('host multiple args', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1107,32 +1319,46 @@ void main() { final String code = sink.toString(); expect(code, contains('class Messages')); expect(code, contains('Long add(@NonNull Long x, @NonNull Long y)')); - expect(code, - contains('ArrayList args = (ArrayList) message;')); + expect( + code, + contains('ArrayList args = (ArrayList) message;'), + ); expect(code, contains('Long xArg = (Long) args.get(0)')); expect(code, contains('Long yArg = (Long) args.get(1)')); expect(code, contains('Long output = api.add(xArg, yArg)')); }); test('if host argType is Object not cast', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'objectTest', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: const TypeDeclaration( - isNullable: false, baseName: 'Object')), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'objectTest', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'Object', + ), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Api', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Api', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1145,28 +1371,46 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1179,34 +1423,55 @@ void main() { expect(code, contains('BasicMessageChannel channel')); expect(code, contains('Long output')); expect( - code, - contains( - 'public void add(@NonNull Long xArg, @NonNull Long yArg, @NonNull Result result)')); + code, + contains( + 'public void add(@NonNull Long xArg, @NonNull Long yArg, @NonNull Result result)', + ), + ); expect( - code, - contains(RegExp( - r'channel.send\(\s*new ArrayList<>\(Arrays.asList\(xArg, yArg\)\),\s*channelReply ->'))); + code, + contains( + RegExp( + r'channel.send\(\s*new ArrayList<>\(Arrays.asList\(xArg, yArg\)\),\s*channelReply ->', + ), + ), + ); }); test('flutter single args', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'send', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'send', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1216,31 +1481,41 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains(RegExp( - r'channel.send\(\s*new ArrayList<>\(Collections.singletonList\(xArg\)\),\s*channelReply ->'))); + code, + contains( + RegExp( + r'channel.send\(\s*new ArrayList<>\(Collections.singletonList\(xArg\)\),\s*channelReply ->', + ), + ), + ); }); test('return nullable host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1255,8 +1530,10 @@ void main() { test('return nullable host async', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( @@ -1264,15 +1541,19 @@ void main() { isNullable: true, ), isAsynchronous: true, - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1288,27 +1569,34 @@ void main() { test('nullable argument host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1323,27 +1611,34 @@ void main() { test('nullable argument flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1353,36 +1648,45 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'public void doit(@Nullable Long fooArg, @NonNull VoidResult result) {')); + code, + contains( + 'public void doit(@Nullable Long fooArg, @NonNull VoidResult result) {', + ), + ); }); test('background platform channel', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), ], - taskQueueType: TaskQueueType.serialBackgroundThread) - ]) + taskQueueType: TaskQueueType.serialBackgroundThread, + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1392,20 +1696,23 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();')); + code, + contains( + 'BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();', + ), + ); expect( - code, - contains(RegExp( - r'new BasicMessageChannel<>\(\s*binaryMessenger, "dev.flutter.pigeon.test_package.Api.doit" \+ messageChannelSuffix, getCodec\(\), taskQueue\)'))); + code, + contains( + RegExp( + r'new BasicMessageChannel<>\(\s*binaryMessenger, "dev.flutter.pigeon.test_package.Api.doit" \+ messageChannelSuffix, getCodec\(\), taskQueue\)', + ), + ), + ); }); test('generated annotation', () { - final Class classDefinition = Class( - name: 'Foobar', - fields: [], - ); + final Class classDefinition = Class(name: 'Foobar', fields: []); final Root root = Root( apis: [], classes: [classDefinition], @@ -1429,18 +1736,17 @@ void main() { }); test('no generated annotation', () { - final Class classDefinition = Class( - name: 'Foobar', - fields: [], - ); + final Class classDefinition = Class(name: 'Foobar', fields: []); final Root root = Root( apis: [], classes: [classDefinition], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1449,8 +1755,10 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - isNot(contains('@javax.annotation.Generated("dev.flutter.pigeon")'))); + expect( + code, + isNot(contains('@javax.annotation.Generated("dev.flutter.pigeon")')), + ); }); test('transfers documentation comments', () { @@ -1487,9 +1795,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -1499,12 +1807,13 @@ void main() { NamedType( documentationComments: [comments[count++]], type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'field1', ), ], @@ -1515,7 +1824,7 @@ void main() { name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -1528,8 +1837,10 @@ void main() { ], ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1541,57 +1852,72 @@ void main() { for (final String comment in comments) { // This regex finds the comment only between the open and close comment block expect( - RegExp(r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', dotAll: true) - .hasMatch(code), - true); + RegExp( + r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', + dotAll: true, + ).hasMatch(code), + true, + ); } expect(code, isNot(contains('*//'))); }); test('creates custom codecs', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1612,8 +1938,10 @@ void main() { containsHostApi: true, ); final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, @@ -1644,9 +1972,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], @@ -1654,8 +1982,10 @@ void main() { ); final StringBuffer sink = StringBuffer(); const JavaGenerator generator = JavaGenerator(); - const InternalJavaOptions javaOptions = - InternalJavaOptions(className: 'Messages', javaOut: ''); + const InternalJavaOptions javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); generator.generate( javaOptions, root, @@ -1665,8 +1995,10 @@ void main() { final String code = sink.toString(); expect(code, contains('createConnectionError(channelName)')); expect( - code, - contains( - 'return new FlutterError("channel-error", "Unable to establish connection on channel: " + channelName + ".", "");')); + code, + contains( + 'return new FlutterError("channel-error", "Unable to establish connection on channel: " + channelName + ".", "");', + ), + ); }); } diff --git a/packages/pigeon/test/kotlin/proxy_api_test.dart b/packages/pigeon/test/kotlin/proxy_api_test.dart index 561acd364a0..26ff5be201d 100644 --- a/packages/pigeon/test/kotlin/proxy_api_test.dart +++ b/packages/pigeon/test/kotlin/proxy_api_test.dart @@ -35,11 +35,8 @@ void main() { fields: [ ApiField( name: 'someField', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ) + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ), ], methods: [ Method( @@ -52,7 +49,7 @@ void main() { isNullable: false, ), name: 'input', - ) + ), ], returnType: const TypeDeclaration( baseName: 'String', @@ -78,7 +75,7 @@ void main() { ), ), ], - ) + ), ], classes: [], enums: [], @@ -87,7 +84,9 @@ void main() { const KotlinGenerator generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions( - fileSpecificClassNameComponent: 'MyFile', kotlinOut: ''), + fileSpecificClassNameComponent: 'MyFile', + kotlinOut: '', + ), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -109,9 +108,11 @@ void main() { // Codec expect( - code, - contains( - 'private class MyFilePigeonProxyApiBaseCodec(val registrar: MyFilePigeonProxyApiRegistrar) : MyFilePigeonCodec()')); + code, + contains( + 'private class MyFilePigeonProxyApiBaseCodec(val registrar: MyFilePigeonProxyApiRegistrar) : MyFilePigeonCodec()', + ), + ); // Proxy API class expect( @@ -124,9 +125,7 @@ void main() { // Constructors expect( collapsedCode, - contains( - r'abstract fun name(someField: Long, input: Input)', - ), + contains(r'abstract fun name(someField: Long, input: Input)'), ); expect( collapsedCode, @@ -172,20 +171,24 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - superClass: TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + superClass: TypeDeclaration( + baseName: api2.name, + isNullable: false, + associatedProxyApi: api2, + ), ), - ), - api2, - ], classes: [], enums: []); + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( @@ -209,22 +212,26 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ) - }, - ), - api2, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: api2.name, + isNullable: false, + associatedProxyApi: api2, + ), + }, + ), + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( @@ -250,28 +257,32 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ), - TypeDeclaration( - baseName: api3.name, - isNullable: false, - associatedProxyApi: api3, - ), - }, - ), - api2, - api3, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: api2.name, + isNullable: false, + associatedProxyApi: api2, + ), + TypeDeclaration( + baseName: api3.name, + isNullable: false, + associatedProxyApi: api3, + ), + }, + ), + api2, + api3, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( @@ -290,12 +301,14 @@ void main() { test('empty name and no params constructor', () { final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: '', - parameters: [], - ) - ], fields: [], methods: []), + AstProxyApi( + name: 'Api', + constructors: [ + Constructor(name: '', parameters: []), + ], + fields: [], + methods: [], + ), ], classes: [], enums: [], @@ -341,57 +354,62 @@ void main() { ); final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: 'name', - parameters: [ - Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', + AstProxyApi( + name: 'Api', + constructors: [ + Constructor( + name: 'name', + parameters: [ + Parameter( + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + name: 'validType', ), - name: 'validType', - ), - Parameter( - type: TypeDeclaration( - isNullable: false, - baseName: 'AnEnum', - associatedEnum: anEnum, + Parameter( + type: TypeDeclaration( + isNullable: false, + baseName: 'AnEnum', + associatedEnum: anEnum, + ), + name: 'enumType', ), - name: 'enumType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', + Parameter( + type: const TypeDeclaration( + isNullable: false, + baseName: 'Api2', + ), + name: 'proxyApiType', ), - name: 'proxyApiType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', + Parameter( + type: const TypeDeclaration( + isNullable: true, + baseName: 'int', + ), + name: 'nullableValidType', ), - name: 'nullableValidType', - ), - Parameter( - type: TypeDeclaration( - isNullable: true, - baseName: 'AnEnum', - associatedEnum: anEnum, + Parameter( + type: TypeDeclaration( + isNullable: true, + baseName: 'AnEnum', + associatedEnum: anEnum, + ), + name: 'nullableEnumType', ), - name: 'nullableEnumType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', + Parameter( + type: const TypeDeclaration( + isNullable: true, + baseName: 'Api2', + ), + name: 'nullableProxyApiType', ), - name: 'nullableProxyApiType', - ), - ], - ) - ], fields: [], methods: []), + ], + ), + ], + fields: [], + methods: [], + ), AstProxyApi( name: 'Api2', constructors: [], @@ -460,7 +478,9 @@ void main() { const KotlinGenerator generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions( - errorClassName: 'TestError', kotlinOut: ''), + errorClassName: 'TestError', + kotlinOut: '', + ), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -477,46 +497,47 @@ void main() { }); test( - 'host platform constructor calls new instance error for required callbacks', - () { - final Root root = Root( - apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [ - Method( - name: 'aCallbackMethod', - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [], - location: ApiLocation.flutter, - ), - ], + 'host platform constructor calls new instance error for required callbacks', + () { + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [ + Method( + name: 'aCallbackMethod', + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [], + location: ApiLocation.flutter, + ), + ], + ), + ], + classes: [], + enums: [], + ); + final StringBuffer sink = StringBuffer(); + const KotlinGenerator generator = KotlinGenerator(); + generator.generate( + const InternalKotlinOptions( + errorClassName: 'TestError', + kotlinOut: '', ), - ], - classes: [], - enums: [], - ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); - generator.generate( - const InternalKotlinOptions( - errorClassName: 'TestError', kotlinOut: ''), - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final String code = sink.toString(); - final String collapsedCode = _collapseNewlineAndIndentation(code); + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final String code = sink.toString(); + final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains( - r'Result.failure( TestError("new-instance-error"', - ), - ); - }); + expect( + collapsedCode, + contains(r'Result.failure( TestError("new-instance-error"'), + ); + }, + ); }); group('Fields', () { @@ -530,10 +551,7 @@ void main() { AstProxyApi( name: 'Api', constructors: [ - Constructor( - name: 'name', - parameters: [], - ) + Constructor(name: 'name', parameters: []), ], fields: [ ApiField( @@ -750,10 +768,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect( - code, - contains(r'abstract fun aField(): Api2'), - ); + expect(code, contains(r'abstract fun aField(): Api2')); expect( code, contains( @@ -909,8 +924,9 @@ void main() { name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root(apis: [ - AstProxyApi( + final Root root = Root( + apis: [ + AstProxyApi( name: 'Api', constructors: [], fields: [], @@ -965,11 +981,13 @@ void main() { ), ], returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [], enums: [ - anEnum - ]); + ), + ], + ), + ], + classes: [], + enums: [anEnum], + ); final StringBuffer sink = StringBuffer(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( @@ -1002,55 +1020,56 @@ void main() { group('InstanceManager', () { test( - 'InstanceManager passes runnable field and not a new runnable instance', - () { - final Root root = Root( - apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - ), - ], - classes: [], - enums: [], - ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); - generator.generate( - const InternalKotlinOptions(kotlinOut: ''), - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final String code = sink.toString(); - final String collapsedCode = _collapseNewlineAndIndentation(code); + 'InstanceManager passes runnable field and not a new runnable instance', + () { + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + ), + ], + classes: [], + enums: [], + ); + final StringBuffer sink = StringBuffer(); + const KotlinGenerator generator = KotlinGenerator(); + generator.generate( + const InternalKotlinOptions(kotlinOut: ''), + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final String code = sink.toString(); + final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - code, - contains( - 'handler.removeCallbacks(releaseAllFinalizedInstancesRunnable)', - ), - ); - expect( - code, - contains( - 'handler.postDelayed(releaseAllFinalizedInstancesRunnable', - ), - ); + expect( + code, + contains( + 'handler.removeCallbacks(releaseAllFinalizedInstancesRunnable)', + ), + ); + expect( + code, + contains( + 'handler.postDelayed(releaseAllFinalizedInstancesRunnable', + ), + ); - expect( - collapsedCode, - contains( - 'private val releaseAllFinalizedInstancesRunnable = Runnable { this.releaseAllFinalizedInstances() }', - ), - ); - expect( - 'this.releaseAllFinalizedInstances()'.allMatches(code).length, - 1, - ); - }); + expect( + collapsedCode, + contains( + 'private val releaseAllFinalizedInstancesRunnable = Runnable { this.releaseAllFinalizedInstances() }', + ), + ); + expect( + 'this.releaseAllFinalizedInstances()'.allMatches(code).length, + 1, + ); + }, + ); }); }); } diff --git a/packages/pigeon/test/kotlin_generator_test.dart b/packages/pigeon/test/kotlin_generator_test.dart index 2a72e608804..91dbc1c9c7a 100644 --- a/packages/pigeon/test/kotlin_generator_test.dart +++ b/packages/pigeon/test/kotlin_generator_test.dart @@ -8,12 +8,15 @@ import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); final Enum emptyEnum = Enum( name: 'enumName', @@ -26,10 +29,7 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), name: 'field1', ), ], @@ -40,8 +40,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -59,10 +60,7 @@ 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: [], @@ -70,8 +68,9 @@ void main() { enums: [anEnum], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -121,8 +120,9 @@ void main() { ], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -143,31 +143,44 @@ void main() { }); test('primitive enum host', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( - name: 'bar', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Bar', + methods: [ + Method( + name: 'bar', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', isNullable: false, associatedEnum: emptyEnum, - )) - ]) - ]) - ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) - ]); + ), + ), + ], + ), + ], + ), + ], + classes: [], + enums: [ + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -181,51 +194,59 @@ void main() { }); test('gen one host api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: 'input', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), name: 'input', - ) + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input', - ) - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output', - ) - ]) - ], enums: []); + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -236,12 +257,17 @@ void main() { final String code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('fun doSomething(input: Input): Output')); - expect(code, contains(''' + expect( + code, + contains(''' @JvmOverloads fun setUp(binaryMessenger: BinaryMessenger, api: Api?, messageChannelSuffix: String = "") { - ''')); + '''), + ); expect(code, contains('channel.setMessageHandler')); - expect(code, contains(''' + expect( + code, + contains(''' if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List @@ -256,131 +282,122 @@ void main() { } else { channel.setMessageHandler(null) } - ''')); + '''), + ); }); test('all the simple datatypes header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), - name: 'aBool', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - name: 'aInt', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'double', - isNullable: false, - ), - name: 'aDouble', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - name: 'aString', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), - name: 'aUint8List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: false, - ), - name: 'aInt32List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: false, - ), - name: 'aInt64List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: false, - ), - name: 'aFloat64List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), - name: 'aNullableBool', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'aNullableInt', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'double', - isNullable: true, - ), - name: 'aNullableDouble', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'aNullableString', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), - name: 'aNullableUint8List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, - ), - name: 'aNullableInt32List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, - ), - name: 'aNullableInt64List', - ), - NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, - ), - name: 'aNullableFloat64List', + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: false), + name: 'aBool', + ), + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'aInt', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'double', + isNullable: false, + ), + name: 'aDouble', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: 'aString', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Uint8List', + isNullable: true, + ), + name: 'aUint8List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Int32List', + isNullable: false, + ), + name: 'aInt32List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Int64List', + isNullable: false, + ), + name: 'aInt64List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Float64List', + isNullable: false, + ), + name: 'aFloat64List', + ), + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'aNullableBool', + ), + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'aNullableInt', + ), + NamedType( + type: const TypeDeclaration(baseName: 'double', isNullable: true), + name: 'aNullableDouble', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'aNullableString', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Uint8List', + isNullable: true, + ), + name: 'aNullableUint8List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Int32List', + isNullable: true, + ), + name: 'aNullableInt32List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Int64List', + isNullable: true, + ), + name: 'aNullableInt64List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Float64List', + isNullable: true, + ), + name: 'aNullableFloat64List', + ), + ], ), - ]), - ], enums: []); + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -408,51 +425,59 @@ void main() { }); test('gen one flutter api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), - name: '', - ) + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input', - ) - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output', - ) - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -462,45 +487,55 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'class Api(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "")')); + code, + contains( + 'class Api(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "")', + ), + ); expect(code, matches('fun doSomething.*Input.*Output')); }); test('gen host void api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, - ), - name: '', - ) + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input', - ) - ]), - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -514,38 +549,46 @@ void main() { }); test('gen flutter void return api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, - ), - name: '', - ) + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input', - ) - ]), - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -553,41 +596,49 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - expect(code, contains('callback: (Result) -> Unit')); - expect(code, contains('callback(Result.success(Unit))')); - // Lines should not end in semicolons. - expect(code, isNot(contains(RegExp(r';\n')))); - }); - - test('gen host void argument api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output', - ) - ]), - ], enums: []); + final String code = sink.toString(); + expect(code, contains('callback: (Result) -> Unit')); + expect(code, contains('callback(Result.success(Unit))')); + // Lines should not end in semicolons. + expect(code, isNot(contains(RegExp(r';\n')))); + }); + + test('gen host void argument api', () { + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -603,33 +654,41 @@ void main() { }); test('gen flutter void argument api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output', - ) - ]), - ], enums: []); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -639,25 +698,32 @@ void main() { ); final String code = sink.toString(); expect( - code, contains('fun doSomething(callback: (Result) -> Unit)')); + code, + contains('fun doSomething(callback: (Result) -> Unit)'), + ); expect(code, contains('channel.send(null)')); }); test('gen list', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, - ), - name: 'field1', - ) - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'List', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -671,20 +737,25 @@ void main() { }); test('gen map', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - ), - name: 'field1', - ) - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'Map', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -708,19 +779,16 @@ void main() { isNullable: true, ), name: 'nested', - ) + ), ], ); final Class nestedClass = Class( name: 'Nested', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), name: 'data', - ) + ), ], ); final Root root = Root( @@ -729,8 +797,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -748,52 +817,60 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: 'arg', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), - name: 'arg', - ) + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input', - ) - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output', - ) - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -808,52 +885,60 @@ void main() { }); test('gen one async Flutter Api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), - name: '', - ) + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'input', - ) - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), - name: 'output', - ) - ]) - ], enums: []); + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -893,8 +978,9 @@ void main() { enums: [anEnum], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -936,11 +1022,12 @@ void main() { fields: [ NamedType( type: const TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), + baseName: 'List', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'field1', ), ], @@ -951,8 +1038,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -971,12 +1059,13 @@ void main() { fields: [ NamedType( type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'String', isNullable: true), - ]), + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'String', isNullable: true), + ], + ), name: 'field1', ), ], @@ -987,8 +1076,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1004,30 +1094,36 @@ void main() { test('host generics argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'arg', - ) - ]) - ]) + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1042,30 +1138,36 @@ void main() { test('flutter generics argument', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'arg', - ) - ]) - ]) + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1080,25 +1182,31 @@ void main() { test('host generics return', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1115,25 +1223,31 @@ void main() { test('flutter generics return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1148,28 +1262,45 @@ void main() { }); test('host multiple args', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1185,28 +1316,45 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(baseName: 'int', isNullable: false)), - Parameter( - name: 'y', - type: - const TypeDeclaration(baseName: 'int', isNullable: false)), + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1218,32 +1366,39 @@ void main() { expect(code, contains('val channel = BasicMessageChannel')); expect(code, contains('callback(Result.success(output))')); expect( - code, - contains( - 'fun add(xArg: Long, yArg: Long, callback: (Result) -> Unit)')); + code, + contains( + 'fun add(xArg: Long, yArg: Long, callback: (Result) -> Unit)', + ), + ); expect(code, contains('channel.send(listOf(xArg, yArg)) {')); }); test('return nullable host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1258,8 +1413,10 @@ void main() { test('return nullable host async', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( @@ -1267,15 +1424,18 @@ void main() { isNullable: true, ), isAsynchronous: true, - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1290,27 +1450,33 @@ void main() { test('nullable argument host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1325,27 +1491,33 @@ void main() { test('nullable argument flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1361,38 +1533,49 @@ void main() { }); test('nonnull fields', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration( + baseName: 'String', isNullable: false, ), - name: '', - ) + name: 'input', + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), - name: 'input', - ) - ]), - ], enums: []); + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1438,9 +1621,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -1450,12 +1633,13 @@ void main() { NamedType( documentationComments: [comments[count++]], type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'field1', ), ], @@ -1466,7 +1650,7 @@ void main() { name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -1479,8 +1663,9 @@ void main() { ], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1492,57 +1677,71 @@ void main() { for (final String comment in comments) { // This regex finds the comment only between the open and close comment block expect( - RegExp(r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', dotAll: true) - .hasMatch(code), - true); + RegExp( + r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', + dotAll: true, + ).hasMatch(code), + true, + ); } expect(code, isNot(contains('*//'))); }); test('creates custom codecs', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1556,12 +1755,15 @@ void main() { test('creates api error class for custom errors', () { final Method method = Method( - name: 'doSomething', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: []); - final AstHostApi api = - AstHostApi(name: 'SomeApi', methods: [method]); + name: 'doSomething', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [], + ); + final AstHostApi api = AstHostApi( + name: 'SomeApi', + methods: [method], + ); final Root root = Root( apis: [api], classes: [], @@ -1569,8 +1771,10 @@ void main() { containsHostApi: true, ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(errorClassName: 'SomeError', kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + errorClassName: 'SomeError', + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1605,17 +1809,18 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], containsFlutterApi: true, ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1625,13 +1830,17 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'return FlutterError("channel-error", "Unable to establish connection on channel: \'\$channelName\'.", "")')); + code, + contains( + 'return FlutterError("channel-error", "Unable to establish connection on channel: \'\$channelName\'.", "")', + ), + ); expect( - code, - contains( - 'callback(Result.failure(PigeonUtils.createConnectionError(channelName)))')); + code, + contains( + 'callback(Result.failure(PigeonUtils.createConnectionError(channelName)))', + ), + ); }); test('gen host uses default error class', () { @@ -1653,16 +1862,17 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1693,16 +1903,17 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1733,17 +1944,19 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); const String errorClassName = 'FooError'; - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(errorClassName: errorClassName, kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + errorClassName: errorClassName, + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1775,17 +1988,19 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); const String errorClassName = 'FooError'; - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(errorClassName: errorClassName, kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + errorClassName: errorClassName, + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, @@ -1817,19 +2032,16 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( name: 'Foo', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'foo', ), ], @@ -1838,17 +2050,11 @@ void main() { name: 'Bar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'Foo', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Foo', isNullable: false), name: 'foo', ), NamedType( - type: const TypeDeclaration( - baseName: 'Foo', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Foo', isNullable: true), name: 'foo2', ), ], @@ -1859,8 +2065,10 @@ void main() { final StringBuffer sink = StringBuffer(); const String errorClassName = 'FooError'; - const InternalKotlinOptions kotlinOptions = - InternalKotlinOptions(errorClassName: errorClassName, kotlinOut: ''); + const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + errorClassName: errorClassName, + kotlinOut: '', + ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, diff --git a/packages/pigeon/test/objc_generator_test.dart b/packages/pigeon/test/objc_generator_test.dart index 7d7d730bb92..037da774209 100644 --- a/packages/pigeon/test/objc_generator_test.dart +++ b/packages/pigeon/test/objc_generator_test.dart @@ -10,12 +10,15 @@ import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); final Enum emptyEnum = Enum( name: 'enumName', @@ -24,24 +27,32 @@ final Enum emptyEnum = Enum( void main() { test('gen one class header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -54,24 +65,32 @@ void main() { }); test('gen one class source', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -84,26 +103,30 @@ void main() { }); test('gen one enum header', () { - final Root root = Root(apis: [], classes: [], enums: [ - Enum( - name: 'Enum1', - members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ], - ) - ]); + final Root root = Root( + apis: [], + classes: [], + enums: [ + Enum( + name: 'Enum1', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -117,27 +140,31 @@ void main() { }); test('gen one enum header with prefix', () { - final Root root = Root(apis: [], classes: [], enums: [ - Enum( - name: 'Enum1', - members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ], - ) - ]); + final Root root = Root( + apis: [], + classes: [], + enums: [ + Enum( + name: 'Enum1', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'PREFIX', - headerIncludePath: '', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'PREFIX', + headerIncludePath: '', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -158,16 +185,17 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: - const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'field1'), + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field1', + ), NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), - name: 'enum1'), + type: TypeDeclaration( + baseName: 'Enum1', + associatedEnum: emptyEnum, + isNullable: true, + ), + name: 'enum1', + ), ], ), ], @@ -178,20 +206,20 @@ void main() { EnumMember(name: 'one'), EnumMember(name: 'two'), ], - ) + ), ], ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -202,34 +230,48 @@ void main() { expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Foobar')); expect( - code, - contains( - 'return enumAsNumber == nil ? nil : [[Enum1Box alloc] initWithValue:[enumAsNumber integerValue]];')); + code, + contains( + 'return enumAsNumber == nil ? nil : [[Enum1Box alloc] initWithValue:[enumAsNumber integerValue]];', + ), + ); }); test('primitive enum host', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( - name: 'bar', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Bar', + methods: [ + Method( + name: 'bar', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', associatedEnum: emptyEnum, isNullable: false, - )) - ]) - ]) - ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) - ]); + ), + ), + ], + ), + ], + ), + ], + classes: [], + enums: [ + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); const InternalObjcOptions options = InternalObjcOptions( headerIncludePath: 'foo.h', @@ -241,9 +283,9 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: options, - ); + fileType: FileType.header, + languageOptions: options, + ); generator.generate( generatorOptions, root, @@ -258,9 +300,9 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: options, - ); + fileType: FileType.source, + languageOptions: options, + ); generator.generate( generatorOptions, root, @@ -269,37 +311,51 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'return enumAsNumber == nil ? nil : [[ACFooBox alloc] initWithValue:[enumAsNumber integerValue]];')); + code, + contains( + 'return enumAsNumber == nil ? nil : [[ACFooBox alloc] initWithValue:[enumAsNumber integerValue]];', + ), + ); expect(code, contains('ACFooBox *box = (ACFooBox *)value;')); } }); test('validate nullable primitive enum', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( - name: 'bar', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Bar', + methods: [ + Method( + name: 'bar', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', associatedEnum: emptyEnum, isNullable: true, - )) - ]) - ]) - ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) - ]); + ), + ), + ], + ), + ], + ), + ], + classes: [], + enums: [ + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); const InternalObjcOptions options = InternalObjcOptions( headerIncludePath: 'foo.h', objcHeaderOut: '', @@ -318,16 +374,17 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: - const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'field1'), + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field1', + ), NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), - name: 'enum1'), + type: TypeDeclaration( + baseName: 'Enum1', + associatedEnum: emptyEnum, + isNullable: true, + ), + name: 'enum1', + ), ], ), ], @@ -338,20 +395,20 @@ void main() { EnumMember(name: 'one'), EnumMember(name: 'two'), ], - ) + ), ], ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -359,54 +416,73 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - contains('@property(nonatomic, strong, nullable) Enum1Box * enum1;')); + expect( + code, + contains('@property(nonatomic, strong, nullable) Enum1Box * enum1;'), + ); }); test('gen one api header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]) - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -423,49 +499,66 @@ void main() { }); test('gen one api source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]) - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -478,99 +571,140 @@ void main() { expect(code, contains('@implementation Output')); expect(code, contains('SetUpApi(')); expect( - code, - contains( - 'NSCAssert([api respondsToSelector:@selector(doSomething:error:)')); - }); - - test('all the simple datatypes header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'bool', isNullable: true), - name: 'aBool'), - NamedType( - type: const TypeDeclaration(baseName: 'int', isNullable: true), - name: 'aInt'), - NamedType( - type: const TypeDeclaration(baseName: 'double', isNullable: true), - name: 'aDouble'), - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'aString'), - NamedType( - type: - const TypeDeclaration(baseName: 'Uint8List', isNullable: true), - name: 'aUint8List'), - NamedType( - type: - const TypeDeclaration(baseName: 'Int32List', isNullable: true), - name: 'aInt32List'), - NamedType( - type: - const TypeDeclaration(baseName: 'Int64List', isNullable: true), - name: 'aInt64List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', isNullable: true), - name: 'aFloat64List'), - ]), - ], enums: []); - - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', + code, + contains( + 'NSCAssert([api respondsToSelector:@selector(doSomething:error:)', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final String code = sink.toString(); - expect(code, contains('@interface Foobar')); - expect(code, contains('@class FlutterStandardTypedData;')); - expect(code, matches('@property.*strong.*NSNumber.*aBool')); - expect(code, matches('@property.*strong.*NSNumber.*aInt')); - expect(code, matches('@property.*strong.*NSNumber.*aDouble')); - expect(code, matches('@property.*copy.*NSString.*aString')); - expect(code, - matches('@property.*strong.*FlutterStandardTypedData.*aUint8List')); - expect(code, - matches('@property.*strong.*FlutterStandardTypedData.*aInt32List')); - expect(code, - matches('@property.*strong.*FlutterStandardTypedData.*Int64List')); - expect(code, - matches('@property.*strong.*FlutterStandardTypedData.*Float64List')); }); - test('bool source', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'bool', isNullable: true), - name: 'aBool'), - ]), - ], enums: []); + test('all the simple datatypes header', () { + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'aBool', + ), + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'aInt', + ), + NamedType( + type: const TypeDeclaration(baseName: 'double', isNullable: true), + name: 'aDouble', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'aString', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Uint8List', + isNullable: true, + ), + name: 'aUint8List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Int32List', + isNullable: true, + ), + name: 'aInt32List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Int64List', + isNullable: true, + ), + name: 'aInt64List', + ), + NamedType( + type: const TypeDeclaration( + baseName: 'Float64List', + isNullable: true, + ), + name: 'aFloat64List', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final String code = sink.toString(); + expect(code, contains('@interface Foobar')); + expect(code, contains('@class FlutterStandardTypedData;')); + expect(code, matches('@property.*strong.*NSNumber.*aBool')); + expect(code, matches('@property.*strong.*NSNumber.*aInt')); + expect(code, matches('@property.*strong.*NSNumber.*aDouble')); + expect(code, matches('@property.*copy.*NSString.*aString')); + expect( + code, + matches('@property.*strong.*FlutterStandardTypedData.*aUint8List'), + ); + expect( + code, + matches('@property.*strong.*FlutterStandardTypedData.*aInt32List'), ); + expect( + code, + matches('@property.*strong.*FlutterStandardTypedData.*Int64List'), + ); + expect( + code, + matches('@property.*strong.*FlutterStandardTypedData.*Float64List'), + ); + }); + + test('bool source', () { + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'aBool', + ), + ], + ), + ], + enums: [], + ); + + final StringBuffer sink = StringBuffer(); + const ObjcGenerator generator = ObjcGenerator(); + final OutputFileOptions generatorOptions = + OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -579,38 +713,52 @@ void main() { ); final String code = sink.toString(); expect(code, contains('@implementation Foobar')); - expect(code, - contains('pigeonResult.aBool = GetNullableObjectAtIndex(list, 0);')); + expect( + code, + contains('pigeonResult.aBool = GetNullableObjectAtIndex(list, 0);'), + ); }); test('nested class header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Nested', fields: [ - NamedType( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: true, - ), - name: 'nested') - ]) - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Nested', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: true, + ), + name: 'nested', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -618,38 +766,52 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - contains('@property(nonatomic, strong, nullable) Input * nested;')); + expect( + code, + contains('@property(nonatomic, strong, nullable) Input * nested;'), + ); }); test('nested class source', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Nested', fields: [ - NamedType( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: true, - ), - name: 'nested') - ]) - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Nested', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: true, + ), + name: 'nested', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -657,30 +819,40 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - contains('pigeonResult.nested = GetNullableObjectAtIndex(list, 0);')); + expect( + code, + contains('pigeonResult.nested = GetNullableObjectAtIndex(list, 0);'), + ); }); test('prefix class header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -692,25 +864,33 @@ void main() { }); test('prefix class source', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -722,54 +902,71 @@ void main() { }); test('prefix nested class header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Nested', fields: [ - NamedType( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: true, - ), - name: 'nested') - ]) - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Nested', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Nested', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: true, + ), + name: 'nested', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -783,54 +980,71 @@ void main() { }); test('prefix nested class source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Nested', fields: [ - NamedType( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: true, - ), - name: 'nested') - ]) - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Nested', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Nested', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: true, + ), + name: 'nested', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -844,49 +1058,66 @@ void main() { }); test('gen flutter api header', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]) - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -896,56 +1127,75 @@ void main() { final String code = sink.toString(); expect(code, contains('@interface Api : NSObject')); expect( - code, - contains( - 'initWithBinaryMessenger:(id)binaryMessenger;')); + code, + contains( + 'initWithBinaryMessenger:(id)binaryMessenger;', + ), + ); expect(code, matches('void.*doSomething.*Input.*Output')); }); test('gen flutter api source', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]) - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -958,41 +1208,54 @@ void main() { }); test('gen host void header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: const TypeDeclaration.voidDeclaration()) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - ], enums: []); + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1004,41 +1267,54 @@ void main() { }); test('gen host void source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: const TypeDeclaration.voidDeclaration()) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - ], enums: []); + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1052,41 +1328,54 @@ void main() { }); test('gen flutter void return header', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: const TypeDeclaration.voidDeclaration()) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - ], enums: []); + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1098,84 +1387,109 @@ void main() { }); test('gen flutter void return source', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: const TypeDeclaration.voidDeclaration()) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - ], enums: []); + name: '', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - expect(code, contains('completion:(void (^)(FlutterError *_Nullable))')); - expect(code, contains('completion(nil)')); - }); - - test('gen host void arg header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + final String code = sink.toString(); + expect(code, contains('completion:(void (^)(FlutterError *_Nullable))')); + expect(code, contains('completion(nil)')); + }); + + test('gen host void arg header', () { + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1187,37 +1501,49 @@ void main() { }); test('gen host void arg source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1229,37 +1555,49 @@ void main() { }); test('gen flutter void arg header', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1268,43 +1606,57 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion')); + code, + contains( + '(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion', + ), + ); }); test('gen flutter void arg source', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - )) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1313,31 +1665,41 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion')); + code, + contains( + '(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion', + ), + ); expect(code, contains('channel sendMessage:nil')); }); test('gen list', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'List', isNullable: true), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'List', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1350,24 +1712,32 @@ void main() { }); test('gen map', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'Map', isNullable: true), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'Map', isNullable: true), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1380,30 +1750,39 @@ void main() { }); test('gen map field with object', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration( baseName: 'Map', isNullable: true, typeArguments: [ TypeDeclaration(baseName: 'String', isNullable: true), TypeDeclaration(baseName: 'Object', isNullable: true), - ]), - name: 'field1') - ]), - ], enums: []); + ], + ), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1413,42 +1792,54 @@ void main() { final String code = sink.toString(); expect(code, contains('@interface Foobar')); expect( - code, - contains( - '@property(nonatomic, copy, nullable) NSDictionary *')); + code, + contains( + '@property(nonatomic, copy, nullable) NSDictionary *', + ), + ); }); test('gen map argument with object', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doit', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doit', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( name: 'foo', type: const TypeDeclaration( - baseName: 'Map', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'Object', isNullable: true), - ])) - ]), - ]) - ], classes: [], enums: []); + baseName: 'Map', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'Object', isNullable: true), + ], + ), + ), + ], + ), + ], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -1460,47 +1851,64 @@ void main() { }); test('async void (input) HostApi header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: 'input') - ], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + name: 'input', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1509,57 +1917,76 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '(void)doSomethingInput:(ABCInput *)input completion:(void (^)(FlutterError *_Nullable))completion')); + code, + contains( + '(void)doSomethingInput:(ABCInput *)input completion:(void (^)(FlutterError *_Nullable))completion', + ), + ); }); test('async output(input) HostApi header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: 'input') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + name: 'input', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1568,44 +1995,58 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '(void)doSomethingInput:(ABCInput *)input completion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion')); + code, + contains( + '(void)doSomethingInput:(ABCInput *)input completion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion', + ), + ); }); test('async output(void) HostApi header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1614,34 +2055,44 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion')); + code, + contains( + '(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion', + ), + ); }); test('async void (void) HostApi header', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, + ), + ], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1650,57 +2101,76 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '(void)doSomethingWithCompletion:(void (^)(FlutterError *_Nullable))completion')); + code, + contains( + '(void)doSomethingWithCompletion:(void (^)(FlutterError *_Nullable))completion', + ), + ); }); test('async output(input) HostApi source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: '') - ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + name: '', + ), + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1709,53 +2179,72 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '[api doSomething:arg0 completion:^(ABCOutput *_Nullable output, FlutterError *_Nullable error) {')); + code, + contains( + '[api doSomething:arg0 completion:^(ABCOutput *_Nullable output, FlutterError *_Nullable error) {', + ), + ); }); test('async void (input) HostApi source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), - name: 'foo') - ], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + name: 'foo', + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, + ), + ], + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1764,34 +2253,44 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '[api doSomethingFoo:arg_foo completion:^(FlutterError *_Nullable error) {')); + code, + contains( + '[api doSomethingFoo:arg_foo completion:^(FlutterError *_Nullable error) {', + ), + ); }); test('async void (void) HostApi source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: const TypeDeclaration.voidDeclaration(), - isAsynchronous: true) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: const TypeDeclaration.voidDeclaration(), + isAsynchronous: true, + ), + ], + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1800,44 +2299,58 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '[api doSomethingWithCompletion:^(FlutterError *_Nullable error) {')); + code, + contains( + '[api doSomethingWithCompletion:^(FlutterError *_Nullable error) {', + ), + ); }); test('async output(void) HostApi source', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: true), - name: 'output') - ]), - ], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1846,9 +2359,11 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '[api doSomethingWithCompletion:^(ABCOutput *_Nullable output, FlutterError *_Nullable error) {')); + code, + contains( + '[api doSomethingWithCompletion:^(ABCOutput *_Nullable output, FlutterError *_Nullable error) {', + ), + ); }); Iterable makeIterable(String string) sync* { @@ -1861,15 +2376,15 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - copyrightHeader: makeIterable('hello world'), - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + copyrightHeader: makeIterable('hello world'), + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1886,15 +2401,15 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - copyrightHeader: makeIterable('hello world'), - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + copyrightHeader: makeIterable('hello world'), + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1910,13 +2425,15 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'List', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -1928,14 +2445,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1949,22 +2466,28 @@ void main() { test('host generics argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -1974,14 +2497,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -1996,14 +2519,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2012,31 +2535,39 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'NSArray *arg_arg = GetNullableObjectAtIndex(args, 0)')); + code, + contains( + 'NSArray *arg_arg = GetNullableObjectAtIndex(args, 0)', + ), + ); } }); test('flutter generics argument', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -2046,14 +2577,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2068,14 +2599,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2090,28 +2621,34 @@ void main() { test('host nested generic argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration( baseName: 'List', - isNullable: false, + isNullable: true, typeArguments: [ - TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration( - baseName: 'bool', isNullable: true) - ]), - ]), - name: 'arg') - ]) - ]) + TypeDeclaration(baseName: 'bool', isNullable: true), + ], + ), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -2121,14 +2658,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2143,18 +2680,23 @@ void main() { test('host generics return', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -2164,14 +2706,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2180,21 +2722,23 @@ void main() { ); final String code = sink.toString(); expect( - code, contains('- (nullable NSArray *)doitWithError:')); + code, + contains('- (nullable NSArray *)doitWithError:'), + ); } { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2209,18 +2753,23 @@ void main() { test('flutter generics return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -2230,14 +2779,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2246,21 +2795,23 @@ void main() { ); final String code = sink.toString(); expect( - code, contains('doitWithCompletion:(void (^)(NSArray *')); + code, + contains('doitWithCompletion:(void (^)(NSArray *'), + ); } { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2269,43 +2820,61 @@ void main() { ); final String code = sink.toString(); expect( - code, contains('doitWithCompletion:(void (^)(NSArray *')); + code, + contains('doitWithCompletion:(void (^)(NSArray *'), + ); } }); test('host multiple args', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2314,23 +2883,25 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '- (nullable NSNumber *)addX:(NSInteger)x y:(NSInteger)y error:(FlutterError *_Nullable *_Nonnull)error;')); + code, + contains( + '- (nullable NSNumber *)addX:(NSInteger)x y:(NSInteger)y error:(FlutterError *_Nullable *_Nonnull)error;', + ), + ); } { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2340,52 +2911,74 @@ void main() { final String code = sink.toString(); expect(code, contains('NSArray *args = message;')); expect( - code, - contains( - 'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];')); + code, + contains( + 'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];', + ), + ); + expect( + code, + contains( + 'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];', + ), + ); expect( - code, - contains( - 'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];')); - expect(code, - contains('NSNumber *output = [api addX:arg_x y:arg_y error:&error]')); + code, + contains('NSNumber *output = [api addX:arg_x y:arg_y error:&error]'), + ); } }); test('host multiple args async', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - isAsynchronous: true, - ) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + isAsynchronous: true, + ), + ], + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2394,23 +2987,25 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '- (void)addX:(NSInteger)x y:(NSInteger)y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;')); + code, + contains( + '- (void)addX:(NSInteger)x y:(NSInteger)y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;', + ), + ); } { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2420,50 +3015,70 @@ void main() { final String code = sink.toString(); expect(code, contains('NSArray *args = message;')); expect( - code, - contains( - 'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];')); + code, + contains( + 'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];', + ), + ); expect( - code, - contains( - 'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];')); + code, + contains( + 'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];', + ), + ); expect(code, contains('[api addX:arg_x y:arg_y completion:')); } }); test('flutter multiple args', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + ), + ], + classes: [], + enums: [], + ); { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2472,23 +3087,25 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '- (void)addX:(NSInteger)x y:(NSInteger)y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;')); + code, + contains( + '- (void)addX:(NSInteger)x y:(NSInteger)y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;', + ), + ); } { final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, @@ -2497,62 +3114,86 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - '- (void)addX:(NSInteger)arg_x y:(NSInteger)arg_y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {')); + code, + contains( + '- (void)addX:(NSInteger)arg_x y:(NSInteger)arg_y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {', + ), + ); expect( - code, contains('[channel sendMessage:@[@(arg_x), @(arg_y)] reply:')); + code, + contains('[channel sendMessage:@[@(arg_x), @(arg_y)] reply:'), + ); } }); Root getDivideRoot(ApiLocation location) => Root( - apis: [ - switch (location) { - ApiLocation.host => AstHostApi(name: 'Api', methods: [ - Method( - name: 'divide', - location: location, - objcSelector: 'divideValue:by:', - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'int', isNullable: false), - name: 'x', - ), - Parameter( - type: const TypeDeclaration( - baseName: 'int', isNullable: false), - name: 'y', - ), - ], - returnType: const TypeDeclaration( - baseName: 'double', isNullable: false)) - ]), - ApiLocation.flutter => AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'divide', - location: location, - objcSelector: 'divideValue:by:', - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'int', isNullable: false), - name: 'x', - ), - Parameter( - type: const TypeDeclaration( - baseName: 'int', isNullable: false), - name: 'y', - ), - ], - returnType: const TypeDeclaration( - baseName: 'double', isNullable: false)) - ]), - } - ], - classes: [], - enums: [], - ); + apis: [ + switch (location) { + ApiLocation.host => AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'divide', + location: location, + objcSelector: 'divideValue:by:', + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: 'x', + ), + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: 'y', + ), + ], + returnType: const TypeDeclaration( + baseName: 'double', + isNullable: false, + ), + ), + ], + ), + ApiLocation.flutter => AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'divide', + location: location, + objcSelector: 'divideValue:by:', + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: 'x', + ), + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: 'y', + ), + ], + returnType: const TypeDeclaration( + baseName: 'double', + isNullable: false, + ), + ), + ], + ), + }, + ], + classes: [], + enums: [], + ); test('host custom objc selector', () { final Root divideRoot = getDivideRoot(ApiLocation.host); @@ -2561,14 +3202,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, @@ -2583,14 +3224,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, @@ -2609,14 +3250,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, @@ -2631,14 +3272,14 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, @@ -2651,24 +3292,35 @@ void main() { }); test('test non null field', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration(baseName: 'String', isNullable: false), - name: 'field1') - ]), - ], enums: []); + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2683,16 +3335,20 @@ void main() { test('return nullable flutter header', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -2701,13 +3357,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2716,24 +3372,30 @@ void main() { ); final String code = sink.toString(); expect( - code, - matches( - r'doitWithCompletion.*void.*NSNumber \*_Nullable.*FlutterError.*completion;')); + code, + matches( + r'doitWithCompletion.*void.*NSNumber \*_Nullable.*FlutterError.*completion;', + ), + ); }); test('return nullable flutter source', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -2742,13 +3404,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2762,16 +3424,20 @@ void main() { test('return nullable host header', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], @@ -2780,13 +3446,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2800,20 +3466,25 @@ void main() { test('nullable argument host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -2823,13 +3494,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2844,13 +3515,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2858,28 +3529,35 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - contains('NSNumber *arg_foo = GetNullableObjectAtIndex(args, 0);')); + expect( + code, + contains('NSNumber *arg_foo = GetNullableObjectAtIndex(args, 0);'), + ); } }); test('nullable argument flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], @@ -2889,13 +3567,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2910,13 +3588,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2931,8 +3609,10 @@ void main() { test('background platform channel', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( @@ -2940,8 +3620,10 @@ void main() { isNullable: true, ), parameters: [], - taskQueueType: TaskQueueType.serialBackgroundThread) - ]) + taskQueueType: TaskQueueType.serialBackgroundThread, + ), + ], + ), ], classes: [], enums: [], @@ -2950,13 +3632,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -2965,9 +3647,11 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'NSObject *taskQueue = [binaryMessenger makeBackgroundTaskQueue];')); + code, + contains( + 'NSObject *taskQueue = [binaryMessenger makeBackgroundTaskQueue];', + ), + ); expect(code, contains('taskQueue:taskQueue')); }); @@ -3005,9 +3689,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -3017,12 +3701,13 @@ void main() { NamedType( documentationComments: [comments[count++]], type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'field1', ), ], @@ -3033,7 +3718,7 @@ void main() { name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -3049,13 +3734,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -3070,57 +3755,67 @@ void main() { }); test('creates custom codecs', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -3150,9 +3845,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], @@ -3162,13 +3857,13 @@ void main() { const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -3177,49 +3872,53 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'return [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: \'", channelName, @"\'."] details:@""]')); + code, + contains( + 'return [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: \'", channelName, @"\'."] details:@""]', + ), + ); expect(code, contains('completion(createConnectionError(channelName))')); }); test('header of FlutterApi uses correct enum name with prefix', () { final Enum enum1 = Enum( name: 'Enum1', - members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ], - ); - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - isAsynchronous: true, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Enum1', - isNullable: false, - associatedEnum: enum1, - ), - ) - ]), - ], classes: [], enums: [ - enum1, - ]); + members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + ); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + isAsynchronous: true, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Enum1', + isNullable: false, + associatedEnum: enum1, + ), + ), + ], + ), + ], + classes: [], + enums: [enum1], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -3234,40 +3933,42 @@ 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'), - ], - ); - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - isAsynchronous: true, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Enum1', - isNullable: false, - associatedEnum: enum1, - ), - ) - ]), - ], classes: [], enums: [ - enum1, - ]); + members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + ); + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + isAsynchronous: true, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Enum1', + isNullable: false, + associatedEnum: enum1, + ), + ), + ], + ), + ], + classes: [], + enums: [enum1], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -3282,41 +3983,43 @@ 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', isNullable: false, associatedEnum: enum1, ); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - isAsynchronous: true, - parameters: [Parameter(name: 'value', type: enumType)], - returnType: enumType, - ) - ]), - ], classes: [], enums: [ - enum1, - ]); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + isAsynchronous: true, + parameters: [Parameter(name: 'value', type: enumType)], + returnType: enumType, + ), + ], + ), + ], + classes: [], + enums: [enum1], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, @@ -3331,41 +4034,43 @@ 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', isNullable: false, associatedEnum: enum1, ); - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - isAsynchronous: true, - parameters: [Parameter(name: 'value', type: enumType)], - returnType: enumType, - ) - ]), - ], classes: [], enums: [ - enum1, - ]); + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + isAsynchronous: true, + parameters: [Parameter(name: 'value', type: enumType)], + returnType: enumType, + ), + ], + ), + ], + classes: [], + enums: [enum1], + ); final StringBuffer sink = StringBuffer(); const ObjcGenerator generator = ObjcGenerator(); final OutputFileOptions generatorOptions = OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, diff --git a/packages/pigeon/test/pigeon_lib_test.dart b/packages/pigeon/test/pigeon_lib_test.dart index ef5d96126b4..c55d14464b6 100644 --- a/packages/pigeon/test/pigeon_lib_test.dart +++ b/packages/pigeon/test/pigeon_lib_test.dart @@ -22,8 +22,12 @@ class _ValidatorGeneratorAdapter implements GeneratorAdapter { final IOSink? sink; @override - void generate(StringSink sink, InternalPigeonOptions options, Root root, - FileType fileType) {} + void generate( + StringSink sink, + InternalPigeonOptions options, + Root root, + FileType fileType, + ) {} @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) => sink; @@ -31,9 +35,7 @@ class _ValidatorGeneratorAdapter implements GeneratorAdapter { @override List validate(InternalPigeonOptions options, Root root) { didCallValidate = true; - return [ - Error(message: '_ValidatorGenerator'), - ]; + return [Error(message: '_ValidatorGenerator')]; } } @@ -64,86 +66,113 @@ void main() { } test('parse args - input', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--input', 'foo.dart']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--input', + 'foo.dart', + ]); expect(opts.input, equals('foo.dart')); }); test('parse args - dart_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--dart_out', 'foo.dart']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--dart_out', + 'foo.dart', + ]); expect(opts.dartOut, equals('foo.dart')); }); test('parse args - java_package', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--java_package', 'com.google.foo']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--java_package', + 'com.google.foo', + ]); expect(opts.javaOptions?.package, equals('com.google.foo')); }); test('parse args - input', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--java_out', 'foo.java']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--java_out', + 'foo.java', + ]); expect(opts.javaOut, equals('foo.java')); }); test('parse args - objc_header_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--objc_header_out', 'foo.h']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--objc_header_out', + 'foo.h', + ]); expect(opts.objcHeaderOut, equals('foo.h')); }); test('parse args - objc_source_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--objc_source_out', 'foo.m']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--objc_source_out', + 'foo.m', + ]); expect(opts.objcSourceOut, equals('foo.m')); }); test('parse args - swift_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--swift_out', 'Foo.swift']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--swift_out', + 'Foo.swift', + ]); expect(opts.swiftOut, equals('Foo.swift')); }); test('parse args - kotlin_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--kotlin_out', 'Foo.kt']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--kotlin_out', + 'Foo.kt', + ]); expect(opts.kotlinOut, equals('Foo.kt')); }); test('parse args - kotlin_package', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--kotlin_package', 'com.google.foo']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--kotlin_package', + 'com.google.foo', + ]); expect(opts.kotlinOptions?.package, equals('com.google.foo')); }); test('parse args - cpp_header_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--cpp_header_out', 'foo.h']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--cpp_header_out', + 'foo.h', + ]); expect(opts.cppHeaderOut, equals('foo.h')); }); test('parse args - java_use_generated_annotation', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--java_use_generated_annotation']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--java_use_generated_annotation', + ]); expect(opts.javaOptions!.useGeneratedAnnotation, isTrue); }); test('parse args - cpp_source_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--cpp_source_out', 'foo.cpp']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--cpp_source_out', + 'foo.cpp', + ]); expect(opts.cppSourceOut, equals('foo.cpp')); }); test('parse args - ast_out', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--ast_out', 'stdout']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--ast_out', + 'stdout', + ]); expect(opts.astOut, equals('stdout')); }); test('parse args - base_path', () { - final PigeonOptions opts = - Pigeon.parseArgs(['--base_path', './foo/']); + final PigeonOptions opts = Pigeon.parseArgs([ + '--base_path', + './foo/', + ]); expect(opts.basePath, equals('./foo/')); }); @@ -176,7 +205,9 @@ abstract class Api1 { expect(root.apis[0].methods[0].name, equals('doit')); expect(root.apis[0].methods[0].parameters[0].name, equals('input')); expect( - root.apis[0].methods[0].parameters[0].type.baseName, equals('Input1')); + root.apis[0].methods[0].parameters[0].type.baseName, + equals('Input1'), + ); expect(root.apis[0].methods[0].returnType.baseName, equals('Output1')); Class? input; @@ -239,9 +270,11 @@ abstract class Api { final ParseResults results = parseSource(source); expect(results.errors.length, 1); expect( - results.errors[0].message, - contains( - 'API "Api" can only have one API annotation but contains: [@HostApi(), @FlutterApi()]')); + results.errors[0].message, + contains( + 'API "Api" can only have one API annotation but contains: [@HostApi(), @FlutterApi()]', + ), + ); }); test('Only allow one api annotation plus @ConfigurePigeon', () { @@ -329,8 +362,9 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.classes.length, equals(2)); - final Class nested = - results.root.classes.firstWhere((Class x) => x.name == 'Nested'); + final Class nested = results.root.classes.firstWhere( + (Class x) => x.name == 'Nested', + ); expect(nested.fields.length, equals(1)); expect(nested.fields[0].type.baseName, equals('Input1')); expect(nested.fields[0].type.isNullable, isTrue); @@ -394,7 +428,9 @@ abstract class VoidArgApi { expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].name, equals('VoidArgApi')); expect( - results.root.apis[0].methods[0].returnType.baseName, equals('Output1')); + results.root.apis[0].methods[0].returnType.baseName, + equals('Output1'), + ); expect(results.root.apis[0].methods[0].parameters.isEmpty, isTrue); }); @@ -444,30 +480,44 @@ abstract class NestorApi { }); test('copyright flag', () { - final PigeonOptions results = - Pigeon.parseArgs(['--copyright_header', 'foobar.txt']); + final PigeonOptions results = Pigeon.parseArgs([ + '--copyright_header', + 'foobar.txt', + ]); expect(results.copyrightHeader, 'foobar.txt'); }); test('Dart generator copyright flag', () { final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = - PigeonOptions(copyrightHeader: './copyright_header.txt', dartOut: ''); + const PigeonOptions options = PigeonOptions( + copyrightHeader: './copyright_header.txt', + dartOut: '', + ); final DartGeneratorAdapter dartGeneratorAdapter = DartGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); - dartGeneratorAdapter.generate(buffer, - InternalPigeonOptions.fromPigeonOptions(options), root, FileType.na); + dartGeneratorAdapter.generate( + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.na, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('Java generator copyright flag', () { final Root root = Root(apis: [], classes: [], enums: []); const PigeonOptions options = PigeonOptions( - javaOut: 'Foo.java', copyrightHeader: './copyright_header.txt'); + javaOut: 'Foo.java', + copyrightHeader: './copyright_header.txt', + ); final JavaGeneratorAdapter javaGeneratorAdapter = JavaGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); - javaGeneratorAdapter.generate(buffer, - InternalPigeonOptions.fromPigeonOptions(options), root, FileType.na); + javaGeneratorAdapter.generate( + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.na, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); @@ -482,10 +532,11 @@ abstract class NestorApi { ObjcGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); objcHeaderGeneratorAdapter.generate( - buffer, - InternalPigeonOptions.fromPigeonOptions(options), - root, - FileType.header); + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.header, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); @@ -500,37 +551,46 @@ abstract class NestorApi { ObjcGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); objcSourceGeneratorAdapter.generate( - buffer, - InternalPigeonOptions.fromPigeonOptions(options), - root, - FileType.source); + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.source, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('Swift generator copyright flag', () { final Root root = Root(apis: [], classes: [], enums: []); const PigeonOptions options = PigeonOptions( - swiftOut: 'Foo.swift', copyrightHeader: './copyright_header.txt'); + swiftOut: 'Foo.swift', + copyrightHeader: './copyright_header.txt', + ); final SwiftGeneratorAdapter swiftGeneratorAdapter = SwiftGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); - swiftGeneratorAdapter.generate(buffer, - InternalPigeonOptions.fromPigeonOptions(options), root, FileType.na); + swiftGeneratorAdapter.generate( + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.na, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('C++ header generator copyright flag', () { final Root root = Root(apis: [], classes: [], enums: []); const PigeonOptions options = PigeonOptions( - cppSourceOut: '', - cppHeaderOut: 'Foo.h', - copyrightHeader: './copyright_header.txt'); + cppSourceOut: '', + cppHeaderOut: 'Foo.h', + copyrightHeader: './copyright_header.txt', + ); final CppGeneratorAdapter cppHeaderGeneratorAdapter = CppGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); cppHeaderGeneratorAdapter.generate( - buffer, - InternalPigeonOptions.fromPigeonOptions(options), - root, - FileType.header); + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.header, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); @@ -541,14 +601,16 @@ abstract class NestorApi { cppHeaderOut: '', cppSourceOut: '', ); - final CppGeneratorAdapter cppSourceGeneratorAdapter = - CppGeneratorAdapter(fileTypeList: [FileType.source]); + final CppGeneratorAdapter cppSourceGeneratorAdapter = CppGeneratorAdapter( + fileTypeList: [FileType.source], + ); final StringBuffer buffer = StringBuffer(); cppSourceGeneratorAdapter.generate( - buffer, - InternalPigeonOptions.fromPigeonOptions(options), - root, - FileType.source); + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.source, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); @@ -599,8 +661,9 @@ abstract class NotificationsHostApi { final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.classes.length, 2); - final Class foo = - results.root.classes.firstWhere((Class aClass) => aClass.name == 'Foo'); + final Class foo = results.root.classes.firstWhere( + (Class aClass) => aClass.name == 'Foo', + ); expect(foo.fields.length, 1); expect(foo.fields[0].type.baseName, 'Bar'); }); @@ -902,13 +965,19 @@ abstract class Api { final ParseResults parseResult = parseSource(code); expect(parseResult.root.apis[0].methods[0].returnType.baseName, 'List'); expect( - parseResult - .root.apis[0].methods[0].returnType.typeArguments[0].baseName, - 'double'); + parseResult.root.apis[0].methods[0].returnType.typeArguments[0].baseName, + 'double', + ); expect( - parseResult - .root.apis[0].methods[0].returnType.typeArguments[0].isNullable, - isTrue); + parseResult + .root + .apis[0] + .methods[0] + .returnType + .typeArguments[0] + .isNullable, + isTrue, + ); }); test('argument generics', () { @@ -919,16 +988,32 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.root.apis[0].methods[0].parameters[1].type.baseName, - 'List'); expect( - parseResult.root.apis[0].methods[0].parameters[1].type.typeArguments[0] - .baseName, - 'double'); + parseResult.root.apis[0].methods[0].parameters[1].type.baseName, + 'List', + ); + expect( + parseResult + .root + .apis[0] + .methods[0] + .parameters[1] + .type + .typeArguments[0] + .baseName, + 'double', + ); expect( - parseResult.root.apis[0].methods[0].parameters[1].type.typeArguments[0] - .isNullable, - isTrue); + parseResult + .root + .apis[0] + .methods[0] + .parameters[1] + .type + .typeArguments[0] + .isNullable, + isTrue, + ); }); test('map generics', () { @@ -977,8 +1062,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); - expect(results.errors[0].message, - contains('Parameters must specify their type')); + expect( + results.errors[0].message, + contains('Parameters must specify their type'), + ); }); test('custom objc selector', () { @@ -993,8 +1080,10 @@ abstract class Api { expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); - expect(results.root.apis[0].methods[0].objcSelector, - equals('subtractValue:by:')); + expect( + results.root.apis[0].methods[0].objcSelector, + equals('subtractValue:by:'), + ); }); test('custom objc invalid selector', () { @@ -1008,8 +1097,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); - expect(results.errors[0].message, - contains('Invalid selector, expected 2 parameters')); + expect( + results.errors[0].message, + contains('Invalid selector, expected 2 parameters'), + ); }); test('custom objc no parameters', () { @@ -1039,8 +1130,10 @@ abstract class Api { expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); - expect(results.root.apis[0].methods[0].swiftFunction, - equals('subtractValue(_:by:)')); + expect( + results.root.apis[0].methods[0].swiftFunction, + equals('subtractValue(_:by:)'), + ); }); test('custom swift invalid function signature', () { @@ -1054,8 +1147,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); - expect(results.errors[0].message, - contains('Invalid function signature, expected 2 parameters')); + expect( + results.errors[0].message, + contains('Invalid function signature, expected 2 parameters'), + ); }); test('custom swift function signature no parameters', () { @@ -1084,10 +1179,11 @@ abstract class Api { DartTestGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); dartTestGeneratorAdapter.generate( - buffer, - InternalPigeonOptions.fromPigeonOptions(options), - root, - FileType.source); + buffer, + InternalPigeonOptions.fromPigeonOptions(options), + root, + FileType.source, + ); expect(buffer.toString(), startsWith('// Copyright 2013')); }); @@ -1145,15 +1241,17 @@ abstract class Api { expect(results.errors.length, 0); expect(results.root.classes.length, 2); expect( - results.root.classes - .where((Class element) => element.name == 'Foo') - .length, - 1); + results.root.classes + .where((Class element) => element.name == 'Foo') + .length, + 1, + ); expect( - results.root.classes - .where((Class element) => element.name == 'Bar') - .length, - 1); + results.root.classes + .where((Class element) => element.name == 'Bar') + .length, + 1, + ); }); test('undeclared class in argument type argument', () { @@ -1301,7 +1399,9 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect( - results.root.apis[0].methods[0].parameters[0].type.isNullable, isTrue); + results.root.apis[0].methods[0].parameters[0].type.isNullable, + isTrue, + ); }); test('task queue specified', () { @@ -1315,8 +1415,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 0); - expect(results.root.apis[0].methods[0].taskQueueType, - equals(TaskQueueType.serialBackgroundThread)); + expect( + results.root.apis[0].methods[0].taskQueueType, + equals(TaskQueueType.serialBackgroundThread), + ); }); test('task queue unspecified', () { @@ -1329,8 +1431,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 0); - expect(results.root.apis[0].methods[0].taskQueueType, - equals(TaskQueueType.serial)); + expect( + results.root.apis[0].methods[0].taskQueueType, + equals(TaskQueueType.serial), + ); }); test('unsupported task queue on FlutterApi', () { @@ -1344,17 +1448,22 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 1); - expect(results.errors[0].message, - contains('Unsupported TaskQueue specification')); + expect( + results.errors[0].message, + contains('Unsupported TaskQueue specification'), + ); }); test('generator validation', () async { final Completer completer = Completer(); withTempFile('foo.dart', (File input) async { - final _ValidatorGeneratorAdapter generator = - _ValidatorGeneratorAdapter(stdout); - final int result = await Pigeon.run(['--input', input.path], - adapters: [generator]); + final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter( + stdout, + ); + final int result = await Pigeon.run( + ['--input', input.path], + adapters: [generator], + ); expect(generator.didCallValidate, isTrue); expect(result, isNot(0)); completer.complete(); @@ -1365,11 +1474,13 @@ abstract class Api { test('generator validation skipped', () async { final Completer completer = Completer(); withTempFile('foo.dart', (File input) async { - final _ValidatorGeneratorAdapter generator = - _ValidatorGeneratorAdapter(null); + final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter( + null, + ); final int result = await Pigeon.run( - ['--input', input.path, '--dart_out', 'foo.dart'], - adapters: [generator]); + ['--input', input.path, '--dart_out', 'foo.dart'], + adapters: [generator], + ); expect(generator.didCallValidate, isFalse); expect(result, equals(0)); completer.complete(); @@ -1380,11 +1491,13 @@ abstract class Api { test('run with PigeonOptions', () async { final Completer completer = Completer(); withTempFile('foo.dart', (File input) async { - final _ValidatorGeneratorAdapter generator = - _ValidatorGeneratorAdapter(null); + final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter( + null, + ); final int result = await Pigeon.runWithOptions( - PigeonOptions(input: input.path, dartOut: 'foo.dart'), - adapters: [generator]); + PigeonOptions(input: input.path, dartOut: 'foo.dart'), + adapters: [generator], + ); expect(generator.didCallValidate, isFalse); expect(result, equals(0)); completer.complete(); @@ -1402,8 +1515,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 1); - expect(results.errors[0].message, - contains('FlutterApi method parameters must be positional')); + expect( + results.errors[0].message, + contains('FlutterApi method parameters must be positional'), + ); }); test('unsupported optional parameters on FlutterApi', () { @@ -1416,8 +1531,10 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors.length, 1); - expect(results.errors[0].message, - contains('FlutterApi method parameters must not be optional')); + expect( + results.errors[0].message, + contains('FlutterApi method parameters must not be optional'), + ); }); test('simple parse ProxyApi', () { @@ -1528,9 +1645,9 @@ abstract class MyOtherClass { }); test( - 'api is not used as an attached field while having an unattached field', - () { - const String code = ''' + 'api is not used as an attached field while having an unattached field', + () { + const String code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1542,20 +1659,21 @@ abstract class MyOtherClass { late int aField; } '''; - final ParseResults parseResult = parseSource(code); - expect(parseResult.errors, isNotEmpty); - expect( - parseResult.errors[0].message, - contains( - 'ProxyApis with unattached fields can not be used as attached fields: anAttachedField', - ), - ); - }); + final ParseResults parseResult = parseSource(code); + expect(parseResult.errors, isNotEmpty); + expect( + parseResult.errors[0].message, + contains( + 'ProxyApis with unattached fields can not be used as attached fields: anAttachedField', + ), + ); + }, + ); test( - 'api is not used as an attached field while having a required Flutter method', - () { - const String code = ''' + 'api is not used as an attached field while having a required Flutter method', + () { + const String code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1567,15 +1685,16 @@ abstract class MyOtherClass { late void Function() aCallbackMethod; } '''; - final ParseResults parseResult = parseSource(code); - expect(parseResult.errors, isNotEmpty); - expect( - parseResult.errors[0].message, - contains( - 'ProxyApis with required callback methods can not be used as attached fields: anAttachedField', - ), - ); - }); + final ParseResults parseResult = parseSource(code); + expect(parseResult.errors, isNotEmpty); + expect( + parseResult.errors[0].message, + contains( + 'ProxyApis with required callback methods can not be used as attached fields: anAttachedField', + ), + ); + }, + ); test('interfaces can only have callback methods', () { const String code = ''' @@ -1661,7 +1780,8 @@ abstract class EventChannelApi { expect( parseResult.errors.single.message, contains( - 'event channel methods must not be contain parameters, in method "streamInts" in API: "EventChannelApi"'), + 'event channel methods must not be contain parameters, in method "streamInts" in API: "EventChannelApi"', + ), ); }); }); diff --git a/packages/pigeon/test/swift/proxy_api_test.dart b/packages/pigeon/test/swift/proxy_api_test.dart index 8a7538d9bb0..c2d25cde62a 100644 --- a/packages/pigeon/test/swift/proxy_api_test.dart +++ b/packages/pigeon/test/swift/proxy_api_test.dart @@ -16,7 +16,9 @@ void main() { AstProxyApi( name: 'Api', swiftOptions: const SwiftProxyApiOptions( - name: 'MyLibraryApi', import: 'MyLibrary'), + name: 'MyLibraryApi', + import: 'MyLibrary', + ), constructors: [ Constructor( name: 'name', @@ -34,11 +36,8 @@ void main() { fields: [ ApiField( name: 'someField', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ) + type: const TypeDeclaration(baseName: 'int', isNullable: false), + ), ], methods: [ Method( @@ -51,7 +50,7 @@ void main() { isNullable: false, ), name: 'input', - ) + ), ], returnType: const TypeDeclaration( baseName: 'String', @@ -77,7 +76,7 @@ void main() { ), ), ], - ) + ), ], classes: [], enums: [], @@ -86,7 +85,9 @@ void main() { const SwiftGenerator generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions( - fileSpecificClassNameComponent: 'MyFile', swiftOut: ''), + fileSpecificClassNameComponent: 'MyFile', + swiftOut: '', + ), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -98,32 +99,20 @@ void main() { expect(code, contains('import MyLibrary')); // Instance Manager - expect( - code, - contains( - r'final class MyFilePigeonInstanceManager', - ), - ); - expect( - code, - contains( - r'private class MyFilePigeonInstanceManagerApi', - ), - ); + expect(code, contains(r'final class MyFilePigeonInstanceManager')); + expect(code, contains(r'private class MyFilePigeonInstanceManagerApi')); // ProxyApi Delegate expect(code, contains(r'protocol MyFilePigeonProxyApiDelegate')); expect( collapsedCode, contains( - r'func pigeonApiApi(_ registrar: MyFilePigeonProxyApiRegistrar) -> PigeonApiApi'), + r'func pigeonApiApi(_ registrar: MyFilePigeonProxyApiRegistrar) -> PigeonApiApi', + ), ); // API registrar - expect( - code, - contains('open class MyFilePigeonProxyApiRegistrar'), - ); + expect(code, contains('open class MyFilePigeonProxyApiRegistrar')); // ReaderWriter expect( @@ -136,12 +125,7 @@ void main() { // Delegate and class expect(code, contains('protocol PigeonApiDelegateApi')); expect(code, contains('protocol PigeonApiProtocolApi')); - expect( - code, - contains( - r'class PigeonApiApi: PigeonApiProtocolApi', - ), - ); + expect(code, contains(r'class PigeonApiApi: PigeonApiProtocolApi')); // Constructors expect( @@ -298,9 +282,7 @@ void main() { ), AstProxyApi( name: 'Api2', - swiftOptions: const SwiftProxyApiOptions( - import: 'MyImport', - ), + swiftOptions: const SwiftProxyApiOptions(import: 'MyImport'), constructors: [], fields: [], methods: [], @@ -331,20 +313,24 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - superClass: TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + superClass: TypeDeclaration( + baseName: api2.name, + isNullable: false, + associatedProxyApi: api2, + ), ), - ), - api2, - ], classes: [], enums: []); + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const SwiftGenerator generator = SwiftGenerator(); generator.generate( @@ -354,10 +340,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect( - code, - contains('var pigeonApiApi2: PigeonApiApi2'), - ); + expect(code, contains('var pigeonApiApi2: PigeonApiApi2')); }); test('implements', () { @@ -367,22 +350,26 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ) - }, - ), - api2, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: api2.name, + isNullable: false, + associatedProxyApi: api2, + ), + }, + ), + api2, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const SwiftGenerator generator = SwiftGenerator(); generator.generate( @@ -408,28 +395,32 @@ void main() { fields: [], methods: [], ); - final Root root = Root(apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ), - TypeDeclaration( - baseName: api3.name, - isNullable: false, - associatedProxyApi: api3, - ), - }, - ), - api2, - api3, - ], classes: [], enums: []); + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], + interfaces: { + TypeDeclaration( + baseName: api2.name, + isNullable: false, + associatedProxyApi: api2, + ), + TypeDeclaration( + baseName: api3.name, + isNullable: false, + associatedProxyApi: api3, + ), + }, + ), + api2, + api3, + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); const SwiftGenerator generator = SwiftGenerator(); generator.generate( @@ -448,12 +439,14 @@ void main() { test('empty name and no params constructor', () { final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: '', - parameters: [], - ) - ], fields: [], methods: []), + AstProxyApi( + name: 'Api', + constructors: [ + Constructor(name: '', parameters: []), + ], + fields: [], + methods: [], + ), ], classes: [], enums: [], @@ -468,14 +461,12 @@ void main() { ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - code, - contains('class PigeonApiApi: PigeonApiProtocolApi '), - ); + expect(code, contains('class PigeonApiApi: PigeonApiProtocolApi ')); expect( collapsedCode, contains( - 'func pigeonDefaultConstructor(pigeonApi: PigeonApiApi) throws -> Api'), + 'func pigeonDefaultConstructor(pigeonApi: PigeonApiApi) throws -> Api', + ), ); expect( collapsedCode, @@ -494,12 +485,17 @@ void main() { test('named constructor', () { final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: 'myConstructorName', - parameters: [], - ) - ], fields: [], methods: []), + AstProxyApi( + name: 'Api', + constructors: [ + Constructor( + name: 'myConstructorName', + parameters: [], + ), + ], + fields: [], + methods: [], + ), ], classes: [], enums: [], @@ -535,57 +531,62 @@ void main() { ); final Root root = Root( apis: [ - AstProxyApi(name: 'Api', constructors: [ - Constructor( - name: 'name', - parameters: [ - Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', + AstProxyApi( + name: 'Api', + constructors: [ + Constructor( + name: 'name', + parameters: [ + Parameter( + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + name: 'validType', ), - name: 'validType', - ), - Parameter( - type: TypeDeclaration( - isNullable: false, - baseName: 'AnEnum', - associatedEnum: anEnum, + Parameter( + type: TypeDeclaration( + isNullable: false, + baseName: 'AnEnum', + associatedEnum: anEnum, + ), + name: 'enumType', ), - name: 'enumType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', + Parameter( + type: const TypeDeclaration( + isNullable: false, + baseName: 'Api2', + ), + name: 'proxyApiType', ), - name: 'proxyApiType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', + Parameter( + type: const TypeDeclaration( + isNullable: true, + baseName: 'int', + ), + name: 'nullableValidType', ), - name: 'nullableValidType', - ), - Parameter( - type: TypeDeclaration( - isNullable: true, - baseName: 'AnEnum', - associatedEnum: anEnum, + Parameter( + type: TypeDeclaration( + isNullable: true, + baseName: 'AnEnum', + associatedEnum: anEnum, + ), + name: 'nullableEnumType', ), - name: 'nullableEnumType', - ), - Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', + Parameter( + type: const TypeDeclaration( + isNullable: true, + baseName: 'Api2', + ), + name: 'nullableProxyApiType', ), - name: 'nullableProxyApiType', - ), - ], - ) - ], fields: [], methods: []), + ], + ), + ], + fields: [], + methods: [], + ), AstProxyApi( name: 'Api2', constructors: [], @@ -606,12 +607,7 @@ void main() { ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - code, - contains( - 'class PigeonApiApi: PigeonApiProtocolApi ', - ), - ); + expect(code, contains('class PigeonApiApi: PigeonApiProtocolApi ')); expect( collapsedCode, contains( @@ -630,45 +626,49 @@ void main() { }); test( - 'host platform constructor calls new instance error for required callbacks', - () { - final Root root = Root( - apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [ - Method( - name: 'aCallbackMethod', - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [], - location: ApiLocation.flutter, - ), - ], + 'host platform constructor calls new instance error for required callbacks', + () { + final Root root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [ + Method( + name: 'aCallbackMethod', + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [], + location: ApiLocation.flutter, + ), + ], + ), + ], + classes: [], + enums: [], + ); + final StringBuffer sink = StringBuffer(); + const SwiftGenerator generator = SwiftGenerator(); + generator.generate( + const InternalSwiftOptions( + errorClassName: 'TestError', + swiftOut: '', ), - ], - classes: [], - enums: [], - ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); - generator.generate( - const InternalSwiftOptions(errorClassName: 'TestError', swiftOut: ''), - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final String code = sink.toString(); - final String collapsedCode = _collapseNewlineAndIndentation(code); + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final String code = sink.toString(); + final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains( - r'completion( .failure( TestError( code: "new-instance-error"', - ), - ); - }); + expect( + collapsedCode, + contains( + r'completion( .failure( TestError( code: "new-instance-error"', + ), + ); + }, + ); }); group('Fields', () { @@ -682,10 +682,7 @@ void main() { AstProxyApi( name: 'Api', constructors: [ - Constructor( - name: 'name', - parameters: [], - ) + Constructor(name: 'name', parameters: []), ], fields: [ ApiField( @@ -774,23 +771,27 @@ void main() { expect( collapsedCode, contains( - 'channel.sendMessage([pigeonIdentifierArg, validTypeArg, enumTypeArg, ' - 'proxyApiTypeArg, nullableValidTypeArg, nullableEnumTypeArg, nullableProxyApiTypeArg] as [Any?])'), + 'channel.sendMessage([pigeonIdentifierArg, validTypeArg, enumTypeArg, ' + 'proxyApiTypeArg, nullableValidTypeArg, nullableEnumTypeArg, nullableProxyApiTypeArg] as [Any?])', + ), ); expect( code, contains( - r'func validType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Int64'), + r'func validType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Int64', + ), ); expect( code, contains( - r'func enumType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> AnEnum'), + r'func enumType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> AnEnum', + ), ); expect( code, contains( - r'func proxyApiType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Api2'), + r'func proxyApiType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Api2', + ), ); expect( code, @@ -854,7 +855,8 @@ void main() { expect( code, contains( - r'func aField(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Api2'), + r'func aField(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Api2', + ), ); expect( code, @@ -1070,8 +1072,9 @@ void main() { name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root(apis: [ - AstProxyApi( + final Root root = Root( + apis: [ + AstProxyApi( name: 'Api', constructors: [], fields: [], @@ -1126,11 +1129,13 @@ void main() { ), ], returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [], enums: [ - anEnum - ]); + ), + ], + ), + ], + classes: [], + enums: [anEnum], + ); final StringBuffer sink = StringBuffer(); const SwiftGenerator generator = SwiftGenerator(); generator.generate( diff --git a/packages/pigeon/test/swift_generator_test.dart b/packages/pigeon/test/swift_generator_test.dart index a06f555b716..1e4cc84dc5c 100644 --- a/packages/pigeon/test/swift_generator_test.dart +++ b/packages/pigeon/test/swift_generator_test.dart @@ -8,12 +8,15 @@ import 'package:test/test.dart'; import 'dart_generator_test.dart'; -final Class emptyClass = Class(name: 'className', fields: [ - NamedType( - name: 'namedTypeName', - type: const TypeDeclaration(baseName: 'baseName', isNullable: false), - ) -]); +final Class emptyClass = Class( + name: 'className', + fields: [ + NamedType( + name: 'namedTypeName', + type: const TypeDeclaration(baseName: 'baseName', isNullable: false), + ), + ], +); final Enum emptyEnum = Enum( name: 'enumName', @@ -26,11 +29,9 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'field1'), + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), ], ); final Root root = Root( @@ -39,8 +40,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -51,8 +53,10 @@ void main() { final String code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: Int64? = nil')); - expect(code, - contains('static func fromList(_ pigeonVar_list: [Any?]) -> Foobar?')); + expect( + code, + contains('static func fromList(_ pigeonVar_list: [Any?]) -> Foobar?'), + ); expect(code, contains('func toList() -> [Any?]')); expect(code, isNot(contains('if ('))); }); @@ -60,10 +64,7 @@ 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: [], @@ -71,8 +72,9 @@ void main() { enums: [anEnum], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -88,31 +90,44 @@ void main() { }); test('primitive enum host', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Bar', methods: [ - Method( - name: 'bar', - location: ApiLocation.host, - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [ - Parameter( + final Root root = Root( + apis: [ + AstHostApi( + name: 'Bar', + methods: [ + Method( + name: 'bar', + location: ApiLocation.host, + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [ + Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', associatedEnum: emptyEnum, isNullable: false, - )) - ]) - ]) - ], classes: [], enums: [ - Enum(name: 'Foo', members: [ - EnumMember(name: 'one'), - EnumMember(name: 'two'), - ]) - ]); + ), + ), + ], + ), + ], + ), + ], + classes: [], + enums: [ + Enum( + name: 'Foo', + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], + ), + ], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -123,57 +138,70 @@ void main() { final String code = sink.toString(); expect(code, contains('enum Foo: Int')); expect( - code, - contains( - 'let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)')); + code, + contains( + 'let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)', + ), + ); expect(code, contains('return Foo(rawValue: enumResultAsInt)')); expect(code, contains('let fooArg = args[0] as! Foo')); expect(code, isNot(contains('if ('))); }); test('gen one host api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -189,62 +217,66 @@ void main() { }); test('all the simple datatypes header', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'bool', isNullable: true), + name: 'aBool', ), - name: 'aBool'), - NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'aInt', ), - name: 'aInt'), - NamedType( - type: const TypeDeclaration( - baseName: 'double', - isNullable: true, + NamedType( + type: const TypeDeclaration(baseName: 'double', isNullable: true), + name: 'aDouble', ), - name: 'aDouble'), - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'aString', ), - name: 'aString'), - NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Uint8List', + isNullable: true, + ), + name: 'aUint8List', ), - name: 'aUint8List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Int32List', + isNullable: true, + ), + name: 'aInt32List', ), - name: 'aInt32List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Int64List', + isNullable: true, + ), + name: 'aInt64List', ), - name: 'aInt64List'), - NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, + NamedType( + type: const TypeDeclaration( + baseName: 'Float64List', + isNullable: true, + ), + name: 'aFloat64List', ), - name: 'aFloat64List'), - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -266,8 +298,9 @@ void main() { test('gen pigeon error type', () { final Root root = Root(apis: [], classes: [], enums: []); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( @@ -281,53 +314,66 @@ void main() { expect(code, contains('let code: String')); expect(code, contains('let message: String?')); expect(code, contains('let details: Sendable?')); - expect(code, - contains('init(code: String, message: String?, details: Sendable?)')); + expect( + code, + contains('init(code: String, message: String?, details: Sendable?)'), + ); }); test('gen one flutter api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -338,45 +384,57 @@ void main() { final String code = sink.toString(); expect(code, contains('class Api')); expect( - code, - contains( - 'init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "")')); + code, + contains( + 'init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "")', + ), + ); expect(code, matches('func doSomething.*Input.*Output')); expect(code, isNot(contains('if ('))); expect(code, isNot(matches(RegExp(r';$', multiLine: true)))); }); test('gen host void api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -391,36 +449,46 @@ void main() { }); test('gen flutter void return api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -429,39 +497,50 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); - expect(code, - contains('completion: @escaping (Result) -> Void')); + expect( + code, + contains('completion: @escaping (Result) -> Void'), + ); expect(code, contains('completion(.success(()))')); expect(code, isNot(contains('if ('))); }); test('gen host void argument api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + ), + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -477,32 +556,41 @@ void main() { }); test('gen flutter void argument api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - ) - ]) - ], classes: [ - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), ), - name: 'output') - ]), - ], enums: []); + ], + ), + ], + classes: [ + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', + ), + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -512,27 +600,35 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'func doSomething(completion: @escaping (Result) -> Void)')); + code, + contains( + 'func doSomething(completion: @escaping (Result) -> Void)', + ), + ); expect(code, contains('channel.sendMessage(nil')); expect(code, isNot(contains('if ('))); }); test('gen list', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'List', isNullable: true), + name: 'field1', ), - name: 'field1') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -547,19 +643,25 @@ void main() { }); test('gen map', () { - final Root root = Root(apis: [], classes: [ - Class(name: 'Foobar', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, + final Root root = Root( + apis: [], + classes: [ + Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'Map', isNullable: true), + name: 'field1', ), - name: 'field1') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -578,23 +680,22 @@ void main() { name: 'Outer', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: true, - ), - name: 'nested') + type: TypeDeclaration( + baseName: 'Nested', + associatedClass: emptyClass, + isNullable: true, + ), + name: 'nested', + ), ], ); final Class nestedClass = Class( name: 'Nested', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), - name: 'data') + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'data', + ), ], ); final Root root = Root( @@ -603,8 +704,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -616,10 +718,14 @@ void main() { expect(code, contains('struct Outer')); expect(code, contains('struct Nested')); expect(code, contains('var nested: Nested? = nil')); - expect(code, - contains('static func fromList(_ pigeonVar_list: [Any?]) -> Outer?')); expect( - code, contains('let nested: Nested? = nilOrValue(pigeonVar_list[0])')); + code, + contains('static func fromList(_ pigeonVar_list: [Any?]) -> Outer?'), + ); + expect( + code, + contains('let nested: Nested? = nilOrValue(pigeonVar_list[0])'), + ); expect(code, contains('func toList() -> [Any?]')); expect(code, isNot(contains('if ('))); // Single-element list serializations should not have a trailing comma. @@ -627,49 +733,60 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: 'arg', ), - name: 'arg') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -685,49 +802,60 @@ void main() { }); test('gen one async Flutter Api', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -744,21 +872,19 @@ 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', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), - name: 'enum1'), + type: TypeDeclaration( + baseName: 'Enum1', + associatedEnum: emptyEnum, + isNullable: true, + ), + name: 'enum1', + ), ], ); final Root root = Root( @@ -767,8 +893,9 @@ void main() { enums: [anEnum], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -808,13 +935,15 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'List', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'List', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -823,8 +952,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -842,14 +972,16 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'String', isNullable: true), - ]), - name: 'field1'), + type: const TypeDeclaration( + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'String', isNullable: true), + ], + ), + name: 'field1', + ), ], ); final Root root = Root( @@ -858,8 +990,9 @@ void main() { enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -875,29 +1008,36 @@ void main() { test('host generics argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -912,29 +1052,36 @@ void main() { test('flutter generics argument', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - name: 'arg') - ]) - ]) + type: const TypeDeclaration( + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + name: 'arg', + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -949,25 +1096,31 @@ void main() { test('host generics return', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -984,64 +1137,89 @@ void main() { test('flutter generics return', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( - baseName: 'List', - isNullable: false, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true) - ]), - parameters: []) - ]) + baseName: 'List', + isNullable: false, + typeArguments: [ + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), + parameters: [], + ), + ], + ), + ], + classes: [], + enums: [], + ); + final StringBuffer sink = StringBuffer(); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); + const SwiftGenerator generator = SwiftGenerator(); + generator.generate( + swiftOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final String code = sink.toString(); + expect( + code, + contains( + 'func doit(completion: @escaping (Result<[Int64?], PigeonError>) -> Void)', + ), + ); + expect(code, contains('let result = listResponse[0] as! [Int64?]')); + expect(code, contains('completion(.success(result))')); + }); + + test('host multiple args', () { + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.host, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + isNullable: false, + baseName: 'int', + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); - const SwiftGenerator generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', ); - final String code = sink.toString(); - expect( - code, - contains( - 'func doit(completion: @escaping (Result<[Int64?], PigeonError>) -> Void)')); - expect(code, contains('let result = listResponse[0] as! [Int64?]')); - expect(code, contains('completion(.success(result))')); - }); - - test('host multiple args', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.host, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - Parameter( - name: 'y', - type: - const TypeDeclaration(isNullable: false, baseName: 'int')), - ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1059,28 +1237,45 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'add', - location: ApiLocation.flutter, - parameters: [ - Parameter( - name: 'x', - type: - const TypeDeclaration(baseName: 'int', isNullable: false)), - Parameter( - name: 'y', - type: - const TypeDeclaration(baseName: 'int', isNullable: false)), + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'add', + location: ApiLocation.flutter, + parameters: [ + Parameter( + name: 'x', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + Parameter( + name: 'y', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ], + returnType: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), ], - returnType: const TypeDeclaration(baseName: 'int', isNullable: false), - ) - ]) - ], classes: [], enums: []); + ), + ], + classes: [], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1093,33 +1288,42 @@ void main() { expect(code, contains('let result = listResponse[0] as! Int64')); expect(code, contains('completion(.success(result))')); expect( - code, - contains( - 'func add(x xArg: Int64, y yArg: Int64, completion: @escaping (Result) -> Void)')); - expect(code, - contains('channel.sendMessage([xArg, yArg] as [Any?]) { response in')); + code, + contains( + 'func add(x xArg: Int64, y yArg: Int64, completion: @escaping (Result) -> Void)', + ), + ); + expect( + code, + contains('channel.sendMessage([xArg, yArg] as [Any?]) { response in'), + ); }); test('return nullable host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1134,8 +1338,10 @@ void main() { test('return nullable host async', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( @@ -1143,15 +1349,18 @@ void main() { isNullable: true, ), isAsynchronous: true, - parameters: []) - ]) + parameters: [], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1161,35 +1370,43 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'func doit(completion: @escaping (Result) -> Void')); + code, + contains( + 'func doit(completion: @escaping (Result) -> Void', + ), + ); }); test('nullable argument host', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( + AstHostApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1204,27 +1421,33 @@ void main() { test('nullable argument flutter', () { final Root root = Root( apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( + AstFlutterApi( + name: 'Api', + methods: [ + Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: [ Parameter( - name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - )), - ]) - ]) + name: 'foo', + type: const TypeDeclaration( + baseName: 'int', + isNullable: true, + ), + ), + ], + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1234,42 +1457,57 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'func doit(foo fooArg: Int64?, completion: @escaping (Result) -> Void)')); + code, + contains( + 'func doit(foo fooArg: Int64?, completion: @escaping (Result) -> Void)', + ), + ); }); test('nonnull fields', () { - final Root root = Root(apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.host, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.host, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: const TypeDeclaration.voidDeclaration(), + ), ], - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: 'input', ), - name: 'input') - ]), - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1315,9 +1553,9 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [ Class( @@ -1327,12 +1565,13 @@ void main() { NamedType( documentationComments: [comments[count++]], type: const TypeDeclaration( - baseName: 'Map', - isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'String', isNullable: true), - TypeDeclaration(baseName: 'int', isNullable: true), - ]), + baseName: 'Map', + isNullable: true, + typeArguments: [ + TypeDeclaration(baseName: 'String', isNullable: true), + TypeDeclaration(baseName: 'int', isNullable: true), + ], + ), name: 'field1', ), ], @@ -1343,7 +1582,7 @@ void main() { name: 'enum', documentationComments: [ comments[count++], - unspacedComments[unspacedCount++] + unspacedComments[unspacedCount++], ], members: [ EnumMember( @@ -1356,8 +1595,9 @@ void main() { ], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1373,49 +1613,60 @@ void main() { }); test('creates custom codecs', () { - final Root root = Root(apis: [ - AstFlutterApi(name: 'Api', methods: [ - Method( - name: 'doSomething', - location: ApiLocation.flutter, - parameters: [ - Parameter( - type: TypeDeclaration( - baseName: 'Input', - associatedClass: emptyClass, - isNullable: false, + final Root root = Root( + apis: [ + AstFlutterApi( + name: 'Api', + methods: [ + Method( + name: 'doSomething', + location: ApiLocation.flutter, + parameters: [ + Parameter( + type: TypeDeclaration( + baseName: 'Input', + associatedClass: emptyClass, + isNullable: false, + ), + name: '', ), - name: '') + ], + returnType: TypeDeclaration( + baseName: 'Output', + associatedClass: emptyClass, + isNullable: false, + ), + isAsynchronous: true, + ), ], - returnType: TypeDeclaration( - baseName: 'Output', - associatedClass: emptyClass, - isNullable: false, - ), - isAsynchronous: true, - ) - ]) - ], classes: [ - Class(name: 'Input', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ), + ], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', ), - name: 'input') - ]), - Class(name: 'Output', fields: [ - NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, + ], + ), + Class( + name: 'Output', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'output', ), - name: 'output') - ]) - ], enums: []); + ], + ), + ], + enums: [], + ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1430,37 +1681,41 @@ void main() { test('swift function signature', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'set', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'set', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + name: 'value', ), - name: 'value', - ), - Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, + Parameter( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: 'key', ), - name: 'key', - ), - ], - swiftFunction: 'setValue(_:for:)', - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) + ], + swiftFunction: 'setValue(_:for:)', + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1475,30 +1730,34 @@ void main() { test('swift function signature with same name argument', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'set', - location: ApiLocation.host, - parameters: [ - Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'set', + location: ApiLocation.host, + parameters: [ + Parameter( + type: const TypeDeclaration( + baseName: 'String', + isNullable: false, + ), + name: 'key', ), - name: 'key', - ), - ], - swiftFunction: 'removeValue(key:)', - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) + ], + swiftFunction: 'removeValue(key:)', + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1513,22 +1772,26 @@ void main() { test('swift function signature with no arguments', () { final Root root = Root( apis: [ - AstHostApi(name: 'Api', methods: [ - Method( - name: 'clear', - location: ApiLocation.host, - parameters: [], - swiftFunction: 'removeAll()', - returnType: const TypeDeclaration.voidDeclaration(), - ) - ]) + AstHostApi( + name: 'Api', + methods: [ + Method( + name: 'clear', + location: ApiLocation.host, + parameters: [], + swiftFunction: 'removeAll()', + returnType: const TypeDeclaration.voidDeclaration(), + ), + ], + ), ], classes: [], enums: [], ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -1559,17 +1822,18 @@ void main() { ), ), ], - ) + ), ], - ) + ), ], classes: [], enums: [], containsFlutterApi: true, ); final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions kotlinOptions = - InternalSwiftOptions(swiftOut: ''); + const InternalSwiftOptions kotlinOptions = InternalSwiftOptions( + swiftOut: '', + ); const SwiftGenerator generator = SwiftGenerator(); generator.generate( kotlinOptions, @@ -1579,12 +1843,16 @@ void main() { ); final String code = sink.toString(); expect( - code, - contains( - 'completion(.failure(createConnectionError(withChannelName: channelName)))')); + code, + contains( + 'completion(.failure(createConnectionError(withChannelName: channelName)))', + ), + ); expect( - code, - contains( - 'return PigeonError(code: "channel-error", message: "Unable to establish connection on channel: \'\\(channelName)\'.", details: "")')); + code, + contains( + 'return PigeonError(code: "channel-error", message: "Unable to establish connection on channel: \'\\(channelName)\'.", details: "")', + ), + ); }); } diff --git a/packages/pigeon/test/version_test.dart b/packages/pigeon/test/version_test.dart index c08d4306dd4..fe7ca13e4dc 100644 --- a/packages/pigeon/test/version_test.dart +++ b/packages/pigeon/test/version_test.dart @@ -14,8 +14,11 @@ void main() { final RegExp regex = RegExp(r'version:\s*(.*?) #'); final RegExpMatch? match = regex.firstMatch(pubspec); expect(match, isNotNull); - expect(pigeonVersion, match?.group(1)?.trim(), - reason: - 'Update lib/src/generator_tools.dart pigeonVersion to the value in the pubspec'); + expect( + pigeonVersion, + match?.group(1)?.trim(), + reason: + 'Update lib/src/generator_tools.dart pigeonVersion to the value in the pubspec', + ); }); } diff --git a/packages/pigeon/tool/generate.dart b/packages/pigeon/tool/generate.dart index 752e2ffadc2..528cbc08122 100644 --- a/packages/pigeon/tool/generate.dart +++ b/packages/pigeon/tool/generate.dart @@ -28,33 +28,40 @@ 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)) { @@ -69,14 +76,17 @@ ${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...'); final int generateExitCode = await generateTestPigeons( - baseDir: baseDir, includeOverflow: includeOverflow); + baseDir: baseDir, + includeOverflow: includeOverflow, + ); if (generateExitCode == 0) { print('Generation complete!'); } else { @@ -98,8 +108,9 @@ ${parser.usage}'''); if (!argResults.wasParsed(_noFormatFlag)) { print('Formatting generated output...'); - final int formatExitCode = - await formatAllFiles(repositoryRoot: p.dirname(p.dirname(baseDir))); + final int formatExitCode = await formatAllFiles( + repositoryRoot: p.dirname(p.dirname(baseDir)), + ); if (formatExitCode != 0) { print('Formatting failed; see above for errors.'); exit(formatExitCode); diff --git a/packages/pigeon/tool/run_tests.dart b/packages/pigeon/tool/run_tests.dart index 7c6c12c428a..70d51fa6859 100644 --- a/packages/pigeon/tool/run_tests.dart +++ b/packages/pigeon/tool/run_tests.dart @@ -73,9 +73,7 @@ Future _validateGeneratedFiles( GeneratorLanguage.objc, }; } else if (Platform.isMacOS) { - languagesToValidate = { - GeneratorLanguage.swift, - }; + languagesToValidate = {GeneratorLanguage.swift}; } else { return; } @@ -103,7 +101,9 @@ Future _validateGeneratedFiles( print(' Formatting output...'); final int formatExitCode = await formatAllFiles( - repositoryRoot: repositoryRoot, languages: languagesToValidate); + repositoryRoot: repositoryRoot, + languages: languagesToValidate, + ); if (formatExitCode != 0) { print('Formatting failed; see above for errors.'); exit(formatExitCode); @@ -111,13 +111,18 @@ Future _validateGeneratedFiles( print(' Checking for changes...'); final List modifiedFiles = await _modifiedFiles( - repositoryRoot: repositoryRoot, relativePigeonPath: relativePigeonPath); - final Set extensions = languagesToValidate - .map((GeneratorLanguage lang) => _extensionsForLanguage(lang)) - .flattened - .toSet(); - final Iterable filteredFiles = modifiedFiles.where((String path) => - extensions.contains(p.extension(path).replaceFirst('.', ''))); + repositoryRoot: repositoryRoot, + relativePigeonPath: relativePigeonPath, + ); + final Set extensions = + languagesToValidate + .map((GeneratorLanguage lang) => _extensionsForLanguage(lang)) + .flattened + .toSet(); + final Iterable filteredFiles = modifiedFiles.where( + (String path) => + extensions.contains(p.extension(path).replaceFirst('.', '')), + ); if (filteredFiles.isEmpty) { return; @@ -126,14 +131,15 @@ Future _validateGeneratedFiles( print(incorrectFilesMessage); filteredFiles.map((String line) => ' $line').forEach(print); - print('\nTo fix run "dart run tool/generate.dart --format" from the pigeon/ ' - 'directory, or apply the diff with the command below.\n'); - - final ProcessResult diffResult = await Process.run( - 'git', - ['diff', ...filteredFiles], - workingDirectory: repositoryRoot, + print( + '\nTo fix run "dart run tool/generate.dart --format" from the pigeon/ ' + 'directory, or apply the diff with the command below.\n', ); + + final ProcessResult diffResult = await Process.run('git', [ + 'diff', + ...filteredFiles, + ], workingDirectory: repositoryRoot); if (diffResult.exitCode != 0) { print('Unable to determine diff.'); exit(1); @@ -156,14 +162,15 @@ Set _extensionsForLanguage(GeneratorLanguage language) { }; } -Future> _modifiedFiles( - {required String repositoryRoot, - required String relativePigeonPath}) async { - final ProcessResult result = await Process.run( - 'git', - ['ls-files', '--modified', relativePigeonPath], - workingDirectory: repositoryRoot, - ); +Future> _modifiedFiles({ + required String repositoryRoot, + required String relativePigeonPath, +}) async { + final ProcessResult result = await Process.run('git', [ + 'ls-files', + '--modified', + relativePigeonPath, + ], workingDirectory: repositoryRoot); if (result.exitCode != 0) { print('Unable to determine changed files.'); print(result.stdout); diff --git a/packages/pigeon/tool/shared/flutter_utils.dart b/packages/pigeon/tool/shared/flutter_utils.dart index 635b6dafac2..8669564f4d9 100644 --- a/packages/pigeon/tool/shared/flutter_utils.dart +++ b/packages/pigeon/tool/shared/flutter_utils.dart @@ -10,11 +10,10 @@ String getFlutterCommand() => Platform.isWindows ? 'flutter.bat' : 'flutter'; /// Returns the first device listed by `flutter devices` that targets /// [platform], or null if there is no such device. Future getDeviceForPlatform(String platform) async { - final ProcessResult result = await Process.run( - getFlutterCommand(), - ['devices', '--machine'], - stdoutEncoding: utf8, - ); + final ProcessResult result = await Process.run(getFlutterCommand(), [ + 'devices', + '--machine', + ], stdoutEncoding: utf8); if (result.exitCode != 0) { return null; } diff --git a/packages/pigeon/tool/shared/generation.dart b/packages/pigeon/tool/shared/generation.dart index 1714ffe22b4..6d9727b9b87 100644 --- a/packages/pigeon/tool/shared/generation.dart +++ b/packages/pigeon/tool/shared/generation.dart @@ -11,45 +11,38 @@ import 'package:pigeon/src/generator_tools.dart'; import 'process_utils.dart'; -enum GeneratorLanguage { - cpp, - dart, - gobject, - java, - kotlin, - objc, - swift, -} +enum GeneratorLanguage { cpp, dart, gobject, java, kotlin, objc, swift } // A map of pigeons/ files to the languages that they can't yet be generated // for due to limitations of that generator. const Map> _unsupportedFiles = >{ - 'event_channel_tests': { - GeneratorLanguage.cpp, - GeneratorLanguage.gobject, - GeneratorLanguage.java, - GeneratorLanguage.objc, - }, - 'event_channel_without_classes_tests': { - GeneratorLanguage.cpp, - GeneratorLanguage.gobject, - GeneratorLanguage.java, - GeneratorLanguage.objc, - }, - 'proxy_api_tests': { - GeneratorLanguage.cpp, - GeneratorLanguage.gobject, - GeneratorLanguage.java, - GeneratorLanguage.objc, - }, -}; + 'event_channel_tests': { + GeneratorLanguage.cpp, + GeneratorLanguage.gobject, + GeneratorLanguage.java, + GeneratorLanguage.objc, + }, + 'event_channel_without_classes_tests': { + GeneratorLanguage.cpp, + GeneratorLanguage.gobject, + GeneratorLanguage.java, + GeneratorLanguage.objc, + }, + 'proxy_api_tests': { + GeneratorLanguage.cpp, + GeneratorLanguage.gobject, + GeneratorLanguage.java, + GeneratorLanguage.objc, + }, + }; String _snakeToPascalCase(String snake) { final List parts = snake.split('_'); return parts - .map((String part) => - part.substring(0, 1).toUpperCase() + part.substring(1)) + .map( + (String part) => part.substring(0, 1).toUpperCase() + part.substring(1), + ) .join(); } @@ -82,8 +75,10 @@ Future generateExamplePigeons() async { return success; } -Future generateTestPigeons( - {required String baseDir, bool includeOverflow = false}) async { +Future generateTestPigeons({ + required String baseDir, + bool includeOverflow = false, +}) async { // TODO(stuartmorgan): Make this dynamic rather than hard-coded. Or eliminate // it entirely; see https://github.com/flutter/flutter/issues/115169. const Set inputs = { @@ -104,10 +99,16 @@ Future generateTestPigeons( const String testPluginName = 'test_plugin'; const String alternateTestPluginName = 'alternate_language_test_plugin'; final String outputBase = p.join(baseDir, 'platform_tests', testPluginName); - final String alternateOutputBase = - p.join(baseDir, 'platform_tests', alternateTestPluginName); - final String sharedDartOutputBase = - p.join(baseDir, 'platform_tests', 'shared_test_plugin_code'); + final String alternateOutputBase = p.join( + baseDir, + 'platform_tests', + alternateTestPluginName, + ); + final String sharedDartOutputBase = p.join( + baseDir, + 'platform_tests', + 'shared_test_plugin_code', + ); for (final String input in inputs) { final String pascalCaseName = _snakeToPascalCase(input); @@ -117,9 +118,10 @@ 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'; @@ -131,39 +133,46 @@ Future generateTestPigeons( 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', ); @@ -181,22 +190,26 @@ 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' + objcPrefix: + input == 'core_tests' + ? 'FLT' + : input == 'enum' ? 'PGN' : '', suppressVersion: true, @@ -261,8 +274,9 @@ Future runPigeon({ totalCustomCodecKeysAllowed - 1, (final int tag) { return Enum( - name: 'FillerEnum$tag', - members: [EnumMember(name: 'FillerMember$tag')]); + name: 'FillerEnum$tag', + members: [EnumMember(name: 'FillerMember$tag')], + ); }, ); addedEnums.addAll(parseResults.root.enums); @@ -332,36 +346,31 @@ Future formatAllFiles({ }) { final String dartCommand = Platform.isWindows ? 'dart.exe' : 'dart'; return runProcess( - dartCommand, - [ - 'run', - 'script/tool/bin/flutter_plugin_tools.dart', - 'format', - '--packages=pigeon', - if (languages.contains(GeneratorLanguage.cpp) || - languages.contains(GeneratorLanguage.gobject) || - languages.contains(GeneratorLanguage.objc)) - '--clang-format' - else - '--no-clang-format', - if (languages.contains(GeneratorLanguage.java)) - '--java' - else - '--no-java', - if (languages.contains(GeneratorLanguage.dart)) - '--dart' - else - '--no-dart', - if (languages.contains(GeneratorLanguage.kotlin)) - '--kotlin' - else - '--no-kotlin', - if (languages.contains(GeneratorLanguage.swift)) - '--swift' - else - '--no-swift', - ], - workingDirectory: repositoryRoot, - streamOutput: false, - logFailure: true); + dartCommand, + [ + 'run', + 'script/tool/bin/flutter_plugin_tools.dart', + 'format', + '--packages=pigeon', + if (languages.contains(GeneratorLanguage.cpp) || + languages.contains(GeneratorLanguage.gobject) || + languages.contains(GeneratorLanguage.objc)) + '--clang-format' + else + '--no-clang-format', + if (languages.contains(GeneratorLanguage.java)) '--java' else '--no-java', + if (languages.contains(GeneratorLanguage.dart)) '--dart' else '--no-dart', + if (languages.contains(GeneratorLanguage.kotlin)) + '--kotlin' + else + '--no-kotlin', + if (languages.contains(GeneratorLanguage.swift)) + '--swift' + else + '--no-swift', + ], + workingDirectory: repositoryRoot, + streamOutput: false, + logFailure: true, + ); } diff --git a/packages/pigeon/tool/shared/native_project_runners.dart b/packages/pigeon/tool/shared/native_project_runners.dart index 71ee6272232..c323887e7e6 100644 --- a/packages/pigeon/tool/shared/native_project_runners.dart +++ b/packages/pigeon/tool/shared/native_project_runners.dart @@ -12,15 +12,11 @@ Future runFlutterCommand( String? wrapperCommand, }) { final String flutterCommand = getFlutterCommand(); - return runProcess( - wrapperCommand ?? flutterCommand, - [ - if (wrapperCommand != null) flutterCommand, - command, - ...commandArguments, - ], - workingDirectory: projectDirectory, - ); + return runProcess(wrapperCommand ?? flutterCommand, [ + if (wrapperCommand != null) flutterCommand, + command, + ...commandArguments, + ], workingDirectory: projectDirectory); } Future runFlutterBuild( @@ -29,15 +25,11 @@ Future runFlutterBuild( bool debug = true, List flags = const [], }) { - return runFlutterCommand( - projectDirectory, - 'build', - [ - target, - if (debug) '--debug', - ...flags, - ], - ); + return runFlutterCommand(projectDirectory, 'build', [ + target, + if (debug) '--debug', + ...flags, + ]); } Future runXcodeBuild( @@ -46,27 +38,19 @@ Future runXcodeBuild( String? destination, List extraArguments = const [], }) { - return runProcess( - 'xcodebuild', - [ - '-workspace', - 'Runner.xcworkspace', - '-scheme', - 'Runner', - if (sdk != null) ...['-sdk', sdk], - if (destination != null) ...['-destination', destination], - ...extraArguments, - ], - workingDirectory: nativeProjectDirectory, - ); + return runProcess('xcodebuild', [ + '-workspace', + 'Runner.xcworkspace', + '-scheme', + 'Runner', + if (sdk != null) ...['-sdk', sdk], + if (destination != null) ...['-destination', destination], + ...extraArguments, + ], workingDirectory: nativeProjectDirectory); } Future runGradleBuild(String nativeProjectDirectory, [String? command]) { - return runProcess( - './gradlew', - [ - if (command != null) command, - ], - workingDirectory: nativeProjectDirectory, - ); + return runProcess('./gradlew', [ + if (command != null) command, + ], workingDirectory: nativeProjectDirectory); } diff --git a/packages/pigeon/tool/shared/process_utils.dart b/packages/pigeon/tool/shared/process_utils.dart index e38a4af777f..48abf3d434e 100644 --- a/packages/pigeon/tool/shared/process_utils.dart +++ b/packages/pigeon/tool/shared/process_utils.dart @@ -5,10 +5,13 @@ import 'dart:async'; import 'dart:io' show Process, ProcessStartMode, stderr, stdout; -Future runProcess(String command, List arguments, - {String? workingDirectory, - bool streamOutput = true, - bool logFailure = false}) async { +Future runProcess( + String command, + List arguments, { + String? workingDirectory, + bool streamOutput = true, + bool logFailure = false, +}) async { final Process process = await Process.start( command, arguments, @@ -26,20 +29,14 @@ Future runProcess(String command, List arguments, final Future stdoutFuture = process.stdout.forEach(stdoutBuffer.addAll); final Future stderrFuture = process.stderr.forEach(stderrBuffer.addAll); final int exitCode = await process.exitCode; - await Future.wait(>[ - stdoutFuture, - stderrFuture, - ]); + await Future.wait(>[stdoutFuture, stderrFuture]); if (exitCode != 0 && logFailure) { // ignore: avoid_print print('$command $arguments failed:'); stdout.add(stdoutBuffer); stderr.add(stderrBuffer); - await Future.wait(>[ - stdout.flush(), - stderr.flush(), - ]); + await Future.wait(>[stdout.flush(), stderr.flush()]); } return exitCode; } diff --git a/packages/pigeon/tool/shared/test_runner.dart b/packages/pigeon/tool/shared/test_runner.dart index 8fa487f42ef..21f1bf032f8 100644 --- a/packages/pigeon/tool/shared/test_runner.dart +++ b/packages/pigeon/tool/shared/test_runner.dart @@ -37,11 +37,14 @@ Future runTests( // TODO(tarrinneal): Remove linux filter once overflow class is added to gobject generator. // https://github.com/flutter/flutter/issues/152916 await _runTests( - testsToRun - .where((String test) => - test.contains('integration') && !test.contains('linux')) - .toList(), - ciMode: ciMode); + testsToRun + .where( + (String test) => + test.contains('integration') && !test.contains('linux'), + ) + .toList(), + ciMode: ciMode, + ); if (!ciMode) { await _runGenerate(baseDir, ciMode: ciMode); @@ -75,18 +78,16 @@ Future _runGenerate( Future _runFormat(String baseDir, {required bool ciMode}) async { _printHeading('Formatting generated output', ciMode: ciMode); - final int formatExitCode = - await formatAllFiles(repositoryRoot: p.dirname(p.dirname(baseDir))); + final int formatExitCode = await formatAllFiles( + repositoryRoot: p.dirname(p.dirname(baseDir)), + ); if (formatExitCode != 0) { print('Formatting failed; see above for errors.'); exit(formatExitCode); } } -Future _runTests( - List testsToRun, { - required bool ciMode, -}) async { +Future _runTests(List testsToRun, {required bool ciMode}) async { for (final String test in testsToRun) { final TestInfo? info = testSuites[test]; if (info != null) { diff --git a/packages/pigeon/tool/shared/test_suites.dart b/packages/pigeon/tool/shared/test_suites.dart index a16afe0c2e7..d4a14d52021 100644 --- a/packages/pigeon/tool/shared/test_suites.dart +++ b/packages/pigeon/tool/shared/test_suites.dart @@ -60,64 +60,85 @@ const String commandLineTests = 'command_line_tests'; const Map testSuites = { windowsUnitTests: TestInfo( - function: _runWindowsUnitTests, - description: 'Unit tests on generated Windows C++ code.'), + function: _runWindowsUnitTests, + description: 'Unit tests on generated Windows C++ code.', + ), windowsIntegrationTests: TestInfo( - function: _runWindowsIntegrationTests, - description: 'Integration tests on generated Windows C++ code.'), + function: _runWindowsIntegrationTests, + description: 'Integration tests on generated Windows C++ code.', + ), androidJavaUnitTests: TestInfo( - function: _runAndroidJavaUnitTests, - description: 'Unit tests on generated Java code.'), + function: _runAndroidJavaUnitTests, + description: 'Unit tests on generated Java code.', + ), androidJavaIntegrationTests: TestInfo( - function: _runAndroidJavaIntegrationTests, - description: 'Integration tests on generated Java code.'), + function: _runAndroidJavaIntegrationTests, + description: 'Integration tests on generated Java code.', + ), androidJavaLint: TestInfo( - function: _runAndroidJavaLint, description: 'Lint generated Java code.'), + function: _runAndroidJavaLint, + description: 'Lint generated Java code.', + ), androidKotlinUnitTests: TestInfo( - function: _runAndroidKotlinUnitTests, - description: 'Unit tests on generated Kotlin code.'), + function: _runAndroidKotlinUnitTests, + description: 'Unit tests on generated Kotlin code.', + ), androidKotlinLint: TestInfo( - function: _runAndroidKotlinLint, - description: 'Lint generated Kotlin code.'), + function: _runAndroidKotlinLint, + description: 'Lint generated Kotlin code.', + ), androidKotlinIntegrationTests: TestInfo( - function: _runAndroidKotlinIntegrationTests, - description: 'Integration tests on generated Kotlin code.'), + function: _runAndroidKotlinIntegrationTests, + description: 'Integration tests on generated Kotlin code.', + ), dartUnitTests: TestInfo( - function: _runDartUnitTests, - description: "Unit tests on and analysis on Pigeon's implementation."), + function: _runDartUnitTests, + description: "Unit tests on and analysis on Pigeon's implementation.", + ), flutterUnitTests: TestInfo( - function: _runFlutterUnitTests, - description: 'Unit tests on generated Dart code.'), + function: _runFlutterUnitTests, + description: 'Unit tests on generated Dart code.', + ), iOSObjCUnitTests: TestInfo( - function: _runIOSObjCUnitTests, - description: 'Unit tests on generated Objective-C code.'), + function: _runIOSObjCUnitTests, + description: 'Unit tests on generated Objective-C code.', + ), iOSObjCIntegrationTests: TestInfo( - function: _runIOSObjCIntegrationTests, - description: 'Integration tests on generated Objective-C code.'), + function: _runIOSObjCIntegrationTests, + description: 'Integration tests on generated Objective-C code.', + ), iOSSwiftUnitTests: TestInfo( - function: _runIOSSwiftUnitTests, - description: 'Unit tests on generated Swift code.'), + function: _runIOSSwiftUnitTests, + description: 'Unit tests on generated Swift code.', + ), iOSSwiftIntegrationTests: TestInfo( - function: _runIOSSwiftIntegrationTests, - description: 'Integration tests on generated Swift code.'), + function: _runIOSSwiftIntegrationTests, + description: 'Integration tests on generated Swift code.', + ), linuxUnitTests: TestInfo( - function: _runLinuxUnitTests, - description: 'Unit tests on generated Linux C code.'), + function: _runLinuxUnitTests, + description: 'Unit tests on generated Linux C code.', + ), linuxIntegrationTests: TestInfo( - function: _runLinuxIntegrationTests, - description: 'Integration tests on generated Linux C code.'), + function: _runLinuxIntegrationTests, + description: 'Integration tests on generated Linux C code.', + ), macOSObjCIntegrationTests: TestInfo( - function: _runMacOSObjCIntegrationTests, - description: 'Integration tests on generated Objective-C code on macOS.'), + function: _runMacOSObjCIntegrationTests, + description: 'Integration tests on generated Objective-C code on macOS.', + ), macOSSwiftUnitTests: TestInfo( - function: _runMacOSSwiftUnitTests, - description: 'Unit tests on generated Swift code on macOS.'), + function: _runMacOSSwiftUnitTests, + description: 'Unit tests on generated Swift code on macOS.', + ), macOSSwiftIntegrationTests: TestInfo( - function: _runMacOSSwiftIntegrationTests, - description: 'Integration tests on generated Swift code on macOS.'), + function: _runMacOSSwiftIntegrationTests, + description: 'Integration tests on generated Swift code on macOS.', + ), commandLineTests: TestInfo( - function: _runCommandLineTests, - description: 'Tests running pigeon with various command-line options.'), + function: _runCommandLineTests, + description: 'Tests running pigeon with various command-line options.', + ), }; Future _runAndroidJavaUnitTests({bool ciMode = false}) async { @@ -126,7 +147,9 @@ Future _runAndroidJavaUnitTests({bool ciMode = false}) async { Future _runAndroidJavaIntegrationTests({bool ciMode = false}) async { return _runMobileIntegrationTests( - 'Android', _alternateLanguageTestPluginRelativePath); + 'Android', + _alternateLanguageTestPluginRelativePath, + ); } Future _runAndroidJavaLint({bool ciMode = false}) async { @@ -169,8 +192,11 @@ Future _runAndroidLint({ final String androidProjectPath = '$examplePath/android'; final File gradleFile = File(p.join(androidProjectPath, 'gradlew')); if (!gradleFile.existsSync()) { - final int compileCode = await runFlutterBuild(examplePath, 'apk', - flags: ['--config-only']); + final int compileCode = await runFlutterBuild( + examplePath, + 'apk', + flags: ['--config-only'], + ); if (compileCode != 0) { return compileCode; } @@ -184,20 +210,24 @@ Future _runAndroidKotlinIntegrationTests({bool ciMode = false}) async { } Future _runMobileIntegrationTests( - String platform, String testPluginPath) async { + String platform, + String testPluginPath, +) async { final String? device = await getDeviceForPlatform(platform.toLowerCase()); if (device == null) { - print('No $platform device available. Attach an $platform device or start ' - 'an emulator/simulator to run integration tests'); + print( + 'No $platform device available. Attach an $platform device or start ' + 'an emulator/simulator to run integration tests', + ); return _noDeviceAvailableExitCode; } final String examplePath = './$testPluginPath/example'; - return runFlutterCommand( - examplePath, - 'test', - [_integrationTestFileRelativePath, '-d', device], - ); + return runFlutterCommand(examplePath, 'test', [ + _integrationTestFileRelativePath, + '-d', + device, + ]); } Future _runDartUnitTests({bool ciMode = false}) async { @@ -225,8 +255,11 @@ Future _analyzeFlutterUnitTests(String flutterUnitTestsPath) async { return generateTestCode; } - final int analyzeCode = - await runFlutterCommand(flutterUnitTestsPath, 'analyze', []); + final int analyzeCode = await runFlutterCommand( + flutterUnitTestsPath, + 'analyze', + [], + ); if (analyzeCode != 0) { return analyzeCode; } @@ -244,8 +277,11 @@ Future _runFlutterUnitTests({bool ciMode = false}) async { return analyzeCode; } - final int testCode = - await runFlutterCommand(flutterUnitTestsPath, 'test', []); + final int testCode = await runFlutterCommand( + flutterUnitTestsPath, + 'test', + [], + ); if (testCode != 0) { return testCode; } @@ -260,28 +296,30 @@ Future _runIOSObjCUnitTests({bool ciMode = false}) async { Future _runIOSObjCIntegrationTests({bool ciMode = false}) async { final String? device = await getDeviceForPlatform('ios'); if (device == null) { - print('No iOS device available. Attach an iOS device or start ' - 'a simulator to run integration tests'); + print( + 'No iOS device available. Attach an iOS device or start ' + 'a simulator to run integration tests', + ); return _noDeviceAvailableExitCode; } const String examplePath = './$_alternateLanguageTestPluginRelativePath/example'; - return runFlutterCommand( - examplePath, - 'test', - [_integrationTestFileRelativePath, '-d', device], - ); + return runFlutterCommand(examplePath, 'test', [ + _integrationTestFileRelativePath, + '-d', + device, + ]); } Future _runMacOSObjCIntegrationTests({bool ciMode = false}) async { const String examplePath = './$_alternateLanguageTestPluginRelativePath/example'; - return runFlutterCommand( - examplePath, - 'test', - [_integrationTestFileRelativePath, '-d', 'macos'], - ); + return runFlutterCommand(examplePath, 'test', [ + _integrationTestFileRelativePath, + '-d', + 'macos', + ]); } Future _runMacOSSwiftUnitTests({bool ciMode = false}) async { @@ -293,21 +331,17 @@ Future _runMacOSSwiftUnitTests({bool ciMode = false}) async { return runXcodeBuild( '$examplePath/macos', - extraArguments: [ - '-configuration', - 'Debug', - 'test', - ], + extraArguments: ['-configuration', 'Debug', 'test'], ); } Future _runMacOSSwiftIntegrationTests({bool ciMode = false}) async { const String examplePath = './$_testPluginRelativePath/example'; - return runFlutterCommand( - examplePath, - 'test', - [_integrationTestFileRelativePath, '-d', 'macos'], - ); + return runFlutterCommand(examplePath, 'test', [ + _integrationTestFileRelativePath, + '-d', + 'macos', + ]); } Future _runIOSSwiftUnitTests({bool ciMode = false}) async { @@ -352,28 +386,18 @@ Future _createSimulator( } return runProcess( 'xcrun', - [ - 'simctl', - 'create', - deviceName, - deviceType, - deviceRuntime, - ], + ['simctl', 'create', deviceName, deviceType, deviceRuntime], streamOutput: false, logFailure: true, ); } Future _deleteSimulator(String deviceName) async { - return runProcess( - 'xcrun', - [ - 'simctl', - 'delete', - deviceName, - ], - streamOutput: false, - ); + return runProcess('xcrun', [ + 'simctl', + 'delete', + deviceName, + ], streamOutput: false); } Future _runIOSSwiftIntegrationTests({bool ciMode = false}) async { @@ -448,11 +472,11 @@ Future _runWindowsUnitTests({bool ciMode = false}) async { Future _runWindowsIntegrationTests({bool ciMode = false}) async { const String examplePath = './$_testPluginRelativePath/example'; - return runFlutterCommand( - examplePath, - 'test', - [_integrationTestFileRelativePath, '-d', 'windows'], - ); + return runFlutterCommand(examplePath, 'test', [ + _integrationTestFileRelativePath, + '-d', + 'windows', + ]); } Future _runCommandLineTests({bool ciMode = false}) async { @@ -465,7 +489,7 @@ Future _runCommandLineTests({bool ciMode = false}) async { if (await runProcess('dart', [ '--snapshot-kind=kernel', '--snapshot=$snapshot', - pigeonScript + pigeonScript, ]) != 0) { print('Unable to generate $snapshot from $pigeonScript'); @@ -492,8 +516,12 @@ Future _runCommandLineTests({bool ciMode = false}) async { int exitCode = 0; for (final List arguments in testArguments) { print('Testing dart $pigeonScript ${arguments.join(', ')}'); - exitCode = await runProcess('dart', [snapshot, ...arguments], - streamOutput: false, logFailure: true); + exitCode = await runProcess( + 'dart', + [snapshot, ...arguments], + streamOutput: false, + logFailure: true, + ); if (exitCode != 0) { break; } diff --git a/packages/pigeon/tool/test.dart b/packages/pigeon/tool/test.dart index dd1b331c43d..6b6212c804a 100644 --- a/packages/pigeon/tool/test.dart +++ b/packages/pigeon/tool/test.dart @@ -26,20 +26,42 @@ 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 = []; @@ -93,7 +115,7 @@ ${parser.usage}'''); const List macOSTests = [ macOSObjCIntegrationTests, macOSSwiftUnitTests, - macOSSwiftIntegrationTests + macOSSwiftIntegrationTests, ]; const List windowsTests = [ windowsUnitTests, @@ -108,16 +130,9 @@ ${parser.usage}'''); ...macOSTests, ]; } else if (Platform.isWindows) { - testsToRun = [ - ...dartTests, - ...windowsTests, - ]; + testsToRun = [...dartTests, ...windowsTests]; } else if (Platform.isLinux) { - testsToRun = [ - ...dartTests, - ...androidTests, - ...linuxTests, - ]; + testsToRun = [...dartTests, ...androidTests, ...linuxTests]; } else { print('Unsupported host platform.'); exit(1); diff --git a/packages/plugin_platform_interface/CHANGELOG.md b/packages/plugin_platform_interface/CHANGELOG.md index bfedc3dca13..e5dbb81d85b 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.1.8 diff --git a/packages/plugin_platform_interface/lib/plugin_platform_interface.dart b/packages/plugin_platform_interface/lib/plugin_platform_interface.dart index 32309547832..5c8f495c0e2 100644 --- a/packages/plugin_platform_interface/lib/plugin_platform_interface.dart +++ b/packages/plugin_platform_interface/lib/plugin_platform_interface.dart @@ -93,7 +93,8 @@ abstract class PlatformInterface { }()); if (!assertionsEnabled) { throw AssertionError( - '`MockPlatformInterfaceMixin` is not intended for use in release builds.'); + '`MockPlatformInterfaceMixin` is not intended for use in release builds.', + ); } return; } @@ -103,7 +104,8 @@ abstract class PlatformInterface { } if (!identical(token, _instanceTokens[instance])) { throw AssertionError( - 'Platform interfaces must not be implemented with `implements`'); + 'Platform interfaces must not be implemented with `implements`', + ); } } } diff --git a/packages/plugin_platform_interface/pubspec.yaml b/packages/plugin_platform_interface/pubspec.yaml index 148ac7c4670..7c850f65faf 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.6.0 + sdk: ^3.7.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 c058b86b6a6..e684b840f44 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.10.1+2 diff --git a/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart index f62f5ad5ea0..a7433f27318 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart @@ -69,10 +69,7 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - 'Last click on: $_lastClick', - key: const Key('last-clicked'), - ), + Text('Last click on: $_lastClick', key: const Key('last-clicked')), Container( color: Colors.black, width: _videoWidth, @@ -100,8 +97,9 @@ class _MyHomePageState extends State { intercepting: false, child: ElevatedButton( key: const Key('wrapped-transparent-button'), - child: - const Text('Never calls onPressed transparent'), + child: const Text( + 'Never calls onPressed transparent', + ), onPressed: () { _clickedOn('wrapped-transparent-button'); }, 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 5b9458796c5..a625c014f76 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,12 +8,13 @@ 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... @@ -55,8 +56,6 @@ class NativeWidget extends StatelessWidget { (int viewId) => htmlElement, ); - return const HtmlElementView( - viewType: _htmlElementViewType, - ); + return const HtmlElementView(viewType: _htmlElementViewType); } } diff --git a/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml index 41801280c0b..37ee177731a 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart b/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart index c561e1403b9..065952bfef6 100644 --- a/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart +++ b/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart @@ -33,7 +33,10 @@ class PointerInterceptor extends StatelessWidget { if (!intercepting) { return child; } - return PointerInterceptorPlatform.instance - .buildWidget(child: child, debug: debug, key: key); + return PointerInterceptorPlatform.instance.buildWidget( + child: child, + debug: debug, + key: key, + ); } } diff --git a/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml index 3b6f3120c80..edc465003a9 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_ios/CHANGELOG.md index f7ece75bdf3..703ee140238 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor_ios/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.10.1 diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart index e55563bde6b..ec3095b9fd7 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart @@ -45,24 +45,28 @@ class _PointerInterceptorIOSExampleState @override Widget build(BuildContext context) { return Scaffold( - body: Center( - child: Stack( - alignment: AlignmentDirectional.center, - children: [ - const _DummyPlatformView(), - PointerInterceptorPlatform.instance.buildWidget( + body: Center( + child: Stack( + alignment: AlignmentDirectional.center, + children: [ + const _DummyPlatformView(), + PointerInterceptorPlatform.instance.buildWidget( child: TextButton( - style: TextButton.styleFrom(foregroundColor: Colors.red), - child: _buttonTapped - ? const Text('Tapped') - : const Text('Initial'), - onPressed: () { - setState(() { - _buttonTapped = !_buttonTapped; - }); - })), - ], + style: TextButton.styleFrom(foregroundColor: Colors.red), + child: + _buttonTapped + ? const Text('Tapped') + : const Text('Initial'), + onPressed: () { + setState(() { + _buttonTapped = !_buttonTapped; + }); + }, + ), + ), + ], + ), ), - )); + ); } } diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_ios/example/pubspec.yaml index 0892d11c098..99e6a578ecd 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/pubspec.yaml @@ -3,8 +3,8 @@ description: "Demonstrates how to use the pointer_interceptor_ios plugin." publish_to: 'none' environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: cupertino_icons: ^1.0.2 diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/lib/pointer_interceptor_ios.dart b/packages/pointer_interceptor/pointer_interceptor_ios/lib/pointer_interceptor_ios.dart index f92e8faaec0..d0991ebc4e0 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/lib/pointer_interceptor_ios.dart +++ b/packages/pointer_interceptor/pointer_interceptor_ios/lib/pointer_interceptor_ios.dart @@ -15,16 +15,18 @@ class PointerInterceptorIOS extends PointerInterceptorPlatform { @override Widget buildWidget({required Widget child, bool debug = false, Key? key}) { - return Stack(alignment: Alignment.center, children: [ - Positioned.fill( + return Stack( + alignment: Alignment.center, + children: [ + Positioned.fill( child: UiKitView( - viewType: 'plugins.flutter.dev/pointer_interceptor_ios', - creationParams: { - 'debug': debug, - }, - creationParamsCodec: const StandardMessageCodec(), - )), - child - ]); + viewType: 'plugins.flutter.dev/pointer_interceptor_ios', + creationParams: {'debug': debug}, + creationParamsCodec: const StandardMessageCodec(), + ), + ), + child, + ], + ); } } diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_ios/pubspec.yaml index 85aa7b7beab..8d53a5fd75d 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_ios/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.1 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart b/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart index 35671246ea5..a098034e170 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart @@ -21,26 +21,30 @@ class TestAppState extends State { @override Widget build(BuildContext context) { return MaterialApp( - home: Scaffold( - body: const Text('Body'), - floatingActionButton: FloatingActionButton( + home: Scaffold( + body: const Text('Body'), + floatingActionButton: FloatingActionButton( onPressed: () {}, child: PointerInterceptorIOS().buildWidget( - child: TextButton( - onPressed: () => setState(() { - _buttonText = 'Clicked'; - }), - child: Text(_buttonText), - ))), - )); + child: TextButton( + onPressed: + () => setState(() { + _buttonText = 'Clicked'; + }), + child: Text(_buttonText), + ), + ), + ), + ), + ); } } void main() { - testWidgets( - 'Button remains clickable and is added to ' - 'hierarchy after being wrapped in pointer interceptor', - (WidgetTester tester) async { + testWidgets('Button remains clickable and is added to ' + 'hierarchy after being wrapped in pointer interceptor', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const TestApp()); await tester.tap(find.text('Test Button')); await tester.pump(); diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md index d4b6bb3b375..d10ca7524b0 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.10.0+1 diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/default_pointer_interceptor.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/default_pointer_interceptor.dart index e3a591120d5..a9c685a391c 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/default_pointer_interceptor.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/default_pointer_interceptor.dart @@ -9,11 +9,7 @@ import 'pointer_interceptor_platform.dart'; /// A default no-op implementation of [PointerInterceptorPlatform]. class DefaultPointerInterceptor extends PointerInterceptorPlatform { @override - Widget buildWidget({ - required Widget child, - bool debug = false, - Key? key, - }) { + Widget buildWidget({required Widget child, bool debug = false, Key? key}) { return child; } } diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart index 59b558a7b1f..d1aefc2b1e5 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart @@ -21,7 +21,8 @@ abstract class PointerInterceptorPlatform extends PlatformInterface { static set instance(PointerInterceptorPlatform? instance) { if (instance == null) { throw AssertionError( - 'Platform interfaces can only be set to a non-null instance'); + 'Platform interfaces can only be set to a non-null instance', + ); } PlatformInterface.verify(instance, _token); @@ -35,11 +36,7 @@ abstract class PointerInterceptorPlatform extends PlatformInterface { /// Platform-specific implementations should override this function their own /// implementation of a pointer interceptor widget. - Widget buildWidget({ - required Widget child, - bool debug = false, - Key? key, - }) { + Widget buildWidget({required Widget child, bool debug = false, Key? key}) { throw UnimplementedError('buildWidget() has not been implemented.'); } } diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml index 53e84d61a4c..604062d901a 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart index bf3291deea4..5c0ee797af7 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart @@ -10,17 +10,20 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); test( - 'Default implementation of PointerInterceptorPlatform should throw unimplemented error', - () { - final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform = - UnimplementedPointerInterceptorPlatform(); + 'Default implementation of PointerInterceptorPlatform should throw unimplemented error', + () { + final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform = + UnimplementedPointerInterceptorPlatform(); - final Container testChild = Container(); - expect( + final Container testChild = Container(); + expect( () => unimplementedPointerInterceptorPlatform.buildWidget( - child: testChild), - throwsUnimplementedError); - }); + child: testChild, + ), + throwsUnimplementedError, + ); + }, + ); } class UnimplementedPointerInterceptorPlatform diff --git a/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md index bff77a7eee6..7af1c73a4c2 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.10.3 * Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. 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 d2efc26ffe7..a1d17935dee 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 @@ -11,10 +11,12 @@ import 'package:integration_test/integration_test.dart'; import 'package:pointer_interceptor_web_example/main.dart' as app; import 'package:web/web.dart' as web; -final Finder nonClickableButtonFinder = - find.byKey(const Key('transparent-button')); -final Finder clickableWrappedButtonFinder = - find.byKey(const Key('wrapped-transparent-button')); +final Finder nonClickableButtonFinder = find.byKey( + const Key('transparent-button'), +); +final Finder clickableWrappedButtonFinder = find.byKey( + const Key('wrapped-transparent-button'), +); final Finder clickableButtonFinder = find.byKey(const Key('clickable-button')); final Finder backgroundFinder = find.byKey(const Key('background-widget')); @@ -23,69 +25,82 @@ void main() { group('Without semantics', () { testWidgets( - 'on wrapped elements, the browser does not hit the background-html-view', - (WidgetTester tester) async { - await _fullyRenderApp(tester); + 'on wrapped elements, the browser does not hit the background-html-view', + (WidgetTester tester) async { + await _fullyRenderApp(tester); - final web.Element element = - _getHtmlElementAtCenter(clickableButtonFinder, tester); + final web.Element element = _getHtmlElementAtCenter( + clickableButtonFinder, + tester, + ); - expect(element.id, isNot('background-html-view')); - }, semanticsEnabled: false); + expect(element.id, isNot('background-html-view')); + }, + semanticsEnabled: false, + ); testWidgets( - 'on wrapped elements with intercepting set to false, the browser hits the background-html-view', - (WidgetTester tester) async { - await _fullyRenderApp(tester); + 'on wrapped elements with intercepting set to false, the browser hits the background-html-view', + (WidgetTester tester) async { + await _fullyRenderApp(tester); - final web.Element element = - _getHtmlElementAtCenter(clickableWrappedButtonFinder, tester); + final web.Element element = _getHtmlElementAtCenter( + clickableWrappedButtonFinder, + tester, + ); - expect(element.id, 'background-html-view'); - }, semanticsEnabled: false); + expect(element.id, 'background-html-view'); + }, + semanticsEnabled: false, + ); testWidgets( - 'on unwrapped elements, the browser hits the background-html-view', - (WidgetTester tester) async { - await _fullyRenderApp(tester); + 'on unwrapped elements, the browser hits the background-html-view', + (WidgetTester tester) async { + await _fullyRenderApp(tester); - final web.Element element = - _getHtmlElementAtCenter(nonClickableButtonFinder, tester); + final web.Element element = _getHtmlElementAtCenter( + nonClickableButtonFinder, + tester, + ); - expect(element.id, 'background-html-view'); - }, semanticsEnabled: false); + expect(element.id, 'background-html-view'); + }, + semanticsEnabled: false, + ); testWidgets('on background directly', (WidgetTester tester) async { await _fullyRenderApp(tester); - final web.Element element = - _getHtmlElementAt(tester.getTopLeft(backgroundFinder)); + final web.Element element = _getHtmlElementAt( + tester.getTopLeft(backgroundFinder), + ); expect(element.id, 'background-html-view'); }, semanticsEnabled: false); // Regression test for https://github.com/flutter/flutter/issues/157920 - testWidgets( - 'prevents default action of mousedown events', - (WidgetTester tester) async { - await _fullyRenderApp(tester); + testWidgets('prevents default action of mousedown events', ( + WidgetTester tester, + ) async { + await _fullyRenderApp(tester); - final web.Element element = - _getHtmlElementAtCenter(clickableButtonFinder, tester); - expect(element.tagName.toLowerCase(), 'div'); - - for (int i = 0; i <= 4; i++) { - final web.MouseEvent event = web.MouseEvent( - 'mousedown', - web.MouseEventInit(button: i, cancelable: true), - ); - element.dispatchEvent(event); - expect(event.target, element); - expect(event.defaultPrevented, isTrue); - } - }, - semanticsEnabled: false, - ); + final web.Element element = _getHtmlElementAtCenter( + clickableButtonFinder, + tester, + ); + expect(element.tagName.toLowerCase(), 'div'); + + for (int i = 0; i <= 4; i++) { + final web.MouseEvent event = web.MouseEvent( + 'mousedown', + web.MouseEventInit(button: i, cancelable: true), + ); + element.dispatchEvent(event); + expect(event.target, element); + expect(event.defaultPrevented, isTrue); + } + }, semanticsEnabled: false); }); } diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart index d25e8913f41..5ac15953e36 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart @@ -113,10 +113,7 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - 'Last click on: $_lastClick', - key: const Key('last-clicked'), - ), + Text('Last click on: $_lastClick', key: const Key('last-clicked')), Container( color: Colors.black, width: _containerWidth, @@ -141,15 +138,17 @@ class _MyHomePageState extends State { }, ), PointerInterceptorWeb().buildWidget( - intercepting: false, - child: ElevatedButton( - key: const Key('wrapped-transparent-button'), - child: - const Text('Never calls onPressed transparent'), - onPressed: () { - _clickedOn('wrapped-transparent-button'); - }, - )), + intercepting: false, + child: ElevatedButton( + key: const Key('wrapped-transparent-button'), + child: const Text( + 'Never calls onPressed transparent', + ), + onPressed: () { + _clickedOn('wrapped-transparent-button'); + }, + ), + ), PointerInterceptorPlatform.instance.buildWidget( child: ElevatedButton( key: const Key('clickable-button'), @@ -224,8 +223,6 @@ class HtmlElement extends StatelessWidget { }.toJS, ); - return const HtmlElementView( - viewType: _htmlElementViewType, - ); + return const HtmlElementView(viewType: _htmlElementViewType); } } diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml index af57dc66230..b2361de7c2d 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 11ec6a7d437..338da340227 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions/CHANGELOG.md b/packages/quick_actions/quick_actions/CHANGELOG.md index 0a3eff99e42..127c8162e8f 100644 --- a/packages/quick_actions/quick_actions/CHANGELOG.md +++ b/packages/quick_actions/quick_actions/CHANGELOG.md @@ -1,7 +1,7 @@ ## NEXT +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. * Updates README to indicate that Andoid SDK <21 is no longer supported. -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. ## 1.1.0 diff --git a/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart b/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart index 37846c32359..3657a86e272 100644 --- a/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart @@ -19,6 +19,8 @@ void main() { icon: 'AppIcon', ); expect( - quickActions.setShortcutItems([shortCutItem]), completes); + quickActions.setShortcutItems([shortCutItem]), + completes, + ); }); } diff --git a/packages/quick_actions/quick_actions/example/lib/main.dart b/packages/quick_actions/quick_actions/example/lib/main.dart index d137710031a..83b59ae2fba 100644 --- a/packages/quick_actions/quick_actions/example/lib/main.dart +++ b/packages/quick_actions/quick_actions/example/lib/main.dart @@ -18,9 +18,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Quick Actions Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(), ); } @@ -47,41 +45,43 @@ class _MyHomePageState extends State { }); }); - quickActions.setShortcutItems([ - // NOTE: This first action icon will only work on iOS. - // In a real world project keep the same file name for both platforms. - const ShortcutItem( - type: 'action_one', - localizedTitle: 'Action one', - localizedSubtitle: 'Action one subtitle', - icon: 'AppIcon', - ), - // NOTE: This second action icon will only work on Android. - // In a real world project keep the same file name for both platforms. - const ShortcutItem( - type: 'action_two', - localizedTitle: 'Action two', - icon: 'ic_launcher', - ), - ]).then((void _) { - setState(() { - if (shortcut == 'no action set') { - shortcut = 'actions ready'; - } - }); - }); + quickActions + .setShortcutItems([ + // NOTE: This first action icon will only work on iOS. + // In a real world project keep the same file name for both platforms. + const ShortcutItem( + type: 'action_one', + localizedTitle: 'Action one', + localizedSubtitle: 'Action one subtitle', + icon: 'AppIcon', + ), + // NOTE: This second action icon will only work on Android. + // In a real world project keep the same file name for both platforms. + const ShortcutItem( + type: 'action_two', + localizedTitle: 'Action two', + icon: 'ic_launcher', + ), + ]) + .then((void _) { + setState(() { + if (shortcut == 'no action set') { + shortcut = 'actions ready'; + } + }); + }); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(shortcut), - ), + appBar: AppBar(title: Text(shortcut)), body: const Center( - child: Text('On home screen, long press the app icon to ' - 'get Action one or Action two options. Tapping on that action should ' - 'set the toolbar title.'), + child: Text( + 'On home screen, long press the app icon to ' + 'get Action one or Action two options. Tapping on that action should ' + 'set the toolbar title.', + ), ), ); } diff --git a/packages/quick_actions/quick_actions/example/pubspec.yaml b/packages/quick_actions/quick_actions/example/pubspec.yaml index f478d9ca736..1803e2aecbc 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions/pubspec.yaml b/packages/quick_actions/quick_actions/pubspec.yaml index 599b5747248..0ed48370198 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions/test/quick_actions_test.dart b/packages/quick_actions/quick_actions/test/quick_actions_test.dart index 8e93b55fcd1..cd5212537bb 100644 --- a/packages/quick_actions/quick_actions/test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions/test/quick_actions_test.dart @@ -34,8 +34,9 @@ void main() { quickActions.setShortcutItems([]); verify(QuickActionsPlatform.instance.initialize(handler)).called(1); - verify(QuickActionsPlatform.instance.setShortcutItems([])) - .called(1); + verify( + QuickActionsPlatform.instance.setShortcutItems([]), + ).called(1); }); test('clearShortcutItems() PlatformInterface', () { diff --git a/packages/quick_actions/quick_actions_android/CHANGELOG.md b/packages/quick_actions/quick_actions_android/CHANGELOG.md index b7682806bdd..b3fabf936bd 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.29/Dart 3.7. + ## 1.0.22 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/quick_actions/quick_actions_android/example/lib/main.dart b/packages/quick_actions/quick_actions_android/example/lib/main.dart index a0352c8e482..364619c23ad 100644 --- a/packages/quick_actions/quick_actions_android/example/lib/main.dart +++ b/packages/quick_actions/quick_actions_android/example/lib/main.dart @@ -18,9 +18,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Quick Actions Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(), ); } @@ -47,35 +45,38 @@ class _MyHomePageState extends State { }); }); - quickActions.setShortcutItems([ - const ShortcutItem( - type: 'action_one', - localizedTitle: 'Action one', - icon: 'AppIcon', - ), - const ShortcutItem( - type: 'action_two', - localizedTitle: 'Action two', - icon: 'ic_launcher'), - ]).then((void _) { - setState(() { - if (shortcut == 'no action set') { - shortcut = 'actions ready'; - } - }); - }); + quickActions + .setShortcutItems([ + const ShortcutItem( + type: 'action_one', + localizedTitle: 'Action one', + icon: 'AppIcon', + ), + const ShortcutItem( + type: 'action_two', + localizedTitle: 'Action two', + icon: 'ic_launcher', + ), + ]) + .then((void _) { + setState(() { + if (shortcut == 'no action set') { + shortcut = 'actions ready'; + } + }); + }); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(shortcut), - ), + appBar: AppBar(title: Text(shortcut)), body: const Center( - child: Text('On home screen, long press the app icon to ' - 'get Action one or Action two options. Tapping on that action should ' - 'set the toolbar title.'), + child: Text( + 'On home screen, long press the app icon to ' + 'get Action one or Action two options. Tapping on that action should ' + 'set the toolbar title.', + ), ), ); } diff --git a/packages/quick_actions/quick_actions_android/example/pubspec.yaml b/packages/quick_actions/quick_actions_android/example/pubspec.yaml index 8f8274d9324..db0dfa6472a 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart b/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart index 7adafe74306..98140687e66 100644 --- a/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart +++ b/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart @@ -14,9 +14,8 @@ late QuickActionHandler _handler; /// An implementation of [QuickActionsPlatform] for Android. class QuickActionsAndroid extends QuickActionsPlatform { /// Creates a new plugin implementation instance. - QuickActionsAndroid({ - @visibleForTesting AndroidQuickActionsApi? api, - }) : _hostApi = api ?? AndroidQuickActionsApi(); + QuickActionsAndroid({@visibleForTesting AndroidQuickActionsApi? api}) + : _hostApi = api ?? AndroidQuickActionsApi(); final AndroidQuickActionsApi _hostApi; diff --git a/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart b/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart index 3e50ffa9513..27ffe6350d5 100644 --- a/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart +++ b/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -47,11 +50,7 @@ class ShortcutItemMessage { String? icon; Object encode() { - return [ - type, - localizedTitle, - icon, - ]; + return [type, localizedTitle, icon]; } static ShortcutItemMessage decode(Object result) { @@ -94,11 +93,12 @@ class AndroidQuickActionsApi { /// Constructor for [AndroidQuickActionsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - AndroidQuickActionsApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + AndroidQuickActionsApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -111,10 +111,10 @@ class AndroidQuickActionsApi { 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.getLaunchAction$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -136,10 +136,10 @@ class AndroidQuickActionsApi { 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.setShortcutItems$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([itemsList]) as List?; if (pigeonVar_replyList == null) { @@ -161,10 +161,10 @@ class AndroidQuickActionsApi { 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.clearShortcutItems$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -195,22 +195,26 @@ abstract class AndroidQuickActionsFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction was null.', + ); final List args = (message as List?)!; final String? arg_action = (args[0] as String?); - assert(arg_action != null, - 'Argument for dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction was null, expected non-null String.'); + assert( + arg_action != null, + 'Argument for dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction was null, expected non-null String.', + ); try { api.launchAction(arg_action!); return wrapResponse(empty: true); @@ -218,7 +222,8 @@ abstract class AndroidQuickActionsFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/quick_actions/quick_actions_android/pigeons/messages.dart b/packages/quick_actions/quick_actions_android/pigeons/messages.dart index 5bc3e1e5e37..067449f2634 100644 --- a/packages/quick_actions/quick_actions_android/pigeons/messages.dart +++ b/packages/quick_actions/quick_actions_android/pigeons/messages.dart @@ -4,23 +4,18 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - javaOut: - 'android/src/main/java/io/flutter/plugins/quickactions/Messages.java', - javaOptions: JavaOptions( - package: 'io.flutter.plugins.quickactions', +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + javaOut: + 'android/src/main/java/io/flutter/plugins/quickactions/Messages.java', + javaOptions: JavaOptions(package: 'io.flutter.plugins.quickactions'), + copyrightHeader: 'pigeons/copyright.txt', ), - copyrightHeader: 'pigeons/copyright.txt', -)) - +) /// Home screen quick-action shortcut item. class ShortcutItemMessage { - ShortcutItemMessage( - this.type, - this.localizedTitle, - this.icon, - ); + ShortcutItemMessage(this.type, this.localizedTitle, this.icon); /// The identifier of this item; should be unique within the app. String type; diff --git a/packages/quick_actions/quick_actions_android/pubspec.yaml b/packages/quick_actions/quick_actions_android/pubspec.yaml index 9a957c00e65..780d60722ad 100644 --- a/packages/quick_actions/quick_actions_android/pubspec.yaml +++ b/packages/quick_actions/quick_actions_android/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.0.22 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart b/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart index a0ba35568f4..480bc4de7f4 100644 --- a/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart +++ b/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart @@ -49,8 +49,11 @@ void main() { test('setShortCutItems', () async { await quickActions.initialize((String type) {}); - const ShortcutItem item = - ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg'); + const ShortcutItem item = ShortcutItem( + type: 'test', + localizedTitle: 'title', + icon: 'icon.svg', + ); await quickActions.setShortcutItems([item]); expect(api.items.first.type, item.type); @@ -60,8 +63,11 @@ void main() { test('clearShortCutItems', () { quickActions.initialize((String type) {}); - const ShortcutItem item = - ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg'); + const ShortcutItem item = ShortcutItem( + type: 'test', + localizedTitle: 'title', + icon: 'icon.svg', + ); quickActions.setShortcutItems([item]); quickActions.clearShortcutItems(); @@ -73,8 +79,11 @@ void main() { const String localizedTitle = 'title'; const String icon = 'foo'; - const ShortcutItem item = - ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon); + const ShortcutItem item = ShortcutItem( + type: type, + localizedTitle: localizedTitle, + icon: icon, + ); expect(item.type, type); expect(item.localizedTitle, localizedTitle); diff --git a/packages/quick_actions/quick_actions_ios/CHANGELOG.md b/packages/quick_actions/quick_actions_ios/CHANGELOG.md index cfbb740a98f..36cbb338807 100644 --- a/packages/quick_actions/quick_actions_ios/CHANGELOG.md +++ b/packages/quick_actions/quick_actions_ios/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 1.2.1 * Updates to Pigeon 25.5.0. diff --git a/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart b/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart index b89c09d639d..174d5daddcd 100644 --- a/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart @@ -19,6 +19,8 @@ void main() { icon: 'AppIcon', ); expect( - quickActions.setShortcutItems([shortCutItem]), completes); + quickActions.setShortcutItems([shortCutItem]), + completes, + ); }); } diff --git a/packages/quick_actions/quick_actions_ios/example/lib/main.dart b/packages/quick_actions/quick_actions_ios/example/lib/main.dart index a170376135d..57cc3b21c7c 100644 --- a/packages/quick_actions/quick_actions_ios/example/lib/main.dart +++ b/packages/quick_actions/quick_actions_ios/example/lib/main.dart @@ -18,9 +18,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Quick Actions Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(), ); } @@ -47,36 +45,39 @@ class _MyHomePageState extends State { }); }); - quickActions.setShortcutItems([ - const ShortcutItem( - type: 'action_one', - localizedTitle: 'Action one', - localizedSubtitle: 'Action one subtitle', - icon: 'AppIcon', - ), - const ShortcutItem( - type: 'action_two', - localizedTitle: 'Action two', - icon: 'ic_launcher'), - ]).then((void _) { - setState(() { - if (shortcut == 'no action set') { - shortcut = 'actions ready'; - } - }); - }); + quickActions + .setShortcutItems([ + const ShortcutItem( + type: 'action_one', + localizedTitle: 'Action one', + localizedSubtitle: 'Action one subtitle', + icon: 'AppIcon', + ), + const ShortcutItem( + type: 'action_two', + localizedTitle: 'Action two', + icon: 'ic_launcher', + ), + ]) + .then((void _) { + setState(() { + if (shortcut == 'no action set') { + shortcut = 'actions ready'; + } + }); + }); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(shortcut), - ), + appBar: AppBar(title: Text(shortcut)), body: const Center( - child: Text('On home screen, long press the app icon to ' - 'get Action one or Action two options. Tapping on that action should ' - 'set the toolbar title.'), + child: Text( + 'On home screen, long press the app icon to ' + 'get Action one or Action two options. Tapping on that action should ' + 'set the toolbar title.', + ), ), ); } diff --git a/packages/quick_actions/quick_actions_ios/example/pubspec.yaml b/packages/quick_actions/quick_actions_ios/example/pubspec.yaml index 48517c187f3..cd049d10332 100644 --- a/packages/quick_actions/quick_actions_ios/example/pubspec.yaml +++ b/packages/quick_actions/quick_actions_ios/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the quick_actions plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions_ios/lib/messages.g.dart b/packages/quick_actions/quick_actions_ios/lib/messages.g.dart index 8f2633adea0..7491f7b1088 100644 --- a/packages/quick_actions/quick_actions_ios/lib/messages.g.dart +++ b/packages/quick_actions/quick_actions_ios/lib/messages.g.dart @@ -18,8 +18,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -32,14 +35,17 @@ List wrapResponse( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -66,12 +72,7 @@ class ShortcutItemMessage { String? icon; List _toList() { - return [ - type, - localizedTitle, - localizedSubtitle, - icon, - ]; + return [type, localizedTitle, localizedSubtitle, icon]; } Object encode() { @@ -135,11 +136,12 @@ class IOSQuickActionsApi { /// Constructor for [IOSQuickActionsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - IOSQuickActionsApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + IOSQuickActionsApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -152,12 +154,13 @@ class IOSQuickActionsApi { 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.setShortcutItems$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemsList], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([itemsList]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -179,10 +182,10 @@ class IOSQuickActionsApi { 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.clearShortcutItems$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -214,22 +217,26 @@ abstract class IOSQuickActionsFlutterApi { messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction$messageChannelSuffix', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction was null.', + ); final List args = (message as List?)!; final String? arg_action = (args[0] as String?); - assert(arg_action != null, - 'Argument for dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction was null, expected non-null String.'); + assert( + arg_action != null, + 'Argument for dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction was null, expected non-null String.', + ); try { api.launchAction(arg_action!); return wrapResponse(empty: true); @@ -237,7 +244,8 @@ abstract class IOSQuickActionsFlutterApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart b/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart index e90b68333ed..7b2f64e6045 100644 --- a/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart +++ b/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart @@ -14,9 +14,8 @@ late QuickActionHandler _handler; /// An implementation of [QuickActionsPlatform] for iOS. class QuickActionsIos extends QuickActionsPlatform { /// Creates a new plugin implementation instance. - QuickActionsIos({ - @visibleForTesting IOSQuickActionsApi? api, - }) : _hostApi = api ?? IOSQuickActionsApi(); + QuickActionsIos({@visibleForTesting IOSQuickActionsApi? api}) + : _hostApi = api ?? IOSQuickActionsApi(); final IOSQuickActionsApi _hostApi; diff --git a/packages/quick_actions/quick_actions_ios/pigeons/messages.dart b/packages/quick_actions/quick_actions_ios/pigeons/messages.dart index 043d4ba7cc3..7b4c3189156 100644 --- a/packages/quick_actions/quick_actions_ios/pigeons/messages.dart +++ b/packages/quick_actions/quick_actions_ios/pigeons/messages.dart @@ -4,12 +4,14 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/messages.g.dart', - swiftOut: 'ios/quick_actions_ios/Sources/quick_actions_ios/messages.g.swift', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/messages.g.dart', + swiftOut: + 'ios/quick_actions_ios/Sources/quick_actions_ios/messages.g.swift', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Home screen quick-action shortcut item. class ShortcutItemMessage { ShortcutItemMessage( diff --git a/packages/quick_actions/quick_actions_ios/pubspec.yaml b/packages/quick_actions/quick_actions_ios/pubspec.yaml index dcc278b2da2..b731abd88a1 100644 --- a/packages/quick_actions/quick_actions_ios/pubspec.yaml +++ b/packages/quick_actions/quick_actions_ios/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.2.1 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md b/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md index 96eff95e7f6..dc43898e11a 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 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 2d5b6874344..37394766116 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 @@ -8,8 +8,9 @@ import 'package:flutter/services.dart'; import '../platform_interface/quick_actions_platform.dart'; import '../types/types.dart'; -const MethodChannel _channel = - MethodChannel('plugins.flutter.io/quick_actions'); +const MethodChannel _channel = MethodChannel( + 'plugins.flutter.io/quick_actions', +); /// An implementation of [QuickActionsPlatform] that uses method channels. class MethodChannelQuickActions extends QuickActionsPlatform { @@ -23,8 +24,9 @@ class MethodChannelQuickActions extends QuickActionsPlatform { assert(call.method == 'launch'); handler(call.arguments as String); }); - final String? action = - await channel.invokeMethod('getLaunchAction'); + final String? action = await channel.invokeMethod( + 'getLaunchAction', + ); if (action != null) { handler(action); } diff --git a/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml b/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml index 768ed8b144e..5e932dd8957 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart b/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart index 0005fda5228..0c047ccd936 100644 --- a/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart +++ b/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart @@ -19,11 +19,12 @@ void main() { setUp(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(quickActions.channel, - (MethodCall methodCall) async { - log.add(methodCall); - return ''; - }); + .setMockMethodCallHandler(quickActions.channel, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return ''; + }); log.clear(); }); @@ -32,24 +33,19 @@ void main() { test('passes getLaunchAction on launch method', () { quickActions.initialize((String type) {}); - expect( - log, - [ - isMethodCall('getLaunchAction', arguments: null), - ], - ); + expect(log, [ + isMethodCall('getLaunchAction', arguments: null), + ]); }); test('initialize', () async { final Completer quickActionsHandler = Completer(); - await quickActions - .initialize((_) => quickActionsHandler.complete(true)); - expect( - log, - [ - isMethodCall('getLaunchAction', arguments: null), - ], + await quickActions.initialize( + (_) => quickActionsHandler.complete(true), ); + expect(log, [ + isMethodCall('getLaunchAction', arguments: null), + ]); log.clear(); expect(quickActionsHandler.future, completion(isTrue)); @@ -65,81 +61,79 @@ void main() { localizedTitle: 'title', localizedSubtitle: 'subtitle', icon: 'icon.svg', - ) + ), ]); - expect( - log, - [ - isMethodCall('getLaunchAction', arguments: null), - isMethodCall('setShortcutItems', arguments: >[ + expect(log, [ + isMethodCall('getLaunchAction', arguments: null), + isMethodCall( + 'setShortcutItems', + arguments: >[ { 'type': 'test', 'localizedTitle': 'title', 'localizedSubtitle': 'subtitle', 'icon': 'icon.svg', - } - ]), - ], - ); + }, + ], + ), + ]); }); - test('passes shortcutItem through channel with null localizedSubtitle', - () { - quickActions.initialize((String type) {}); - quickActions.setShortcutItems([ - const ShortcutItem( - type: 'test', - localizedTitle: 'title', - icon: 'icon.svg', - ) - ]); + test( + 'passes shortcutItem through channel with null localizedSubtitle', + () { + quickActions.initialize((String type) {}); + quickActions.setShortcutItems([ + const ShortcutItem( + type: 'test', + localizedTitle: 'title', + icon: 'icon.svg', + ), + ]); - expect( - log, - [ + expect(log, [ isMethodCall('getLaunchAction', arguments: null), - isMethodCall('setShortcutItems', arguments: >[ - { - 'type': 'test', - 'localizedTitle': 'title', - 'icon': 'icon.svg', - } - ]), - ], - ); - }); - - test('setShortcutItems with demo data', () async { - const String type = 'type'; - const String localizedTitle = 'localizedTitle'; - const String localizedSubtitle = 'localizedSubtitle'; - const String icon = 'icon'; - await quickActions.setShortcutItems( - const [ - ShortcutItem( - type: type, - localizedTitle: localizedTitle, - localizedSubtitle: localizedSubtitle, - icon: icon) - ], - ); - expect( - log, - [ isMethodCall( 'setShortcutItems', arguments: >[ { - 'type': type, - 'localizedTitle': localizedTitle, - 'localizedSubtitle': localizedSubtitle, - 'icon': icon, - } + 'type': 'test', + 'localizedTitle': 'title', + 'icon': 'icon.svg', + }, ], ), - ], - ); + ]); + }, + ); + + test('setShortcutItems with demo data', () async { + const String type = 'type'; + const String localizedTitle = 'localizedTitle'; + const String localizedSubtitle = 'localizedSubtitle'; + const String icon = 'icon'; + await quickActions.setShortcutItems(const [ + ShortcutItem( + type: type, + localizedTitle: localizedTitle, + localizedSubtitle: localizedSubtitle, + icon: icon, + ), + ]); + expect(log, [ + isMethodCall( + 'setShortcutItems', + arguments: >[ + { + 'type': type, + 'localizedTitle': localizedTitle, + 'localizedSubtitle': localizedSubtitle, + 'icon': icon, + }, + ], + ), + ]); log.clear(); }); }); @@ -149,23 +143,17 @@ void main() { quickActions.initialize((String type) {}); quickActions.clearShortcutItems(); - expect( - log, - [ - isMethodCall('getLaunchAction', arguments: null), - isMethodCall('clearShortcutItems', arguments: null), - ], - ); + expect(log, [ + isMethodCall('getLaunchAction', arguments: null), + isMethodCall('clearShortcutItems', arguments: null), + ]); }); test('clearShortcutItems', () { quickActions.clearShortcutItems(); - expect( - log, - [ - isMethodCall('clearShortcutItems', arguments: null), - ], - ); + expect(log, [ + isMethodCall('clearShortcutItems', arguments: null), + ]); log.clear(); }); }); diff --git a/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart b/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart index ab3299b0cc1..f985f423664 100644 --- a/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart +++ b/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart @@ -36,46 +36,49 @@ void main() { }); test( - 'Default implementation of initialize() should throw unimplemented error', - () { - // Arrange - final ExtendsQuickActionsPlatform quickActionsPlatform = - ExtendsQuickActionsPlatform(); + 'Default implementation of initialize() should throw unimplemented error', + () { + // Arrange + final ExtendsQuickActionsPlatform quickActionsPlatform = + ExtendsQuickActionsPlatform(); - // Act & Assert - expect( - () => quickActionsPlatform.initialize((String type) {}), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => quickActionsPlatform.initialize((String type) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setShortcutItems() should throw unimplemented error', - () { - // Arrange - final ExtendsQuickActionsPlatform quickActionsPlatform = - ExtendsQuickActionsPlatform(); + 'Default implementation of setShortcutItems() should throw unimplemented error', + () { + // Arrange + final ExtendsQuickActionsPlatform quickActionsPlatform = + ExtendsQuickActionsPlatform(); - // Act & Assert - expect( - () => quickActionsPlatform.setShortcutItems([]), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => quickActionsPlatform.setShortcutItems([]), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of clearShortcutItems() should throw unimplemented error', - () { - // Arrange - final ExtendsQuickActionsPlatform quickActionsPlatform = - ExtendsQuickActionsPlatform(); + 'Default implementation of clearShortcutItems() should throw unimplemented error', + () { + // Arrange + final ExtendsQuickActionsPlatform quickActionsPlatform = + ExtendsQuickActionsPlatform(); - // Act & Assert - expect( - () => quickActionsPlatform.clearShortcutItems(), - throwsUnimplementedError, - ); - }); + // Act & Assert + expect( + () => quickActionsPlatform.clearShortcutItems(), + throwsUnimplementedError, + ); + }, + ); }); } diff --git a/packages/rfw/CHANGELOG.md b/packages/rfw/CHANGELOG.md index ccf06fdf7d2..02234a2b447 100644 --- a/packages/rfw/CHANGELOG.md +++ b/packages/rfw/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. * Removes the wasm example. ## 1.0.31 diff --git a/packages/rfw/README.md b/packages/rfw/README.md index 93574a63d19..b43a2caa071 100644 --- a/packages/rfw/README.md +++ b/packages/rfw/README.md @@ -199,6 +199,7 @@ class _ExampleState extends State { ); } } + ``` In this example, the "remote" widgets are hardcoded into the @@ -323,12 +324,15 @@ class _ExampleState extends State { // server, and decode it with [decodeLibraryBlob] rather than parsing the // text version using [parseLibraryFile]. However, to make it easier to // play with this sample, this uses the slower text format. - _runtime.update(remoteName, parseLibraryFile(''' + _runtime.update( + remoteName, + parseLibraryFile(''' import local; widget root = GreenBox( child: Hello(name: "World"), ); - ''')); + '''), + ); } @override @@ -343,6 +347,7 @@ class _ExampleState extends State { ); } } + ``` Widgets in local widget libraries are represented by closures that are diff --git a/packages/rfw/example/hello/lib/main.dart b/packages/rfw/example/hello/lib/main.dart index 4df4c180e05..df1563042cd 100644 --- a/packages/rfw/example/hello/lib/main.dart +++ b/packages/rfw/example/hello/lib/main.dart @@ -80,4 +80,5 @@ class _ExampleState extends State { ); } } + // #enddocregion Example diff --git a/packages/rfw/example/hello/pubspec.yaml b/packages/rfw/example/hello/pubspec.yaml index ef6f0ee5e2c..83c7475ee70 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/rfw/example/local/lib/main.dart b/packages/rfw/example/local/lib/main.dart index e7a40b49399..08659b14719 100644 --- a/packages/rfw/example/local/lib/main.dart +++ b/packages/rfw/example/local/lib/main.dart @@ -74,12 +74,15 @@ class _ExampleState extends State { // server, and decode it with [decodeLibraryBlob] rather than parsing the // text version using [parseLibraryFile]. However, to make it easier to // play with this sample, this uses the slower text format. - _runtime.update(remoteName, parseLibraryFile(''' + _runtime.update( + remoteName, + parseLibraryFile(''' import local; widget root = GreenBox( child: Hello(name: "World"), ); - ''')); + '''), + ); } @override @@ -94,4 +97,5 @@ class _ExampleState extends State { ); } } + // #enddocregion Example diff --git a/packages/rfw/example/local/pubspec.yaml b/packages/rfw/example/local/pubspec.yaml index 837bf61559f..4bd596c8775 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/rfw/example/remote/pubspec.yaml b/packages/rfw/example/remote/pubspec.yaml index d4633aefe9d..47cdb0e225b 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/rfw/pubspec.yaml b/packages/rfw/pubspec.yaml index fa41eb7ef24..574faad5ee1 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/rfw/test/material_widgets_test.dart b/packages/rfw/test/material_widgets_test.dart index 67801119de5..0982414ecfd 100644 --- a/packages/rfw/test/material_widgets_test.dart +++ b/packages/rfw/test/material_widgets_test.dart @@ -27,9 +27,10 @@ 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; } @@ -63,7 +64,9 @@ void main() { contains('Could not find remote widget named'), ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; import material; widget root = Scaffold( @@ -208,7 +211,8 @@ void main() { child: Placeholder(), ), ); - ''')); + '''), + ); await tester.pump(); await expectLater( find.byType(RemoteWidget), @@ -238,8 +242,10 @@ void main() { await tester.tap(find.text('second')); await tester.pumpAndSettle(); expect(eventLog, contains('menu_item {args: second}')); - expect(eventLog, - contains(kIsJS ? 'dropdown {value: 2}' : 'dropdown {value: 2.0}')); + expect( + eventLog, + contains(kIsJS ? 'dropdown {value: 2}' : 'dropdown {value: 2.0}'), + ); await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(); @@ -277,7 +283,9 @@ void main() { await tester.binding.setSurfaceSize(null); }); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Scaffold( @@ -306,7 +314,8 @@ void main() { ), ), ); - ''')); + '''), + ); await tester.pump(); await expectLater( @@ -324,13 +333,15 @@ void main() { await expectLater( find.byType(RemoteWidget), matchesGoldenFile( - 'goldens/material_test.button_bar_properties.overflow.png'), + 'goldens/material_test.button_bar_properties.overflow.png', + ), skip: !runGoldens || true, ); }); - testWidgets('OverflowBar configured to resemble ButtonBar', - (WidgetTester tester) async { + testWidgets('OverflowBar configured to resemble ButtonBar', ( + WidgetTester tester, + ) async { final Runtime runtime = setupRuntime(); final DynamicContent data = DynamicContent(); final List eventLog = []; @@ -352,7 +363,9 @@ void main() { contains('Could not find remote widget named'), ); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Scaffold( @@ -380,12 +393,14 @@ void main() { ), ), ); - ''')); + '''), + ); await tester.pump(); await expectLater( find.byType(RemoteWidget), matchesGoldenFile( - 'goldens/material_test.overflow_bar_resembles_button_bar.png'), + 'goldens/material_test.overflow_bar_resembles_button_bar.png', + ), // TODO(louisehsu): Unskip once golden file is updated. See // https://github.com/flutter/flutter/issues/151995 skip: !runGoldens || true, @@ -418,7 +433,9 @@ void main() { await tester.binding.setSurfaceSize(null); }); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Scaffold( @@ -446,7 +463,8 @@ void main() { ), ), ); - ''')); + '''), + ); await tester.pump(); await expectLater( @@ -462,7 +480,8 @@ void main() { await expectLater( find.byType(RemoteWidget), matchesGoldenFile( - 'goldens/material_test.overflow_bar_properties.overflow.png'), + 'goldens/material_test.overflow_bar_properties.overflow.png', + ), // TODO(louisehsu): Unskip once golden file is updated. See // https://github.com/flutter/flutter/issues/151995 skip: !runGoldens || true, @@ -491,7 +510,9 @@ void main() { contains('Could not find remote widget named'), ); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Scaffold( @@ -509,15 +530,17 @@ void main() { ), ), ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(InkResponse), findsOneWidget); // Hover final Offset center = tester.getCenter(find.byType(InkResponse)); - final TestGesture gesture = - await tester.createGesture(kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); await gesture.addPointer(); addTearDown(gesture.removePointer); await gesture.moveTo(center); @@ -533,8 +556,9 @@ void main() { // Tap await gesture.down(center); await tester.pump(); // start gesture - await tester.pump(const Duration( - milliseconds: 200)); // wait for splash to be well under way + await tester.pump( + const Duration(milliseconds: 200), + ); // wait for splash to be well under way await expectLater( find.byType(RemoteWidget), @@ -569,7 +593,9 @@ void main() { contains('Could not find remote widget named'), ); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Material( @@ -585,13 +611,18 @@ void main() { height: 20.0, ), ); - ''')); + '''), + ); await tester.pump(); - expect(tester.widget(find.byType(Material)).animationDuration, - const Duration(milliseconds: 300)); - expect(tester.widget(find.byType(Material)).borderOnForeground, - false); + expect( + tester.widget(find.byType(Material)).animationDuration, + const Duration(milliseconds: 300), + ); + expect( + tester.widget(find.byType(Material)).borderOnForeground, + false, + ); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/material_test.material_properties.png'), @@ -600,7 +631,9 @@ void main() { skip: !runGoldens || true, ); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Material( @@ -611,11 +644,14 @@ void main() { height: 20.0, ), ); - ''')); + '''), + ); await tester.pump(); - expect(tester.widget(find.byType(Material)).clipBehavior, - Clip.antiAlias); + expect( + tester.widget(find.byType(Material)).clipBehavior, + Clip.antiAlias, + ); }); testWidgets('Slider properties', (WidgetTester tester) async { @@ -640,7 +676,9 @@ void main() { contains('Could not find remote widget named'), ); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; widget root = Scaffold( @@ -656,7 +694,8 @@ void main() { secondaryActiveColor: 0xFFFF0000, thumbColor: 0xFF000000, ))); - ''')); + '''), + ); await tester.pump(); final Finder sliderFinder = find.byType(Slider); @@ -670,7 +709,9 @@ void main() { expect(slider.secondaryActiveColor, const Color(0xFFFF0000)); expect(slider.thumbColor, const Color(0xFF000000)); - runtime.update(testName, parseLibraryFile(''' + runtime.update( + testName, + parseLibraryFile(''' import core; import material; @@ -685,30 +726,37 @@ void main() { divisions: 100, value: 0.0, ))); - ''')); + '''), + ); await tester.pump(); //drag slider await _slideToValue(tester, sliderFinder, 20.0); await tester.pumpAndSettle(); - expect(eventLog, - contains(kIsJS ? 'slider {value: 20}' : 'slider {value: 20.0}')); expect( - eventLog, - contains( - kIsJS ? 'slider.start {value: 0}' : 'slider.start {value: 0.0}')); + eventLog, + contains(kIsJS ? 'slider {value: 20}' : 'slider {value: 20.0}'), + ); + expect( + eventLog, + contains(kIsJS ? 'slider.start {value: 0}' : 'slider.start {value: 0.0}'), + ); expect( - eventLog, - contains( - kIsJS ? 'slider.end {value: 20}' : 'slider.end {value: 20.0}')); + eventLog, + contains(kIsJS ? 'slider.end {value: 20}' : 'slider.end {value: 20.0}'), + ); }); } // slide to value for material slider in tests Future _slideToValue( - WidgetTester widgetTester, Finder slider, double value, - {double paddingOffset = 24.0}) async { - final Offset zeroPoint = widgetTester.getTopLeft(slider) + + WidgetTester widgetTester, + Finder slider, + double value, { + double paddingOffset = 24.0, +}) async { + final Offset zeroPoint = + widgetTester.getTopLeft(slider) + Offset(paddingOffset, widgetTester.getSize(slider).height / 2); final double totalWidth = widgetTester.getSize(slider).width - (2 * paddingOffset); diff --git a/packages/rfw/test/remote_widget_test.dart b/packages/rfw/test/remote_widget_test.dart index 89477735519..8918bbc1536 100644 --- a/packages/rfw/test/remote_widget_test.dart +++ b/packages/rfw/test/remote_widget_test.dart @@ -9,19 +9,27 @@ 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( @@ -29,7 +37,9 @@ void main() { runtime: runtime1, data: data, widget: const FullyQualifiedWidgetName( - LibraryName(['test']), 'root'), + LibraryName(['test']), + 'root', + ), ), ); expect(find.byType(RemoteWidget), findsOneWidget); @@ -41,7 +51,9 @@ void main() { runtime: runtime2, data: data, widget: const FullyQualifiedWidgetName( - LibraryName(['test']), 'root'), + LibraryName(['test']), + 'root', + ), ), ); expect(find.byType(RemoteWidget), findsOneWidget); diff --git a/packages/rfw/test/tolerant_comparator.dart b/packages/rfw/test/tolerant_comparator.dart index 0c8cbee97c3..1cb569181c6 100644 --- a/packages/rfw/test/tolerant_comparator.dart +++ b/packages/rfw/test/tolerant_comparator.dart @@ -7,12 +7,16 @@ import 'package:flutter_test/flutter_test.dart'; /// Sets [_TolerantGoldenFileComparator] as the default golden file comparator /// in tests. -void setUpTolerantComparator( - {required String testPath, required double precisionTolerance}) { +void setUpTolerantComparator({ + required String testPath, + required double precisionTolerance, +}) { final GoldenFileComparator oldComparator = goldenFileComparator; final _TolerantGoldenFileComparator newComparator = - _TolerantGoldenFileComparator(Uri.parse(testPath), - precisionTolerance: precisionTolerance); + _TolerantGoldenFileComparator( + Uri.parse(testPath), + precisionTolerance: precisionTolerance, + ); goldenFileComparator = newComparator; @@ -23,11 +27,11 @@ class _TolerantGoldenFileComparator extends LocalFileComparator { _TolerantGoldenFileComparator( super.testFile, { required double precisionTolerance, - }) : assert( - 0 <= precisionTolerance && precisionTolerance <= 1, - 'precisionTolerance must be between 0 and 1', - ), - _precisionTolerance = precisionTolerance; + }) : assert( + 0 <= precisionTolerance && precisionTolerance <= 1, + 'precisionTolerance must be between 0 and 1', + ), + _precisionTolerance = precisionTolerance; /// How much the golden image can differ from the test image. /// diff --git a/packages/rfw/test/tolerant_comparator_web.dart b/packages/rfw/test/tolerant_comparator_web.dart index 7de66496871..935e34ed605 100644 --- a/packages/rfw/test/tolerant_comparator_web.dart +++ b/packages/rfw/test/tolerant_comparator_web.dart @@ -2,5 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -void setUpTolerantComparator( - {required String testPath, required double precisionTolerance}) {} +void setUpTolerantComparator({ + required String testPath, + required double precisionTolerance, +}) {} diff --git a/packages/rfw/test_coverage/bin/test_coverage.dart b/packages/rfw/test_coverage/bin/test_coverage.dart index 6097086dae4..f2f74862616 100644 --- a/packages/rfw/test_coverage/bin/test_coverage.dart +++ b/packages/rfw/test_coverage/bin/test_coverage.dart @@ -56,14 +56,11 @@ Future main(List arguments) async { coverageDirectory.deleteSync(recursive: true); } - final ProcessResult result = Process.runSync( - 'flutter', - [ - 'test', - '--coverage', - if (arguments.isNotEmpty) ...arguments, - ], - ); + final ProcessResult result = Process.runSync('flutter', [ + 'test', + '--coverage', + if (arguments.isNotEmpty) ...arguments, + ]); if (result.exitCode != 0) { print(result.stdout); @@ -83,11 +80,12 @@ 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) { @@ -158,8 +156,8 @@ Future main(List arguments) async { exit(1); } - final String coveredPercent = - (100.0 * coveredLines / totalLines).toStringAsFixed(1); + final String coveredPercent = (100.0 * coveredLines / totalLines) + .toStringAsFixed(1); if (targetLines != null) { if (targetLines! < totalLines) { @@ -193,9 +191,7 @@ Future main(List arguments) async { 'Please add sufficient tests to get coverage back to 100%.', ); print(''); - print( - 'When in doubt, ask @Hixie for advice. Thanks!', - ); + print('When in doubt, ask @Hixie for advice. Thanks!'); exit(1); } diff --git a/packages/rfw/test_coverage/pubspec.yaml b/packages/rfw/test_coverage/pubspec.yaml index 48150903e9e..0e18f5a2842 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.6.0 + sdk: ^3.7.0 dependencies: lcov_parser: 0.1.1 diff --git a/packages/standard_message_codec/CHANGELOG.md b/packages/standard_message_codec/CHANGELOG.md index 5593c945f8b..6196c6ad631 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.0.1+4 diff --git a/packages/standard_message_codec/README.md b/packages/standard_message_codec/README.md index ab736b611a5..9714a6dd178 100644 --- a/packages/standard_message_codec/README.md +++ b/packages/standard_message_codec/README.md @@ -45,11 +45,10 @@ or pure Dart applications. ```dart void main() { - final ByteData? data = - const StandardMessageCodec().encodeMessage({ - 'foo': true, - 3: 'fizz', - }); + final ByteData? data = const StandardMessageCodec().encodeMessage( + {'foo': true, 3: 'fizz'}, + ); print('The encoded message is $data'); } + ``` diff --git a/packages/standard_message_codec/example/lib/readme_excerpts.dart b/packages/standard_message_codec/example/lib/readme_excerpts.dart index f403ad0e592..6e68003939d 100644 --- a/packages/standard_message_codec/example/lib/readme_excerpts.dart +++ b/packages/standard_message_codec/example/lib/readme_excerpts.dart @@ -12,11 +12,10 @@ import 'package:standard_message_codec/standard_message_codec.dart'; // #docregion Encoding void main() { - final ByteData? data = - const StandardMessageCodec().encodeMessage({ - 'foo': true, - 3: 'fizz', - }); + final ByteData? data = const StandardMessageCodec().encodeMessage( + {'foo': true, 3: 'fizz'}, + ); print('The encoded message is $data'); } + // #enddocregion Encoding diff --git a/packages/standard_message_codec/example/pubspec.yaml b/packages/standard_message_codec/example/pubspec.yaml index 44e0ee84b06..e3faa9400ab 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.6.0 + sdk: ^3.7.0 dependencies: standard_message_codec: diff --git a/packages/standard_message_codec/lib/src/serialization.dart b/packages/standard_message_codec/lib/src/serialization.dart index cdcf9b3994f..73dc6509e6b 100644 --- a/packages/standard_message_codec/lib/src/serialization.dart +++ b/packages/standard_message_codec/lib/src/serialization.dart @@ -31,7 +31,10 @@ class WriteBuffer { final ByteData eightBytes = ByteData(8); final Uint8List eightBytesAsList = eightBytes.buffer.asUint8List(); return WriteBuffer._( - Uint8List(startCapacity), eightBytes, eightBytesAsList); + Uint8List(startCapacity), + eightBytes, + eightBytesAsList, + ); } WriteBuffer._(this._buffer, this._eightBytes, this._eightBytesAsList); @@ -166,7 +169,8 @@ class WriteBuffer { ByteData done() { if (_isDone) { throw StateError( - 'done() must not be called more than once on the same $runtimeType.'); + 'done() must not be called more than once on the same $runtimeType.', + ); } final ByteData result = _buffer.buffer.asByteData(0, _currentSize); _buffer = Uint8List(0); @@ -234,8 +238,10 @@ class ReadBuffer { /// Reads the given number of Uint8s from the buffer. Uint8List getUint8List(int length) { - final Uint8List list = - data.buffer.asUint8List(data.offsetInBytes + _position, length); + final Uint8List list = data.buffer.asUint8List( + data.offsetInBytes + _position, + length, + ); _position += length; return list; } @@ -243,8 +249,10 @@ class ReadBuffer { /// Reads the given number of Int32s from the buffer. Int32List getInt32List(int length) { _alignTo(4); - final Int32List list = - data.buffer.asInt32List(data.offsetInBytes + _position, length); + final Int32List list = data.buffer.asInt32List( + data.offsetInBytes + _position, + length, + ); _position += 4 * length; return list; } @@ -252,8 +260,10 @@ class ReadBuffer { /// Reads the given number of Int64s from the buffer. Int64List getInt64List(int length) { _alignTo(8); - final Int64List list = - data.buffer.asInt64List(data.offsetInBytes + _position, length); + final Int64List list = data.buffer.asInt64List( + data.offsetInBytes + _position, + length, + ); _position += 8 * length; return list; } @@ -261,8 +271,10 @@ class ReadBuffer { /// Reads the given number of Float32s from the buffer Float32List getFloat32List(int length) { _alignTo(4); - final Float32List list = - data.buffer.asFloat32List(data.offsetInBytes + _position, length); + final Float32List list = data.buffer.asFloat32List( + data.offsetInBytes + _position, + length, + ); _position += 4 * length; return list; } @@ -270,8 +282,10 @@ class ReadBuffer { /// Reads the given number of Float64s from the buffer. Float64List getFloat64List(int length) { _alignTo(8); - final Float64List list = - data.buffer.asFloat64List(data.offsetInBytes + _position, length); + final Float64List list = data.buffer.asFloat64List( + data.offsetInBytes + _position, + length, + ); _position += 8 * length; return list; } diff --git a/packages/standard_message_codec/lib/standard_message_codec.dart b/packages/standard_message_codec/lib/standard_message_codec.dart index cdb70feef5b..f7421257df8 100644 --- a/packages/standard_message_codec/lib/standard_message_codec.dart +++ b/packages/standard_message_codec/lib/standard_message_codec.dart @@ -160,8 +160,9 @@ class StandardMessageCodec implements MessageCodec { if (message == null) { return null; } - final WriteBuffer buffer = - WriteBuffer(startCapacity: _writeBufferStartCapacity); + final WriteBuffer buffer = WriteBuffer( + startCapacity: _writeBufferStartCapacity, + ); writeValue(buffer, message); return buffer.done(); } diff --git a/packages/standard_message_codec/pubspec.yaml b/packages/standard_message_codec/pubspec.yaml index 0421d5d395c..ddfb1a8c94f 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.6.0 + sdk: ^3.7.0 dev_dependencies: test: ^1.16.0 diff --git a/packages/standard_message_codec/test/standard_message_codec_test.dart b/packages/standard_message_codec/test/standard_message_codec_test.dart index 299bfa295d8..bb4cfc710be 100644 --- a/packages/standard_message_codec/test/standard_message_codec_test.dart +++ b/packages/standard_message_codec/test/standard_message_codec_test.dart @@ -68,14 +68,18 @@ void main() { expect(read.getInt64(), equals(-9000000000000)); }, testOn: 'vm' /* Int64 isn't supported on web */); - test('of 64-bit integer in big endian', () { - final WriteBuffer write = WriteBuffer(); - write.putInt64(-9000000000000, endian: Endian.big); - final ByteData written = write.done(); - expect(written.lengthInBytes, equals(8)); - final ReadBuffer read = ReadBuffer(written); - expect(read.getInt64(endian: Endian.big), equals(-9000000000000)); - }, testOn: 'vm' /* Int64 isn't supported on web */); + test( + 'of 64-bit integer in big endian', + () { + final WriteBuffer write = WriteBuffer(); + write.putInt64(-9000000000000, endian: Endian.big); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(8)); + final ReadBuffer read = ReadBuffer(written); + expect(read.getInt64(endian: Endian.big), equals(-9000000000000)); + }, + testOn: 'vm' /* Int64 isn't supported on web */, + ); test('of double', () { final WriteBuffer write = WriteBuffer(); @@ -105,21 +109,27 @@ void main() { expect(read.getInt32List(3), equals(integers)); }); - test('of 64-bit int list when unaligned', () { - final Int64List integers = Int64List.fromList([-99, 2, 99]); - final WriteBuffer write = WriteBuffer(); - write.putUint8(9); - write.putInt64List(integers); - final ByteData written = write.done(); - expect(written.lengthInBytes, equals(32)); - final ReadBuffer read = ReadBuffer(written); - read.getUint8(); - expect(read.getInt64List(3), equals(integers)); - }, testOn: 'vm' /* Int64 isn't supported on web */); + test( + 'of 64-bit int list when unaligned', + () { + final Int64List integers = Int64List.fromList([-99, 2, 99]); + final WriteBuffer write = WriteBuffer(); + write.putUint8(9); + write.putInt64List(integers); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(32)); + final ReadBuffer read = ReadBuffer(written); + read.getUint8(); + expect(read.getInt64List(3), equals(integers)); + }, + testOn: 'vm' /* Int64 isn't supported on web */, + ); test('of float list when unaligned', () { - final Float32List floats = - Float32List.fromList([3.14, double.nan]); + final Float32List floats = Float32List.fromList([ + 3.14, + double.nan, + ]); final WriteBuffer write = WriteBuffer(); write.putUint8(9); write.putFloat32List(floats); @@ -133,8 +143,10 @@ void main() { }); test('of double list when unaligned', () { - final Float64List doubles = - Float64List.fromList([3.14, double.nan]); + final Float64List doubles = Float64List.fromList([ + 3.14, + double.nan, + ]); final WriteBuffer write = WriteBuffer(); write.putUint8(9); write.putFloat64List(doubles); @@ -155,7 +167,9 @@ void main() { test('empty WriteBuffer', () { expect( - () => WriteBuffer(startCapacity: 0), throwsA(isA())); + () => WriteBuffer(startCapacity: 0), + throwsA(isA()), + ); }); test('size 1', () { diff --git a/packages/two_dimensional_scrollables/CHANGELOG.md b/packages/two_dimensional_scrollables/CHANGELOG.md index 321bbbfdfd2..21bce2fa2b5 100644 --- a/packages/two_dimensional_scrollables/CHANGELOG.md +++ b/packages/two_dimensional_scrollables/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 0.3.7 * Fixes missing leading cache extent in TableView. diff --git a/packages/two_dimensional_scrollables/example/lib/main.dart b/packages/two_dimensional_scrollables/example/lib/main.dart index a065a41938e..ebbd60dcd2e 100644 --- a/packages/two_dimensional_scrollables/example/lib/main.dart +++ b/packages/two_dimensional_scrollables/example/lib/main.dart @@ -42,29 +42,29 @@ class ExampleHome extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Tables & Trees'), - ), + appBar: AppBar(title: const Text('Tables & Trees')), body: Center( - child: Column(children: [ - const Spacer(flex: 3), - FilledButton( - onPressed: () { - // Go to table explorer - Navigator.of(context).pushNamed('/table'); - }, - child: const Text('TableView Explorer'), - ), - const Spacer(), - FilledButton( - onPressed: () { - // Go to tree explorer - Navigator.of(context).pushNamed('/tree'); - }, - child: const Text('TreeView Explorer'), - ), - const Spacer(flex: 3), - ]), + child: Column( + children: [ + const Spacer(flex: 3), + FilledButton( + onPressed: () { + // Go to table explorer + Navigator.of(context).pushNamed('/table'); + }, + child: const Text('TableView Explorer'), + ), + const Spacer(), + FilledButton( + onPressed: () { + // Go to tree explorer + Navigator.of(context).pushNamed('/tree'); + }, + child: const Text('TreeView Explorer'), + ), + const Spacer(flex: 3), + ], + ), ), ); } diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart b/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart index 97099139480..185e617b650 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart @@ -65,27 +65,25 @@ class _InfiniteExampleState extends State { } }); }, - child: Text( - 'Make rows ${_rowCount == null ? 'fixed' : 'infinite'}', - ), + child: Text('Make rows ${_rowCount == null ? 'fixed' : 'infinite'}'), ), ], ); } TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) { - final Color boxColor = - switch ((vicinity.row.isEven, vicinity.column.isEven)) { + final Color boxColor = switch (( + vicinity.row.isEven, + vicinity.column.isEven, + )) { (true, false) || (false, true) => Colors.white, (false, false) => Colors.indigo[100]!, - (true, true) => Colors.indigo[200]! + (true, true) => Colors.indigo[200]!, }; return TableViewCell( child: ColoredBox( color: boxColor, - child: Center( - child: Text('${vicinity.column}:${vicinity.row}'), - ), + child: Center(child: Text('${vicinity.column}:${vicinity.row}')), ), ); } 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 e5b718ad74b..48f833d1676 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 @@ -113,9 +113,7 @@ class _MergedTableExampleState extends State { rowMergeSpan: vicinity.column == 0 ? 3 : null, child: ColoredBox( color: cell.color, - child: Center( - child: Text(cell.name, style: style), - ), + child: Center(child: Text(cell.name, style: style)), ), ); } @@ -123,16 +121,14 @@ 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, + foregroundDecoration: + index == 0 + ? const TableSpanDecoration( + border: TableSpanBorder( + trailing: BorderSide(width: 5, color: Colors.white), ), - ), - ) - : null, + ) + : 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 1a6298f3c16..648379394f3 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,9 +37,21 @@ class _TableExampleState extends State { return Scaffold( body: Padding( padding: const EdgeInsets.symmetric(horizontal: 50.0), - child: _selectionMode == _TableSelection.multiCell - ? SelectionArea( - child: TableView.builder( + 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( verticalDetails: ScrollableDetails.vertical( controller: _verticalController, ), @@ -49,17 +61,6 @@ 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( @@ -156,10 +157,10 @@ class _TableExampleState extends State { recognizerFactories: { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => - t.onTap = () => print('Tap column $index'), - ), + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => + t.onTap = () => print('Tap column $index'), + ), }, ); case 1: @@ -208,10 +209,10 @@ class _TableExampleState extends State { recognizerFactories: { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => - t.onTap = () => print('Tap row $index'), - ), + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => + t.onTap = () => print('Tap row $index'), + ), }, ); case 1: 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 cbca2fb35dd..8301aedefd8 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 @@ -109,10 +109,7 @@ class CustomTreeExampleState extends State { AnimationStyle toggleAnimationStyle, ) { final bool isParentNode = node.children.isNotEmpty; - final BorderSide border = BorderSide( - width: 2, - color: Colors.purple[300]!, - ); + final BorderSide border = BorderSide(width: 2, color: Colors.purple[300]!); // TRY THIS: TreeView.toggleNodeWith can be wrapped around any Widget (even // the whole row) to trigger parent nodes to toggle opened and closed. // Currently, the toggle is triggered in _getTapRecognizer below using the @@ -123,9 +120,10 @@ 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), ), @@ -135,10 +133,7 @@ class CustomTreeExampleState extends State { decoration: BoxDecoration(border: Border.all()), child: SizedBox.square( dimension: 20.0, - child: Icon( - node.isExpanded ? Icons.remove : Icons.add, - size: 14, - ), + child: Icon(node.isExpanded ? Icons.remove : Icons.add, size: 14), ), ), // Spacer @@ -153,26 +148,26 @@ class CustomTreeExampleState extends State { TreeViewNode node, ) { return { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers< + TapGestureRecognizer + >( () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () { - setState(() { - // Toggling the node here instead means any tap on the row can - // toggle parent nodes opened and closed. - treeController.toggleNode(node); - _selectedNode = node; - }); - }, + (TapGestureRecognizer t) => + t.onTap = () { + setState(() { + // Toggling the node here instead means any tap on the row can + // toggle parent nodes opened and closed. + treeController.toggleNode(node); + _selectedNode = node; + }); + }, ), }; } Widget _getTree() { return DecoratedBox( - decoration: BoxDecoration( - border: Border.all(), - ), + decoration: BoxDecoration(border: Border.all()), child: Scrollbar( controller: _horizontalController, thumbVisibility: true, @@ -205,7 +200,8 @@ class CustomTreeExampleState extends State { color: Colors.amber[100], ), foregroundDecoration: const TreeRowDecoration( - border: TreeRowBorder.all(BorderSide())), + border: TreeRowBorder.all(BorderSide()), + ), ); } return TreeRow( @@ -254,27 +250,23 @@ class CustomTreeExampleState extends State { behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), - child: Row(children: [ - SizedBox( - width: (screenSize.width - 50) / 2, - height: double.infinity, - child: _getTree(), - ), - DecoratedBox( - decoration: BoxDecoration( - border: Border.all(), - ), - child: SizedBox( + child: Row( + children: [ + SizedBox( width: (screenSize.width - 50) / 2, height: double.infinity, - child: Center( - child: Column( - children: selectedChildren, - ), + child: _getTree(), + ), + DecoratedBox( + decoration: BoxDecoration(border: Border.all()), + child: SizedBox( + width: (screenSize.width - 50) / 2, + height: double.infinity, + child: Center(child: Column(children: selectedChildren)), ), ), - ), - ]), + ], + ), ), ), ); 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 c5e0fe85a8c..20f3cf25bee 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 @@ -53,9 +53,7 @@ class TreeExampleState extends State { TreeViewNode( 'Um-dittle-ittl-um-dittle-I', children: >[ - TreeViewNode( - 'Um-dittle-ittl-um-dittle-I', - ), + TreeViewNode('Um-dittle-ittl-um-dittle-I'), ], ), ], @@ -72,13 +70,14 @@ class TreeExampleState extends State { return { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () { - setState(() { - _selectedNode = node; - }); - }, - ), + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => + t.onTap = () { + setState(() { + _selectedNode = node; + }); + }, + ), }; } @@ -114,9 +113,9 @@ class TreeExampleState extends State { ), ); } - return TreeView.defaultTreeRowBuilder(node).copyWith( - recognizerFactories: _getTapRecognizer(node), - ); + return TreeView.defaultTreeRowBuilder( + node, + ).copyWith(recognizerFactories: _getTapRecognizer(node)); }, // Exaggerated indentation to exceed viewport bounds. indentation: TreeViewIndentationType.custom(50.0), diff --git a/packages/two_dimensional_scrollables/example/pubspec.yaml b/packages/two_dimensional_scrollables/example/pubspec.yaml index d881cbb0681..5801de5d0b3 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart b/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart index 60cfb381f62..5580c0c45a3 100644 --- a/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart +++ b/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart @@ -57,8 +57,9 @@ void main() { expect(position.pixels, 0.0); }); - testWidgets('Selection SegmentedButton control works', - (WidgetTester tester) async { + testWidgets('Selection SegmentedButton control works', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const MaterialApp(home: TableExample())); await tester.pump(); diff --git a/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart b/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart index 3de3b4204f7..5c5e59be23c 100644 --- a/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart +++ b/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart @@ -10,8 +10,9 @@ import 'package:two_dimensional_examples/table_view/simple_table.dart'; import 'package:two_dimensional_examples/table_view/table_explorer.dart'; void main() { - testWidgets('Table explorer switches between samples', - (WidgetTester tester) async { + testWidgets('Table explorer switches between samples', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const MaterialApp(home: TableExplorer())); await tester.pumpAndSettle(); // The first example diff --git a/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart b/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart index 4146fb3f544..fb24a7316e4 100644 --- a/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart +++ b/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart @@ -7,8 +7,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_examples/tree_view/custom_tree.dart'; void main() { - testWidgets('Example builds and can be interacted with', - (WidgetTester tester) async { + testWidgets('Example builds and can be interacted with', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const MaterialApp(home: CustomTreeExample())); await tester.pumpAndSettle(); expect(find.text('README.md'), findsOneWidget); @@ -34,9 +35,8 @@ void main() { expect(verticalPosition.maxScrollExtent, 0.0); expect(verticalPosition.pixels, 0.0); - final CustomTreeExampleState state = tester.state( - find.byType(CustomTreeExample), - ) as CustomTreeExampleState; + final CustomTreeExampleState state = + tester.state(find.byType(CustomTreeExample)) as CustomTreeExampleState; state.treeController.toggleNode(state.treeController.getNodeFor('lib')!); await tester.pumpAndSettle(); diff --git a/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart b/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart index 6c15316923d..d064e5b4404 100644 --- a/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart +++ b/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart @@ -7,24 +7,19 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_examples/tree_view/simple_tree.dart'; void main() { - testWidgets('Example builds and can be interacted with', - (WidgetTester tester) async { + testWidgets('Example builds and can be interacted with', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const MaterialApp(home: TreeExample())); await tester.pumpAndSettle(); expect( find.text("It's supercalifragilisticexpialidocious"), findsOneWidget, ); - expect( - find.text('Um-dittle-ittl-um-dittle-I'), - findsNothing, - ); + expect(find.text('Um-dittle-ittl-um-dittle-I'), findsNothing); await tester.tap(find.byType(Icon).last); await tester.pumpAndSettle(); - expect( - find.text('Um-dittle-ittl-um-dittle-I'), - findsOneWidget, - ); + expect(find.text('Um-dittle-ittl-um-dittle-I'), findsOneWidget); }); testWidgets('Can scroll ', (WidgetTester tester) async { @@ -41,9 +36,8 @@ void main() { expect(horizontalPosition.maxScrollExtent, greaterThan(190)); expect(horizontalPosition.pixels, 0.0); - final TreeExampleState state = tester.state( - find.byType(TreeExample), - ) as TreeExampleState; + final TreeExampleState state = + tester.state(find.byType(TreeExample)) as TreeExampleState; state.treeController.expandAll(); await tester.pumpAndSettle(); diff --git a/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart b/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart index d9be8e93cc6..87e33f41e0f 100644 --- a/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart +++ b/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart @@ -9,8 +9,9 @@ import 'package:two_dimensional_examples/tree_view/simple_tree.dart'; import 'package:two_dimensional_examples/tree_view/tree_explorer.dart'; void main() { - testWidgets('Tree explorer switches between samples', - (WidgetTester tester) async { + testWidgets('Tree explorer switches between samples', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const MaterialApp(home: TreeExplorer())); await tester.pumpAndSettle(); // The first example diff --git a/packages/two_dimensional_scrollables/lib/src/common/span.dart b/packages/two_dimensional_scrollables/lib/src/common/span.dart index 08c78b4887d..bfa694995e4 100644 --- a/packages/two_dimensional_scrollables/lib/src/common/span.dart +++ b/packages/two_dimensional_scrollables/lib/src/common/span.dart @@ -11,15 +11,10 @@ import 'package:flutter/widgets.dart'; /// Defines the leading and trailing padding values of a [Span]. class SpanPadding { /// Creates a padding configuration for a [Span]. - const SpanPadding({ - this.leading = 0.0, - this.trailing = 0.0, - }); + const SpanPadding({this.leading = 0.0, this.trailing = 0.0}); /// Creates padding where both the [leading] and [trailing] are `value`. - const SpanPadding.all(double value) - : leading = value, - trailing = value; + const SpanPadding.all(double value) : leading = value, trailing = value; /// The leading amount of pixels to pad a [Span] by. /// @@ -229,9 +224,7 @@ class FractionalSpanExtent extends SpanExtent { /// Creates a [FractionalSpanExtent]. /// /// The provided [fraction] value must be equal to or greater than zero. - const FractionalSpanExtent( - this.fraction, - ) : assert(fraction >= 0.0); + const FractionalSpanExtent(this.fraction) : assert(fraction >= 0.0); /// The fraction of the [SpanExtentDelegate.viewportExtent] that the /// span should occupy. @@ -297,19 +290,15 @@ class CombiningSpanExtent extends SpanExtent { /// Returns the larger pixel extent of the two provided [SpanExtent]. class MaxSpanExtent extends CombiningSpanExtent { /// Creates a [MaxSpanExtent]. - const MaxSpanExtent( - SpanExtent extent1, - SpanExtent extent2, - ) : super(extent1, extent2, math.max); + const MaxSpanExtent(SpanExtent extent1, SpanExtent extent2) + : super(extent1, extent2, math.max); } /// Returns the smaller pixel extent of the two provided [SpanExtent]. class MinSpanExtent extends CombiningSpanExtent { /// Creates a [MinSpanExtent]. - const MinSpanExtent( - SpanExtent extent1, - SpanExtent extent2, - ) : super(extent1, extent2, math.min); + const MinSpanExtent(SpanExtent extent1, SpanExtent extent2) + : super(extent1, extent2, math.min); } /// A decoration for a [Span]. @@ -394,16 +383,14 @@ 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 { - details.canvas.drawRRect( - borderRadius!.toRRect(details.rect), - paint, - ); + details.canvas.drawRRect(borderRadius!.toRRect(details.rect), paint); } } if (border != null) { @@ -451,10 +438,7 @@ class SpanBorder { /// cell representing the pinned column and separately with another /// [SpanDecorationPaintDetails.rect] containing all the other unpinned /// cells. - void paint( - SpanDecorationPaintDetails details, - BorderRadius? borderRadius, - ) { + void paint(SpanDecorationPaintDetails details, BorderRadius? borderRadius) { final AxisDirection axisDirection = details.axisDirection; switch (axisDirectionToAxis(axisDirection)) { case Axis.horizontal: @@ -462,21 +446,13 @@ class SpanBorder { top: axisDirection == AxisDirection.right ? leading : trailing, bottom: axisDirection == AxisDirection.right ? trailing : leading, ); - border.paint( - details.canvas, - details.rect, - borderRadius: borderRadius, - ); + border.paint(details.canvas, details.rect, borderRadius: borderRadius); case Axis.vertical: final Border border = Border( left: axisDirection == AxisDirection.down ? leading : trailing, right: axisDirection == AxisDirection.down ? trailing : leading, ); - border.paint( - details.canvas, - details.rect, - borderRadius: borderRadius, - ); + border.paint(details.canvas, details.rect, borderRadius: borderRadius); } } } 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 7cf1e960c7c..14592d0907c 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table.dart @@ -156,23 +156,23 @@ class TableView extends TwoDimensionalScrollView { required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, required TableViewCellBuilder cellBuilder, - }) : assert(pinnedRowCount >= 0), - assert(rowCount == null || rowCount >= 0), - assert(rowCount == null || rowCount >= pinnedRowCount), - assert(columnCount == null || columnCount >= 0), - assert(pinnedColumnCount >= 0), - assert(columnCount == null || columnCount >= pinnedColumnCount), - super( - delegate: TableCellBuilderDelegate( - columnCount: columnCount, - rowCount: rowCount, - pinnedColumnCount: pinnedColumnCount, - pinnedRowCount: pinnedRowCount, - cellBuilder: cellBuilder, - columnBuilder: columnBuilder, - rowBuilder: rowBuilder, - ), - ); + }) : assert(pinnedRowCount >= 0), + assert(rowCount == null || rowCount >= 0), + assert(rowCount == null || rowCount >= pinnedRowCount), + assert(columnCount == null || columnCount >= 0), + assert(pinnedColumnCount >= 0), + assert(columnCount == null || columnCount >= pinnedColumnCount), + super( + delegate: TableCellBuilderDelegate( + columnCount: columnCount, + rowCount: rowCount, + pinnedColumnCount: pinnedColumnCount, + pinnedRowCount: pinnedRowCount, + cellBuilder: cellBuilder, + columnBuilder: columnBuilder, + rowBuilder: rowBuilder, + ), + ); /// Creates a [TableView] from an explicit two dimensional array of children. /// @@ -200,17 +200,17 @@ class TableView extends TwoDimensionalScrollView { required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, List> cells = const >[], - }) : assert(pinnedRowCount >= 0), - assert(pinnedColumnCount >= 0), - super( - delegate: TableCellListDelegate( - pinnedColumnCount: pinnedColumnCount, - pinnedRowCount: pinnedRowCount, - cells: cells, - columnBuilder: columnBuilder, - rowBuilder: rowBuilder, - ), - ); + }) : assert(pinnedRowCount >= 0), + assert(pinnedColumnCount >= 0), + super( + delegate: TableCellListDelegate( + pinnedColumnCount: pinnedColumnCount, + pinnedRowCount: pinnedRowCount, + cells: cells, + columnBuilder: columnBuilder, + rowBuilder: rowBuilder, + ), + ); @override TableViewport buildViewport( @@ -354,11 +354,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { bool get _rowsAreInfinite => delegate.rowCount == null; // Where row layout begins, potentially outside of the visible area. double get _targetLeadingRowPixel { - return clampDouble( - verticalOffset.pixels - cacheExtent, - 0, - double.infinity, - ); + return clampDouble(verticalOffset.pixels - cacheExtent, 0, double.infinity); } // How far rows should be laid out in a given frame. @@ -401,12 +397,14 @@ 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) => @@ -447,13 +445,15 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); result.add( HitTestEntry( - _columnMetrics[cellParentData.tableVicinity.column]!), + _columnMetrics[cellParentData.tableVicinity.column]!, + ), ); case Axis.horizontal: // Column major order, columns go first. result.add( HitTestEntry( - _columnMetrics[cellParentData.tableVicinity.column]!), + _columnMetrics[cellParentData.tableVicinity.column]!, + ), ); result.add( HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!), @@ -727,10 +727,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _pinnedRowsExtent, ); } - return verticalOffset.applyContentDimensions( - 0.0, - maxVerticalScrollExtent, - ); + return verticalOffset.applyContentDimensions(0.0, maxVerticalScrollExtent); } // Uses the cached metrics to update the currently visible cells. If the @@ -746,9 +743,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // _targetColumnPixel, while keeping the ones we already know about. _updateColumnMetrics(appendColumns: true); lastKnownColumn = _columnMetrics[_columnMetrics.length - 1]!; - assert(_columnMetrics.length == delegate.columnCount || - lastKnownColumn.trailingOffset >= _targetTrailingColumnPixel || - _columnNullTerminatedIndex != null); + assert( + _columnMetrics.length == delegate.columnCount || + lastKnownColumn.trailingOffset >= _targetTrailingColumnPixel || + _columnNullTerminatedIndex != null, + ); } } _firstNonPinnedColumn = null; @@ -780,9 +779,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // _targetRowPixel, while keeping the ones we already know about. _updateRowMetrics(appendRows: true); lastKnownRow = _rowMetrics[_rowMetrics.length - 1]!; - assert(_rowMetrics.length == delegate.rowCount || - lastKnownRow.trailingOffset >= _targetTrailingRowPixel || - _rowNullTerminatedIndex != null); + assert( + _rowMetrics.length == delegate.rowCount || + lastKnownRow.trailingOffset >= _targetTrailingRowPixel || + _rowNullTerminatedIndex != null, + ); } } _firstNonPinnedRow = null; @@ -841,16 +842,18 @@ 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( @@ -960,9 +963,10 @@ 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); @@ -971,32 +975,38 @@ 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; - assert(_debugCheckMergeBounds( - spanOrientation: 'Row', - currentSpan: row, - spanMergeStart: firstRow, - spanMergeEnd: lastRow, - spanCount: delegate.rowCount, - pinnedSpanCount: delegate.pinnedRowCount, - currentVicinity: vicinity, - )); + final int lastRow = + cellParentData.rowMergeStart == null + ? row + : firstRow + cellParentData.rowMergeSpan! - 1; + assert( + _debugCheckMergeBounds( + spanOrientation: 'Row', + currentSpan: row, + spanMergeStart: firstRow, + spanMergeEnd: lastRow, + spanCount: delegate.rowCount, + pinnedSpanCount: delegate.pinnedRowCount, + currentVicinity: vicinity, + ), + ); final int firstColumn = cellParentData.columnMergeStart ?? column; - final int lastColumn = cellParentData.columnMergeStart == null - ? column - : firstColumn + cellParentData.columnMergeSpan! - 1; - assert(_debugCheckMergeBounds( - spanOrientation: 'Column', - currentSpan: column, - spanMergeStart: firstColumn, - spanMergeEnd: lastColumn, - spanCount: delegate.columnCount, - pinnedSpanCount: delegate.pinnedColumnCount, - currentVicinity: vicinity, - )); + final int lastColumn = + cellParentData.columnMergeStart == null + ? column + : firstColumn + cellParentData.columnMergeSpan! - 1; + assert( + _debugCheckMergeBounds( + spanOrientation: 'Column', + currentSpan: column, + spanMergeStart: firstColumn, + spanMergeEnd: lastColumn, + spanCount: delegate.columnCount, + pinnedSpanCount: delegate.pinnedColumnCount, + currentVicinity: vicinity, + ), + ); // Leading padding on the leading cell, and trailing padding on the // trailing cell should be excluded. Interim leading/trailing @@ -1009,20 +1019,23 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // | <--------- extent of merged cell ---------> | // Compute height and layout offset for merged rows. - final bool rowIsInPinnedColumn = _lastPinnedColumn != null && + final bool rowIsInPinnedColumn = + _lastPinnedColumn != null && vicinity.column <= _lastPinnedColumn!; final bool rowIsPinned = _lastPinnedRow != null && firstRow <= _lastPinnedRow!; - final double baseRowOffset = - switch ((rowIsInPinnedColumn, rowIsPinned)) { + final double baseRowOffset = switch (( + rowIsInPinnedColumn, + rowIsPinned, + )) { // Both row and column are pinned at this cell, or just pinned row. (true, true) || (false, true) => 0.0, // Cell is within a pinned column, or no pinned area at all. (true, false) || - (false, false) => - _pinnedRowsExtent - verticalOffset.pixels, + (false, false) => _pinnedRowsExtent - verticalOffset.pixels, }; - mergedRowOffset = baseRowOffset + + mergedRowOffset = + baseRowOffset + _rowMetrics[firstRow]!.leadingOffset + _rowMetrics[firstRow]!.configuration.padding.leading; if (_rowsAreInfinite && _rowMetrics[lastRow] == null) { @@ -1038,7 +1051,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { 'null, signifying the end, at row $_rowNullTerminatedIndex but the ' 'merged cell is configured to end with row $lastRow.', ); - mergedRowHeight = _rowMetrics[lastRow]!.trailingOffset - + mergedRowHeight = + _rowMetrics[lastRow]!.trailingOffset - _rowMetrics[firstRow]!.leadingOffset - _rowMetrics[lastRow]!.configuration.padding.trailing - _rowMetrics[firstRow]!.configuration.padding.leading; @@ -1047,16 +1061,18 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _lastPinnedRow != null && vicinity.row <= _lastPinnedRow!; final bool columnIsPinned = _lastPinnedColumn != null && firstColumn <= _lastPinnedColumn!; - final double baseColumnOffset = - switch ((columnIsInPinnedRow, columnIsPinned)) { + final double baseColumnOffset = switch (( + columnIsInPinnedRow, + columnIsPinned, + )) { // Both row and column are pinned at this cell, or just pinned column. (true, true) || (false, true) => 0.0, // Cell is within a pinned row, or no pinned area at all. (true, false) || - (false, false) => - _pinnedColumnsExtent - horizontalOffset.pixels, + (false, false) => _pinnedColumnsExtent - horizontalOffset.pixels, }; - mergedColumnOffset = baseColumnOffset + + mergedColumnOffset = + baseColumnOffset + _columnMetrics[firstColumn]!.leadingOffset + _columnMetrics[firstColumn]!.configuration.padding.leading; @@ -1076,7 +1092,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { 'null, signifying the end, at column $_columnNullTerminatedIndex but ' 'the merged cell is configured to end with column $lastColumn.', ); - mergedColumnWidth = _columnMetrics[lastColumn]!.trailingOffset - + mergedColumnWidth = + _columnMetrics[lastColumn]!.trailingOffset - _columnMetrics[firstColumn]!.leadingOffset - _columnMetrics[lastColumn]!.configuration.padding.trailing - _columnMetrics[firstColumn]!.configuration.padding.leading; @@ -1117,7 +1134,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { mergedColumnOffset = null; mergedColumnWidth = null; } - columnOffset += standardColumnWidth + + columnOffset += + standardColumnWidth + _columnMetrics[column]!.configuration.padding.trailing; } rowOffset += @@ -1199,7 +1217,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { offset: offset, leadingVicinity: TableVicinity(column: 0, row: _firstNonPinnedRow!), trailingVicinity: TableVicinity( - column: _lastPinnedColumn!, row: _lastNonPinnedRow!), + column: _lastPinnedColumn!, + row: _lastNonPinnedRow!, + ), ); }, clipBehavior: clipBehavior, @@ -1229,10 +1249,14 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _paintCells( context: context, offset: offset, - leadingVicinity: - TableVicinity(column: _firstNonPinnedColumn!, row: 0), + leadingVicinity: TableVicinity( + column: _firstNonPinnedColumn!, + row: 0, + ), trailingVicinity: TableVicinity( - column: _lastNonPinnedColumn!, row: _lastPinnedRow!), + column: _lastNonPinnedColumn!, + row: _lastPinnedRow!, + ), ); }, clipBehavior: clipBehavior, @@ -1249,8 +1273,10 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { context: context, offset: offset, leadingVicinity: TableVicinity.zero, - trailingVicinity: - TableVicinity(column: _lastPinnedColumn!, row: _lastPinnedRow!), + trailingVicinity: TableVicinity( + column: _lastPinnedColumn!, + row: _lastPinnedRow!, + ), ); } } @@ -1301,9 +1327,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { LinkedHashMap(); final TableSpan rowSpan = _rowMetrics[leadingVicinity.row]!.configuration; - for (int column = leadingVicinity.column; - column <= trailingVicinity.column; - column++) { + for ( + int column = leadingVicinity.column; + column <= trailingVicinity.column; + column++ + ) { TableSpan columnSpan = _columnMetrics[column]!.configuration; if (columnSpan.backgroundDecoration != null || columnSpan.foregroundDecoration != null || @@ -1313,14 +1341,14 @@ 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 @@ -1374,10 +1402,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { mapMergedVicinityToCanonicalChild: false, ); } - decorationCells.add(( - leading: leadingCell, - trailing: trailingCell, - )); + decorationCells.add((leading: leadingCell, trailing: trailingCell)); } } @@ -1389,9 +1414,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final ({double leading, double trailing}) offsetCorrection = axisDirectionIsReversed(verticalAxisDirection) ? ( - leading: leadingCell.size.height, - trailing: trailingCell.size.height, - ) + leading: leadingCell.size.height, + trailing: trailingCell.size.height, + ) : (leading: 0.0, trailing: 0.0); return Rect.fromPoints( parentDataOf(leadingCell).paintOffset! + @@ -1414,7 +1439,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { in decorationCells) { // If this was a merged cell, the decoration is defined by the leading // cell, which may come from a different column. - final int columnIndex = parentDataOf(cell.leading).columnMergeStart ?? + final int columnIndex = + parentDataOf(cell.leading).columnMergeStart ?? parentDataOf(cell.leading).tableVicinity.column; columnSpan = _columnMetrics[columnIndex]!.configuration; if (columnSpan.backgroundDecoration != null) { @@ -1456,14 +1482,14 @@ 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 @@ -1517,10 +1543,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { mapMergedVicinityToCanonicalChild: false, ); } - decorationCells.add(( - leading: leadingCell, - trailing: trailingCell, - )); + decorationCells.add((leading: leadingCell, trailing: trailingCell)); } } @@ -1532,9 +1555,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final ({double leading, double trailing}) offsetCorrection = axisDirectionIsReversed(horizontalAxisDirection) ? ( - leading: leadingCell.size.width, - trailing: trailingCell.size.width, - ) + leading: leadingCell.size.width, + trailing: trailingCell.size.width, + ) : (leading: 0.0, trailing: 0.0); return Rect.fromPoints( parentDataOf(leadingCell).paintOffset! + @@ -1557,7 +1580,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { in decorationCells) { // If this was a merged cell, the decoration is defined by the leading // cell, which may come from a different row. - final int rowIndex = parentDataOf(cell.leading).rowMergeStart ?? + final int rowIndex = + parentDataOf(cell.leading).rowMergeStart ?? parentDataOf(cell.trailing).tableVicinity.row; rowSpan = _rowMetrics[rowIndex]!.configuration; if (rowSpan.backgroundDecoration != null) { @@ -1592,19 +1616,19 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { backgroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: horizontalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: horizontalAxisDirection, + ); decoration.paint(paintingDetails); }); backgroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: verticalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: verticalAxisDirection, + ); decoration.paint(paintingDetails); }); // Column major order. Columns go first. @@ -1612,27 +1636,29 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { backgroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: verticalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: verticalAxisDirection, + ); decoration.paint(paintingDetails); }); backgroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: horizontalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: horizontalAxisDirection, + ); decoration.paint(paintingDetails); }); } // Cells - for (int column = leadingVicinity.column; - column <= trailingVicinity.column; - column++) { + for ( + int column = leadingVicinity.column; + column <= trailingVicinity.column; + column++ + ) { for (int row = leadingVicinity.row; row <= trailingVicinity.row; row++) { final TableVicinity vicinity = TableVicinity(column: column, row: row); final RenderBox? cell = getChildFor( @@ -1664,19 +1690,19 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { foregroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: horizontalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: horizontalAxisDirection, + ); decoration.paint(paintingDetails); }); foregroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: verticalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: verticalAxisDirection, + ); decoration.paint(paintingDetails); }); // Column major order. Columns go first. @@ -1684,19 +1710,19 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { foregroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: verticalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: verticalAxisDirection, + ); decoration.paint(paintingDetails); }); foregroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: horizontalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: horizontalAxisDirection, + ); decoration.paint(paintingDetails); }); } @@ -1777,7 +1803,8 @@ class _Span {}; for (final Type type in configuration.recognizerFactories.keys) { assert(!newRecognizers.containsKey(type)); - newRecognizers[type] = _recognizers?.remove(type) ?? + newRecognizers[type] = + _recognizers?.remove(type) ?? configuration.recognizerFactories[type]!.constructor(); assert( newRecognizers[type].runtimeType == type, @@ -1786,8 +1813,9 @@ class _Span 'GestureRecognizerFactory must be specialized with the type of the ' 'class that it returns from its constructor method.', ); - configuration.recognizerFactories[type]! - .initializer(newRecognizers[type]!); + configuration.recognizerFactories[type]!.initializer( + newRecognizers[type]!, + ); } _disposeRecognizers(); // only disposes the ones that where not re-used above. _recognizers = newRecognizers; diff --git a/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart b/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart index 3474c4874c1..e12951b4f07 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart @@ -17,10 +17,8 @@ import 'table.dart'; class TableVicinity extends ChildVicinity { /// Creates a reference to a child in a [TableView], with the [xIndex] and /// [yIndex] converted to terms of [row] and [column]. - const TableVicinity({ - required int row, - required int column, - }) : super(xIndex: column, yIndex: row); + const TableVicinity({required int row, required int column}) + : super(xIndex: column, yIndex: row); /// The row index of the child in the [TableView]. /// @@ -37,14 +35,8 @@ class TableVicinity extends ChildVicinity { /// Returns a new [TableVicinity], copying over the row and column fields with /// those provided, or maintaining the original values. - TableVicinity copyWith({ - int? row, - int? column, - }) { - return TableVicinity( - row: row ?? this.row, - column: column ?? this.column, - ); + TableVicinity copyWith({int? row, int? column}) { + return TableVicinity(row: row ?? this.row, column: column ?? this.column); } @override @@ -87,11 +79,13 @@ class TableViewParentData extends TwoDimensionalViewportParentData { mergeDetails += ', merged'; } if (rowMergeStart != null) { - mergeDetails += ', rowMergeStart=$rowMergeStart, ' + mergeDetails += + ', rowMergeStart=$rowMergeStart, ' 'rowMergeSpan=$rowMergeSpan'; } if (columnMergeStart != null) { - mergeDetails += ', columnMergeStart=$columnMergeStart, ' + mergeDetails += + ', columnMergeStart=$columnMergeStart, ' 'columnMergeSpan=$columnMergeSpan'; } return super.toString() + mergeDetails; @@ -117,20 +111,20 @@ class TableViewCell extends StatelessWidget { this.columnMergeSpan, this.addRepaintBoundaries = true, required this.child, - }) : assert( - (rowMergeStart == null && rowMergeSpan == null) || - (rowMergeStart != null && rowMergeSpan != null), - 'Row merge start and span must both be set, or both unset.', - ), - assert(rowMergeStart == null || rowMergeStart >= 0), - assert(rowMergeSpan == null || rowMergeSpan > 0), - assert( - (columnMergeStart == null && columnMergeSpan == null) || - (columnMergeStart != null && columnMergeSpan != null), - 'Column merge start and span must both be set, or both unset.', - ), - assert(columnMergeStart == null || columnMergeStart >= 0), - assert(columnMergeSpan == null || columnMergeSpan > 0); + }) : assert( + (rowMergeStart == null && rowMergeSpan == null) || + (rowMergeStart != null && rowMergeSpan != null), + 'Row merge start and span must both be set, or both unset.', + ), + assert(rowMergeStart == null || rowMergeStart >= 0), + assert(rowMergeSpan == null || rowMergeSpan > 0), + assert( + (columnMergeStart == null && columnMergeSpan == null) || + (columnMergeStart != null && columnMergeSpan != null), + 'Column merge start and span must both be set, or both unset.', + ), + assert(columnMergeStart == null || columnMergeStart >= 0), + assert(columnMergeSpan == null || columnMergeSpan > 0); /// The child contained in this cell of the [TableView]. final Widget child; 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 3bc7d4b64c8..cd5aada1619 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 @@ -24,10 +24,8 @@ typedef TableSpanBuilder = TableSpan? Function(int index); /// /// Used by [TableCellBuilderDelegate.builder] to build cells on demand for the /// table. -typedef TableViewCellBuilder = TableViewCell Function( - BuildContext context, - TableVicinity vicinity, -); +typedef TableViewCellBuilder = + TableViewCell Function(BuildContext context, TableVicinity vicinity); /// A mixin that defines the model for a [TwoDimensionalChildDelegate] to be /// used with a [TableView]. @@ -150,24 +148,25 @@ class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate required TableViewCellBuilder cellBuilder, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, - }) : assert(pinnedColumnCount >= 0), - assert(pinnedRowCount >= 0), - assert(rowCount == null || rowCount >= 0), - assert(columnCount == null || columnCount >= 0), - assert(columnCount == null || pinnedColumnCount <= columnCount), - assert(rowCount == null || pinnedRowCount <= rowCount), - _rowBuilder = rowBuilder, - _columnBuilder = columnBuilder, - _pinnedColumnCount = pinnedColumnCount, - _pinnedRowCount = pinnedRowCount, - super( - 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 - addRepaintBoundaries: false, - ); + }) : assert(pinnedColumnCount >= 0), + assert(pinnedRowCount >= 0), + assert(rowCount == null || rowCount >= 0), + assert(columnCount == null || columnCount >= 0), + assert(columnCount == null || pinnedColumnCount <= columnCount), + assert(rowCount == null || pinnedRowCount <= rowCount), + _rowBuilder = rowBuilder, + _columnBuilder = columnBuilder, + _pinnedColumnCount = pinnedColumnCount, + _pinnedRowCount = pinnedRowCount, + super( + 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 + addRepaintBoundaries: false, + ); @override int? get columnCount => maxXIndex == null ? null : maxXIndex! + 1; @@ -252,17 +251,17 @@ class TableCellListDelegate extends TwoDimensionalChildListDelegate required List> cells, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, - }) : assert(pinnedColumnCount >= 0), - assert(pinnedRowCount >= 0), - _columnBuilder = columnBuilder, - _rowBuilder = rowBuilder, - _pinnedColumnCount = pinnedColumnCount, - _pinnedRowCount = pinnedRowCount, - super( - children: cells, - // repaintBoundaries handled by TableViewCell - addRepaintBoundaries: false, - ) { + }) : assert(pinnedColumnCount >= 0), + assert(pinnedRowCount >= 0), + _columnBuilder = columnBuilder, + _rowBuilder = rowBuilder, + _pinnedColumnCount = pinnedColumnCount, + _pinnedRowCount = pinnedRowCount, + super( + children: cells, + // repaintBoundaries handled by TableViewCell + addRepaintBoundaries: false, + ) { // Even if there are merged cells, they should be represented by the same // child in each cell location. This ensures that no matter which direction // the merged cell scrolls into view from, we can build the correct child 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 49628937381..f5a88402623 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 @@ -39,14 +39,16 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { required super.childManager, super.cacheExtent, super.clipBehavior, - }) : _activeAnimations = activeAnimations, - _rowDepths = rowDepths, - _indentation = indentation, - assert(indentation >= 0), - assert(verticalAxisDirection == AxisDirection.down && - horizontalAxisDirection == AxisDirection.right), - // This is fixed as there is currently only one traversal pattern, https://github.com/flutter/flutter/issues/148357 - super(mainAxis: Axis.vertical); + }) : _activeAnimations = activeAnimations, + _rowDepths = rowDepths, + _indentation = indentation, + assert(indentation >= 0), + assert( + verticalAxisDirection == AxisDirection.down && + horizontalAxisDirection == AxisDirection.right, + ), + // This is fixed as there is currently only one traversal pattern, https://github.com/flutter/flutter/issues/148357 + super(mainAxis: Axis.vertical); @override TreeRowDelegateMixin get delegate => super.delegate as TreeRowDelegateMixin; @@ -126,25 +128,27 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { // Updates the cache at the start of eah layout pass. void _updateAnimationCache() { _animationLeadingIndices.clear(); - _activeAnimations.forEach( - (UniqueKey key, TreeViewNodesAnimation animation) { - _animationLeadingIndices[animation.fromIndex] = key; - }, - ); + _activeAnimations.forEach(( + UniqueKey key, + TreeViewNodesAnimation animation, + ) { + _animationLeadingIndices[animation.fromIndex] = key; + }); // Remove any stored offsets or clip layers that are no longer actively // animating. _animationOffsets.removeWhere((UniqueKey key, _) { return !_activeAnimations.keys.contains(key); }); - _clipHandles.removeWhere( - (UniqueKey key, LayerHandle handle) { - if (!_activeAnimations.keys.contains(key)) { - handle.layer = null; - return true; - } - return false; - }, - ); + _clipHandles.removeWhere(( + UniqueKey key, + LayerHandle handle, + ) { + if (!_activeAnimations.keys.contains(key)) { + handle.layer = null; + return true; + } + return false; + }); } @override @@ -157,7 +161,8 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { row = childAfter(row); continue; } - final Rect rowRect = parentData.paintOffset! & + final Rect rowRect = + parentData.paintOffset! & Size(viewportDimension.width, row.size.height); if (rowRect.contains(position)) { result.addWithPaintOffset( @@ -168,9 +173,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { return row!.hitTest(result, position: transformed); }, ); - result.add( - HitTestEntry(_rowMetrics[parentData.vicinity.yIndex]!), - ); + result.add(HitTestEntry(_rowMetrics[parentData.vicinity.yIndex]!)); return true; } row = childAfter(row); @@ -180,12 +183,13 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { @override void dispose() { - _clipHandles.removeWhere( - (UniqueKey key, LayerHandle handle) { - handle.layer = null; - return true; - }, - ); + _clipHandles.removeWhere(( + UniqueKey key, + LayerHandle handle, + ) { + handle.layer = null; + return true; + }); for (final _Span span in _rowMetrics.values) { span.dispose(); } @@ -206,12 +210,15 @@ 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( @@ -243,12 +250,12 @@ 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( @@ -264,7 +271,8 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { _computeAnimationOffsetFor(animationKey, startOfRow); } // We add the offset accounting for the animation value. - totalAnimationOffset += _animationOffsets[animationKey]! * + totalAnimationOffset += + _animationOffsets[animationKey]! * (1 - _activeAnimations[animationKey]!.value); } span.update( @@ -327,14 +335,9 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { ); _verticalOverflows = maxVerticalExtent > 0.0; - final bool acceptedDimension = horizontalOffset.applyContentDimensions( - 0.0, - maxHorizontalExtent, - ) && - verticalOffset.applyContentDimensions( - 0.0, - maxVerticalExtent, - ); + final bool acceptedDimension = + horizontalOffset.applyContentDimensions(0.0, maxHorizontalExtent) && + verticalOffset.applyContentDimensions(0.0, maxVerticalExtent); if (!acceptedDimension) { _updateFirstAndLastVisibleRow(); @@ -447,8 +450,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); @@ -545,13 +548,15 @@ 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(child); + final TwoDimensionalViewportParentData parentData = parentDataOf( + child, + ); // Decoration rects cover the whole row from the left and right // edge of the viewport. return Rect.fromPoints( @@ -584,19 +589,19 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { backgroundRows.forEach((Rect rect, TreeRowDecoration decoration) { final TreeRowDecorationPaintDetails paintingDetails = TreeRowDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: horizontalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: horizontalAxisDirection, + ); decoration.paint(paintingDetails); }); // Child nodes. for (int row = leadingRow; row <= trailingRow; row++) { - final RenderBox child = getChildFor( - TreeVicinity(depth: _rowDepths[row]!, row: row), - )!; - final TwoDimensionalViewportParentData rowParentData = - parentDataOf(child); + final RenderBox child = + getChildFor(TreeVicinity(depth: _rowDepths[row]!, row: row))!; + final TwoDimensionalViewportParentData rowParentData = parentDataOf( + child, + ); if (rowParentData.isVisible) { context.paintChild(child, offset + rowParentData.paintOffset!); } @@ -605,10 +610,10 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { foregroundRows.forEach((Rect rect, TreeRowDecoration decoration) { final TreeRowDecorationPaintDetails paintingDetails = TreeRowDecorationPaintDetails( - canvas: context.canvas, - rect: rect, - axisDirection: horizontalAxisDirection, - ); + canvas: context.canvas, + rect: rect, + axisDirection: horizontalAxisDirection, + ); decoration.paint(paintingDetails); }); } @@ -674,7 +679,8 @@ class _Span {}; for (final Type type in configuration.recognizerFactories.keys) { assert(!newRecognizers.containsKey(type)); - newRecognizers[type] = _recognizers?.remove(type) ?? + newRecognizers[type] = + _recognizers?.remove(type) ?? configuration.recognizerFactories[type]!.constructor(); assert( newRecognizers[type].runtimeType == type, @@ -683,8 +689,9 @@ class _Span 'GestureRecognizerFactory must be specialized with the type of the ' 'class that it returns from its constructor method.', ); - configuration.recognizerFactories[type]! - .initializer(newRecognizers[type]!); + configuration.recognizerFactories[type]!.initializer( + newRecognizers[type]!, + ); } _disposeRecognizers(); // only disposes the ones that where not re-used above. _recognizers = newRecognizers; 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 4f7dd216d27..330dc629a0f 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart @@ -34,9 +34,9 @@ class TreeViewNode { T content, { List>? children, bool expanded = false, - }) : _expanded = children != null && children.isNotEmpty && expanded, - _content = content, - _children = children ?? >[]; + }) : _expanded = children != null && children.isNotEmpty && expanded, + _content = content, + _children = children ?? >[]; /// The subject matter of the node. /// @@ -322,8 +322,10 @@ class TreeView extends StatefulWidget { this.clipBehavior = Clip.hardEdge, this.addAutomaticKeepAlives = true, this.addRepaintBoundaries = true, - }) : assert(verticalDetails.direction == AxisDirection.down && - horizontalDetails.direction == AxisDirection.right); + }) : assert( + verticalDetails.direction == AxisDirection.down && + horizontalDetails.direction == AxisDirection.right, + ); /// The list of [TreeViewNode]s that may be displayed in the [TreeView]. /// @@ -527,15 +529,17 @@ class TreeView extends StatefulWidget { required TreeViewNode node, required Widget child, }) { - return Builder(builder: (BuildContext context) { - return GestureDetector( - behavior: HitTestBehavior.translucent, - onTap: () { - TreeViewController.of(context).toggleNode(node); - }, - child: child, - ); - }); + return Builder( + builder: (BuildContext context) { + return GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: () { + TreeViewController.of(context).toggleNode(node); + }, + child: child, + ); + }, + ); } /// Returns the fixed height, default [TreeRow] for rows in the tree, @@ -543,9 +547,7 @@ class TreeView extends StatefulWidget { /// /// Used by [TreeView.treeRowBuilder]. static TreeRow defaultTreeRowBuilder(TreeViewNode node) { - return const TreeRow( - extent: FixedTreeRowExtent(_kDefaultRowExtent), - ); + return const TreeRow(extent: FixedTreeRowExtent(_kDefaultRowExtent)); } /// Default builder for the widget representing a given [TreeViewNode] in the @@ -570,29 +572,32 @@ class TreeView extends StatefulWidget { final int index = TreeViewController.of(context).getActiveIndexFor(node)!; return Padding( padding: const EdgeInsets.all(8.0), - child: Row(children: [ - // Icon for parent nodes - TreeView.wrapChildToToggleNode( - 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: Row( + children: [ + // Icon for parent nodes + TreeView.wrapChildToToggleNode( + 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, + ), ), - ), - // Spacer - const SizedBox(width: 8.0), - // Content - Text(node.content.toString()), - ]), + // Spacer + const SizedBox(width: 8.0), + // Content + Text(node.content.toString()), + ], + ), ); } @@ -601,11 +606,12 @@ 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 { @@ -898,12 +904,13 @@ class _TreeViewState extends State> final AnimationController controller = _currentAnimationForParent[node]?.controller ?? - AnimationController( - value: node._expanded ? 0.0 : 1.0, - vsync: this, - duration: widget.toggleAnimationStyle?.duration ?? - TreeView.defaultAnimationDuration, - ); + AnimationController( + value: node._expanded ? 0.0 : 1.0, + vsync: this, + duration: + widget.toggleAnimationStyle?.duration ?? + TreeView.defaultAnimationDuration, + ); controller ..addStatusListener((AnimationStatus status) { switch (status) { @@ -939,7 +946,8 @@ class _TreeViewState extends State> final CurvedAnimation newAnimation = CurvedAnimation( parent: controller, - curve: widget.toggleAnimationStyle?.curve ?? + curve: + widget.toggleAnimationStyle?.curve ?? TreeView.defaultAnimationCurve, ); _currentAnimationForParent[node] = ( @@ -980,15 +988,16 @@ class _TreeView extends TwoDimensionalScrollView { required this.indentation, required int rowCount, bool addAutomaticKeepAlives = true, - }) : assert(verticalDetails.direction == AxisDirection.down), - assert(horizontalDetails.direction == AxisDirection.right), - super( - delegate: TreeRowBuilderDelegate( - nodeBuilder: nodeBuilder, - rowBuilder: rowBuilder, - rowCount: rowCount, - addAutomaticKeepAlives: addAutomaticKeepAlives, - )); + }) : assert(verticalDetails.direction == AxisDirection.down), + assert(horizontalDetails.direction == AxisDirection.right), + super( + delegate: TreeRowBuilderDelegate( + nodeBuilder: nodeBuilder, + rowBuilder: rowBuilder, + rowCount: rowCount, + addAutomaticKeepAlives: addAutomaticKeepAlives, + ), + ); final Map activeAnimations; final Map rowDepths; @@ -1032,10 +1041,12 @@ class TreeViewport extends TwoDimensionalViewport { required this.activeAnimations, required this.rowDepths, required this.indentation, - }) : assert(verticalAxisDirection == AxisDirection.down && - horizontalAxisDirection == AxisDirection.right), - // This is fixed as there is currently only one traversal pattern, https://github.com/flutter/flutter/issues/148357 - super(mainAxis: Axis.vertical); + }) : assert( + verticalAxisDirection == AxisDirection.down && + horizontalAxisDirection == AxisDirection.right, + ), + // This is fixed as there is currently only one traversal pattern, https://github.com/flutter/flutter/issues/148357 + super(mainAxis: Axis.vertical); /// The currently active [TreeViewNode] animations. /// diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart index 2c4caea45e3..3f5e473d601 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart @@ -86,11 +86,7 @@ mixin TreeViewStateMixin { /// Provided to [RenderTreeViewport] as part of /// [RenderTreeViewport.activeAnimations] by [TreeView] to properly offset /// animating children. -typedef TreeViewNodesAnimation = ({ - int fromIndex, - int toIndex, - double value, -}); +typedef TreeViewNodesAnimation = ({int fromIndex, int toIndex, double value}); /// The style of indentation for [TreeViewNode]s in a [TreeView], as handled /// by [RenderTreeViewport]. @@ -126,8 +122,9 @@ class TreeViewIndentationType { /// [TreeView.treeNodeBuilder] instead for more customization options. /// /// Child nodes will not be offset in the tree. - static const TreeViewIndentationType none = - TreeViewIndentationType._internal(0.0); + static const TreeViewIndentationType none = TreeViewIndentationType._internal( + 0.0, + ); /// Configures a custom offset for indenting child nodes in a [TreeView]. /// diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart index c96bc789713..da79101c4cb 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart @@ -19,11 +19,12 @@ typedef TreeViewRowBuilder = TreeRow Function(TreeViewNode node); /// /// Used by [TreeView.treeRowBuilder] to build rows on demand for the /// tree. -typedef TreeViewNodeBuilder = Widget Function( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, -); +typedef TreeViewNodeBuilder = + Widget Function( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ); /// The position of a [TreeRow] in a [TreeViewport] in relation /// to other children of the viewport. @@ -35,10 +36,8 @@ typedef TreeViewNodeBuilder = Widget Function( class TreeVicinity extends ChildVicinity { /// Creates a reference to a [TreeRow] in a [TreeView], with the [xIndex] and /// [yIndex] converted to terms of [depth] and [row], respectively. - const TreeVicinity({ - required int depth, - required int row, - }) : super(xIndex: depth, yIndex: row); + const TreeVicinity({required int depth, required int row}) + : super(xIndex: depth, yIndex: row); /// The row index of the [TreeRow] in the [TreeView]. /// @@ -99,15 +98,15 @@ class TreeRowBuilderDelegate extends TwoDimensionalChildBuilderDelegate super.addAutomaticKeepAlives, required TwoDimensionalIndexedWidgetBuilder nodeBuilder, required TreeVicinityToRowBuilder rowBuilder, - }) : assert(rowCount >= 0), - _rowBuilder = rowBuilder, - super( - builder: nodeBuilder, - // No maxXIndex, since we do not know the max depth. - maxYIndex: rowCount - 1, - // repaintBoundaries handled by TreeView - addRepaintBoundaries: false, - ); + }) : assert(rowCount >= 0), + _rowBuilder = rowBuilder, + super( + builder: nodeBuilder, + // No maxXIndex, since we do not know the max depth. + maxYIndex: rowCount - 1, + // repaintBoundaries handled by TreeView + addRepaintBoundaries: false, + ); @override int get rowCount => maxYIndex! + 1; diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_span.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_span.dart index b909279482e..da2bcd8caed 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_span.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_span.dart @@ -85,9 +85,9 @@ class TreeRowBorder extends SpanBorder { /// Creates a [TreeRowBorder] with the provided [BorderSide] applied to all /// sides. const TreeRowBorder.all(BorderSide side) - : left = side, - right = side, - super(leading: side, trailing: side); + : left = side, + right = side, + super(leading: side, trailing: side); /// The border to paint on the top, or leading edge of the [TreeRow]. BorderSide get top => leading; @@ -102,21 +102,14 @@ class TreeRowBorder extends SpanBorder { final BorderSide right; @override - void paint( - SpanDecorationPaintDetails details, - BorderRadius? borderRadius, - ) { + void paint(SpanDecorationPaintDetails details, BorderRadius? borderRadius) { final Border border = Border( top: top, bottom: bottom, left: left, right: right, ); - border.paint( - details.canvas, - details.rect, - borderRadius: borderRadius, - ); + border.paint(details.canvas, details.rect, borderRadius: borderRadius); } } diff --git a/packages/two_dimensional_scrollables/pubspec.yaml b/packages/two_dimensional_scrollables/pubspec.yaml index d116e0faee3..2e83c725bc7 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/two_dimensional_scrollables/test/common/span_test.dart b/packages/two_dimensional_scrollables/test/common/span_test.dart index 147ad2fd958..d89e5cdcac2 100644 --- a/packages/two_dimensional_scrollables/test/common/span_test.dart +++ b/packages/two_dimensional_scrollables/test/common/span_test.dart @@ -145,9 +145,7 @@ void main() { }); test('SpanDecoration', () { - SpanDecoration decoration = const SpanDecoration( - color: Color(0xffff0000), - ); + SpanDecoration decoration = const SpanDecoration(color: Color(0xffff0000)); final TestCanvas canvas = TestCanvas(); const Rect rect = Rect.fromLTWH(0, 0, 10, 10); final SpanDecorationPaintDetails details = SpanDecorationPaintDetails( @@ -160,13 +158,8 @@ void main() { expect(canvas.rect, rect); expect(canvas.paint.color, const Color(0xffff0000)); expect(canvas.paint.isAntiAlias, isFalse); - final TestSpanBorder border = TestSpanBorder( - leading: const BorderSide(), - ); - decoration = SpanDecoration( - border: border, - borderRadius: radius, - ); + final TestSpanBorder border = TestSpanBorder(leading: const BorderSide()); + decoration = SpanDecoration(border: border, borderRadius: radius); decoration.paint(details); expect(border.details, details); expect(border.radius, radius); diff --git a/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart index f68004b8bc7..b7f418b9c94 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart @@ -172,8 +172,9 @@ void main() { expect(cell, isNull); }); - testWidgets('Merge start cannot exceed current index', - (WidgetTester tester) async { + testWidgets('Merge start cannot exceed current index', ( + WidgetTester tester, + ) async { // Merge span start is greater than given index, ex: column 10 has merge // start at 20. final List exceptions = []; @@ -198,13 +199,15 @@ void main() { rowMergeSpan: 2, child: SizedBox.shrink(), ); - await tester.pumpWidget(TableView.builder( - cellBuilder: (_, __) => cell, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 1, - rowCount: 3, - )); + await tester.pumpWidget( + TableView.builder( + cellBuilder: (_, __) => cell, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 1, + rowCount: 3, + ), + ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( @@ -228,13 +231,15 @@ void main() { columnMergeSpan: 2, child: SizedBox.shrink(), ); - await tester.pumpWidget(TableView.builder( - cellBuilder: (_, __) => cell, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 3, - rowCount: 1, - )); + await tester.pumpWidget( + TableView.builder( + cellBuilder: (_, __) => cell, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 3, + rowCount: 1, + ), + ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( @@ -243,8 +248,9 @@ void main() { ); }); - testWidgets('Merge cannot exceed table contents', - (WidgetTester tester) async { + testWidgets('Merge cannot exceed table contents', ( + WidgetTester tester, + ) async { // Merge exceeds table content, ex: at column 10, cell spans 4 columns, // but table only has 12 columns. final List exceptions = []; @@ -258,13 +264,15 @@ void main() { rowMergeSpan: 10, // Exceeds the number of rows child: SizedBox.shrink(), ); - await tester.pumpWidget(TableView.builder( - cellBuilder: (_, __) => cell, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 1, - rowCount: 3, - )); + await tester.pumpWidget( + TableView.builder( + cellBuilder: (_, __) => cell, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 1, + rowCount: 3, + ), + ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( @@ -283,13 +291,15 @@ void main() { columnMergeSpan: 10, // Exceeds the number of columns child: SizedBox.shrink(), ); - await tester.pumpWidget(TableView.builder( - cellBuilder: (_, __) => cell, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 3, - rowCount: 1, - )); + await tester.pumpWidget( + TableView.builder( + cellBuilder: (_, __) => cell, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 3, + rowCount: 1, + ), + ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( @@ -298,8 +308,9 @@ void main() { ); }); - testWidgets('Merge cannot contain pinned and unpinned cells', - (WidgetTester tester) async { + testWidgets('Merge cannot contain pinned and unpinned cells', ( + WidgetTester tester, + ) async { // Merge spans pinned and unpinned cells, ex: column 0 is pinned, 0-2 // expected merge. final List exceptions = []; @@ -313,14 +324,16 @@ void main() { rowMergeSpan: 3, child: SizedBox.shrink(), ); - await tester.pumpWidget(TableView.builder( - cellBuilder: (_, __) => cell, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 1, - rowCount: 3, - pinnedRowCount: 1, - )); + await tester.pumpWidget( + TableView.builder( + cellBuilder: (_, __) => cell, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 1, + rowCount: 3, + pinnedRowCount: 1, + ), + ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( @@ -339,14 +352,16 @@ void main() { columnMergeSpan: 3, child: SizedBox.shrink(), ); - await tester.pumpWidget(TableView.builder( - cellBuilder: (_, __) => cell, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 3, - rowCount: 1, - pinnedColumnCount: 1, - )); + await tester.pumpWidget( + TableView.builder( + cellBuilder: (_, __) => cell, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 3, + rowCount: 1, + pinnedColumnCount: 1, + ), + ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( @@ -384,22 +399,22 @@ void main() { // ... ... ... final Map mergedColumns = { - const TableVicinity(row: 0, column: 1): (1, 2), // M(0, 1) - const TableVicinity(row: 0, column: 2): (1, 2), // M(0, 1) - const TableVicinity(row: 1, column: 1): (1, 2), // M(1, 1) - const TableVicinity(row: 1, column: 2): (1, 2), // M(1, 1) - const TableVicinity(row: 2, column: 1): (1, 2), // M(1, 1) - const TableVicinity(row: 2, column: 2): (1, 2), // M(1, 1) - }; + const TableVicinity(row: 0, column: 1): (1, 2), // M(0, 1) + const TableVicinity(row: 0, column: 2): (1, 2), // M(0, 1) + const TableVicinity(row: 1, column: 1): (1, 2), // M(1, 1) + const TableVicinity(row: 1, column: 2): (1, 2), // M(1, 1) + const TableVicinity(row: 2, column: 1): (1, 2), // M(1, 1) + const TableVicinity(row: 2, column: 2): (1, 2), // M(1, 1) + }; final Map mergedRows = { - TableVicinity.zero: (0, 2), // M(0, 0) - TableVicinity.zero.copyWith(row: 1): (0, 2), // M(0,0) - const TableVicinity(row: 1, column: 1): (1, 2), // M(1, 1) - const TableVicinity(row: 1, column: 2): (1, 2), // M(1, 1) - const TableVicinity(row: 2, column: 1): (1, 2), // M(1, 1) - const TableVicinity(row: 2, column: 2): (1, 2), // M(1, 1) - }; + TableVicinity.zero: (0, 2), // M(0, 0) + TableVicinity.zero.copyWith(row: 1): (0, 2), // M(0,0) + const TableVicinity(row: 1, column: 1): (1, 2), // M(1, 1) + const TableVicinity(row: 1, column: 2): (1, 2), // M(1, 1) + const TableVicinity(row: 2, column: 1): (1, 2), // M(1, 1) + const TableVicinity(row: 2, column: 2): (1, 2), // M(1, 1) + }; TableViewCell cellBuilder(BuildContext context, TableVicinity vicinity) { if (mergedColumns.keys.contains(vicinity) || @@ -436,24 +451,27 @@ void main() { horizontalController.dispose(); }); - testWidgets('vertical main axis and natural scroll directions', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, + testWidgets('vertical main axis and natural scroll directions', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -553,7 +571,9 @@ void main() { ); expect( - tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, -25.0)); + tester.getTopLeft(find.text('M(0,0)')), + const Offset(-30.0, -25.0), + ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], @@ -587,25 +607,28 @@ void main() { expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('vertical main axis, reversed vertical', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, + testWidgets('vertical main axis, reversed vertical', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + reverse: true, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -744,25 +767,28 @@ void main() { expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('vertical main axis, reversed horizontal', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - reverse: true, + testWidgets('vertical main axis, reversed horizontal', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + reverse: true, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -868,10 +894,7 @@ void main() { tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, -25.0), ); - expect( - tester.getSize(find.text('M(0,0)')), - const Size(100.0, 200.0), - ); + expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), @@ -881,10 +904,7 @@ void main() { tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, -25.0), ); - expect( - tester.getSize(find.text('M(0,1)')), - const Size(200.0, 100.0), - ); + expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), @@ -894,10 +914,7 @@ void main() { tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 75.0), ); - expect( - tester.getSize(find.text('M(1,1)')), - const Size(200.0, 200.0), - ); + expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), @@ -910,26 +927,29 @@ void main() { expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('vertical main axis, both axes reversed', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - reverse: true, + testWidgets('vertical main axis, both axes reversed', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + reverse: true, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + reverse: true, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -965,10 +985,7 @@ void main() { tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 400.0), ); - expect( - tester.getSize(find.text('M(0,0)')), - const Size(100.0, 200.0), - ); + expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), @@ -978,10 +995,7 @@ void main() { tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 500.0), ); - expect( - tester.getSize(find.text('M(0,1)')), - const Size(200.0, 100.0), - ); + expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), @@ -991,10 +1005,7 @@ void main() { tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 300.0), ); - expect( - tester.getSize(find.text('M(1,1)')), - const Size(200.0, 200.0), - ); + expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), @@ -1004,10 +1015,7 @@ void main() { tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 300.0), ); - expect( - tester.getSize(find.text('M(2,0)')), - const Size(100.0, 100.0), - ); + expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); @@ -1047,10 +1055,7 @@ void main() { tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, 425.0), ); - expect( - tester.getSize(find.text('M(0,0)')), - const Size(100.0, 200.0), - ); + expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), @@ -1060,10 +1065,7 @@ void main() { tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, 525.0), ); - expect( - tester.getSize(find.text('M(0,1)')), - const Size(200.0, 100.0), - ); + expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), @@ -1073,10 +1075,7 @@ void main() { tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 325.0), ); - expect( - tester.getSize(find.text('M(1,1)')), - const Size(200.0, 200.0), - ); + expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), @@ -1086,31 +1085,31 @@ void main() { tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 325.0), ); - expect( - tester.getSize(find.text('M(2,0)')), - const Size(100.0, 100.0), - ); + expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis and natural scroll directions', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, + testWidgets('horizontal main axis and natural scroll directions', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + mainAxis: Axis.horizontal, + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -1210,7 +1209,9 @@ void main() { ); expect( - tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, -25.0)); + tester.getTopLeft(find.text('M(0,0)')), + const Offset(-30.0, -25.0), + ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], @@ -1244,26 +1245,29 @@ void main() { expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis, reversed vertical', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, + testWidgets('horizontal main axis, reversed vertical', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + mainAxis: Axis.horizontal, + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + reverse: true, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -1366,7 +1370,9 @@ void main() { ); expect( - tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, 425.0)); + tester.getTopLeft(find.text('M(0,0)')), + const Offset(-30.0, 425.0), + ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], @@ -1400,26 +1406,29 @@ void main() { expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis, reversed horizontal', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - reverse: true, + testWidgets('horizontal main axis, reversed horizontal', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + mainAxis: Axis.horizontal, + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + reverse: true, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -1525,10 +1534,7 @@ void main() { tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, -25.0), ); - expect( - tester.getSize(find.text('M(0,0)')), - const Size(100.0, 200.0), - ); + expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), @@ -1538,10 +1544,7 @@ void main() { tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, -25.0), ); - expect( - tester.getSize(find.text('M(0,1)')), - const Size(200.0, 100.0), - ); + expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), @@ -1551,10 +1554,7 @@ void main() { tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 75.0), ); - expect( - tester.getSize(find.text('M(1,1)')), - const Size(200.0, 200.0), - ); + expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), @@ -1567,27 +1567,30 @@ void main() { expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis, both axes reversed', - (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TableView.builder( - mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - reverse: true, + testWidgets('horizontal main axis, both axes reversed', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TableView.builder( + mainAxis: Axis.horizontal, + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + reverse: true, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + reverse: true, + ), + cellBuilder: cellBuilder, + columnBuilder: (_) => span, + rowBuilder: (_) => span, + columnCount: 10, + rowCount: 10, ), - cellBuilder: cellBuilder, - columnBuilder: (_) => span, - rowBuilder: (_) => span, - columnCount: 10, - rowCount: 10, ), - )); + ); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); @@ -1623,10 +1626,7 @@ void main() { tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 400.0), ); - expect( - tester.getSize(find.text('M(0,0)')), - const Size(100.0, 200.0), - ); + expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), @@ -1636,10 +1636,7 @@ void main() { tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 500.0), ); - expect( - tester.getSize(find.text('M(0,1)')), - const Size(200.0, 100.0), - ); + expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), @@ -1649,10 +1646,7 @@ void main() { tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 300.0), ); - expect( - tester.getSize(find.text('M(1,1)')), - const Size(200.0, 200.0), - ); + expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), @@ -1662,10 +1656,7 @@ void main() { tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 300.0), ); - expect( - tester.getSize(find.text('M(2,0)')), - const Size(100.0, 100.0), - ); + expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); @@ -1705,10 +1696,7 @@ void main() { tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, 425.0), ); - expect( - tester.getSize(find.text('M(0,0)')), - const Size(100.0, 200.0), - ); + expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), @@ -1718,10 +1706,7 @@ void main() { tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, 525.0), ); - expect( - tester.getSize(find.text('M(0,1)')), - const Size(200.0, 100.0), - ); + expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), @@ -1731,10 +1716,7 @@ void main() { tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 325.0), ); - expect( - tester.getSize(find.text('M(1,1)')), - const Size(200.0, 200.0), - ); + expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), @@ -1744,10 +1726,7 @@ void main() { tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 325.0), ); - expect( - tester.getSize(find.text('M(2,0)')), - const Size(100.0, 100.0), - ); + expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); }); }); 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 70f2b1a0259..48315eee2d9 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 @@ -328,7 +328,8 @@ void main() { (AssertionError error) => error.toString(), 'description', contains( - 'Each list of Widgets within cells must be of the same length.'), + 'Each list of Widgets within cells must be of the same length.', + ), ), ), ); @@ -383,9 +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,9 +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); @@ -413,12 +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); @@ -430,12 +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); @@ -448,12 +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, ); @@ -470,12 +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 53fe69b816a..101b08c9335 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 @@ -20,7 +20,9 @@ void main() { expect( extent.calculateExtent( const TableSpanExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 150, ); @@ -50,7 +52,9 @@ void main() { expect( extent.calculateExtent( const TableSpanExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 500, ); @@ -80,7 +84,9 @@ void main() { expect( extent.calculateExtent( const TableSpanExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 900, ); @@ -103,7 +109,9 @@ void main() { expect( extent.calculateExtent( const TableSpanExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 1000, ); @@ -123,7 +131,9 @@ void main() { expect( extent.calculateExtent( const TableSpanExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 900, ); @@ -143,7 +153,9 @@ void main() { expect( extent.calculateExtent( const TableSpanExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 100, ); @@ -158,10 +170,10 @@ void main() { const Rect rect = Rect.fromLTWH(0, 0, 10, 10); final TableSpanDecorationPaintDetails details = TableSpanDecorationPaintDetails( - canvas: canvas, - rect: rect, - axisDirection: AxisDirection.down, - ); + canvas: canvas, + rect: rect, + axisDirection: AxisDirection.down, + ); final BorderRadius radius = BorderRadius.circular(10.0); decoration.paint(details); expect(canvas.rect, rect); @@ -170,10 +182,7 @@ void main() { final TestTableSpanBorder border = TestTableSpanBorder( leading: const BorderSide(), ); - decoration = TableSpanDecoration( - border: border, - borderRadius: radius, - ); + decoration = TableSpanDecoration(border: border, borderRadius: radius); decoration.paint(details); expect(border.details, details); expect(border.radius, radius); @@ -206,8 +215,9 @@ void main() { ); } - testWidgets('Vertical main axis, vertical reversed', - (WidgetTester tester) async { + testWidgets('Vertical main axis, vertical reversed', ( + WidgetTester tester, + ) async { final TableView table = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, @@ -222,10 +232,9 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: table, - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: table), + ); await tester.pumpAndSettle(); expect( @@ -312,8 +321,9 @@ void main() { ); }); - testWidgets('Vertical main axis, horizontal reversed', - (WidgetTester tester) async { + testWidgets('Vertical main axis, horizontal reversed', ( + WidgetTester tester, + ) async { final TableView table = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, @@ -328,10 +338,9 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: table, - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: table), + ); await tester.pumpAndSettle(); expect( @@ -418,8 +427,9 @@ void main() { ); }); - testWidgets('Vertical main axis, both reversed', - (WidgetTester tester) async { + testWidgets('Vertical main axis, both reversed', ( + WidgetTester tester, + ) async { final TableView table = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, @@ -435,10 +445,9 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: table, - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: table), + ); await tester.pumpAndSettle(); expect( @@ -525,8 +534,9 @@ void main() { ); }); - testWidgets('Horizontal main axis, vertical reversed', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, vertical reversed', ( + WidgetTester tester, + ) async { final TableView table = TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( @@ -542,10 +552,9 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: table, - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: table), + ); await tester.pumpAndSettle(); expect( @@ -632,8 +641,9 @@ void main() { ); }); - testWidgets('Horizontal main axis, horizontal reversed', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, horizontal reversed', ( + WidgetTester tester, + ) async { final TableView table = TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( @@ -649,10 +659,9 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: table, - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: table), + ); await tester.pumpAndSettle(); expect( @@ -739,8 +748,9 @@ void main() { ); }); - testWidgets('Horizontal main axis, both reversed', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, both reversed', ( + WidgetTester tester, + ) async { final TableView table = TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( @@ -757,10 +767,9 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: table, - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: table), + ); await tester.pumpAndSettle(); expect( @@ -877,22 +886,20 @@ void main() { // +---------+--------+--------+ final Map scenario1MergedRows = { - TableVicinity.zero: (0, 2), - TableVicinity.zero.copyWith(row: 1): (0, 2), - const TableVicinity(row: 1, column: 1): (1, 2), - const TableVicinity(row: 2, column: 1): (1, 2), - const TableVicinity(row: 2, column: 2): (2, 2), - const TableVicinity(row: 3, column: 2): (2, 2), - }; + TableVicinity.zero: (0, 2), + TableVicinity.zero.copyWith(row: 1): (0, 2), + const TableVicinity(row: 1, column: 1): (1, 2), + const TableVicinity(row: 2, column: 1): (1, 2), + const TableVicinity(row: 2, column: 2): (2, 2), + const TableVicinity(row: 3, column: 2): (2, 2), + }; TableView buildScenario1({ bool reverseVertical = false, bool reverseHorizontal = false, }) { return TableView.builder( - verticalDetails: ScrollableDetails.vertical( - reverse: reverseVertical, - ), + verticalDetails: ScrollableDetails.vertical(reverse: reverseVertical), horizontalDetails: ScrollableDetails.horizontal( reverse: reverseHorizontal, ), @@ -941,22 +948,20 @@ void main() { // +--------+--------+--------+--------+ final Map scenario2MergedColumns = { - TableVicinity.zero: (0, 2), - TableVicinity.zero.copyWith(column: 1): (0, 2), - const TableVicinity(row: 1, column: 1): (1, 2), - const TableVicinity(row: 1, column: 2): (1, 2), - const TableVicinity(row: 2, column: 2): (2, 2), - const TableVicinity(row: 2, column: 3): (2, 2), - }; + TableVicinity.zero: (0, 2), + TableVicinity.zero.copyWith(column: 1): (0, 2), + const TableVicinity(row: 1, column: 1): (1, 2), + const TableVicinity(row: 1, column: 2): (1, 2), + const TableVicinity(row: 2, column: 2): (2, 2), + const TableVicinity(row: 2, column: 3): (2, 2), + }; TableView buildScenario2({ bool reverseVertical = false, bool reverseHorizontal = false, }) { return TableView.builder( - verticalDetails: ScrollableDetails.vertical( - reverse: reverseVertical, - ), + verticalDetails: ScrollableDetails.vertical(reverse: reverseVertical), horizontalDetails: ScrollableDetails.horizontal( reverse: reverseHorizontal, ), @@ -1008,26 +1013,26 @@ void main() { // +--------+--------+--------+--------+ final Map scenario3MergedRows = { - TableVicinity.zero: (0, 2), - const TableVicinity(row: 1, column: 0): (0, 2), - const TableVicinity(row: 0, column: 1): (0, 2), - const TableVicinity(row: 1, column: 1): (0, 2), - const TableVicinity(row: 1, column: 2): (1, 2), - const TableVicinity(row: 2, column: 2): (1, 2), - const TableVicinity(row: 1, column: 3): (1, 2), - const TableVicinity(row: 2, column: 3): (1, 2), - }; + TableVicinity.zero: (0, 2), + const TableVicinity(row: 1, column: 0): (0, 2), + const TableVicinity(row: 0, column: 1): (0, 2), + const TableVicinity(row: 1, column: 1): (0, 2), + const TableVicinity(row: 1, column: 2): (1, 2), + const TableVicinity(row: 2, column: 2): (1, 2), + const TableVicinity(row: 1, column: 3): (1, 2), + const TableVicinity(row: 2, column: 3): (1, 2), + }; final Map scenario3MergedColumns = { - TableVicinity.zero: (0, 2), - const TableVicinity(row: 1, column: 0): (0, 2), - const TableVicinity(row: 0, column: 1): (0, 2), - const TableVicinity(row: 1, column: 1): (0, 2), - const TableVicinity(row: 1, column: 2): (2, 2), - const TableVicinity(row: 2, column: 2): (2, 2), - const TableVicinity(row: 1, column: 3): (2, 2), - const TableVicinity(row: 2, column: 3): (2, 2), - }; + TableVicinity.zero: (0, 2), + const TableVicinity(row: 1, column: 0): (0, 2), + const TableVicinity(row: 0, column: 1): (0, 2), + const TableVicinity(row: 1, column: 1): (0, 2), + const TableVicinity(row: 1, column: 2): (2, 2), + const TableVicinity(row: 2, column: 2): (2, 2), + const TableVicinity(row: 1, column: 3): (2, 2), + const TableVicinity(row: 2, column: 3): (2, 2), + }; TableView buildScenario3({ Axis mainAxis = Axis.vertical, @@ -1036,9 +1041,7 @@ void main() { }) { return TableView.builder( mainAxis: mainAxis, - verticalDetails: ScrollableDetails.vertical( - reverse: reverseVertical, - ), + verticalDetails: ScrollableDetails.vertical(reverse: reverseVertical), horizontalDetails: ScrollableDetails.horizontal( reverse: reverseHorizontal, ), @@ -1081,28 +1084,30 @@ void main() { ); } - testWidgets('Vertical main axis, natural scroll directions', - (WidgetTester tester) async { + testWidgets('Vertical main axis, natural scroll directions', ( + WidgetTester tester, + ) async { // Scenario 1 await tester.pumpWidget(buildScenario1()); expect( - find.byType(TableViewport), - paints - // Top row decorations - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), // M(0,0) - color: const Color(0xFF2196F3), - ) - ..rect( - // Rest of the unmerged first row - rect: const Rect.fromLTRB(100.0, 0.0, 300.0, 100.0), - color: const Color(0xFF2196F3), - ) - // Bottom row decoration, does not extend into last column - ..rect( - rect: const Rect.fromLTRB(0.0, 300.0, 200.0, 400.0), - color: const Color(0xff4caf50), - )); + find.byType(TableViewport), + paints + // Top row decorations + ..rect( + rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), // M(0,0) + color: const Color(0xFF2196F3), + ) + ..rect( + // Rest of the unmerged first row + rect: const Rect.fromLTRB(100.0, 0.0, 300.0, 100.0), + color: const Color(0xFF2196F3), + ) + // Bottom row decoration, does not extend into last column + ..rect( + rect: const Rect.fromLTRB(0.0, 300.0, 200.0, 400.0), + color: const Color(0xff4caf50), + ), + ); // Scenario 2 await tester.pumpWidget(buildScenario2()); @@ -1163,8 +1168,9 @@ void main() { ); }); - testWidgets('Vertical main axis, vertical reversed', - (WidgetTester tester) async { + testWidgets('Vertical main axis, vertical reversed', ( + WidgetTester tester, + ) async { // Scenario 1 await tester.pumpWidget(buildScenario1(reverseVertical: true)); expect( @@ -1240,15 +1246,20 @@ void main() { color: const Color(0xff4caf50), ) ..rect( - rect: - const Rect.fromLTRB(300.0, 500.0, 400.0, 600.0), // Last column + rect: const Rect.fromLTRB( + 300.0, + 500.0, + 400.0, + 600.0, + ), // Last column color: const Color(0xff4caf50), ), ); }); - testWidgets('Vertical main axis, horizontal reversed', - (WidgetTester tester) async { + testWidgets('Vertical main axis, horizontal reversed', ( + WidgetTester tester, + ) async { // Scenario 1 await tester.pumpWidget(buildScenario1(reverseHorizontal: true)); expect( @@ -1330,13 +1341,13 @@ void main() { ); }); - testWidgets('Vertical main axis, both reversed', - (WidgetTester tester) async { + testWidgets('Vertical main axis, both reversed', ( + WidgetTester tester, + ) async { // Scenario 1 - await tester.pumpWidget(buildScenario1( - reverseHorizontal: true, - reverseVertical: true, - )); + await tester.pumpWidget( + buildScenario1(reverseHorizontal: true, reverseVertical: true), + ); expect( find.byType(TableViewport), paints @@ -1358,10 +1369,9 @@ void main() { ); // Scenario 2 - await tester.pumpWidget(buildScenario2( - reverseHorizontal: true, - reverseVertical: true, - )); + await tester.pumpWidget( + buildScenario2(reverseHorizontal: true, reverseVertical: true), + ); expect( find.byType(TableViewport), paints @@ -1388,10 +1398,9 @@ void main() { ); // Scenario 3 - await tester.pumpWidget(buildScenario3( - reverseHorizontal: true, - reverseVertical: true, - )); + await tester.pumpWidget( + buildScenario3(reverseHorizontal: true, reverseVertical: true), + ); expect( find.byType(TableViewport), paints @@ -1423,8 +1432,9 @@ void main() { ); }); - testWidgets('Horizontal main axis, natural scroll directions', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, natural scroll directions', ( + WidgetTester tester, + ) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. @@ -1460,16 +1470,16 @@ void main() { ); }); - testWidgets('Horizontal main axis, vertical reversed', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, vertical reversed', ( + WidgetTester tester, + ) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 - await tester.pumpWidget(buildScenario3( - reverseVertical: true, - mainAxis: Axis.horizontal, - )); + await tester.pumpWidget( + buildScenario3(reverseVertical: true, mainAxis: Axis.horizontal), + ); expect( find.byType(TableViewport), paints @@ -1501,16 +1511,16 @@ void main() { ); }); - testWidgets('Horizontal main axis, horizontal reversed', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, horizontal reversed', ( + WidgetTester tester, + ) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 - await tester.pumpWidget(buildScenario3( - reverseHorizontal: true, - mainAxis: Axis.horizontal, - )); + await tester.pumpWidget( + buildScenario3(reverseHorizontal: true, mainAxis: Axis.horizontal), + ); expect( find.byType(TableViewport), paints @@ -1541,17 +1551,20 @@ void main() { ); }); - testWidgets('Horizontal main axis, both reversed', - (WidgetTester tester) async { + testWidgets('Horizontal main axis, both reversed', ( + WidgetTester tester, + ) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 - await tester.pumpWidget(buildScenario3( - reverseHorizontal: true, - reverseVertical: true, - mainAxis: Axis.horizontal, - )); + await tester.pumpWidget( + buildScenario3( + reverseHorizontal: true, + reverseVertical: true, + mainAxis: Axis.horizontal, + ), + ); expect( find.byType(TableViewport), paints @@ -1566,8 +1579,12 @@ void main() { color: const Color(0xff4caf50), ) ..rect( - rect: - const Rect.fromLTRB(400.0, 500.0, 500.0, 600.0), // Last column + rect: const Rect.fromLTRB( + 400.0, + 500.0, + 500.0, + 600.0, + ), // Last column color: const Color(0xff4caf50), ) // Row decorations @@ -1584,8 +1601,9 @@ void main() { }); }); - testWidgets('merged cells account for row/column padding', - (WidgetTester tester) async { + testWidgets('merged cells account for row/column padding', ( + WidgetTester tester, + ) async { // Leading padding on the leading cell, and trailing padding on the // trailing cell should be excluded. Interim leading/trailing // paddings are consumed by the merged cell. @@ -1610,8 +1628,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), @@ -1639,9 +1657,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 cc1f28750b8..da5c55fd713 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_test.dart @@ -19,9 +19,9 @@ TableSpan getTappableSpan(int index, VoidCallback callback) { recognizerFactories: { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () => callback(), - ), + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () => callback(), + ), }, ); } @@ -57,13 +57,7 @@ void main() { expect(delegate.columnCount, 3); expect(delegate.buildColumn(0), span); expect(delegate.buildRow(0), span); - expect( - delegate.builder( - _NullBuildContext(), - TableVicinity.zero, - ), - cell, - ); + expect(delegate.builder(_NullBuildContext(), TableVicinity.zero), cell); }); test('asserts correct counts', () { @@ -220,7 +214,8 @@ void main() { rowCount: rowCount, pinnedRowCount: pinnedRowCount, rowBuilder: rowBuilder ?? (_) => largeSpan, - cellBuilder: cellBuilder ?? + cellBuilder: + cellBuilder ?? (_, TableVicinity vicinity) { return TableViewCell( child: Text('R${vicinity.row}:C${vicinity.column}'), @@ -229,12 +224,13 @@ void main() { ); } - testWidgets('infinite rows, columns are finite', - (WidgetTester tester) async { + testWidgets('infinite rows, columns are finite', ( + WidgetTester tester, + ) async { // Nothing pinned --- - await tester.pumpWidget(MaterialApp( - home: getTableView(columnCount: 10), - )); + await tester.pumpWidget( + MaterialApp(home: getTableView(columnCount: 10)), + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -276,12 +272,11 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - pinnedColumnCount: 1, + await tester.pumpWidget( + MaterialApp( + home: getTableView(columnCount: 10, pinnedColumnCount: 1), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -323,12 +318,9 @@ void main() { await tester.pumpWidget(Container()); // Pinned rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - pinnedRowCount: 1, - ), - )); + await tester.pumpWidget( + MaterialApp(home: getTableView(columnCount: 10, pinnedRowCount: 1)), + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -372,13 +364,15 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns and rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - pinnedColumnCount: 1, - pinnedRowCount: 1, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + pinnedColumnCount: 1, + pinnedRowCount: 1, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -420,12 +414,11 @@ void main() { expect(find.text('R10:C0'), findsNothing); }); - testWidgets('infinite columns, rows are finite', - (WidgetTester tester) async { + testWidgets('infinite columns, rows are finite', ( + WidgetTester tester, + ) async { // Nothing pinned --- - await tester.pumpWidget(MaterialApp( - home: getTableView(rowCount: 10), - )); + await tester.pumpWidget(MaterialApp(home: getTableView(rowCount: 10))); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -470,9 +463,9 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget(MaterialApp( - home: getTableView(rowCount: 10, pinnedColumnCount: 1), - )); + await tester.pumpWidget( + MaterialApp(home: getTableView(rowCount: 10, pinnedColumnCount: 1)), + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -517,9 +510,9 @@ void main() { await tester.pumpWidget(Container()); // Pinned rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView(rowCount: 10, pinnedRowCount: 1), - )); + await tester.pumpWidget( + MaterialApp(home: getTableView(rowCount: 10, pinnedRowCount: 1)), + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -564,13 +557,15 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns and rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - pinnedRowCount: 1, - pinnedColumnCount: 1, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + pinnedRowCount: 1, + pinnedColumnCount: 1, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -615,9 +610,7 @@ void main() { testWidgets('infinite rows & columns', (WidgetTester tester) async { // No pinned --- - await tester.pumpWidget(MaterialApp( - home: getTableView(), - )); + await tester.pumpWidget(MaterialApp(home: getTableView())); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -671,9 +664,9 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget(MaterialApp( - home: getTableView(pinnedColumnCount: 1), - )); + await tester.pumpWidget( + MaterialApp(home: getTableView(pinnedColumnCount: 1)), + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -729,9 +722,9 @@ void main() { await tester.pumpWidget(Container()); // Pinned Rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView(pinnedRowCount: 1), - )); + await tester.pumpWidget( + MaterialApp(home: getTableView(pinnedRowCount: 1)), + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -787,12 +780,11 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns and rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - pinnedRowCount: 1, - pinnedColumnCount: 1, + await tester.pumpWidget( + MaterialApp( + home: getTableView(pinnedRowCount: 1, pinnedColumnCount: 1), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -842,25 +834,28 @@ void main() { expect(find.text('R10:C6'), findsNothing); }); - testWidgets('infinite rows can null terminate', - (WidgetTester tester) async { + testWidgets('infinite rows can null terminate', ( + WidgetTester tester, + ) async { // Nothing pinned --- bool calledOutOfBounds = false; - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - if (index > 8) { - calledOutOfBounds = true; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + if (index > 8) { + calledOutOfBounds = true; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -909,19 +904,21 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - pinnedColumnCount: 1, - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + pinnedColumnCount: 1, + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -968,19 +965,21 @@ void main() { await tester.pumpWidget(Container()); // Pinned rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - pinnedRowCount: 1, - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + pinnedRowCount: 1, + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1029,20 +1028,22 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns and rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - pinnedColumnCount: 1, - pinnedRowCount: 1, - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + pinnedColumnCount: 1, + pinnedRowCount: 1, + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1089,20 +1090,23 @@ void main() { expect(find.text('R8:C0'), findsNothing); }); - testWidgets('Null terminated rows will update', - (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, + testWidgets('Null terminated rows will update', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); // Change the vertical scroll offset, validate more rows were populated. // This exceeds the bounds of the scroll view once the rows have been @@ -1131,18 +1135,20 @@ void main() { expect(find.text('R8:C0'), findsNothing); // Increase the number of rows - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - rowBuilder: (int index) { - // There will only be 16 rows. - if (index == 16) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + rowBuilder: (int index) { + // There will only be 16 rows. + if (index == 16) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); // The position should not have changed. @@ -1179,18 +1185,20 @@ void main() { expect(horizontalController.position.maxScrollExtent, 1200.0); // Decrease the number of rows - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnCount: 10, - rowBuilder: (int index) { - // There will only be 5 rows. - if (index == 5) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnCount: 10, + rowBuilder: (int index) { + // There will only be 5 rows. + if (index == 5) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); // The position should have changed. @@ -1214,20 +1222,23 @@ void main() { expect(find.text('R5:C0'), findsNothing); }); - testWidgets('Null terminated columns will update', - (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - columnBuilder: (int index) { - // There will only be 8 columns. - if (index == 8) { - return null; - } - return largeSpan; - }, + testWidgets('Null terminated columns will update', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + columnBuilder: (int index) { + // There will only be 8 columns. + if (index == 8) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); // Change the horizontal scroll offset, validate more columns were // populated. This exceeds the bounds of the scroll view once the @@ -1263,18 +1274,20 @@ void main() { expect(find.text('R4:C5'), findsOneWidget); // trailing // Increase the number of rows - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - columnBuilder: (int index) { - // There will only be 16 column. - if (index == 16) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + columnBuilder: (int index) { + // There will only be 16 column. + if (index == 16) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); // The position should not have changed. @@ -1317,18 +1330,20 @@ void main() { expect(horizontalController.position.maxScrollExtent, 2400.0); // Decrease the number of columns - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - columnBuilder: (int index) { - // There will only be 5 columns. - if (index == 5) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + columnBuilder: (int index) { + // There will only be 5 columns. + if (index == 5) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); // The position should have changed. @@ -1352,25 +1367,28 @@ void main() { expect(find.text('R0:C5'), findsNothing); }); - testWidgets('infinite columns can null terminate', - (WidgetTester tester) async { + testWidgets('infinite columns can null terminate', ( + WidgetTester tester, + ) async { // Nothing pinned --- bool calledOutOfBounds = false; - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - if (index > 10) { - calledOutOfBounds = true; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + if (index > 10) { + calledOutOfBounds = true; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1426,19 +1444,21 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - pinnedColumnCount: 1, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + pinnedColumnCount: 1, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1487,19 +1507,21 @@ void main() { await tester.pumpWidget(Container()); // Pinned rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - pinnedRowCount: 1, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + pinnedRowCount: 1, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1553,20 +1575,22 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns and rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowCount: 10, - pinnedRowCount: 1, - pinnedColumnCount: 1, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowCount: 10, + pinnedRowCount: 1, + pinnedColumnCount: 1, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1612,35 +1636,38 @@ void main() { expect(find.text('R0:C4'), findsNothing); expect(find.text('R0:C10'), findsNothing); }); - testWidgets('infinite rows & columns can null terminate', - (WidgetTester tester) async { + testWidgets('infinite rows & columns can null terminate', ( + WidgetTester tester, + ) async { // Nothing pinned --- bool calledRowOutOfBounds = false; bool calledColumnOutOfBounds = false; - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - if (index > 8) { - calledRowOutOfBounds = true; - } - return largeSpan; - }, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - if (index > 10) { - calledColumnOutOfBounds = true; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + if (index > 8) { + calledRowOutOfBounds = true; + } + return largeSpan; + }, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + if (index > 10) { + calledColumnOutOfBounds = true; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1703,25 +1730,27 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, - pinnedColumnCount: 1, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + pinnedColumnCount: 1, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1781,25 +1810,27 @@ void main() { await tester.pumpWidget(Container()); // Pinned rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, - pinnedRowCount: 1, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + pinnedRowCount: 1, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1861,26 +1892,28 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns and rows --- - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowBuilder: (int index) { - // There will only be 8 rows. - if (index == 8) { - return null; - } - return largeSpan; - }, - pinnedRowCount: 1, - pinnedColumnCount: 1, - columnBuilder: (int index) { - // There will only be 10 columns. - if (index == 10) { - return null; - } - return largeSpan; - }, + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowBuilder: (int index) { + // There will only be 8 rows. + if (index == 8) { + return null; + } + return largeSpan; + }, + pinnedRowCount: 1, + pinnedColumnCount: 1, + columnBuilder: (int index) { + // There will only be 10 columns. + if (index == 10) { + return null; + } + return largeSpan; + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1935,8 +1968,9 @@ void main() { expect(find.text('R3:C6'), findsNothing); expect(find.text('R8:C6'), findsNothing); }); - testWidgets('merged cells work with lazy layout computation', - (WidgetTester tester) async { + testWidgets('merged cells work with lazy layout computation', ( + WidgetTester tester, + ) async { // When columns and rows are finite, the layout is eagerly computed and // the children are lazily laid out. This makes computing merged cell // layouts easy. In an infinite world, the layout is also lazily @@ -1953,32 +1987,34 @@ void main() { 10, (int index) => index + 1, ); - await tester.pumpWidget(MaterialApp( - home: getTableView( - cellBuilder: (_, TableVicinity vicinity) { - // Merged row - if (mergedRows.contains(vicinity.row) && vicinity.column == 0) { - return TableViewCell( - rowMergeStart: rowConfig.start, - rowMergeSpan: rowConfig.span, - child: const Text('R0:C0'), - ); - } - // Merged column - if (mergedColumns.contains(vicinity.column) && - vicinity.row == 0) { + await tester.pumpWidget( + MaterialApp( + home: getTableView( + cellBuilder: (_, TableVicinity vicinity) { + // Merged row + if (mergedRows.contains(vicinity.row) && vicinity.column == 0) { + return TableViewCell( + rowMergeStart: rowConfig.start, + rowMergeSpan: rowConfig.span, + child: const Text('R0:C0'), + ); + } + // Merged column + if (mergedColumns.contains(vicinity.column) && + vicinity.row == 0) { + return TableViewCell( + columnMergeStart: columnConfig.start, + columnMergeSpan: columnConfig.span, + child: const Text('R0:C1'), + ); + } return TableViewCell( - columnMergeStart: columnConfig.start, - columnMergeSpan: columnConfig.span, - child: const Text('R0:C1'), + child: Text('R${vicinity.row}:C${vicinity.column}'), ); - } - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); - }, + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -2001,8 +2037,9 @@ void main() { ); }); - testWidgets('merged column that exceeds metrics will assert', - (WidgetTester tester) async { + testWidgets('merged column that exceeds metrics will assert', ( + WidgetTester tester, + ) async { final List exceptions = []; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { @@ -2013,31 +2050,33 @@ void main() { 10, (int index) => index + 1, ); - await tester.pumpWidget(MaterialApp( - home: getTableView( - columnBuilder: (int index) { - // There will only be 8 columns, but the merge is set up for 10. - if (index == 8) { - return null; - } - return largeSpan; - }, - cellBuilder: (_, TableVicinity vicinity) { - // Merged column - if (mergedColumns.contains(vicinity.column) && - vicinity.row == 0) { + await tester.pumpWidget( + MaterialApp( + home: getTableView( + columnBuilder: (int index) { + // There will only be 8 columns, but the merge is set up for 10. + if (index == 8) { + return null; + } + return largeSpan; + }, + cellBuilder: (_, TableVicinity vicinity) { + // Merged column + if (mergedColumns.contains(vicinity.column) && + vicinity.row == 0) { + return TableViewCell( + columnMergeStart: columnConfig.start, + columnMergeSpan: columnConfig.span, + child: const Text('R0:C1'), + ); + } return TableViewCell( - columnMergeStart: columnConfig.start, - columnMergeSpan: columnConfig.span, - child: const Text('R0:C1'), + child: Text('R${vicinity.row}:C${vicinity.column}'), ); - } - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); - }, + }, + ), ), - )); + ); await tester.pumpWidget(Container()); FlutterError.onError = oldHandler; expect(exceptions.length, 3); @@ -2052,8 +2091,9 @@ void main() { ); }); - testWidgets('merged row that exceeds metrics will assert', - (WidgetTester tester) async { + testWidgets('merged row that exceeds metrics will assert', ( + WidgetTester tester, + ) async { final List exceptions = []; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { @@ -2064,30 +2104,32 @@ void main() { 10, (int index) => index, ); - await tester.pumpWidget(MaterialApp( - home: getTableView( - rowBuilder: (int index) { - // There will only be 8 rows, but the merge is set up for 9. - if (index == 8) { - return null; - } - return largeSpan; - }, - cellBuilder: (_, TableVicinity vicinity) { - // Merged column - if (mergedRows.contains(vicinity.row) && vicinity.column == 0) { + await tester.pumpWidget( + MaterialApp( + home: getTableView( + rowBuilder: (int index) { + // There will only be 8 rows, but the merge is set up for 9. + if (index == 8) { + return null; + } + return largeSpan; + }, + cellBuilder: (_, TableVicinity vicinity) { + // Merged column + if (mergedRows.contains(vicinity.row) && vicinity.column == 0) { + return TableViewCell( + rowMergeStart: rowConfig.start, + rowMergeSpan: rowConfig.span, + child: const Text('R0:C0'), + ); + } return TableViewCell( - rowMergeStart: rowConfig.start, - rowMergeSpan: rowConfig.span, - child: const Text('R0:C0'), + child: Text('R${vicinity.row}:C${vicinity.column}'), ); - } - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); - }, + }, + ), ), - )); + ); await tester.pumpWidget(Container()); FlutterError.onError = oldHandler; expect(exceptions.length, 3); @@ -2111,7 +2153,7 @@ void main() { columnBuilder: (_) => span, cells: const >[ [cell, cell, cell], - [cell, cell, cell] + [cell, cell, cell], ], ); final TableCellListDelegate delegate = @@ -2131,7 +2173,7 @@ void main() { () { tableView = TableView.list( cells: const >[ - [cell] + [cell], ], columnBuilder: (_) => span, rowBuilder: (_) => span, @@ -2150,7 +2192,7 @@ void main() { () { tableView = TableView.list( cells: const >[ - [cell] + [cell], ], columnBuilder: (_) => span, rowBuilder: (_) => span, @@ -2170,8 +2212,9 @@ void main() { }); group('RenderTableViewport', () { - testWidgets('parent data and table vicinities', - (WidgetTester tester) async { + testWidgets('parent data and table vicinities', ( + WidgetTester tester, + ) async { final Map childKeys = {}; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(200)); @@ -2183,10 +2226,7 @@ void main() { cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return TableViewCell( - child: SizedBox.square( - key: childKeys[vicinity], - dimension: 200, - ), + child: SizedBox.square(key: childKeys[vicinity], dimension: 200), ); }, ); @@ -2203,26 +2243,19 @@ void main() { expect(viewport.mainAxis, Axis.vertical); // first child TableVicinity vicinity = TableVicinity.zero; - TableViewParentData parentData = parentDataOf( - viewport.firstChild!, - ); + TableViewParentData parentData = parentDataOf(viewport.firstChild!); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, Offset.zero); expect(parentData.isVisible, isTrue); // after first child vicinity = const TableVicinity(column: 1, row: 0); - parentData = parentDataOf( - viewport.childAfter(viewport.firstChild!)!, - ); + parentData = parentDataOf(viewport.childAfter(viewport.firstChild!)!); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, const Offset(200, 0.0)); expect(parentData.isVisible, isTrue); // before first child (none) - expect( - viewport.childBefore(viewport.firstChild!), - isNull, - ); + expect(viewport.childBefore(viewport.firstChild!), isNull); // last child vicinity = const TableVicinity(column: 4, row: 4); @@ -2231,15 +2264,10 @@ void main() { expect(parentData.layoutOffset, const Offset(800.0, 800.0)); expect(parentData.isVisible, isFalse); // after last child (none) - expect( - viewport.childAfter(viewport.lastChild!), - isNull, - ); + expect(viewport.childAfter(viewport.lastChild!), isNull); // before last child vicinity = const TableVicinity(column: 3, row: 4); - parentData = parentDataOf( - viewport.childBefore(viewport.lastChild!)!, - ); + parentData = parentDataOf(viewport.childBefore(viewport.lastChild!)!); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, const Offset(600.0, 800.0)); expect(parentData.isVisible, isFalse); @@ -2250,17 +2278,11 @@ void main() { {}; const TableSpan columnSpan = TableSpan( extent: FixedTableSpanExtent(200), - padding: TableSpanPadding( - leading: 10.0, - trailing: 20.0, - ), + padding: TableSpanPadding(leading: 10.0, trailing: 20.0), ); const TableSpan rowSpan = TableSpan( extent: FixedTableSpanExtent(200), - padding: TableSpanPadding( - leading: 30.0, - trailing: 40.0, - ), + padding: TableSpanPadding(leading: 30.0, trailing: 40.0), ); TableView tableView = TableView.builder( rowCount: 2, @@ -2270,10 +2292,7 @@ void main() { cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return TableViewCell( - child: SizedBox.square( - key: childKeys[vicinity], - dimension: 200, - ), + child: SizedBox.square(key: childKeys[vicinity], dimension: 200), ); }, ); @@ -2289,9 +2308,7 @@ void main() { ); // first child TableVicinity vicinity = TableVicinity.zero; - TableViewParentData parentData = parentDataOf( - viewport.firstChild!, - ); + TableViewParentData parentData = parentDataOf(viewport.firstChild!); expect(parentData.vicinity, vicinity); expect( parentData.layoutOffset, @@ -2303,9 +2320,7 @@ void main() { // after first child vicinity = const TableVicinity(column: 1, row: 0); - parentData = parentDataOf( - viewport.childAfter(viewport.firstChild!)!, - ); + parentData = parentDataOf(viewport.childAfter(viewport.firstChild!)!); expect(parentData.vicinity, vicinity); expect( parentData.layoutOffset, @@ -2338,34 +2353,24 @@ void main() { cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return TableViewCell( - child: SizedBox.square( - key: childKeys[vicinity], - dimension: 200, - ), + child: SizedBox.square(key: childKeys[vicinity], dimension: 200), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); - viewport = getViewport( - tester, - childKeys.values.first, - ); + viewport = getViewport(tester, childKeys.values.first); // first child vicinity = TableVicinity.zero; - parentData = parentDataOf( - viewport.firstChild!, - ); + parentData = parentDataOf(viewport.firstChild!); expect(parentData.vicinity, vicinity); // layoutOffset is later corrected for reverse in the paintOffset expect(parentData.paintOffset, const Offset(590.0, 370.0)); // after first child vicinity = const TableVicinity(column: 1, row: 0); - parentData = parentDataOf( - viewport.childAfter(viewport.firstChild!)!, - ); + parentData = parentDataOf(viewport.childAfter(viewport.firstChild!)!); expect(parentData.vicinity, vicinity); expect(parentData.paintOffset, const Offset(360.0, 370.0)); @@ -2383,12 +2388,11 @@ 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( @@ -2429,12 +2433,11 @@ 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( @@ -2475,18 +2478,16 @@ 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( @@ -2534,18 +2535,16 @@ 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( @@ -2570,8 +2569,9 @@ void main() { expect(rowTapCounter, 0); }); - testWidgets('provides correct details in TableSpanExtentDelegate', - (WidgetTester tester) async { + testWidgets('provides correct details in TableSpanExtentDelegate', ( + WidgetTester tester, + ) async { final TestTableSpanExtent columnExtent = TestTableSpanExtent(); final TestTableSpanExtent rowExtent = TestTableSpanExtent(); final ScrollController verticalController = ScrollController(); @@ -2582,9 +2582,7 @@ void main() { columnBuilder: (_) => TableSpan(extent: columnExtent), rowBuilder: (_) => TableSpan(extent: rowExtent), cellBuilder: (_, TableVicinity vicinity) { - return const TableViewCell( - child: SizedBox.square(dimension: 100), - ); + return const TableViewCell(child: SizedBox.square(dimension: 100)); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, @@ -2625,18 +2623,20 @@ void main() { expect(rowExtent.delegate.viewportExtent, 600.0); }); - testWidgets('First row/column layout based on padding', - (WidgetTester tester) async { + testWidgets('First row/column layout based on padding', ( + WidgetTester tester, + ) async { // Huge padding, first span layout // Column-wise 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,10 +2666,11 @@ 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( @@ -2695,16 +2696,16 @@ void main() { expect(find.text('Row: 2 Column: 1'), findsNothing); }); - testWidgets('lazy layout accounts for gradually accrued padding', - (WidgetTester tester) async { + testWidgets('lazy layout accounts for gradually accrued padding', ( + WidgetTester tester, + ) async { // Check with gradually accrued paddings // Column-wise 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( @@ -2731,10 +2732,11 @@ 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( @@ -2762,9 +2764,7 @@ void main() { tableView = TableView.builder( rowCount: 50, columnCount: 50, - rowBuilder: (_) => const TableSpan( - extent: FixedTableSpanExtent(200), - ), + rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(200)), columnBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -2790,10 +2790,11 @@ 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( @@ -3209,49 +3210,46 @@ void main() { expect(cellNeedsPaint('Row: 6 Column: 8'), isTrue); // also in cacheExtent }); - testWidgets('paints decorations in correct order', - (WidgetTester tester) async { + testWidgets('paints decorations in correct order', ( + WidgetTester tester, + ) async { 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, + 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), ), ), - ), - 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, + 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( - color: index.isOdd ? Colors.blue : null, - borderRadius: BorderRadius.circular(30.0), - consumeSpanPadding: false, - ), - ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( @@ -3383,34 +3381,30 @@ 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, + 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, ), ), - ), - 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, + 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.isOdd ? Colors.blue : null, - ), - ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( @@ -3496,8 +3490,9 @@ void main() { ); }); - testWidgets('child paint rects are correct when reversed and pinned', - (WidgetTester tester) async { + testWidgets('child paint rects are correct when reversed and pinned', ( + WidgetTester tester, + ) async { // Both reversed - Regression test for https://github.com/flutter/flutter/issues/135386 TableView tableView = TableView.builder( verticalDetails: const ScrollableDetails.vertical(reverse: true), @@ -3506,12 +3501,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( @@ -3554,12 +3547,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( @@ -3602,13 +3593,15 @@ 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( @@ -3658,29 +3651,29 @@ void main() { // variety of combinations. final Map bothMerged = { - TableVicinity.zero: (start: 0, span: 2), - const TableVicinity(row: 1, column: 0): (start: 0, span: 2), - const TableVicinity(row: 0, column: 1): (start: 0, span: 2), - const TableVicinity(row: 1, column: 1): (start: 0, span: 2), - }; + TableVicinity.zero: (start: 0, span: 2), + const TableVicinity(row: 1, column: 0): (start: 0, span: 2), + const TableVicinity(row: 0, column: 1): (start: 0, span: 2), + const TableVicinity(row: 1, column: 1): (start: 0, span: 2), + }; final Map rowMerged = { - const TableVicinity(row: 2, column: 0): (start: 2, span: 2), - const TableVicinity(row: 3, column: 0): (start: 2, span: 2), - const TableVicinity(row: 4, column: 1): (start: 4, span: 3), - const TableVicinity(row: 5, column: 1): (start: 4, span: 3), - const TableVicinity(row: 6, column: 1): (start: 4, span: 3), - }; + const TableVicinity(row: 2, column: 0): (start: 2, span: 2), + const TableVicinity(row: 3, column: 0): (start: 2, span: 2), + const TableVicinity(row: 4, column: 1): (start: 4, span: 3), + const TableVicinity(row: 5, column: 1): (start: 4, span: 3), + const TableVicinity(row: 6, column: 1): (start: 4, span: 3), + }; final Map columnMerged = { - const TableVicinity(row: 0, column: 2): (start: 2, span: 2), - const TableVicinity(row: 0, column: 3): (start: 2, span: 2), - const TableVicinity(row: 1, column: 4): (start: 4, span: 3), - const TableVicinity(row: 1, column: 5): (start: 4, span: 3), - const TableVicinity(row: 1, column: 6): (start: 4, span: 3), - }; + const TableVicinity(row: 0, column: 2): (start: 2, span: 2), + const TableVicinity(row: 0, column: 3): (start: 2, span: 2), + const TableVicinity(row: 1, column: 4): (start: 4, span: 3), + const TableVicinity(row: 1, column: 5): (start: 4, span: 3), + const TableVicinity(row: 1, column: 6): (start: 4, span: 3), + }; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(75)); testWidgets('Normal axes', (WidgetTester tester) async { @@ -4130,72 +4123,74 @@ void main() { }); testWidgets( - 'Merged unpinned cells following pinned cells are laid out correctly', - (WidgetTester tester) async { - final ScrollController verticalController = ScrollController(); - final ScrollController horizontalController = ScrollController(); - final Set mergedCell = { - const TableVicinity(row: 2, column: 2), - const TableVicinity(row: 3, column: 2), - const TableVicinity(row: 2, column: 3), - const TableVicinity(row: 3, column: 3), - }; - final TableView tableView = TableView.builder( - columnCount: 10, - rowCount: 10, - columnBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), - cellBuilder: (BuildContext context, TableVicinity vicinity) { - if (mergedCell.contains(vicinity)) { - return const TableViewCell( - rowMergeStart: 2, - rowMergeSpan: 2, - columnMergeStart: 2, - columnMergeSpan: 2, - child: Text('Tile c: 2, r: 2'), + 'Merged unpinned cells following pinned cells are laid out correctly', + (WidgetTester tester) async { + final ScrollController verticalController = ScrollController(); + final ScrollController horizontalController = ScrollController(); + final Set mergedCell = { + const TableVicinity(row: 2, column: 2), + const TableVicinity(row: 3, column: 2), + const TableVicinity(row: 2, column: 3), + const TableVicinity(row: 3, column: 3), + }; + final TableView tableView = TableView.builder( + columnCount: 10, + rowCount: 10, + columnBuilder: + (_) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), + cellBuilder: (BuildContext context, TableVicinity vicinity) { + if (mergedCell.contains(vicinity)) { + return const TableViewCell( + rowMergeStart: 2, + rowMergeSpan: 2, + columnMergeStart: 2, + columnMergeSpan: 2, + child: Text('Tile c: 2, r: 2'), + ); + } + return TableViewCell( + child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}'), ); - } - return TableViewCell( - child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}'), - ); - }, - pinnedRowCount: 1, - pinnedColumnCount: 1, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), - ); - await tester.pumpWidget(MaterialApp(home: tableView)); - await tester.pumpAndSettle(); - - expect(verticalController.position.pixels, 0.0); - expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('Tile c: 2, r: 2')), - const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), - ); - - verticalController.jumpTo(10.0); - await tester.pumpAndSettle(); - expect(verticalController.position.pixels, 10.0); - expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('Tile c: 2, r: 2')), - const Rect.fromLTWH(200.0, 190.0, 200.0, 200.0), - ); - - horizontalController.jumpTo(10.0); - await tester.pumpAndSettle(); - expect(verticalController.position.pixels, 10.0); - expect(horizontalController.position.pixels, 10.0); - expect( - tester.getRect(find.text('Tile c: 2, r: 2')), - const Rect.fromLTWH(190.0, 190.0, 200.0, 200.0), - ); - }); + }, + pinnedRowCount: 1, + pinnedColumnCount: 1, + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: horizontalController, + ), + ); + await tester.pumpWidget(MaterialApp(home: tableView)); + await tester.pumpAndSettle(); + + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect( + tester.getRect(find.text('Tile c: 2, r: 2')), + const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), + ); + + verticalController.jumpTo(10.0); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 10.0); + expect(horizontalController.position.pixels, 0.0); + expect( + tester.getRect(find.text('Tile c: 2, r: 2')), + const Rect.fromLTWH(200.0, 190.0, 200.0, 200.0), + ); + + horizontalController.jumpTo(10.0); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 10.0); + expect(horizontalController.position.pixels, 10.0); + expect( + tester.getRect(find.text('Tile c: 2, r: 2')), + const Rect.fromLTWH(190.0, 190.0, 200.0, 200.0), + ); + }, + ); } class _NullBuildContext implements BuildContext, TwoDimensionalChildManager { 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 5ffd419bf7f..ed3e80a9457 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 @@ -17,9 +17,9 @@ TreeRow getTappableRow(TreeViewNode node, VoidCallback callback) { recognizerFactories: { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () => callback(), - ), + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () => callback(), + ), }, ); } @@ -87,9 +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 {}, @@ -115,9 +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 {}, @@ -143,13 +141,10 @@ void main() { tree: treeNodes, treeRowBuilder: (TreeViewNode node) { if (node.depth! == 0) { - return getTappableRow( - node, - () { - log.add(node.content); - tapCounter++; - }, - ); + return getTappableRow(node, () { + log.add(node.content); + tapCounter++; + }); } return row; }, @@ -218,8 +213,9 @@ void main() { ); }); - testWidgets('Scrolls when there is enough content', - (WidgetTester tester) async { + testWidgets('Scrolls when there is enough content', ( + WidgetTester tester, + ) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TreeViewController treeController = TreeViewController(); @@ -270,9 +266,7 @@ void main() { testWidgets('Basic', (WidgetTester tester) async { // Default layout, custom indentation values, row extents. - TreeView treeView = TreeView( - tree: treeNodes, - ); + TreeView treeView = TreeView(tree: treeNodes); await tester.pumpWidget(MaterialApp(home: treeView)); await tester.pump(); expect(find.text('First'), findsOneWidget); @@ -470,20 +464,11 @@ void main() { ); // Progress the animation. await tester.pump(const Duration(milliseconds: 50)); - expect( - tester.getRect(find.text('alpha')).top.floor(), - 8.0, - ); + expect(tester.getRect(find.text('alpha')).top.floor(), 8.0); expect(find.text('beta'), findsOneWidget); - expect( - tester.getRect(find.text('beta')).top.floor(), - 48.0, - ); + expect(tester.getRect(find.text('beta')).top.floor(), 48.0); expect(find.text('kappa'), findsOneWidget); - expect( - tester.getRect(find.text('kappa')).top.floor(), - 88.0, - ); + expect(tester.getRect(find.text('kappa')).top.floor(), 88.0); // Complete the animation await tester.pumpAndSettle(); expect(find.text('alpha'), findsOneWidget); @@ -524,37 +509,19 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(find.text('alpha'), findsOneWidget); - expect( - tester.getRect(find.text('alpha')).top.floor(), - -22, - ); + expect(tester.getRect(find.text('alpha')).top.floor(), -22); expect(find.text('beta'), findsOneWidget); - expect( - tester.getRect(find.text('beta')).top.floor(), - 18, - ); + expect(tester.getRect(find.text('beta')).top.floor(), 18); expect(find.text('kappa'), findsOneWidget); - expect( - tester.getRect(find.text('kappa')).top.floor(), - 58, - ); + expect(tester.getRect(find.text('kappa')).top.floor(), 58); // Progress the animation. await tester.pump(const Duration(milliseconds: 200)); expect(find.text('alpha'), findsOneWidget); - expect( - tester.getRect(find.text('alpha')).top.floor(), - -25, - ); + expect(tester.getRect(find.text('alpha')).top.floor(), -25); expect(find.text('beta'), findsOneWidget); - expect( - tester.getRect(find.text('beta')).top.floor(), - 15, - ); + expect(tester.getRect(find.text('beta')).top.floor(), 15); expect(find.text('kappa'), findsOneWidget); - expect( - tester.getRect(find.text('kappa')).top.floor(), - 55.0, - ); + expect(tester.getRect(find.text('kappa')).top.floor(), 55.0); // Complete the animation await tester.pumpAndSettle(); expect(find.text('alpha'), findsNothing); @@ -589,15 +556,15 @@ void main() { ); }); - testWidgets('Multiple animating node segments', - (WidgetTester tester) async { + testWidgets('Multiple animating node segments', ( + WidgetTester tester, + ) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: treeNodes, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: treeNodes, controller: controller), ), - )); + ); await tester.pump(); expect(find.text('Second'), findsOneWidget); expect(find.text('alpha'), findsNothing); // Second is collapsed @@ -638,17 +605,11 @@ void main() { const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), ); // alpha has been added and is animating into view. - expect( - tester.getRect(find.text('alpha')).top.floor(), - -32.0, - ); + expect(tester.getRect(find.text('alpha')).top.floor(), -32.0); await tester.pump(const Duration(milliseconds: 15)); // Third is still collapsing. Third is sliding down // as Seconds's children slide in, gamma is still exiting. - expect( - tester.getRect(find.text('Third')).top.floor(), - 100.0, - ); + expect(tester.getRect(find.text('Third')).top.floor(), 100.0); // gamma appears to not have moved, this is because it is // intersecting both animations, the positive offset of // Second animation == the negative offset of Third @@ -662,18 +623,12 @@ void main() { const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), ); // alpha is still animating into view. - expect( - tester.getRect(find.text('alpha')).top.floor(), - -20.0, - ); + expect(tester.getRect(find.text('alpha')).top.floor(), -20.0); // Progress the animation further await tester.pump(const Duration(milliseconds: 15)); // Third is still collapsing. Third is sliding down // as Seconds's children slide in, gamma is still exiting. - expect( - tester.getRect(find.text('Third')).top.floor(), - 112.0, - ); + expect(tester.getRect(find.text('Third')).top.floor(), 112.0); // gamma appears to not have moved, this is because it is // intersecting both animations, the positive offset of // Second animation == the negative offset of Third @@ -687,10 +642,7 @@ void main() { const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), ); // alpha is still animating into view. - expect( - tester.getRect(find.text('alpha')).top.floor(), - -8.0, - ); + expect(tester.getRect(find.text('alpha')).top.floor(), -8.0); // Complete the animations await tester.pumpAndSettle(); expect( @@ -769,12 +721,14 @@ 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_span_test.dart b/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart index 0ccf49297e4..7b907717ca6 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart @@ -20,7 +20,9 @@ void main() { expect( extent.calculateExtent( const TreeRowExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 150, ); @@ -50,7 +52,9 @@ void main() { expect( extent.calculateExtent( const TreeRowExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 500, ); @@ -80,7 +84,9 @@ void main() { expect( extent.calculateExtent( const TreeRowExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 900, ); @@ -103,7 +109,9 @@ void main() { expect( extent.calculateExtent( const TreeRowExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 1000, ); @@ -123,7 +131,9 @@ void main() { expect( extent.calculateExtent( const TreeRowExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 900, ); @@ -143,7 +153,9 @@ void main() { expect( extent.calculateExtent( const TreeRowExtentDelegate( - precedingExtent: 100, viewportExtent: 1000), + precedingExtent: 100, + viewportExtent: 1000, + ), ), 100, ); @@ -166,13 +178,8 @@ void main() { expect(canvas.rect, rect); expect(canvas.paint.color, const Color(0xffff0000)); expect(canvas.paint.isAntiAlias, isFalse); - final TestTreeRowBorder border = TestTreeRowBorder( - top: const BorderSide(), - ); - decoration = TreeRowDecoration( - border: border, - borderRadius: radius, - ); + final TestTreeRowBorder border = TestTreeRowBorder(top: const BorderSide()); + decoration = TreeRowDecoration(border: border, borderRadius: radius); decoration.paint(details); expect(border.details, details); expect(border.radius, radius); 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 5d7b47e12a0..4a71ebf9379 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart @@ -60,8 +60,9 @@ void main() { ); }); - testWidgets('TreeView sets ups parent and depth properties', - (WidgetTester tester) async { + testWidgets('TreeView sets ups parent and depth properties', ( + WidgetTester tester, + ) async { final List> children = >[ TreeViewNode('child'), ]; @@ -70,11 +71,9 @@ void main() { children: children, expanded: true, ); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: >[node], - ), - )); + await tester.pumpWidget( + MaterialApp(home: TreeView(tree: >[node])), + ); expect(node.content, 'parent'); expect(node.children, children); expect(node.isExpanded, isTrue); @@ -124,200 +123,143 @@ void main() { testWidgets('Can set controller on TreeView', (WidgetTester tester) async { final TreeViewController controller = TreeViewController(); TreeViewController? returnedController; - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - returnedController ??= TreeViewController.of(context); - return TreeView.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); - }, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + controller: controller, + treeNodeBuilder: ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + returnedController ??= TreeViewController.of(context); + return TreeView.defaultTreeNodeBuilder( + context, + node, + toggleAnimationStyle, + ); + }, + ), ), - )); + ); expect(controller, returnedController); }); - testWidgets('Can get default controller on TreeView', - (WidgetTester tester) async { + testWidgets('Can get default controller on TreeView', ( + WidgetTester tester, + ) async { TreeViewController? returnedController; - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - returnedController ??= TreeViewController.maybeOf(context); - return TreeView.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); - }, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + treeNodeBuilder: ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + returnedController ??= TreeViewController.maybeOf(context); + return TreeView.defaultTreeNodeBuilder( + context, + node, + toggleAnimationStyle, + ); + }, + ), ), - )); + ); expect(returnedController, isNotNull); }); - testWidgets('Can get node for TreeViewNode.content', - (WidgetTester tester) async { + testWidgets('Can get node for TreeViewNode.content', ( + WidgetTester tester, + ) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: simpleNodeSet, controller: controller), ), - )); + ); expect(controller.getNodeFor('Root 0'), simpleNodeSet[0]); }); testWidgets('Can get isExpanded for a node', (WidgetTester tester) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: simpleNodeSet, controller: controller), ), - )); - expect( - controller.isExpanded(simpleNodeSet[0]), - isFalse, - ); - expect( - controller.isExpanded(simpleNodeSet[1]), - isTrue, ); + expect(controller.isExpanded(simpleNodeSet[0]), isFalse); + expect(controller.isExpanded(simpleNodeSet[1]), isTrue); }); testWidgets('Can get isActive for a node', (WidgetTester tester) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: simpleNodeSet, controller: controller), ), - )); - expect( - controller.isActive(simpleNodeSet[0]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[1]), - isTrue, ); + expect(controller.isActive(simpleNodeSet[0]), isTrue); + expect(controller.isActive(simpleNodeSet[1]), isTrue); // The parent 'Root 2' is not expanded, so its children are not active. - expect( - controller.isExpanded(simpleNodeSet[2]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isFalse); + expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); }); - testWidgets('Can toggleNode, to collapse or expand', - (WidgetTester tester) async { + testWidgets('Can toggleNode, to collapse or expand', ( + WidgetTester tester, + ) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: simpleNodeSet, controller: controller), ), - )); + ); // The parent 'Root 2' is not expanded, so its children are not active. - expect( - controller.isExpanded(simpleNodeSet[2]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isFalse); + expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); // Toggle 'Root 2' to expand it controller.toggleNode(simpleNodeSet[2]); - expect( - controller.isExpanded(simpleNodeSet[2]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isTrue); + expect(controller.isActive(simpleNodeSet[2].children[0]), isTrue); // The parent 'Root 1' is expanded, so its children are active. - expect( - controller.isExpanded(simpleNodeSet[1]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isTrue); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Collapse 'Root 1' controller.toggleNode(simpleNodeSet[1]); - expect( - controller.isExpanded(simpleNodeSet[1]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isFalse); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Nodes are not removed from the active list until the collapse animation // completes. The parent's expansions status also does not change until the // animation completes. await tester.pumpAndSettle(); - expect( - controller.isExpanded(simpleNodeSet[1]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isFalse); + expect(controller.isActive(simpleNodeSet[1].children[0]), isFalse); }); - testWidgets('Can expandNode, then collapseAll', - (WidgetTester tester) async { + testWidgets('Can expandNode, then collapseAll', ( + WidgetTester tester, + ) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: simpleNodeSet, controller: controller), ), - )); + ); // The parent 'Root 2' is not expanded, so its children are not active. - expect( - controller.isExpanded(simpleNodeSet[2]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isFalse); + expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); // Expand 'Root 2' controller.expandNode(simpleNodeSet[2]); - expect( - controller.isExpanded(simpleNodeSet[2]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isTrue); + expect(controller.isActive(simpleNodeSet[2].children[0]), isTrue); // Both parents from our simple node set are expanded. // 'Root 1' @@ -334,42 +276,27 @@ void main() { expect(controller.isExpanded(simpleNodeSet[2]), isFalse); }); - testWidgets('Can collapseNode, then expandAll', - (WidgetTester tester) async { + testWidgets('Can collapseNode, then expandAll', ( + WidgetTester tester, + ) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, + await tester.pumpWidget( + MaterialApp( + home: TreeView(tree: simpleNodeSet, controller: controller), ), - )); + ); // The parent 'Root 1' is expanded, so its children are active. - expect( - controller.isExpanded(simpleNodeSet[1]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isTrue); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Collapse 'Root 1' controller.collapseNode(simpleNodeSet[1]); - expect( - controller.isExpanded(simpleNodeSet[1]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isFalse); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Nodes are not removed from the active list until the collapse animation // completes. await tester.pumpAndSettle(); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isFalse, - ); + expect(controller.isActive(simpleNodeSet[1].children[0]), isFalse); // Both parents from our simple node set are collapsed. // 'Root 1' @@ -430,8 +357,9 @@ void main() { () { treeView = TreeView( tree: simpleNodeSet, - horizontalDetails: - const ScrollableDetails.horizontal(reverse: true), + horizontalDetails: const ScrollableDetails.horizontal( + reverse: true, + ), ); }, throwsA( @@ -450,16 +378,18 @@ void main() { // The default node builder wraps the leading icon with toggleNodeWith. bool toggled = false; TreeViewNode? toggledNode; - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, - onNodeToggle: (TreeViewNode node) { - toggled = true; - toggledNode = node; - }, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + controller: controller, + onNodeToggle: (TreeViewNode node) { + toggled = true; + toggledNode = node; + }, + ), ), - )); + ); expect(controller.isExpanded(simpleNodeSet[1]), isTrue); await tester.tap(find.byType(Icon).first); await tester.pump(); @@ -472,51 +402,57 @@ void main() { toggledNode = null; // Use toggleNodeWith to make the whole row trigger the node state. - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - controller: controller, - onNodeToggle: (TreeViewNode node) { - 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 - ? AnimatedRotation( - turns: node.isExpanded ? 0.25 : 0.0, - duration: animationDuration, - curve: animationCurve, - child: const Icon(IconData(0x25BA), size: 14), - ) - : null, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + controller: controller, + onNodeToggle: (TreeViewNode node) { + 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 + ? AnimatedRotation( + 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), - ]), - ), - ); - }, + ), + ); + }, + ), ), - )); + ); // Still collapsed from earlier expect(controller.isExpanded(simpleNodeSet[1]), isFalse); // Tapping on the text instead of the Icon. @@ -527,22 +463,25 @@ void main() { expect(toggledNode, simpleNodeSet[1]); }); - testWidgets('AnimationStyle is piped through to node builder', - (WidgetTester tester) async { + testWidgets('AnimationStyle is piped through to node builder', ( + WidgetTester tester, + ) async { AnimationStyle? style; - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - style ??= toggleAnimationStyle; - return Text(node.content); - }, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + treeNodeBuilder: ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + style ??= toggleAnimationStyle; + return Text(node.content); + }, + ), ), - )); + ); // Default expect( style, @@ -553,70 +492,77 @@ void main() { ), ); - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - toggleAnimationStyle: AnimationStyle.noAnimation, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - style = toggleAnimationStyle; - return Text(node.content); - }, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + toggleAnimationStyle: AnimationStyle.noAnimation, + treeNodeBuilder: ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + style = toggleAnimationStyle; + return Text(node.content); + }, + ), ), - )); + ); expect(style, isNotNull); expect(style!.curve, isNull); expect(style!.duration, Duration.zero); style = null; - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: simpleNodeSet, - // ignore: prefer_const_constructors - toggleAnimationStyle: AnimationStyle( - curve: Curves.easeIn, - duration: const Duration(milliseconds: 200), + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: simpleNodeSet, + // ignore: prefer_const_constructors + toggleAnimationStyle: AnimationStyle( + 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); - }, ), - )); + ); expect(style, isNotNull); expect(style!.curve, Curves.easeIn); expect(style!.duration, const Duration(milliseconds: 200)); }); - testWidgets('Adding more root TreeViewNodes are reflected in the tree', - (WidgetTester tester) async { + testWidgets('Adding more root TreeViewNodes are reflected in the tree', ( + WidgetTester tester, + ) async { final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return Scaffold( - body: TreeView( - tree: simpleNodeSet, - controller: controller, - ), - floatingActionButton: FloatingActionButton( - onPressed: () { - setState(() { - simpleNodeSet.add(TreeViewNode('Added root')); - }); - }, - ), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: TreeView( + tree: simpleNodeSet, + controller: controller, + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + simpleNodeSet.add(TreeViewNode('Added root')); + }); + }, + ), + ); + }, + ), ), - )); + ); await tester.pump(); expect(find.text('Root 0'), findsOneWidget); @@ -645,56 +591,59 @@ void main() { }); testWidgets( - 'Adding more TreeViewNodes below the root are reflected in the tree', - (WidgetTester tester) async { - final TreeViewController controller = TreeViewController(); - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return Scaffold( - body: TreeView( - tree: simpleNodeSet, - controller: controller, - ), - floatingActionButton: FloatingActionButton( - onPressed: () { - setState(() { - simpleNodeSet[1].children.add( + 'Adding more TreeViewNodes below the root are reflected in the tree', + (WidgetTester tester) async { + final TreeViewController controller = TreeViewController(); + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: TreeView( + tree: simpleNodeSet, + controller: controller, + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + simpleNodeSet[1].children.add( TreeViewNode('Added child'), ); - }); - }, - ), - ); - }, - ), - )); - await tester.pump(); - - expect(find.text('Root 0'), findsOneWidget); - expect(find.text('Root 1'), findsOneWidget); - expect(find.text('Child 1:0'), findsOneWidget); - expect(find.text('Child 1:1'), findsOneWidget); - expect(find.text('Added child'), findsNothing); - expect(find.text('Root 2'), findsOneWidget); - expect(find.text('Child 2:0'), findsNothing); - expect(find.text('Child 2:1'), findsNothing); - expect(find.text('Root 3'), findsOneWidget); - - await tester.tap(find.byType(FloatingActionButton)); - await tester.pump(); - - expect(find.text('Root 0'), findsOneWidget); - expect(find.text('Root 1'), findsOneWidget); - expect(find.text('Child 1:0'), findsOneWidget); - expect(find.text('Child 1:1'), findsOneWidget); - // Child node was added - expect(find.text('Added child'), findsOneWidget); - expect(find.text('Root 2'), findsOneWidget); - expect(find.text('Child 2:0'), findsNothing); - expect(find.text('Child 2:1'), findsNothing); - expect(find.text('Root 3'), findsOneWidget); - }); + }); + }, + ), + ); + }, + ), + ), + ); + await tester.pump(); + + expect(find.text('Root 0'), findsOneWidget); + expect(find.text('Root 1'), findsOneWidget); + expect(find.text('Child 1:0'), findsOneWidget); + expect(find.text('Child 1:1'), findsOneWidget); + expect(find.text('Added child'), findsNothing); + expect(find.text('Root 2'), findsOneWidget); + expect(find.text('Child 2:0'), findsNothing); + expect(find.text('Child 2:1'), findsNothing); + expect(find.text('Root 3'), findsOneWidget); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pump(); + + expect(find.text('Root 0'), findsOneWidget); + expect(find.text('Root 1'), findsOneWidget); + expect(find.text('Child 1:0'), findsOneWidget); + expect(find.text('Child 1:1'), findsOneWidget); + // Child node was added + expect(find.text('Added child'), findsOneWidget); + expect(find.text('Root 2'), findsOneWidget); + expect(find.text('Child 2:0'), findsNothing); + expect(find.text('Child 2:1'), findsNothing); + expect(find.text('Root 3'), findsOneWidget); + }, + ); test('should use the generic type for callbacks and builders', () { final TreeView treeView = TreeView( @@ -704,11 +653,7 @@ void main() { TreeViewNode node, AnimationStyle animationStyle, ) { - return TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ); + return TreeView.defaultTreeNodeBuilder(context, node, animationStyle); }, treeRowBuilder: (TreeViewNode node) { return TreeView.defaultTreeRowBuilder(node); @@ -722,173 +667,180 @@ void main() { }); testWidgets( - 'TreeViewNode should expand/collapse correctly when the animation duration is set to zero.', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/154292 - final TreeViewController controller = TreeViewController(); - final List> tree = >[ - TreeViewNode('First'), - TreeViewNode( - 'Second', - children: >[ - TreeViewNode( - 'alpha', - children: >[ - TreeViewNode('uno'), - TreeViewNode('dos'), - TreeViewNode('tres'), - ], - ), - TreeViewNode('beta'), - TreeViewNode('kappa'), - ], - ), - TreeViewNode( - 'Third', - expanded: true, - children: >[ - TreeViewNode('gamma'), - TreeViewNode('delta'), - TreeViewNode('epsilon'), - ], - ), - TreeViewNode('Fourth'), - ]; - - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: tree, - controller: controller, - // ignore: prefer_const_constructors - toggleAnimationStyle: AnimationStyle( - curve: Curves.easeInOut, - duration: Duration.zero, + 'TreeViewNode should expand/collapse correctly when the animation duration is set to zero.', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/154292 + final TreeViewController controller = TreeViewController(); + final List> tree = >[ + TreeViewNode('First'), + TreeViewNode( + 'Second', + children: >[ + TreeViewNode( + 'alpha', + children: >[ + TreeViewNode('uno'), + TreeViewNode('dos'), + TreeViewNode('tres'), + ], + ), + TreeViewNode('beta'), + TreeViewNode('kappa'), + ], ), - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) { - final Widget child = GestureDetector( - behavior: HitTestBehavior.translucent, - onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, + TreeViewNode( + 'Third', + expanded: true, + children: >[ + TreeViewNode('gamma'), + TreeViewNode('delta'), + TreeViewNode('epsilon'), + ], + ), + TreeViewNode('Fourth'), + ]; + + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: tree, + controller: controller, + // ignore: prefer_const_constructors + toggleAnimationStyle: AnimationStyle( + curve: Curves.easeInOut, + duration: Duration.zero, ), - ); - - return child; - }, - ), - )); - - expect(find.text('First'), findsOneWidget); - expect(find.text('Second'), findsOneWidget); - expect(find.text('Third'), findsOneWidget); - expect(find.text('Fourth'), findsOneWidget); - expect(find.text('alpha'), findsNothing); - expect(find.text('beta'), findsNothing); - expect(find.text('kappa'), findsNothing); - expect(find.text('gamma'), findsOneWidget); - expect(find.text('delta'), findsOneWidget); - expect(find.text('epsilon'), findsOneWidget); - expect(find.text('uno'), findsNothing); - expect(find.text('dos'), findsNothing); - expect(find.text('tres'), findsNothing); - - await tester.tap(find.text('Second')); - await tester.pumpAndSettle(); - - expect(find.text('alpha'), findsOneWidget); - - await tester.tap(find.text('alpha')); - await tester.pumpAndSettle(); - - expect(find.text('uno'), findsOneWidget); - expect(find.text('dos'), findsOneWidget); - expect(find.text('tres'), findsOneWidget); - - await tester.tap(find.text('alpha')); - await tester.pumpAndSettle(); - - expect(find.text('uno'), findsNothing); - expect(find.text('dos'), findsNothing); - expect(find.text('tres'), findsNothing); - }); + treeNodeBuilder: ( + BuildContext context, + TreeViewNode node, + AnimationStyle animationStyle, + ) { + final Widget child = GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: () => controller.toggleNode(node), + child: TreeView.defaultTreeNodeBuilder( + context, + node, + animationStyle, + ), + ); - testWidgets( - 'TreeViewNode should close all child nodes when collapsed, once the animation is completed', - (WidgetTester tester) async { - final TreeViewController controller = TreeViewController(); - final List> tree = >[ - TreeViewNode( - 'First', - expanded: true, - children: >[ - TreeViewNode( - 'alpha', - expanded: true, - children: >[ - TreeViewNode('uno'), - TreeViewNode('dos'), - TreeViewNode('tres'), - ], + return child; + }, ), - TreeViewNode('beta'), - TreeViewNode('kappa'), - ], - ), - ]; - - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: tree, - controller: controller, - // ignore: prefer_const_constructors - toggleAnimationStyle: AnimationStyle( - 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, - ), - ); + ); + + expect(find.text('First'), findsOneWidget); + expect(find.text('Second'), findsOneWidget); + expect(find.text('Third'), findsOneWidget); + expect(find.text('Fourth'), findsOneWidget); + expect(find.text('alpha'), findsNothing); + expect(find.text('beta'), findsNothing); + expect(find.text('kappa'), findsNothing); + expect(find.text('gamma'), findsOneWidget); + expect(find.text('delta'), findsOneWidget); + expect(find.text('epsilon'), findsOneWidget); + expect(find.text('uno'), findsNothing); + expect(find.text('dos'), findsNothing); + expect(find.text('tres'), findsNothing); - return child; - }, - ), - )); + await tester.tap(find.text('Second')); + await tester.pumpAndSettle(); - expect(find.text('alpha'), findsOneWidget); - expect(find.text('uno'), findsOneWidget); - expect(find.text('dos'), findsOneWidget); - expect(find.text('tres'), findsOneWidget); + expect(find.text('alpha'), findsOneWidget); + + await tester.tap(find.text('alpha')); + await tester.pumpAndSettle(); + + expect(find.text('uno'), findsOneWidget); + expect(find.text('dos'), findsOneWidget); + expect(find.text('tres'), findsOneWidget); - // Using runAsync to handle collapse and animations properly. - await tester.runAsync(() async { await tester.tap(find.text('alpha')); await tester.pumpAndSettle(); expect(find.text('uno'), findsNothing); expect(find.text('dos'), findsNothing); expect(find.text('tres'), findsNothing); - }); - }); + }, + ); + + testWidgets( + 'TreeViewNode should close all child nodes when collapsed, once the animation is completed', + (WidgetTester tester) async { + final TreeViewController controller = TreeViewController(); + final List> tree = >[ + TreeViewNode( + 'First', + expanded: true, + children: >[ + TreeViewNode( + 'alpha', + expanded: true, + children: >[ + TreeViewNode('uno'), + TreeViewNode('dos'), + TreeViewNode('tres'), + ], + ), + TreeViewNode('beta'), + TreeViewNode('kappa'), + ], + ), + ]; + + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: tree, + controller: controller, + // ignore: prefer_const_constructors + toggleAnimationStyle: AnimationStyle( + 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, + ), + ); - testWidgets('Expand then collapse with offscreen nodes (top)', - (WidgetTester tester) async { + return child; + }, + ), + ), + ); + + expect(find.text('alpha'), findsOneWidget); + expect(find.text('uno'), findsOneWidget); + expect(find.text('dos'), findsOneWidget); + expect(find.text('tres'), findsOneWidget); + + // Using runAsync to handle collapse and animations properly. + await tester.runAsync(() async { + await tester.tap(find.text('alpha')); + await tester.pumpAndSettle(); + + expect(find.text('uno'), findsNothing); + expect(find.text('dos'), findsNothing); + expect(find.text('tres'), findsNothing); + }); + }, + ); + + testWidgets('Expand then collapse with offscreen nodes (top)', ( + WidgetTester tester, + ) async { final ScrollController verticalController = ScrollController(); final TreeViewController controller = TreeViewController(); addTearDown(verticalController.dispose); @@ -928,29 +880,31 @@ void main() { ), ]; - await tester.pumpWidget(MaterialApp( - home: TreeView( - tree: tree, - controller: controller, - toggleAnimationStyle: AnimationStyle.noAnimation, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) => - GestureDetector( - onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, + await tester.pumpWidget( + MaterialApp( + home: TreeView( + tree: tree, + controller: controller, + toggleAnimationStyle: AnimationStyle.noAnimation, + verticalDetails: ScrollableDetails.vertical( + controller: verticalController, ), + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle animationStyle, + ) => GestureDetector( + onTap: () => controller.toggleNode(node), + child: TreeView.defaultTreeNodeBuilder( + context, + node, + animationStyle, + ), + ), ), ), - )); + ); // Expand a few nodes await tester.tap(find.text('alpha')); @@ -991,9 +945,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 {}, @@ -1018,9 +971,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 979d2b5feb9..920a7ad8e78 100644 --- a/packages/url_launcher/url_launcher/CHANGELOG.md +++ b/packages/url_launcher/url_launcher/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 6.3.2 * Updates README to indicate that Andoid SDK <21 is no longer supported. diff --git a/packages/url_launcher/url_launcher/README.md b/packages/url_launcher/url_launcher/README.md index 0c6ee7675f2..9e342629d12 100644 --- a/packages/url_launcher/url_launcher/README.md +++ b/packages/url_launcher/url_launcher/README.md @@ -20,23 +20,24 @@ import 'package:url_launcher/url_launcher.dart'; final Uri _url = Uri.parse('https://flutter.dev'); void main() => runApp( - const MaterialApp( - home: Material( - child: Center( - child: ElevatedButton( - onPressed: _launchUrl, - child: Text('Show Flutter homepage'), - ), - ), + const MaterialApp( + home: Material( + child: Center( + child: ElevatedButton( + onPressed: _launchUrl, + child: Text('Show Flutter homepage'), ), ), - ); + ), + ), +); Future _launchUrl() async { if (!await launchUrl(_url)) { throw Exception('Could not launch $_url'); } } + ``` See the example app for more complex examples. @@ -154,8 +155,10 @@ converted to `+` in many cases. ```dart String? encodeQueryParameters(Map params) { return params.entries - .map((MapEntry e) => - '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}') + .map( + (MapEntry e) => + '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}', + ) .join('&'); } // ··· diff --git a/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart b/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart index 51c2ec89240..785a5f4969a 100644 --- a/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart +++ b/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart @@ -14,7 +14,9 @@ void main() { testWidgets('canLaunch', (WidgetTester _) async { expect( - await canLaunchUrl(Uri(scheme: 'randomscheme', path: 'a_path')), false); + await canLaunchUrl(Uri(scheme: 'randomscheme', path: 'a_path')), + false, + ); // Generally all devices should have some default browser. expect(await canLaunchUrl(Uri(scheme: 'http', host: 'flutter.dev')), true); diff --git a/packages/url_launcher/url_launcher/example/lib/basic.dart b/packages/url_launcher/url_launcher/example/lib/basic.dart index 422e2aae460..ecf7b789036 100644 --- a/packages/url_launcher/url_launcher/example/lib/basic.dart +++ b/packages/url_launcher/url_launcher/example/lib/basic.dart @@ -14,21 +14,22 @@ import 'package:url_launcher/url_launcher.dart'; final Uri _url = Uri.parse('https://flutter.dev'); void main() => runApp( - const MaterialApp( - home: Material( - child: Center( - child: ElevatedButton( - onPressed: _launchUrl, - child: Text('Show Flutter homepage'), - ), - ), + const MaterialApp( + home: Material( + child: Center( + child: ElevatedButton( + onPressed: _launchUrl, + child: Text('Show Flutter homepage'), ), ), - ); + ), + ), +); Future _launchUrl() async { if (!await launchUrl(_url)) { throw Exception('Could not launch $_url'); } } + // #enddocregion basic-example diff --git a/packages/url_launcher/url_launcher/example/lib/encoding.dart b/packages/url_launcher/url_launcher/example/lib/encoding.dart index f3bcc57cbda..46583586161 100644 --- a/packages/url_launcher/url_launcher/example/lib/encoding.dart +++ b/packages/url_launcher/url_launcher/example/lib/encoding.dart @@ -15,30 +15,32 @@ import 'package:url_launcher/url_launcher.dart'; // #docregion encode-query-parameters String? encodeQueryParameters(Map params) { return params.entries - .map((MapEntry e) => - '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}') + .map( + (MapEntry e) => + '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}', + ) .join('&'); } // #enddocregion encode-query-parameters void main() => runApp( - const MaterialApp( - home: Material( - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - ElevatedButton( - onPressed: _composeMail, - child: Text('Compose an email'), - ), - ], + const MaterialApp( + home: Material( + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + ElevatedButton( + onPressed: _composeMail, + child: Text('Compose an email'), ), - ), + ], ), - ); + ), + ), +); void _composeMail() { -// #docregion encode-query-parameters + // #docregion encode-query-parameters final Uri emailLaunchUri = Uri( scheme: 'mailto', path: 'smith@example.com', @@ -48,5 +50,5 @@ void _composeMail() { ); launchUrl(emailLaunchUri); -// #enddocregion encode-query-parameters + // #enddocregion encode-query-parameters } diff --git a/packages/url_launcher/url_launcher/example/lib/files.dart b/packages/url_launcher/url_launcher/example/lib/files.dart index 7f9d20669ee..06e660ce486 100644 --- a/packages/url_launcher/url_launcher/example/lib/files.dart +++ b/packages/url_launcher/url_launcher/example/lib/files.dart @@ -13,27 +13,24 @@ import 'package:path/path.dart' as p; import 'package:url_launcher/url_launcher.dart'; void main() => runApp( - const MaterialApp( - home: Material( - child: Center( - child: ElevatedButton( - onPressed: _openFile, - child: Text('Open File'), - ), - ), - ), + const MaterialApp( + home: Material( + child: Center( + child: ElevatedButton(onPressed: _openFile, child: Text('Open File')), ), - ); + ), + ), +); Future _openFile() async { // Prepare a file within tmp final String tempFilePath = p.joinAll([ ...p.split(Directory.systemTemp.path), - 'flutter_url_launcher_example.txt' + 'flutter_url_launcher_example.txt', ]); final File testFile = File(tempFilePath); await testFile.writeAsString('Hello, world!'); -// #docregion file + // #docregion file final String filePath = testFile.absolute.path; final Uri uri = Uri.file(filePath); @@ -43,5 +40,5 @@ Future _openFile() async { if (!await launchUrl(uri)) { throw Exception('Could not launch $uri'); } -// #enddocregion file + // #enddocregion file } diff --git a/packages/url_launcher/url_launcher/example/lib/main.dart b/packages/url_launcher/url_launcher/example/lib/main.dart index e3a353f81ed..3a7a0812c73 100644 --- a/packages/url_launcher/url_launcher/example/lib/main.dart +++ b/packages/url_launcher/url_launcher/example/lib/main.dart @@ -21,9 +21,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'URL Launcher'), ); } @@ -54,10 +52,7 @@ class _MyHomePageState extends State { } Future _launchInBrowser(Uri url) async { - if (!await launchUrl( - url, - mode: LaunchMode.externalApplication, - )) { + if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { throw Exception('Could not launch $url'); } } @@ -89,7 +84,8 @@ class _MyHomePageState extends State { url, mode: LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration( - headers: {'my_header_key': 'my_header_value'}), + headers: {'my_header_key': 'my_header_value'}, + ), )) { throw Exception('Could not launch $url'); } @@ -121,10 +117,7 @@ class _MyHomePageState extends State { mode: LaunchMode.externalNonBrowserApplication, ); if (!nativeAppLaunchSucceeded) { - await launchUrl( - url, - mode: LaunchMode.inAppBrowserView, - ); + await launchUrl(url, mode: LaunchMode.inAppBrowserView); } } @@ -137,10 +130,7 @@ class _MyHomePageState extends State { } Future _makePhoneCall(String phoneNumber) async { - final Uri launchUri = Uri( - scheme: 'tel', - path: phoneNumber, - ); + final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber); await launchUrl(launchUri); } @@ -148,12 +138,13 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { // onPressed calls using this URL are not gated on a 'canLaunch' check // because the assumption is that every device can launch a web URL. - final Uri toLaunch = - Uri(scheme: 'https', host: 'www.cylog.org', path: 'headers/'); + final Uri toLaunch = Uri( + scheme: 'https', + host: 'www.cylog.org', + path: 'headers/', + ); return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: ListView( children: [ Column( @@ -162,84 +153,100 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: TextField( - onChanged: (String text) => _phone = text, - decoration: const InputDecoration( - hintText: 'Input the phone number to launch')), + onChanged: (String text) => _phone = text, + decoration: const InputDecoration( + hintText: 'Input the phone number to launch', + ), + ), ), ElevatedButton( - onPressed: _hasCallSupport - ? () => setState(() { + onPressed: + _hasCallSupport + ? () => setState(() { _launched = _makePhoneCall(_phone); }) - : null, - child: _hasCallSupport - ? const Text('Make phone call') - : const Text('Calling not supported'), + : 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)'), + '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)), Link( uri: Uri.parse( - 'https://pub.dev/documentation/url_launcher/latest/link/link-library.html'), + 'https://pub.dev/documentation/url_launcher/latest/link/link-library.html', + ), target: LinkTarget.blank, builder: (BuildContext ctx, FollowLink? openLink) { return TextButton.icon( diff --git a/packages/url_launcher/url_launcher/example/pubspec.yaml b/packages/url_launcher/url_launcher/example/pubspec.yaml index f42068273a0..6b64e933cb1 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 49165f512c5..47f6b36caf8 100644 --- a/packages/url_launcher/url_launcher/lib/src/legacy_api.dart +++ b/packages/url_launcher/url_launcher/lib/src/legacy_api.dart @@ -80,9 +80,11 @@ Future launch( if (((forceSafariVC ?? false) || forceWebView) && !isWebURL) { throw PlatformException( - code: 'NOT_A_WEB_SCHEME', - message: 'To use webview or safariVC, you need to pass ' - 'in a web URL. This $urlString is not a web URL.'); + code: 'NOT_A_WEB_SCHEME', + message: + 'To use webview or safariVC, you need to pass ' + 'in a web URL. This $urlString is not a web URL.', + ); } /// [true] so that ui is automatically computed if [statusBarBrightness] is set. @@ -95,9 +97,11 @@ Future launch( previousAutomaticSystemUiAdjustment = renderViewToAdjust.automaticSystemUiAdjustment; renderViewToAdjust.automaticSystemUiAdjustment = false; - SystemChrome.setSystemUIOverlayStyle(statusBarBrightness == Brightness.light - ? SystemUiOverlayStyle.dark - : SystemUiOverlayStyle.light); + SystemChrome.setSystemUIOverlayStyle( + statusBarBrightness == Brightness.light + ? SystemUiOverlayStyle.dark + : SystemUiOverlayStyle.light, + ); } final bool result = await UrlLauncherPlatform.instance.launch( diff --git a/packages/url_launcher/url_launcher/lib/src/link.dart b/packages/url_launcher/url_launcher/lib/src/link.dart index b5c47403097..b7fce14119b 100644 --- a/packages/url_launcher/url_launcher/lib/src/link.dart +++ b/packages/url_launcher/url_launcher/lib/src/link.dart @@ -125,20 +125,23 @@ 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; } if (!success) { - FlutterError.reportError(FlutterErrorDetails( - exception: 'Could not launch link $url', - stack: StackTrace.current, - library: 'url_launcher', - context: ErrorDescription('during launching a link'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: 'Could not launch link $url', + stack: StackTrace.current, + library: 'url_launcher', + context: ErrorDescription('during launching a link'), + ), + ); } } diff --git a/packages/url_launcher/url_launcher/lib/src/type_conversion.dart b/packages/url_launcher/url_launcher/lib/src/type_conversion.dart index 0e27da35fe7..18a692cda4f 100644 --- a/packages/url_launcher/url_launcher/lib/src/type_conversion.dart +++ b/packages/url_launcher/url_launcher/lib/src/type_conversion.dart @@ -9,7 +9,8 @@ import 'types.dart'; /// Converts an (app-facing) [WebViewConfiguration] to a (platform interface) /// [InAppWebViewConfiguration]. InAppWebViewConfiguration convertWebViewConfiguration( - WebViewConfiguration config) { + WebViewConfiguration config, +) { return InAppWebViewConfiguration( enableJavaScript: config.enableJavaScript, enableDomStorage: config.enableDomStorage, @@ -20,10 +21,9 @@ InAppWebViewConfiguration convertWebViewConfiguration( /// Converts an (app-facing) [BrowserConfiguration] to a (platform interface) /// [InAppBrowserConfiguration]. InAppBrowserConfiguration convertBrowserConfiguration( - BrowserConfiguration config) { - return InAppBrowserConfiguration( - showTitle: config.showTitle, - ); + BrowserConfiguration config, +) { + return InAppBrowserConfiguration(showTitle: config.showTitle); } /// Converts an (app-facing) [LaunchMode] to a (platform interface) diff --git a/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart b/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart index bf878c60dde..914f57d8ee5 100644 --- a/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart +++ b/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart @@ -29,8 +29,11 @@ Future launchUrlString( if ((mode == LaunchMode.inAppWebView || mode == LaunchMode.inAppBrowserView) && !(urlString.startsWith('https:') || urlString.startsWith('http:'))) { - throw ArgumentError.value(urlString, 'urlString', - 'To use an in-app web view, you must provide an http(s) URL.'); + throw ArgumentError.value( + urlString, + 'urlString', + 'To use an in-app web view, you must provide an http(s) URL.', + ); } return UrlLauncherPlatform.instance.launchUrl( urlString, diff --git a/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart b/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart index 97f8af482cd..9c9492c4183 100644 --- a/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart +++ b/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart @@ -46,8 +46,11 @@ Future launchUrl( if ((mode == LaunchMode.inAppWebView || mode == LaunchMode.inAppBrowserView) && !(url.scheme == 'https' || url.scheme == 'http')) { - throw ArgumentError.value(url, 'url', - 'To use an in-app web view, you must provide an http(s) URL.'); + throw ArgumentError.value( + url, + 'url', + 'To use an in-app web view, you must provide an http(s) URL.', + ); } return UrlLauncherPlatform.instance.launchUrl( url.toString(), diff --git a/packages/url_launcher/url_launcher/pubspec.yaml b/packages/url_launcher/url_launcher/pubspec.yaml index e66df063ec7..1dbe073249a 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 4d8fed20797..a5b9feb957b 100644 --- a/packages/url_launcher/url_launcher/test/link_test.dart +++ b/packages/url_launcher/url_launcher/test/link_test.dart @@ -39,18 +39,21 @@ void main() { expect(followLink, isNull); }); - testWidgets('calls url_launcher for external URLs with blank target', - (WidgetTester tester) async { + testWidgets('calls url_launcher for external URLs with blank target', ( + WidgetTester tester, + ) async { FollowLink? followLink; - await tester.pumpWidget(Link( - uri: Uri.parse('http://example.com/foobar'), - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink2) { - followLink = followLink2; - return Container(); - }, - )); + await tester.pumpWidget( + Link( + uri: Uri.parse('http://example.com/foobar'), + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink2) { + followLink = followLink2; + return Container(); + }, + ), + ); mock ..setLaunchExpectations( @@ -71,18 +74,21 @@ void main() { expect(mock.launchCalled, isTrue); }); - testWidgets('calls url_launcher for external URLs with self target', - (WidgetTester tester) async { + testWidgets('calls url_launcher for external URLs with self target', ( + WidgetTester tester, + ) async { FollowLink? followLink; - await tester.pumpWidget(Link( - uri: Uri.parse('http://example.com/foobar'), - target: LinkTarget.self, - builder: (BuildContext context, FollowLink? followLink2) { - followLink = followLink2; - return Container(); - }, - )); + await tester.pumpWidget( + Link( + uri: Uri.parse('http://example.com/foobar'), + target: LinkTarget.self, + builder: (BuildContext context, FollowLink? followLink2) { + followLink = followLink2; + return Container(); + }, + ), + ); mock ..setLaunchExpectations( @@ -103,23 +109,27 @@ void main() { expect(mock.launchCalled, isTrue); }); - testWidgets('pushes to framework for internal route names', - (WidgetTester tester) async { + testWidgets('pushes to framework for internal route names', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foo/bar'); FollowLink? followLink; - await tester.pumpWidget(MaterialApp( - routes: { - '/': (BuildContext context) => Link( - uri: uri, - builder: (BuildContext context, FollowLink? followLink2) { - followLink = followLink2; - return Container(); - }, - ), - '/foo/bar': (BuildContext context) => Container(), - }, - )); + await tester.pumpWidget( + MaterialApp( + routes: { + '/': + (BuildContext context) => Link( + uri: uri, + builder: (BuildContext context, FollowLink? followLink2) { + followLink = followLink2; + return Container(); + }, + ), + '/foo/bar': (BuildContext context) => Container(), + }, + ), + ); bool frameworkCalled = false; final Future Function(Object?, String) originalPushFunction = diff --git a/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart b/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart index 9f8b989e950..20119591768 100644 --- a/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart +++ b/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart @@ -74,11 +74,12 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'http://flutter.dev/', - headers: {'key': 'value'}, - ), - isTrue); + await launch( + 'http://flutter.dev/', + headers: {'key': 'value'}, + ), + isTrue, + ); }); test('force SafariVC', () async { @@ -113,9 +114,13 @@ void main() { ) ..setResponse(true); expect( - await launch('http://flutter.dev/', - forceSafariVC: false, universalLinksOnly: true), - isTrue); + await launch( + 'http://flutter.dev/', + forceSafariVC: false, + universalLinksOnly: true, + ), + isTrue, + ); }); test('force WebView', () async { @@ -150,9 +155,13 @@ void main() { ) ..setResponse(true); expect( - await launch('http://flutter.dev/', - forceWebView: true, enableJavaScript: true), - isTrue); + await launch( + 'http://flutter.dev/', + forceWebView: true, + enableJavaScript: true, + ), + isTrue, + ); }); test('force WebView enable DOM storage', () async { @@ -170,9 +179,13 @@ void main() { ) ..setResponse(true); expect( - await launch('http://flutter.dev/', - forceWebView: true, enableDomStorage: true), - isTrue); + await launch( + 'http://flutter.dev/', + forceWebView: true, + enableDomStorage: true, + ), + isTrue, + ); }); test('force SafariVC to false', () async { @@ -193,8 +206,10 @@ void main() { }); test('cannot launch a non-web in webview', () async { - expect(() async => launch('tel:555-555-5555', forceWebView: true), - throwsA(isA())); + expect( + () async => launch('tel:555-555-5555', forceWebView: true), + throwsA(isA()), + ); }); test('send e-mail', () async { @@ -211,31 +226,45 @@ void main() { showTitle: false, ) ..setResponse(true); - expect(await launch('mailto:gmail-noreply@google.com?subject=Hello'), - isTrue); + expect( + await launch('mailto:gmail-noreply@google.com?subject=Hello'), + isTrue, + ); }); test('cannot send e-mail with forceSafariVC: true', () async { expect( - () async => launch('mailto:gmail-noreply@google.com?subject=Hello', - forceSafariVC: true), - throwsA(isA())); + () async => launch( + 'mailto:gmail-noreply@google.com?subject=Hello', + forceSafariVC: true, + ), + throwsA(isA()), + ); }); test('cannot send e-mail with forceWebView: true', () async { expect( - () async => launch('mailto:gmail-noreply@google.com?subject=Hello', - forceWebView: true), - throwsA(isA())); + () async => launch( + 'mailto:gmail-noreply@google.com?subject=Hello', + forceWebView: true, + ), + throwsA(isA()), + ); }); - test('cannot send e-mail with forceSafariVC: false and forceWebView: true', - () async { - expect( - () async => launch('mailto:gmail-noreply@google.com?subject=Hello', - forceSafariVC: false, forceWebView: true), - throwsA(isA())); - }); + test( + 'cannot send e-mail with forceSafariVC: false and forceWebView: true', + () async { + expect( + () async => launch( + 'mailto:gmail-noreply@google.com?subject=Hello', + forceSafariVC: false, + forceWebView: true, + ), + throwsA(isA()), + ); + }, + ); test('controls system UI when changing statusBarBrightness', () async { mock @@ -255,12 +284,15 @@ void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final RenderView renderView = - RenderView(view: binding.platformDispatcher.implicitView!); + final RenderView renderView = RenderView( + view: binding.platformDispatcher.implicitView!, + ); binding.addRenderView(renderView); renderView.automaticSystemUiAdjustment = true; - final Future launchResult = - launch('http://flutter.dev/', statusBarBrightness: Brightness.dark); + final Future launchResult = launch( + 'http://flutter.dev/', + statusBarBrightness: Brightness.dark, + ); // Should take over control of the automaticSystemUiAdjustment while it's // pending, then restore it back to normal after the launch finishes. @@ -288,12 +320,15 @@ void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); debugDefaultTargetPlatformOverride = TargetPlatform.android; - final RenderView renderView = - RenderView(view: binding.platformDispatcher.implicitView!); + final RenderView renderView = RenderView( + view: binding.platformDispatcher.implicitView!, + ); binding.addRenderView(renderView); expect(renderView.automaticSystemUiAdjustment, true); - final Future launchResult = - launch('http://flutter.dev/', statusBarBrightness: Brightness.dark); + final Future launchResult = launch( + 'http://flutter.dev/', + statusBarBrightness: Brightness.dark, + ); // The automaticSystemUiAdjustment should be set before the launch // and equal to true after the launch result is complete. @@ -319,25 +354,31 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1'), - isTrue); + await launch( + 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', + ), + isTrue, + ); }); test('cannot open non-parseable url with forceSafariVC: true', () async { expect( - () async => launch( - 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', - forceSafariVC: true), - throwsA(isA())); + () async => launch( + 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', + forceSafariVC: true, + ), + throwsA(isA()), + ); }); test('cannot open non-parseable url with forceWebView: true', () async { expect( - () async => launch( - 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', - forceWebView: true), - throwsA(isA())); + () async => launch( + 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', + forceWebView: true, + ), + throwsA(isA()), + ); }); }); } diff --git a/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart b/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart index 0cd0f9b2eb5..d119cb84633 100644 --- a/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart +++ b/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart @@ -120,8 +120,10 @@ void main() { showTitle: false, ) ..setResponse(true); - expect(await launchUrlString(urlString, mode: LaunchMode.inAppWebView), - isTrue); + expect( + await launchUrlString(urlString, mode: LaunchMode.inAppWebView), + isTrue, + ); }); test('external browser', () async { @@ -139,9 +141,9 @@ void main() { ) ..setResponse(true); expect( - await launchUrlString(urlString, - mode: LaunchMode.externalApplication), - isTrue); + await launchUrlString(urlString, mode: LaunchMode.externalApplication), + isTrue, + ); }); test('in-app browser', () async { @@ -203,9 +205,12 @@ void main() { ) ..setResponse(true); expect( - await launchUrlString(urlString, - mode: LaunchMode.externalNonBrowserApplication), - isTrue); + await launchUrlString( + urlString, + mode: LaunchMode.externalNonBrowserApplication, + ), + isTrue, + ); }); test('in-app webview without javascript', () async { @@ -223,11 +228,15 @@ void main() { ) ..setResponse(true); expect( - await launchUrlString(urlString, - mode: LaunchMode.inAppWebView, - webViewConfiguration: - const WebViewConfiguration(enableJavaScript: false)), - isTrue); + await launchUrlString( + urlString, + mode: LaunchMode.inAppWebView, + webViewConfiguration: const WebViewConfiguration( + enableJavaScript: false, + ), + ), + isTrue, + ); }); test('in-app webview without DOM storage', () async { @@ -245,11 +254,15 @@ void main() { ) ..setResponse(true); expect( - await launchUrlString(urlString, - mode: LaunchMode.inAppWebView, - webViewConfiguration: - const WebViewConfiguration(enableDomStorage: false)), - isTrue); + await launchUrlString( + urlString, + mode: LaunchMode.inAppWebView, + webViewConfiguration: const WebViewConfiguration( + enableDomStorage: false, + ), + ), + isTrue, + ); }); test('in-app webview with headers', () async { @@ -267,18 +280,23 @@ void main() { ) ..setResponse(true); expect( - await launchUrlString(urlString, - mode: LaunchMode.inAppWebView, - webViewConfiguration: const WebViewConfiguration( - headers: {'key': 'value'})), - isTrue); + await launchUrlString( + urlString, + mode: LaunchMode.inAppWebView, + webViewConfiguration: const WebViewConfiguration( + headers: {'key': 'value'}, + ), + ), + isTrue, + ); }); test('cannot launch a non-web URL in a webview', () async { expect( - () async => launchUrlString('tel:555-555-5555', - mode: LaunchMode.inAppWebView), - throwsA(isA())); + () async => + launchUrlString('tel:555-555-5555', mode: LaunchMode.inAppWebView), + throwsA(isA()), + ); }); test('non-web URL with default options', () async { diff --git a/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart b/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart index 15796ea659a..d55a2c5115b 100644 --- a/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart +++ b/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart @@ -143,7 +143,9 @@ void main() { ) ..setResponse(true); expect( - await launchUrl(url, mode: LaunchMode.externalApplication), isTrue); + await launchUrl(url, mode: LaunchMode.externalApplication), + isTrue, + ); }); test('external non-browser only', () async { @@ -161,8 +163,9 @@ void main() { ) ..setResponse(true); expect( - await launchUrl(url, mode: LaunchMode.externalNonBrowserApplication), - isTrue); + await launchUrl(url, mode: LaunchMode.externalNonBrowserApplication), + isTrue, + ); }); test('in-app webview without javascript', () async { @@ -180,11 +183,15 @@ void main() { ) ..setResponse(true); expect( - await launchUrl(url, - mode: LaunchMode.inAppWebView, - webViewConfiguration: - const WebViewConfiguration(enableJavaScript: false)), - isTrue); + await launchUrl( + url, + mode: LaunchMode.inAppWebView, + webViewConfiguration: const WebViewConfiguration( + enableJavaScript: false, + ), + ), + isTrue, + ); }); test('in-app browser view with show title', () async { @@ -202,12 +209,13 @@ void main() { ) ..setResponse(true); expect( - await launchUrl( - url, - mode: LaunchMode.inAppBrowserView, - browserConfiguration: const BrowserConfiguration(showTitle: true), - ), - isTrue); + await launchUrl( + url, + mode: LaunchMode.inAppBrowserView, + browserConfiguration: const BrowserConfiguration(showTitle: true), + ), + isTrue, + ); }); test('in-app webview without DOM storage', () async { @@ -225,11 +233,15 @@ void main() { ) ..setResponse(true); expect( - await launchUrl(url, - mode: LaunchMode.inAppWebView, - webViewConfiguration: - const WebViewConfiguration(enableDomStorage: false)), - isTrue); + await launchUrl( + url, + mode: LaunchMode.inAppWebView, + webViewConfiguration: const WebViewConfiguration( + enableDomStorage: false, + ), + ), + isTrue, + ); }); test('in-app webview with headers', () async { @@ -247,18 +259,25 @@ void main() { ) ..setResponse(true); expect( - await launchUrl(url, - mode: LaunchMode.inAppWebView, - webViewConfiguration: const WebViewConfiguration( - headers: {'key': 'value'})), - isTrue); + await launchUrl( + url, + mode: LaunchMode.inAppWebView, + webViewConfiguration: const WebViewConfiguration( + headers: {'key': 'value'}, + ), + ), + isTrue, + ); }); test('cannot launch a non-web URL in a webview', () async { expect( - () async => launchUrl(Uri(scheme: 'tel', path: '555-555-5555'), - mode: LaunchMode.inAppWebView), - throwsA(isA())); + () async => launchUrl( + Uri(scheme: 'tel', path: '555-555-5555'), + mode: LaunchMode.inAppWebView, + ), + throwsA(isA()), + ); }); test('non-web URL with default options', () async { @@ -304,7 +323,9 @@ void main() { mock.setResponse(true); expect( - await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), true); + await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), + true, + ); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); @@ -312,7 +333,9 @@ void main() { mock.setResponse(false); expect( - await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), false); + await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), + false, + ); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); }); diff --git a/packages/url_launcher/url_launcher_android/CHANGELOG.md b/packages/url_launcher/url_launcher_android/CHANGELOG.md index a50df37cc02..aed3b6e9d8b 100644 --- a/packages/url_launcher/url_launcher_android/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 6.3.17 * Updates kotlin version to 2.2.0 to enable gradle 8.11 support. diff --git a/packages/url_launcher/url_launcher_android/example/integration_test/url_launcher_test.dart b/packages/url_launcher/url_launcher_android/example/integration_test/url_launcher_test.dart index 7aa221b3e1a..001079f1984 100644 --- a/packages/url_launcher/url_launcher_android/example/integration_test/url_launcher_test.dart +++ b/packages/url_launcher/url_launcher_android/example/integration_test/url_launcher_test.dart @@ -29,28 +29,33 @@ void main() { // Setup fake http server. final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0); - unawaited(server.forEach((HttpRequest request) { - if (request.uri.path == '/hello.txt') { - request.response.writeln('Hello, world.'); - } else { - fail('unexpected request: ${request.method} ${request.uri}'); - } - request.response.close(); - })); + unawaited( + server.forEach((HttpRequest request) { + if (request.uri.path == '/hello.txt') { + request.response.writeln('Hello, world.'); + } else { + fail('unexpected request: ${request.method} ${request.uri}'); + } + request.response.close(); + }), + ); // Https to avoid cleartext warning on android. final String prefixUrl = 'https://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; // Launch a url then close. expect( - await launcher.launch(primaryUrl, - useSafariVC: true, - useWebView: true, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: {}), - true); + await launcher.launch( + primaryUrl, + useSafariVC: true, + useWebView: true, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: {}, + ), + true, + ); await launcher.closeWebView(); // Delay required to catch android side crashes in onDestroy. // diff --git a/packages/url_launcher/url_launcher_android/example/lib/main.dart b/packages/url_launcher/url_launcher_android/example/lib/main.dart index 36c32f2ba2b..5fca7946a83 100644 --- a/packages/url_launcher/url_launcher_android/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_android/example/lib/main.dart @@ -20,9 +20,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'URL Launcher'), ); } @@ -53,9 +51,9 @@ class _MyHomePageState extends State { }); }); // Check for Android Custom Tab support. - launcher - .supportsMode(PreferredLaunchMode.inAppBrowserView) - .then((bool result) { + launcher.supportsMode(PreferredLaunchMode.inAppBrowserView).then(( + bool result, + ) { setState(() { _hasCustomTabSupport = result; }); @@ -93,10 +91,11 @@ class _MyHomePageState extends State { if (!await launcher.launchUrl( url, const LaunchOptions( - mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - headers: {'my_header_key': 'my_header_value'}, - )), + mode: PreferredLaunchMode.inAppWebView, + webViewConfiguration: InAppWebViewConfiguration( + headers: {'my_header_key': 'my_header_value'}, + ), + ), )) { throw Exception('Could not launch $url'); } @@ -106,10 +105,11 @@ class _MyHomePageState extends State { if (!await launcher.launchUrl( url, const LaunchOptions( - mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - enableJavaScript: false, - )), + mode: PreferredLaunchMode.inAppWebView, + webViewConfiguration: InAppWebViewConfiguration( + enableJavaScript: false, + ), + ), )) { throw Exception('Could not launch $url'); } @@ -119,10 +119,11 @@ class _MyHomePageState extends State { if (!await launcher.launchUrl( url, const LaunchOptions( - mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - enableDomStorage: false, - )), + mode: PreferredLaunchMode.inAppWebView, + webViewConfiguration: InAppWebViewConfiguration( + enableDomStorage: false, + ), + ), )) { throw Exception('Could not launch $url'); } @@ -139,10 +140,7 @@ class _MyHomePageState extends State { Future _makePhoneCall(String phoneNumber) async { // Use `Uri` to ensure that `phoneNumber` is properly URL-encoded. // Just using 'tel:$phoneNumber' would create invalid URLs in some cases. - final Uri launchUri = Uri( - scheme: 'tel', - path: phoneNumber, - ); + final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber); await launcher.launchUrl(launchUri.toString(), const LaunchOptions()); } @@ -152,9 +150,7 @@ class _MyHomePageState extends State { // because the assumption is that every device can launch a web URL. const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: ListView( children: [ Column( @@ -163,72 +159,83 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: TextField( - onChanged: (String text) => _phone = text, - decoration: const InputDecoration( - hintText: 'Input the phone number to launch')), + onChanged: (String text) => _phone = text, + decoration: const InputDecoration( + hintText: 'Input the phone number to launch', + ), + ), ), ElevatedButton( - onPressed: _hasCallSupport - ? () => setState(() { + onPressed: + _hasCallSupport + ? () => setState(() { _launched = _makePhoneCall(_phone); }) - : null, - child: _hasCallSupport - ? const Text('Make phone call') - : const Text('Calling not supported'), + : null, + child: + _hasCallSupport + ? const Text('Make phone call') + : const Text('Calling not supported'), ), const Padding( padding: EdgeInsets.all(16.0), child: Text(toLaunch), ), ElevatedButton( - onPressed: _hasCustomTabSupport - ? () => setState(() { + onPressed: + _hasCustomTabSupport + ? () => setState(() { _launched = _launchInBrowser(toLaunch); }) - : null, + : null, child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInCustomTab(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInCustomTab(toLaunch); + }), child: const Text('Launch in Android Custom Tab'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebView(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebView(toLaunch); + }), child: const Text('Launch in web view'), ), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewWithCustomHeaders(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewWithCustomHeaders(toLaunch); + }), child: const Text('Launch in web view (Custom headers)'), ), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewWithoutJavaScript(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewWithoutJavaScript(toLaunch); + }), child: const Text('Launch in web view (JavaScript OFF)'), ), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewWithoutDomStorage(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewWithoutDomStorage(toLaunch); + }), child: const Text('Launch in web view (DOM storage OFF)'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebView(toLaunch); - Timer(const Duration(seconds: 5), () { - launcher.closeWebView(); - }); - }), + onPressed: + () => setState(() { + _launched = _launchInWebView(toLaunch); + Timer(const Duration(seconds: 5), () { + launcher.closeWebView(); + }); + }), child: const Text('Launch in web view + close after 5 seconds'), ), const Padding(padding: EdgeInsets.all(16.0)), diff --git a/packages/url_launcher/url_launcher_android/example/pubspec.yaml b/packages/url_launcher/url_launcher_android/example/pubspec.yaml index d92f0ac183c..4649b5f34a0 100644 --- a/packages/url_launcher/url_launcher_android/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart index af74878f86c..b213ddd84a4 100644 --- a/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart @@ -33,11 +33,7 @@ class WebViewOptions { Map headers; Object encode() { - return [ - enableJavaScript, - enableDomStorage, - headers, - ]; + return [enableJavaScript, enableDomStorage, headers]; } static WebViewOptions decode(Object result) { @@ -52,24 +48,18 @@ class WebViewOptions { /// Configuration options for in-app browser views. class BrowserOptions { - BrowserOptions({ - required this.showTitle, - }); + BrowserOptions({required this.showTitle}); /// Whether or not to show the webpage title. bool showTitle; Object encode() { - return [ - showTitle, - ]; + return [showTitle]; } static BrowserOptions decode(Object result) { result as List; - return BrowserOptions( - showTitle: result[0]! as bool, - ); + return BrowserOptions(showTitle: result[0]! as bool); } } @@ -108,11 +98,12 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + UrlLauncherApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -125,10 +116,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([url]) as List?; if (pigeonVar_replyList == null) { @@ -155,10 +146,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([url, headers]) as List?; if (pigeonVar_replyList == null) { @@ -181,19 +172,28 @@ class UrlLauncherApi { /// Opens the URL in an in-app Custom Tab or WebView, returning true if it /// opens successfully. - Future openUrlInApp(String url, bool allowCustomTab, - WebViewOptions webViewOptions, BrowserOptions browserOptions) async { + Future openUrlInApp( + String url, + bool allowCustomTab, + WebViewOptions webViewOptions, + BrowserOptions browserOptions, + ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.openUrlInApp$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel.send( - [url, allowCustomTab, webViewOptions, browserOptions]) - as List?; + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([ + url, + allowCustomTab, + webViewOptions, + browserOptions, + ]) + as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -217,10 +217,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.supportsCustomTabs$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { @@ -247,10 +247,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.closeWebView$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { diff --git a/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart b/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart index 7a447d5203f..d2dc3ca0068 100644 --- a/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart +++ b/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart @@ -12,9 +12,8 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for Android. class UrlLauncherAndroid extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherAndroid({ - @visibleForTesting UrlLauncherApi? api, - }) : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherAndroid({@visibleForTesting UrlLauncherApi? api}) + : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; @@ -61,15 +60,19 @@ class UrlLauncherAndroid extends UrlLauncherPlatform { String? webOnlyWindowName, }) async { return launchUrl( - url, - LaunchOptions( - mode: useWebView + url, + LaunchOptions( + mode: + useWebView ? PreferredLaunchMode.inAppWebView : PreferredLaunchMode.externalApplication, - webViewConfiguration: InAppWebViewConfiguration( - enableDomStorage: enableDomStorage, - enableJavaScript: enableJavaScript, - headers: headers))); + webViewConfiguration: InAppWebViewConfiguration( + enableDomStorage: enableDomStorage, + enableJavaScript: enableJavaScript, + headers: headers, + ), + ), + ); } @override @@ -106,13 +109,13 @@ class UrlLauncherAndroid extends UrlLauncherPlatform { enableDomStorage: options.webViewConfiguration.enableDomStorage, headers: options.webViewConfiguration.headers, ), - BrowserOptions( - showTitle: options.browserConfiguration.showTitle, - ), + BrowserOptions(showTitle: options.browserConfiguration.showTitle), ); } else { - succeeded = - await _hostApi.launchUrl(url, options.webViewConfiguration.headers); + succeeded = await _hostApi.launchUrl( + url, + options.webViewConfiguration.headers, + ); } // TODO(stuartmorgan): Remove this special handling as part of a @@ -120,8 +123,9 @@ class UrlLauncherAndroid extends UrlLauncherPlatform { // current behavior is backwards compatible with the previous Java error. if (!succeeded) { throw PlatformException( - code: 'ACTIVITY_NOT_FOUND', - message: 'No Activity found to handle intent { $url }'); + code: 'ACTIVITY_NOT_FOUND', + message: 'No Activity found to handle intent { $url }', + ); } return succeeded; diff --git a/packages/url_launcher/url_launcher_android/pigeons/messages.dart b/packages/url_launcher/url_launcher_android/pigeons/messages.dart index f3a3795339d..1d206c4815f 100644 --- a/packages/url_launcher/url_launcher_android/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_android/pigeons/messages.dart @@ -4,13 +4,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - javaOptions: JavaOptions(package: 'io.flutter.plugins.urllauncher'), - javaOut: 'android/src/main/java/io/flutter/plugins/urllauncher/Messages.java', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + javaOptions: JavaOptions(package: 'io.flutter.plugins.urllauncher'), + javaOut: + 'android/src/main/java/io/flutter/plugins/urllauncher/Messages.java', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Configuration options for an in-app WebView. class WebViewOptions { const WebViewOptions({ diff --git a/packages/url_launcher/url_launcher_android/pubspec.yaml b/packages/url_launcher/url_launcher_android/pubspec.yaml index 4adcf28d196..f5c48e3c352 100644 --- a/packages/url_launcher/url_launcher_android/pubspec.yaml +++ b/packages/url_launcher/url_launcher_android/pubspec.yaml @@ -4,8 +4,8 @@ repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22 version: 6.3.17 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart b/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart index 63745ec74cb..3dba890bfe3 100644 --- a/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart +++ b/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart @@ -37,16 +37,18 @@ void main() { test('checks a generic URL if an http URL returns false', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); - final bool canLaunch = await launcher - .canLaunch('http://${_FakeUrlLauncherApi.specialHandlerDomain}'); + final bool canLaunch = await launcher.canLaunch( + 'http://${_FakeUrlLauncherApi.specialHandlerDomain}', + ); expect(canLaunch, true); }); test('checks a generic URL if an https URL returns false', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); - final bool canLaunch = await launcher - .canLaunch('https://${_FakeUrlLauncherApi.specialHandlerDomain}'); + final bool canLaunch = await launcher.canLaunch( + 'https://${_FakeUrlLauncherApi.specialHandlerDomain}', + ); expect(canLaunch, true); }); @@ -88,32 +90,39 @@ void main() { test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launch( - 'https://noactivity', - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - throwsA(isA())); + launcher.launch( + 'https://noactivity', + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA(isA()), + ); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launch( - 'unknown://scheme', - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, + launcher.launch( + 'unknown://scheme', + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'ACTIVITY_NOT_FOUND', ), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); + ), + ); }); }); @@ -172,9 +181,7 @@ void main() { await launcher.launchUrl( 'http://example.com/', const LaunchOptions( - browserConfiguration: InAppBrowserConfiguration( - showTitle: true, - ), + browserConfiguration: InAppBrowserConfiguration(showTitle: true), ), ); @@ -184,32 +191,39 @@ void main() { test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launch( - 'https://noactivity', - useSafariVC: false, - useWebView: true, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - throwsA(isA())); + launcher.launch( + 'https://noactivity', + useSafariVC: false, + useWebView: true, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA(isA()), + ); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launch( - 'unknown://scheme', - useSafariVC: false, - useWebView: true, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, + launcher.launch( + 'unknown://scheme', + useSafariVC: false, + useWebView: true, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'ACTIVITY_NOT_FOUND', ), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); + ), + ); }); }); @@ -230,9 +244,11 @@ void main() { await launcher.launchUrl( 'http://example.com/', const LaunchOptions( - mode: PreferredLaunchMode.externalApplication, - webViewConfiguration: InAppWebViewConfiguration( - headers: {'key': 'value'})), + mode: PreferredLaunchMode.externalApplication, + webViewConfiguration: InAppWebViewConfiguration( + headers: {'key': 'value'}, + ), + ), ); expect(api.passedWebViewOptions?.headers.length, 1); expect(api.passedWebViewOptions?.headers['key'], 'value'); @@ -241,24 +257,33 @@ void main() { test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launchUrl('https://noactivity', const LaunchOptions()), - throwsA(isA())); + launcher.launchUrl('https://noactivity', const LaunchOptions()), + throwsA(isA()), + ); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launchUrl('unknown://scheme', const LaunchOptions()), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); + launcher.launchUrl('unknown://scheme', const LaunchOptions()), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'ACTIVITY_NOT_FOUND', + ), + ), + ); }); }); group('launch with webview', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); - final bool launched = await launcher.launchUrl('http://example.com/', - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)); + final bool launched = await launcher.launchUrl( + 'http://example.com/', + const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), + ); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, false); @@ -270,11 +295,14 @@ void main() { test('passes enableJavaScript to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( - 'http://example.com/', - const LaunchOptions( - mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: - InAppWebViewConfiguration(enableJavaScript: false))); + 'http://example.com/', + const LaunchOptions( + mode: PreferredLaunchMode.inAppWebView, + webViewConfiguration: InAppWebViewConfiguration( + enableJavaScript: false, + ), + ), + ); expect(api.passedWebViewOptions?.enableJavaScript, false); }); @@ -282,11 +310,14 @@ void main() { test('passes enableDomStorage to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( - 'http://example.com/', - const LaunchOptions( - mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: - InAppWebViewConfiguration(enableDomStorage: false))); + 'http://example.com/', + const LaunchOptions( + mode: PreferredLaunchMode.inAppWebView, + webViewConfiguration: InAppWebViewConfiguration( + enableDomStorage: false, + ), + ), + ); expect(api.passedWebViewOptions?.enableDomStorage, false); }); @@ -294,26 +325,39 @@ void main() { test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launchUrl('https://noactivity', - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), - throwsA(isA())); + launcher.launchUrl( + 'https://noactivity', + const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), + ), + throwsA(isA()), + ); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( - launcher.launchUrl('unknown://scheme', - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); + launcher.launchUrl( + 'unknown://scheme', + const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'ACTIVITY_NOT_FOUND', + ), + ), + ); }); }); group('launch with custom tab', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); - final bool launched = await launcher.launchUrl('http://example.com/', - const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView)); + final bool launched = await launcher.launchUrl( + 'http://example.com/', + const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView), + ); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); @@ -324,7 +368,9 @@ void main() { test('uses custom tabs for http', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( - 'http://example.com/', const LaunchOptions()); + 'http://example.com/', + const LaunchOptions(), + ); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); @@ -333,7 +379,9 @@ void main() { test('uses custom tabs for https', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( - 'https://example.com/', const LaunchOptions()); + 'https://example.com/', + const LaunchOptions(), + ); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); @@ -342,7 +390,9 @@ void main() { test('uses external for other schemes', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( - 'supportedcustomscheme://example.com/', const LaunchOptions()); + 'supportedcustomscheme://example.com/', + const LaunchOptions(), + ); expect(launched, true); expect(api.usedWebView, false); }); @@ -351,35 +401,44 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); - expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.platformDefault), + true, + ); }); test('returns true for external application', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true); + await launcher.supportsMode(PreferredLaunchMode.externalApplication), + true, + ); }); test('returns true for in app web view', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), true); + await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + true, + ); }); test('returns true for in app browser view when available', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); api.hasCustomTabSupport = true; - expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + true, + ); }); test('returns false for in app browser view when not available', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); api.hasCustomTabSupport = false; - expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + false, + ); }); }); @@ -387,24 +446,31 @@ void main() { test('returns true for in app web view', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), - true); + await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), + true, + ); }); test('returns false for other modes', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.externalApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalApplication, + ), + false, + ); expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalNonBrowserApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.inAppBrowserView, + ), + false, + ); }); }); } diff --git a/packages/url_launcher/url_launcher_ios/CHANGELOG.md b/packages/url_launcher/url_launcher_ios/CHANGELOG.md index b2c1a45be5d..7089a936fb7 100644 --- a/packages/url_launcher/url_launcher_ios/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_ios/CHANGELOG.md @@ -1,5 +1,6 @@ ## NEXT +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. * Fixes integration test button text matcher to work on iOS 26. ## 6.3.4 diff --git a/packages/url_launcher/url_launcher_ios/example/lib/main.dart b/packages/url_launcher/url_launcher_ios/example/lib/main.dart index f01624ff87c..6a688670da0 100644 --- a/packages/url_launcher/url_launcher_ios/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_ios/example/lib/main.dart @@ -20,9 +20,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'URL Launcher'), ); } @@ -163,9 +161,7 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: ListView( children: [ Column( @@ -174,14 +170,17 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: TextField( - onChanged: (String text) => _phone = text, - decoration: const InputDecoration( - hintText: 'Input the phone number to launch')), + onChanged: (String text) => _phone = text, + decoration: const InputDecoration( + hintText: 'Input the phone number to launch', + ), + ), ), ElevatedButton( - onPressed: () => setState(() { - _launched = _makePhoneCall('tel:$_phone'); - }), + onPressed: + () => setState(() { + _launched = _makePhoneCall('tel:$_phone'); + }), child: const Text('Make phone call'), ), const Padding( @@ -189,46 +188,53 @@ 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)), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewOrVC(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewOrVC(toLaunch); + }), child: const Text('Launch in app'), ), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewWithJavaScript(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewWithJavaScript(toLaunch); + }), child: const Text('Launch in app(JavaScript ON)'), ), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewWithDomStorage(toLaunch); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewWithDomStorage(toLaunch); + }), child: const Text('Launch in app(DOM storage ON)'), ), 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)'), + 'Launch a universal link in a native app, fallback to Safari.(Youtube)', + ), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: () => setState(() { - _launched = _launchInWebViewOrVC(toLaunch); - Timer(const Duration(seconds: 5), () { - UrlLauncherPlatform.instance.closeWebView(); - }); - }), + onPressed: + () => setState(() { + _launched = _launchInWebViewOrVC(toLaunch); + Timer(const Duration(seconds: 5), () { + UrlLauncherPlatform.instance.closeWebView(); + }); + }), child: const Text('Launch in app + close after 5 seconds'), ), const Padding(padding: EdgeInsets.all(16.0)), diff --git a/packages/url_launcher/url_launcher_ios/example/pubspec.yaml b/packages/url_launcher/url_launcher_ios/example/pubspec.yaml index fd1d1b1e10e..1cf8214ff94 100644 --- a/packages/url_launcher/url_launcher_ios/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher_ios/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart index 84f98317347..fea704bfe70 100644 --- a/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart @@ -82,11 +82,12 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + UrlLauncherApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -99,12 +100,13 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([url]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -131,12 +133,13 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url, universalLinksOnly], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([url, universalLinksOnly]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -164,12 +167,13 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.openUrlInSafariViewController$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([url]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -196,10 +200,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.closeSafariViewController$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; diff --git a/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart b/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart index 27f48681d85..7118d19576a 100644 --- a/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart +++ b/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart @@ -12,9 +12,8 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for iOS. class UrlLauncherIOS extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherIOS({ - @visibleForTesting UrlLauncherApi? api, - }) : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherIOS({@visibleForTesting UrlLauncherApi? api}) + : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; @@ -57,13 +56,16 @@ class UrlLauncherIOS extends UrlLauncherPlatform { mode = PreferredLaunchMode.externalApplication; } return launchUrl( - url, - LaunchOptions( - mode: mode, - webViewConfiguration: InAppWebViewConfiguration( - enableDomStorage: enableDomStorage, - enableJavaScript: enableJavaScript, - headers: headers))); + url, + LaunchOptions( + mode: mode, + webViewConfiguration: InAppWebViewConfiguration( + enableDomStorage: enableDomStorage, + enableJavaScript: enableJavaScript, + headers: headers, + ), + ), + ); } @override @@ -90,11 +92,16 @@ class UrlLauncherIOS extends UrlLauncherPlatform { if (inApp) { return _mapInAppLoadResult( - await _hostApi.openUrlInSafariViewController(url), - url: url); + await _hostApi.openUrlInSafariViewController(url), + url: url, + ); } else { - return _mapLaunchResult(await _hostApi.launchUrl(url, - options.mode == PreferredLaunchMode.externalNonBrowserApplication)); + return _mapLaunchResult( + await _hostApi.launchUrl( + url, + options.mode == PreferredLaunchMode.externalNonBrowserApplication, + ), + ); } } diff --git a/packages/url_launcher/url_launcher_ios/pigeons/messages.dart b/packages/url_launcher/url_launcher_ios/pigeons/messages.dart index 998970c0ca5..b4ee01c7fc4 100644 --- a/packages/url_launcher/url_launcher_ios/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_ios/pigeons/messages.dart @@ -4,12 +4,13 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - swiftOut: 'ios/url_launcher_ios/Sources/url_launcher_ios/messages.g.swift', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + swiftOut: 'ios/url_launcher_ios/Sources/url_launcher_ios/messages.g.swift', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Possible outcomes of launching a URL. enum LaunchResult { /// The URL was successfully launched (or could be, for `canLaunchUrl`). diff --git a/packages/url_launcher/url_launcher_ios/pubspec.yaml b/packages/url_launcher/url_launcher_ios/pubspec.yaml index b01543bfbb8..55a7057d8e7 100644 --- a/packages/url_launcher/url_launcher_ios/pubspec.yaml +++ b/packages/url_launcher/url_launcher_ios/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 6.3.4 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart index 195db630294..40764e83660 100644 --- a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart +++ b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart @@ -30,136 +30,162 @@ void main() { group('canLaunch', () { test('handles success', () async { - when(api.canLaunchUrl(_webUrl)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.canLaunchUrl(_webUrl), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect(await launcher.canLaunch(_webUrl), true); }); test('handles failure', () async { - when(api.canLaunchUrl(_webUrl)) - .thenAnswer((_) async => LaunchResult.failure); + when( + api.canLaunchUrl(_webUrl), + ).thenAnswer((_) async => LaunchResult.failure); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect(await launcher.canLaunch(_webUrl), false); }); test('throws PlatformException for invalid URL', () async { - when(api.canLaunchUrl(_webUrl)) - .thenAnswer((_) async => LaunchResult.invalidUrl); + when( + api.canLaunchUrl(_webUrl), + ).thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.canLaunch(_webUrl), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'argument_error'))); + launcher.canLaunch(_webUrl), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'argument_error', + ), + ), + ); }); }); group('legacy launch', () { test('handles success', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.launch( - _webUrl, - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - true); + await launcher.launch( + _webUrl, + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + true, + ); verifyNever(api.openUrlInSafariViewController(any)); }); test('handles failure', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.failure); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.failure); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.launch( - _webUrl, - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - false); + await launcher.launch( + _webUrl, + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + false, + ); verifyNever(api.openUrlInSafariViewController(any)); }); test('throws PlatformException for invalid URL', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.invalidUrl); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launch( - _webUrl, - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, + launcher.launch( + _webUrl, + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'argument_error', ), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'argument_error'))); + ), + ); }); test('force SafariVC is handled', () async { - when(api.openUrlInSafariViewController(_webUrl)) - .thenAnswer((_) async => InAppLoadResult.success); + when( + api.openUrlInSafariViewController(_webUrl), + ).thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.launch( - _webUrl, - useSafariVC: true, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - true); + await launcher.launch( + _webUrl, + useSafariVC: true, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + true, + ); verifyNever(api.launchUrl(any, any)); }); test('universal links only is handled', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.launch( - _webUrl, - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: true, - headers: const {}, - ), - true); + await launcher.launch( + _webUrl, + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: true, + headers: const {}, + ), + true, + ); verifyNever(api.openUrlInSafariViewController(any)); }); test('disallowing SafariVC is handled', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.launch( - _webUrl, - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - true); + await launcher.launch( + _webUrl, + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + true, + ); verifyNever(api.openUrlInSafariViewController(any)); }); }); @@ -172,8 +198,9 @@ void main() { group('launch without webview', () { test('calls through', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, @@ -184,121 +211,172 @@ void main() { }); test('throws PlatformException for invalid URL', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.invalidUrl); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl( - _webUrl, - const LaunchOptions(mode: PreferredLaunchMode.externalApplication), + launcher.launchUrl( + _webUrl, + const LaunchOptions(mode: PreferredLaunchMode.externalApplication), + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'argument_error', ), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'argument_error'))); + ), + ); }); }); group('launch with Safari view controller', () { test('calls through with inAppWebView', () async { - when(api.openUrlInSafariViewController(_webUrl)) - .thenAnswer((_) async => InAppLoadResult.success); + when( + api.openUrlInSafariViewController(_webUrl), + ).thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( - _webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)); + _webUrl, + const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), + ); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('calls through with inAppBrowserView', () async { - when(api.openUrlInSafariViewController(_webUrl)) - .thenAnswer((_) async => InAppLoadResult.success); + when( + api.openUrlInSafariViewController(_webUrl), + ).thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); - final bool launched = await launcher.launchUrl(_webUrl, - const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView)); + final bool launched = await launcher.launchUrl( + _webUrl, + const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView), + ); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('throws PlatformException for invalid URL', () async { - when(api.openUrlInSafariViewController(_webUrl)) - .thenAnswer((_) async => InAppLoadResult.invalidUrl); + when( + api.openUrlInSafariViewController(_webUrl), + ).thenAnswer((_) async => InAppLoadResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl(_webUrl, - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'argument_error'))); + launcher.launchUrl( + _webUrl, + const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'argument_error', + ), + ), + ); }); test('throws PlatformException for load failure', () async { - when(api.openUrlInSafariViewController(_webUrl)) - .thenAnswer((_) async => InAppLoadResult.failedToLoad); + when( + api.openUrlInSafariViewController(_webUrl), + ).thenAnswer((_) async => InAppLoadResult.failedToLoad); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl(_webUrl, - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), - throwsA(isA() - .having((PlatformException e) => e.code, 'code', 'Error'))); + launcher.launchUrl( + _webUrl, + const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'Error', + ), + ), + ); }); }); group('launch with universal links', () { test('calls through', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication), + mode: PreferredLaunchMode.externalNonBrowserApplication, + ), ); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); test('throws PlatformException for invalid URL', () async { - when(api.launchUrl(_webUrl, any)) - .thenAnswer((_) async => LaunchResult.invalidUrl); + when( + api.launchUrl(_webUrl, any), + ).thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl( - _webUrl, - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication)), - throwsA(isA().having( - (PlatformException e) => e.code, 'code', 'argument_error'))); + launcher.launchUrl( + _webUrl, + const LaunchOptions( + mode: PreferredLaunchMode.externalNonBrowserApplication, + ), + ), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'argument_error', + ), + ), + ); }); }); group('launch with platform default', () { test('uses Safari view controller for http', () async { const String httpUrl = 'http://example.com/'; - when(api.openUrlInSafariViewController(httpUrl)) - .thenAnswer((_) async => InAppLoadResult.success); + when( + api.openUrlInSafariViewController(httpUrl), + ).thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); - final bool launched = - await launcher.launchUrl(httpUrl, const LaunchOptions()); + final bool launched = await launcher.launchUrl( + httpUrl, + const LaunchOptions(), + ); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('uses Safari view controller for https', () async { const String httpsUrl = 'https://example.com/'; - when(api.openUrlInSafariViewController(httpsUrl)) - .thenAnswer((_) async => InAppLoadResult.success); + when( + api.openUrlInSafariViewController(httpsUrl), + ).thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); - final bool launched = - await launcher.launchUrl(httpsUrl, const LaunchOptions()); + final bool launched = await launcher.launchUrl( + httpsUrl, + const LaunchOptions(), + ); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('uses standard external for other schemes', () async { const String nonWebUrl = 'supportedcustomscheme://example.com/'; - when(api.launchUrl(nonWebUrl, any)) - .thenAnswer((_) async => LaunchResult.success); + when( + api.launchUrl(nonWebUrl, any), + ).thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); - final bool launched = - await launcher.launchUrl(nonWebUrl, const LaunchOptions()); + final bool launched = await launcher.launchUrl( + nonWebUrl, + const LaunchOptions(), + ); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); @@ -307,35 +385,44 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); - expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.platformDefault), + true, + ); }); test('returns true for external application', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true); + await launcher.supportsMode(PreferredLaunchMode.externalApplication), + true, + ); }); test('returns true for external non-browser application', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher - .supportsMode(PreferredLaunchMode.externalNonBrowserApplication), - true); + await launcher.supportsMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + true, + ); }); test('returns true for in app web view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), true); + await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + true, + ); }); test('returns true for in app browser view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); - expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + true, + ); }); }); @@ -343,28 +430,35 @@ void main() { test('returns true for in app web view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), - true); + await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), + true, + ); }); test('returns true for in app browser view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), - true); + await launcher.supportsCloseForMode( + PreferredLaunchMode.inAppBrowserView, + ), + true, + ); }); test('returns false for other modes', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.externalApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalApplication, + ), + false, + ); expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalNonBrowserApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); }); }); } diff --git a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart index ce90785fdec..d3aa97bb6df 100644 --- a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart +++ b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart @@ -31,23 +31,25 @@ class MockUrlLauncherApi extends _i1.Mock implements _i2.UrlLauncherApi { } @override - String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) as String); + String get pigeonVar_messageChannelSuffix => + (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) + as String); @override - _i4.Future<_i2.LaunchResult> canLaunchUrl(String? url) => (super.noSuchMethod( - Invocation.method( - #canLaunchUrl, - [url], - ), - returnValue: - _i4.Future<_i2.LaunchResult>.value(_i2.LaunchResult.success), - ) as _i4.Future<_i2.LaunchResult>); + _i4.Future<_i2.LaunchResult> canLaunchUrl(String? url) => + (super.noSuchMethod( + Invocation.method(#canLaunchUrl, [url]), + returnValue: _i4.Future<_i2.LaunchResult>.value( + _i2.LaunchResult.success, + ), + ) + as _i4.Future<_i2.LaunchResult>); @override _i4.Future<_i2.LaunchResult> launchUrl( @@ -55,35 +57,29 @@ class MockUrlLauncherApi extends _i1.Mock implements _i2.UrlLauncherApi { bool? universalLinksOnly, ) => (super.noSuchMethod( - Invocation.method( - #launchUrl, - [ - url, - universalLinksOnly, - ], - ), - returnValue: - _i4.Future<_i2.LaunchResult>.value(_i2.LaunchResult.success), - ) as _i4.Future<_i2.LaunchResult>); + Invocation.method(#launchUrl, [url, universalLinksOnly]), + returnValue: _i4.Future<_i2.LaunchResult>.value( + _i2.LaunchResult.success, + ), + ) + as _i4.Future<_i2.LaunchResult>); @override _i4.Future<_i2.InAppLoadResult> openUrlInSafariViewController(String? url) => (super.noSuchMethod( - Invocation.method( - #openUrlInSafariViewController, - [url], - ), - returnValue: - _i4.Future<_i2.InAppLoadResult>.value(_i2.InAppLoadResult.success), - ) as _i4.Future<_i2.InAppLoadResult>); + Invocation.method(#openUrlInSafariViewController, [url]), + returnValue: _i4.Future<_i2.InAppLoadResult>.value( + _i2.InAppLoadResult.success, + ), + ) + as _i4.Future<_i2.InAppLoadResult>); @override - _i4.Future closeSafariViewController() => (super.noSuchMethod( - Invocation.method( - #closeSafariViewController, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future closeSafariViewController() => + (super.noSuchMethod( + Invocation.method(#closeSafariViewController, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/url_launcher/url_launcher_linux/CHANGELOG.md b/packages/url_launcher/url_launcher_linux/CHANGELOG.md index 70b1bf37d1e..45b0a2c1dca 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 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 739d09d00c4..432569a6676 100644 --- a/packages/url_launcher/url_launcher_linux/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_linux/example/lib/main.dart @@ -19,9 +19,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'URL Launcher'), ); } @@ -66,9 +64,7 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: ListView( children: [ Column( @@ -79,9 +75,10 @@ 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 7ffb1e15972..264b77c645e 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 19800b1cc21..f52c3ccd026 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 @@ -43,11 +43,12 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + UrlLauncherApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -60,10 +61,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_linux.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([url]) as List?; if (pigeonVar_replyList == null) { @@ -90,10 +91,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_linux.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([url]) as List?; if (pigeonVar_replyList == null) { diff --git a/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart b/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart index b5c85043927..2e98b9ebfa8 100644 --- a/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart +++ b/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart @@ -15,7 +15,7 @@ import 'src/messages.g.dart'; class UrlLauncherLinux extends UrlLauncherPlatform { /// Creates a new URL launcher instance. UrlLauncherLinux({@visibleForTesting UrlLauncherApi? api}) - : _hostApi = api ?? UrlLauncherApi(); + : _hostApi = api ?? UrlLauncherApi(); /// Registers this class as the default instance of [UrlLauncherPlatform]. static void registerWith() { @@ -56,7 +56,9 @@ class UrlLauncherLinux extends UrlLauncherPlatform { // instead of using PlatformException. This preserves the pre-Pigeon // behavior of the C code returning this error response. throw PlatformException( - code: 'Launch Error', message: 'Failed to launch URL: $error'); + code: 'Launch Error', + message: 'Failed to launch URL: $error', + ); } return true; } diff --git a/packages/url_launcher/url_launcher_linux/pigeons/messages.dart b/packages/url_launcher/url_launcher_linux/pigeons/messages.dart index 56d30d75833..2064fea02f6 100644 --- a/packages/url_launcher/url_launcher_linux/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_linux/pigeons/messages.dart @@ -4,13 +4,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - gobjectHeaderOut: 'linux/messages.g.h', - gobjectSourceOut: 'linux/messages.g.cc', - gobjectOptions: GObjectOptions(module: 'Ful'), - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + gobjectHeaderOut: 'linux/messages.g.h', + gobjectSourceOut: 'linux/messages.g.cc', + gobjectOptions: GObjectOptions(module: 'Ful'), + copyrightHeader: 'pigeons/copyright.txt', + ), +) @HostApi() abstract class UrlLauncherApi { /// Returns true if the URL can definitely be launched. diff --git a/packages/url_launcher/url_launcher_linux/pubspec.yaml b/packages/url_launcher/url_launcher_linux/pubspec.yaml index 2d7e109b8d7..c4bc2bca850 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart b/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart index 7b9bba40a58..7d7d3343064 100644 --- a/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart +++ b/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart @@ -57,19 +57,25 @@ void main() { final UrlLauncherLinux launcher = UrlLauncherLinux(api: api); await expectLater( - launcher.launch( - 'http://example.com/', - useSafariVC: true, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - throwsA(isA() + launcher.launch( + 'http://example.com/', + useSafariVC: true, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'Launch Error') - .having((PlatformException e) => e.message, 'message', - contains('Failed to launch URL: An error')))); + .having( + (PlatformException e) => e.message, + 'message', + contains('Failed to launch URL: An error'), + ), + ), + ); }); group('launchUrl', () { @@ -78,8 +84,10 @@ void main() { final UrlLauncherLinux launcher = UrlLauncherLinux(api: api); const String url = 'http://example.com/'; - final bool launched = - await launcher.launchUrl(url, const LaunchOptions()); + final bool launched = await launcher.launchUrl( + url, + const LaunchOptions(), + ); expect(launched, true); expect(api.argument, url); @@ -90,53 +98,70 @@ void main() { final UrlLauncherLinux launcher = UrlLauncherLinux(api: api); await expectLater( - launcher.launchUrl('http://example.com/', const LaunchOptions()), - throwsA(isA() + launcher.launchUrl('http://example.com/', const LaunchOptions()), + throwsA( + isA() .having((PlatformException e) => e.code, 'code', 'Launch Error') - .having((PlatformException e) => e.message, 'message', - contains('Failed to launch URL: An error')))); + .having( + (PlatformException e) => e.message, + 'message', + contains('Failed to launch URL: An error'), + ), + ), + ); }); }); group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); - expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.platformDefault), + true, + ); }); test('returns true for external application', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect( - await launcher - .supportsMode(PreferredLaunchMode.externalApplication), - true); + await launcher.supportsMode(PreferredLaunchMode.externalApplication), + true, + ); }); test('returns false for other modes', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication), - false); + await launcher.supportsMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + false, + ); expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false); - expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), - false); + await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + false, + ); }); }); test('supportsCloseForMode returns false', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.platformDefault), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.platformDefault, + ), + false, + ); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.externalApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalApplication, + ), + false, + ); }); }); } diff --git a/packages/url_launcher/url_launcher_macos/CHANGELOG.md b/packages/url_launcher/url_launcher_macos/CHANGELOG.md index f2c0db11d78..464d47cadbc 100644 --- a/packages/url_launcher/url_launcher_macos/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_macos/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 3.2.3 * Updates to Pigeon 25.5.0. diff --git a/packages/url_launcher/url_launcher_macos/example/lib/main.dart b/packages/url_launcher/url_launcher_macos/example/lib/main.dart index 739d09d00c4..432569a6676 100644 --- a/packages/url_launcher/url_launcher_macos/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_macos/example/lib/main.dart @@ -19,9 +19,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'URL Launcher'), ); } @@ -66,9 +64,7 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: ListView( children: [ Column( @@ -79,9 +75,10 @@ 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_macos/example/pubspec.yaml b/packages/url_launcher/url_launcher_macos/example/pubspec.yaml index 64f6b8b6a14..220483a637f 100644 --- a/packages/url_launcher/url_launcher_macos/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher_macos/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart index 392a393e6c7..b0deb24c65f 100644 --- a/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart @@ -21,14 +21,17 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { return a.length == b.length && - a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } @@ -41,20 +44,14 @@ enum UrlLauncherError { /// Possible results for a [UrlLauncherApi] call with a boolean outcome. class UrlLauncherBoolResult { - UrlLauncherBoolResult({ - required this.value, - this.error, - }); + UrlLauncherBoolResult({required this.value, this.error}); bool value; UrlLauncherError? error; List _toList() { - return [ - value, - error, - ]; + return [value, error]; } Object encode() { @@ -122,11 +119,12 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + UrlLauncherApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -139,12 +137,13 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_macos.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([url]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -171,12 +170,13 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_macos.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([url]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart b/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart index 1d229737c34..3d139f84d8f 100644 --- a/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart +++ b/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart @@ -12,9 +12,8 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for macOS. class UrlLauncherMacOS extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherMacOS({ - @visibleForTesting UrlLauncherApi? api, - }) : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherMacOS({@visibleForTesting UrlLauncherApi? api}) + : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; @@ -75,8 +74,9 @@ class UrlLauncherMacOS extends UrlLauncherPlatform { // return the same thing; currently it throws a PlatformException to // preserve existing behavior. return PlatformException( - code: 'argument_error', - message: 'Unable to parse URL', - details: 'Provided URL: $url'); + code: 'argument_error', + message: 'Unable to parse URL', + details: 'Provided URL: $url', + ); } } diff --git a/packages/url_launcher/url_launcher_macos/pigeons/messages.dart b/packages/url_launcher/url_launcher_macos/pigeons/messages.dart index bd97c681d8e..dcfe4346093 100644 --- a/packages/url_launcher/url_launcher_macos/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_macos/pigeons/messages.dart @@ -4,13 +4,14 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - swiftOut: - 'macos/url_launcher_macos/Sources/url_launcher_macos/messages.g.swift', - copyrightHeader: 'pigeons/copyright.txt', -)) - +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + swiftOut: + 'macos/url_launcher_macos/Sources/url_launcher_macos/messages.g.swift', + copyrightHeader: 'pigeons/copyright.txt', + ), +) /// Possible error conditions for [UrlLauncherApi] calls. enum UrlLauncherError { /// The URL could not be parsed as an NSURL. diff --git a/packages/url_launcher/url_launcher_macos/pubspec.yaml b/packages/url_launcher/url_launcher_macos/pubspec.yaml index d8c42b5d575..ce277ecb890 100644 --- a/packages/url_launcher/url_launcher_macos/pubspec.yaml +++ b/packages/url_launcher/url_launcher_macos/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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart b/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart index eb1c459956a..141b32aa4e6 100644 --- a/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart +++ b/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart @@ -34,14 +34,18 @@ void main() { test('invalid URL returns a PlatformException', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); - await expectLater(launcher.canLaunch('invalid://u r l'), - throwsA(isA())); + await expectLater( + launcher.canLaunch('invalid://u r l'), + throwsA(isA()), + ); }); test('passes unexpected PlatformExceptions through', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); - await expectLater(launcher.canLaunch('unexpectedthrow://someexception'), - throwsA(isA())); + await expectLater( + launcher.canLaunch('unexpectedthrow://someexception'), + throwsA(isA()), + ); }); }); @@ -49,103 +53,118 @@ void main() { test('success', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( - await launcher.launch( - 'http://example.com/', - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - true); + await launcher.launch( + 'http://example.com/', + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + true, + ); }); test('failure', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( - await launcher.launch( - 'unknown://scheme', - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - false); + await launcher.launch( + 'unknown://scheme', + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + false, + ); }); test('invalid URL returns a PlatformException', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); await expectLater( - launcher.launch( - 'invalid://u r l', - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - throwsA(isA())); + launcher.launch( + 'invalid://u r l', + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA(isA()), + ); }); test('passes unexpected PlatformExceptions through', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); await expectLater( - launcher.launch( - 'unexpectedthrow://someexception', - useSafariVC: false, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - throwsA(isA())); + launcher.launch( + 'unexpectedthrow://someexception', + useSafariVC: false, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA(isA()), + ); }); }); group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); - expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.platformDefault), + true, + ); }); test('returns true for external application', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( - await launcher - .supportsMode(PreferredLaunchMode.externalApplication), - true); + await launcher.supportsMode(PreferredLaunchMode.externalApplication), + true, + ); }); test('returns false for other modes', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication), - false); + await launcher.supportsMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + false, + ); expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false); - expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), - false); + await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + false, + ); }); }); test('supportsCloseForMode returns false', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.platformDefault), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.platformDefault, + ), + false, + ); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.externalApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalApplication, + ), + false, + ); }); }); } @@ -172,7 +191,9 @@ class _FakeUrlLauncherApi implements UrlLauncherApi { return UrlLauncherBoolResult(value: true); case 'invalid': return UrlLauncherBoolResult( - value: false, error: UrlLauncherError.invalidUrl); + value: false, + error: UrlLauncherError.invalidUrl, + ); case 'unexpectedthrow': throw PlatformException(code: 'argument_error'); default: diff --git a/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md b/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md index 2151797f614..9f210e84e94 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 2.3.2 diff --git a/packages/url_launcher/url_launcher_platform_interface/lib/link.dart b/packages/url_launcher/url_launcher_platform_interface/lib/link.dart index ef9ca201fcd..c56cca83112 100644 --- a/packages/url_launcher/url_launcher_platform_interface/lib/link.dart +++ b/packages/url_launcher/url_launcher_platform_interface/lib/link.dart @@ -14,10 +14,8 @@ typedef FollowLink = Future Function(); /// Signature for a builder function passed to the [Link] widget to construct /// the widget tree under it. -typedef LinkWidgetBuilder = Widget Function( - BuildContext context, - FollowLink? followLink, -); +typedef LinkWidgetBuilder = + Widget Function(BuildContext context, FollowLink? followLink); /// Signature for a delegate function to build the [Link] widget. typedef LinkDelegate = Widget Function(LinkInfo linkWidget); @@ -43,8 +41,9 @@ class LinkTarget { /// /// iOS, on the other hand, defaults to [self] for web URLs, and [blank] for /// non-web URLs. - static const LinkTarget defaultTarget = - LinkTarget._(debugLabel: 'defaultTarget'); + static const LinkTarget defaultTarget = LinkTarget._( + debugLabel: 'defaultTarget', + ); /// On the web, this opens the link in the same tab where the flutter app is /// running. diff --git a/packages/url_launcher/url_launcher_platform_interface/lib/method_channel_url_launcher.dart b/packages/url_launcher/url_launcher_platform_interface/lib/method_channel_url_launcher.dart index df738046b96..a4873af6d00 100644 --- a/packages/url_launcher/url_launcher_platform_interface/lib/method_channel_url_launcher.dart +++ b/packages/url_launcher/url_launcher_platform_interface/lib/method_channel_url_launcher.dart @@ -18,10 +18,9 @@ class MethodChannelUrlLauncher extends UrlLauncherPlatform { @override Future canLaunch(String url) { - return _channel.invokeMethod( - 'canLaunch', - {'url': url}, - ).then((bool? value) => value ?? false); + return _channel + .invokeMethod('canLaunch', {'url': url}) + .then((bool? value) => value ?? false); } @override @@ -40,17 +39,16 @@ class MethodChannelUrlLauncher extends UrlLauncherPlatform { required Map headers, String? webOnlyWindowName, }) { - return _channel.invokeMethod( - 'launch', - { - 'url': url, - 'useSafariVC': useSafariVC, - 'useWebView': useWebView, - 'enableJavaScript': enableJavaScript, - 'enableDomStorage': enableDomStorage, - 'universalLinksOnly': universalLinksOnly, - 'headers': headers, - }, - ).then((bool? value) => value ?? false); + return _channel + .invokeMethod('launch', { + 'url': url, + 'useSafariVC': useSafariVC, + 'useWebView': useWebView, + 'enableJavaScript': enableJavaScript, + 'enableDomStorage': enableDomStorage, + 'universalLinksOnly': universalLinksOnly, + 'headers': headers, + }) + .then((bool? value) => value ?? false); } } diff --git a/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart b/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart index da7404f98a1..10ff7338582 100644 --- a/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart +++ b/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart @@ -72,7 +72,8 @@ abstract class UrlLauncherPlatform extends PlatformInterface { /// Returns `true` if the given [url] was successfully launched. Future launchUrl(String url, LaunchOptions options) { final bool isWebURL = url.startsWith('http:') || url.startsWith('https:'); - final bool useWebView = options.mode == PreferredLaunchMode.inAppWebView || + final bool useWebView = + options.mode == PreferredLaunchMode.inAppWebView || options.mode == PreferredLaunchMode.inAppBrowserView || (isWebURL && options.mode == PreferredLaunchMode.platformDefault); diff --git a/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml b/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml index 2911735761f..e7a0682b1ee 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart index 9f559e88dcb..978fb2ee1e1 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart @@ -6,23 +6,27 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { - test('LaunchOptions have default InAppBrowserConfiguration when not passed', - () { - expect( - const LaunchOptions().browserConfiguration, - const InAppBrowserConfiguration(), - ); - }); + test( + 'LaunchOptions have default InAppBrowserConfiguration when not passed', + () { + expect( + const LaunchOptions().browserConfiguration, + const InAppBrowserConfiguration(), + ); + }, + ); - test('passing non-default InAppBrowserConfiguration to LaunchOptions works', - () { - const InAppBrowserConfiguration browserConfiguration = - InAppBrowserConfiguration(showTitle: true); + test( + 'passing non-default InAppBrowserConfiguration to LaunchOptions works', + () { + const InAppBrowserConfiguration browserConfiguration = + InAppBrowserConfiguration(showTitle: true); - const LaunchOptions launchOptions = LaunchOptions( - browserConfiguration: browserConfiguration, - ); + const LaunchOptions launchOptions = LaunchOptions( + browserConfiguration: browserConfiguration, + ); - expect(launchOptions.browserConfiguration, browserConfiguration); - }); + expect(launchOptions.browserConfiguration, browserConfiguration); + }, + ); } diff --git a/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart index 09adcbdf49b..ab2ecf0d3c3 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart @@ -12,12 +12,14 @@ import 'package:url_launcher_platform_interface/link.dart'; void main() { testWidgets('Link with Navigator', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: const Placeholder(key: Key('home')), - routes: { - '/a': (BuildContext context) => const Placeholder(key: Key('a')), - }, - )); + await tester.pumpWidget( + MaterialApp( + home: const Placeholder(key: Key('home')), + routes: { + '/a': (BuildContext context) => const Placeholder(key: Key('a')), + }, + ), + ); expect(find.byKey(const Key('home')), findsOneWidget); expect(find.byKey(const Key('a')), findsNothing); await tester.runAsync(() => pushRouteNameToFramework(null, '/a')); @@ -30,10 +32,12 @@ void main() { }); testWidgets('Link with Navigator', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp.router( - routeInformationParser: _RouteInformationParser(), - routerDelegate: _RouteDelegate(), - )); + await tester.pumpWidget( + MaterialApp.router( + routeInformationParser: _RouteInformationParser(), + routerDelegate: _RouteDelegate(), + ), + ); expect(find.byKey(const Key('/')), findsOneWidget); expect(find.byKey(const Key('/a')), findsNothing); await tester.runAsync(() => pushRouteNameToFramework(null, '/a')); @@ -49,7 +53,8 @@ void main() { class _RouteInformationParser extends RouteInformationParser { @override Future parseRouteInformation( - RouteInformation routeInformation) { + RouteInformation routeInformation, + ) { return SynchronousFuture(routeInformation); } diff --git a/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart index 5e9a3817773..cf849a058d0 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart @@ -45,17 +45,18 @@ void main() { }); group('$MethodChannelUrlLauncher', () { - const MethodChannel channel = - MethodChannel('plugins.flutter.io/url_launcher'); + const MethodChannel channel = MethodChannel( + 'plugins.flutter.io/url_launcher', + ); final List log = []; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { - log.add(methodCall); + log.add(methodCall); - // Return null explicitly instead of relying on the implicit null - // returned by the method channel if no return statement is specified. - return null; - }); + // Return null explicitly instead of relying on the implicit null + // returned by the method channel if no return statement is specified. + return null; + }); final MethodChannelUrlLauncher launcher = MethodChannelUrlLauncher(); @@ -65,14 +66,12 @@ void main() { test('canLaunch', () async { await launcher.canLaunch('http://example.com/'); - expect( - log, - [ - isMethodCall('canLaunch', arguments: { - 'url': 'http://example.com/', - }) - ], - ); + expect(log, [ + isMethodCall( + 'canLaunch', + arguments: {'url': 'http://example.com/'}, + ), + ]); }); test('canLaunch should return false if platform returns null', () async { @@ -91,10 +90,10 @@ void main() { universalLinksOnly: false, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': true, 'useWebView': false, @@ -102,9 +101,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch with headers', () async { @@ -117,10 +116,10 @@ void main() { universalLinksOnly: false, headers: const {'key': 'value'}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': true, 'useWebView': false, @@ -128,9 +127,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': {'key': 'value'}, - }) - ], - ); + }, + ), + ]); }); test('launch force SafariVC', () async { @@ -143,10 +142,10 @@ void main() { universalLinksOnly: false, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': true, 'useWebView': false, @@ -154,9 +153,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch universal links only', () async { @@ -169,10 +168,10 @@ void main() { universalLinksOnly: true, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': false, 'useWebView': false, @@ -180,9 +179,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': true, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch force WebView', () async { @@ -195,10 +194,10 @@ void main() { universalLinksOnly: false, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': true, 'useWebView': true, @@ -206,9 +205,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch force WebView enable javascript', () async { @@ -221,10 +220,10 @@ void main() { universalLinksOnly: false, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': true, 'useWebView': true, @@ -232,9 +231,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch force WebView enable DOM storage', () async { @@ -247,10 +246,10 @@ void main() { universalLinksOnly: false, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': true, 'useWebView': true, @@ -258,9 +257,9 @@ void main() { 'enableDomStorage': true, 'universalLinksOnly': false, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch force SafariVC to false', () async { @@ -273,10 +272,10 @@ void main() { universalLinksOnly: false, headers: const {}, ); - expect( - log, - [ - isMethodCall('launch', arguments: { + expect(log, [ + isMethodCall( + 'launch', + arguments: { 'url': 'http://example.com/', 'useSafariVC': false, 'useWebView': false, @@ -284,9 +283,9 @@ void main() { 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': {}, - }) - ], - ); + }, + ), + ]); }); test('launch should return false if platform returns null', () async { @@ -305,10 +304,7 @@ void main() { test('closeWebView default behavior', () async { await launcher.closeWebView(); - expect( - log, - [isMethodCall('closeWebView', arguments: null)], - ); + expect(log, [isMethodCall('closeWebView', arguments: null)]); }); }); } diff --git a/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart index 56920596eb7..1ea933f98ad 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart @@ -44,45 +44,51 @@ class CapturingUrlLauncher extends UrlLauncherPlatform { } void main() { - test('launchUrl calls through to launch with default options for web URL', - () async { - final CapturingUrlLauncher launcher = CapturingUrlLauncher(); - - await launcher.launchUrl('https://flutter.dev', const LaunchOptions()); - - expect(launcher.url, 'https://flutter.dev'); - expect(launcher.useSafariVC, true); - expect(launcher.useWebView, true); - expect(launcher.enableJavaScript, true); - expect(launcher.enableDomStorage, true); - expect(launcher.universalLinksOnly, false); - expect(launcher.headers, isEmpty); - expect(launcher.webOnlyWindowName, null); - }); - - test('launchUrl calls through to launch with default options for non-web URL', - () async { - final CapturingUrlLauncher launcher = CapturingUrlLauncher(); - - await launcher.launchUrl('tel:123456789', const LaunchOptions()); - - expect(launcher.url, 'tel:123456789'); - expect(launcher.useSafariVC, false); - expect(launcher.useWebView, false); - expect(launcher.enableJavaScript, true); - expect(launcher.enableDomStorage, true); - expect(launcher.universalLinksOnly, false); - expect(launcher.headers, isEmpty); - expect(launcher.webOnlyWindowName, null); - }); + test( + 'launchUrl calls through to launch with default options for web URL', + () async { + final CapturingUrlLauncher launcher = CapturingUrlLauncher(); + + await launcher.launchUrl('https://flutter.dev', const LaunchOptions()); + + expect(launcher.url, 'https://flutter.dev'); + expect(launcher.useSafariVC, true); + expect(launcher.useWebView, true); + expect(launcher.enableJavaScript, true); + expect(launcher.enableDomStorage, true); + expect(launcher.universalLinksOnly, false); + expect(launcher.headers, isEmpty); + expect(launcher.webOnlyWindowName, null); + }, + ); + + test( + 'launchUrl calls through to launch with default options for non-web URL', + () async { + final CapturingUrlLauncher launcher = CapturingUrlLauncher(); + + await launcher.launchUrl('tel:123456789', const LaunchOptions()); + + expect(launcher.url, 'tel:123456789'); + expect(launcher.useSafariVC, false); + expect(launcher.useWebView, false); + expect(launcher.enableJavaScript, true); + expect(launcher.enableDomStorage, true); + expect(launcher.universalLinksOnly, false); + expect(launcher.headers, isEmpty); + expect(launcher.webOnlyWindowName, null); + }, + ); test('launchUrl calls through to launch with universal links', () async { final CapturingUrlLauncher launcher = CapturingUrlLauncher(); await launcher.launchUrl( - 'https://flutter.dev', - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication)); + 'https://flutter.dev', + const LaunchOptions( + mode: PreferredLaunchMode.externalNonBrowserApplication, + ), + ); expect(launcher.url, 'https://flutter.dev'); expect(launcher.useSafariVC, false); @@ -94,79 +100,98 @@ void main() { expect(launcher.webOnlyWindowName, null); }); - test('launchUrl calls through to launch with all non-default options', - () async { - final CapturingUrlLauncher launcher = CapturingUrlLauncher(); + test( + 'launchUrl calls through to launch with all non-default options', + () async { + final CapturingUrlLauncher launcher = CapturingUrlLauncher(); - await launcher.launchUrl( + await launcher.launchUrl( 'https://flutter.dev', const LaunchOptions( mode: PreferredLaunchMode.externalApplication, webViewConfiguration: InAppWebViewConfiguration( - enableJavaScript: false, - enableDomStorage: false, - headers: {'foo': 'bar'}), + enableJavaScript: false, + enableDomStorage: false, + headers: {'foo': 'bar'}, + ), webOnlyWindowName: 'a_name', - )); - - expect(launcher.url, 'https://flutter.dev'); - expect(launcher.useSafariVC, false); - expect(launcher.useWebView, false); - expect(launcher.enableJavaScript, false); - expect(launcher.enableDomStorage, false); - expect(launcher.universalLinksOnly, false); - expect(launcher.headers['foo'], 'bar'); - expect(launcher.webOnlyWindowName, 'a_name'); - }); + ), + ); + + expect(launcher.url, 'https://flutter.dev'); + expect(launcher.useSafariVC, false); + expect(launcher.useWebView, false); + expect(launcher.enableJavaScript, false); + expect(launcher.enableDomStorage, false); + expect(launcher.universalLinksOnly, false); + expect(launcher.headers['foo'], 'bar'); + expect(launcher.webOnlyWindowName, 'a_name'); + }, + ); test('supportsMode defaults to true for platform default', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); + await launcher.supportsMode(PreferredLaunchMode.platformDefault), + true, + ); }); test('supportsMode defaults to false for all specific values', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); - expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), - false); expect( - await launcher - .supportsMode(PreferredLaunchMode.externalNonBrowserApplication), - false); - expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false); + await launcher.supportsMode(PreferredLaunchMode.externalApplication), + false, + ); + expect( + await launcher.supportsMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + false, + ); expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); + await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + false, + ); }); test('supportsCloseForMode defaults to true for in-app web views', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), - true); + await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), + true, + ); }); test('supportsCloseForMode defaults to false for all other values', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.externalApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalApplication, + ), + false, + ); expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalNonBrowserApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), - false); + await launcher.supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), + false, + ); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.platformDefault), - false); + await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), + false, + ); }); } diff --git a/packages/url_launcher/url_launcher_web/CHANGELOG.md b/packages/url_launcher/url_launcher_web/CHANGELOG.md index 115414ab252..6c3c1b01071 100644 --- a/packages/url_launcher/url_launcher_web/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_web/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 2.4.1 * Fixes a bug that triggers Links when they are not supposed to. 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 678848b15a4..4f74f4ff1aa 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 @@ -38,19 +38,24 @@ void main() { }); group('Link Widget', () { - testWidgets('creates anchor with correct attributes', - (WidgetTester tester) async { + testWidgets('creates anchor with correct attributes', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('http://foobar/example?q=1'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -60,16 +65,20 @@ void main() { expect(anchor.getAttribute('target'), '_blank'); final Uri uri2 = Uri.parse('http://foobar2/example?q=2'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: WebLinkDelegate(TestLinkInfo( - uri: uri2, - target: LinkTarget.self, - builder: (BuildContext context, FollowLink? followLink) { - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebLinkDelegate( + TestLinkInfo( + uri: uri2, + target: LinkTarget.self, + builder: (BuildContext context, FollowLink? followLink) { + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); await tester.pumpAndSettle(); await tester.pump(); @@ -78,47 +87,57 @@ void main() { expect(anchor.getAttribute('target'), '_self'); final Uri uri3 = Uri.parse('/foobar'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: WebLinkDelegate(TestLinkInfo( - uri: uri3, - target: LinkTarget.self, - builder: (BuildContext context, FollowLink? followLink) { - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebLinkDelegate( + TestLinkInfo( + uri: uri3, + target: LinkTarget.self, + builder: (BuildContext context, FollowLink? followLink) { + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); await tester.pumpAndSettle(); await tester.pump(); // Check that internal route properly prepares using the default // [UrlStrategy] - expect(anchor.getAttribute('href'), - ui_web.urlStrategy?.prepareExternalUrl(uri3.toString())); + expect( + anchor.getAttribute('href'), + ui_web.urlStrategy?.prepareExternalUrl(uri3.toString()), + ); expect(anchor.getAttribute('target'), '_self'); }); testWidgets('sizes itself correctly', (WidgetTester tester) async { final Key containerKey = GlobalKey(); final Uri uri = Uri.parse('http://foobar'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: ConstrainedBox( - constraints: BoxConstraints.tight(const Size(100.0, 100.0)), - child: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - return Container( - key: containerKey, - child: const SizedBox(width: 50.0, height: 50.0), - ); - }, - )), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints.tight(const Size(100.0, 100.0)), + child: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + return Container( + key: containerKey, + child: const SizedBox(width: 50.0, height: 50.0), + ); + }, + ), + ), + ), ), ), - )); + ); await tester.pumpAndSettle(); await tester.pump(); @@ -133,16 +152,20 @@ void main() { // See: https://github.com/flutter/plugins/pull/3522#discussion_r574703724 testWidgets('uri can be null', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: WebLinkDelegate(TestLinkInfo( - uri: null, - target: LinkTarget.defaultTarget, - builder: (BuildContext context, FollowLink? followLink) { - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebLinkDelegate( + TestLinkInfo( + uri: null, + target: LinkTarget.defaultTarget, + builder: (BuildContext context, FollowLink? followLink) { + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -161,12 +184,16 @@ 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), + ), + ), ), ), ), @@ -197,24 +224,29 @@ void main() { UrlLauncherPlatform.instance = originalPlugin; }); - testWidgets('click to navigate to internal link', - (WidgetTester tester) async { + testWidgets('click to navigate to internal link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -234,24 +266,29 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('keydown to navigate to internal link', - (WidgetTester tester) async { + testWidgets('keydown to navigate to internal link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -271,21 +308,26 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('click to navigate to external link', - (WidgetTester tester) async { + testWidgets('click to navigate to external link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + MaterialApp( + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -306,21 +348,26 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('keydown to navigate to external link', - (WidgetTester tester) async { + testWidgets('keydown to navigate to external link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + MaterialApp( + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -346,32 +393,40 @@ void main() { FollowLink? followLinkCallback1; FollowLink? followLinkCallback2; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar1': (BuildContext context) => const Text('Internal route 1'), - '/foobar2': (BuildContext context) => const Text('Internal route 2'), - }, - home: Column( - children: [ - WebLinkDelegate(TestLinkInfo( - uri: uri1, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback1 = followLink; - return const SizedBox(width: 100, height: 100); - }, - )), - WebLinkDelegate(TestLinkInfo( - uri: uri2, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback2 = followLink; - return const SizedBox(width: 100, height: 100); - }, - )), - ], + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar1': + (BuildContext context) => const Text('Internal route 1'), + '/foobar2': + (BuildContext context) => const Text('Internal route 2'), + }, + home: Column( + children: [ + WebLinkDelegate( + TestLinkInfo( + uri: uri1, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback1 = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + WebLinkDelegate( + TestLinkInfo( + uri: uri2, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback2 = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ], + ), ), - )); + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -414,24 +469,29 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('trigger signals are reset after a delay', - (WidgetTester tester) async { + testWidgets('trigger signals are reset after a delay', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -475,24 +535,29 @@ void main() { expect(event3.defaultPrevented, isTrue); }); - testWidgets('ignores clicks on non-Flutter link', - (WidgetTester tester) async { + testWidgets('ignores clicks on non-Flutter link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -516,19 +581,23 @@ void main() { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -548,24 +617,29 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('ignores keydown when it is a modifier key', - (WidgetTester tester) async { + testWidgets('ignores keydown when it is a modifier key', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -607,24 +681,29 @@ void main() { UrlLauncherPlatform.instance = originalPlugin; }); - testWidgets('click to navigate to internal link', - (WidgetTester tester) async { + testWidgets('click to navigate to internal link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -644,24 +723,29 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('keydown to navigate to internal link', - (WidgetTester tester) async { + testWidgets('keydown to navigate to internal link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -681,21 +765,26 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('click to navigate to external link', - (WidgetTester tester) async { + testWidgets('click to navigate to external link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + MaterialApp( + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -716,21 +805,26 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('keydown to navigate to external link', - (WidgetTester tester) async { + testWidgets('keydown to navigate to external link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); - }, - )), - )); + await tester.pumpWidget( + MaterialApp( + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); @@ -765,35 +859,40 @@ void main() { UrlLauncherPlatform.instance = originalPlugin; }); - testWidgets('produces the correct semantics tree with a button', - (WidgetTester tester) async { + testWidgets('produces the correct semantics tree with a button', ( + WidgetTester tester, + ) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); final Key linkKey = UniqueKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: WebLinkDelegate( - key: linkKey, - semanticsIdentifier: 'test-link-12', - TestLinkInfo( - uri: Uri.parse('https://foobar/example?q=1'), - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - return ElevatedButton( - onPressed: followLink, - child: const Text('Button Link Text'), - ); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebLinkDelegate( + key: linkKey, + semanticsIdentifier: 'test-link-12', + TestLinkInfo( + uri: Uri.parse('https://foobar/example?q=1'), + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + return ElevatedButton( + onPressed: followLink, + child: const Text('Button Link Text'), + ); + }, + ), ), ), - )); + ); final Finder linkFinder = find.byKey(linkKey); expect( - tester.getSemantics(find.descendant( - of: linkFinder, - matching: find.byType(Semantics).first, - )), + tester.getSemantics( + find.descendant( + of: linkFinder, + matching: find.byType(Semantics).first, + ), + ), matchesSemantics( isLink: true, identifier: 'test-link-12', @@ -815,35 +914,37 @@ void main() { semanticsHandle.dispose(); }); - testWidgets('produces the correct semantics tree with text', - (WidgetTester tester) async { + testWidgets('produces the correct semantics tree with text', ( + WidgetTester tester, + ) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); final Key linkKey = UniqueKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: WebLinkDelegate( - key: linkKey, - semanticsIdentifier: 'test-link-43', - TestLinkInfo( - uri: Uri.parse('https://foobar/example?q=1'), - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - return GestureDetector( - onTap: followLink, - child: const Text('Link Text'), - ); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebLinkDelegate( + key: linkKey, + semanticsIdentifier: 'test-link-43', + TestLinkInfo( + uri: Uri.parse('https://foobar/example?q=1'), + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + return GestureDetector( + onTap: followLink, + child: const Text('Link Text'), + ); + }, + ), ), ), - )); + ); final Finder linkFinder = find.byKey(linkKey); expect( - tester.getSemantics(find.descendant( - of: linkFinder, - matching: find.byType(Semantics), - )), + tester.getSemantics( + find.descendant(of: linkFinder, matching: find.byType(Semantics)), + ), matchesSemantics( isLink: true, hasTapAction: true, @@ -856,44 +957,50 @@ void main() { semanticsHandle.dispose(); }); - testWidgets('handles clicks on semantic link with a button', - (WidgetTester tester) async { + testWidgets('handles clicks on semantic link with a button', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate( - semanticsIdentifier: 'test-link-27', - TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return ElevatedButton( - onPressed: () {}, - child: const Text('My Button Link'), - ); - }, + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), + }, + home: WebLinkDelegate( + semanticsIdentifier: 'test-link-27', + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return ElevatedButton( + onPressed: () {}, + child: const Text('My Button Link'), + ); + }, + ), ), ), - )); + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = - html.document.createElement('flt-semantics-host'); + final html.Element semanticsHost = html.document.createElement( + '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'); + final html.Element semanticsContainer = html.document.createElement( + 'flt-semantics-container', + ); semanticsAnchor.append(semanticsContainer); final html.Element semanticsButton = html.document.createElement('flt-semantics') @@ -922,42 +1029,47 @@ void main() { expect(event2.defaultPrevented, isTrue); }); - testWidgets('handles clicks on semantic link with text', - (WidgetTester tester) async { + testWidgets('handles clicks on semantic link with text', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate( - semanticsIdentifier: 'test-link-71', - TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); - }, + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), + }, + home: WebLinkDelegate( + semanticsIdentifier: 'test-link-71', + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return GestureDetector( + onTap: () {}, + child: const Text('My Link'), + ); + }, + ), ), ), - )); + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = - html.document.createElement('flt-semantics-host'); + final html.Element semanticsHost = html.document.createElement( + '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); @@ -971,39 +1083,44 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('handles debounced clicks on semantic link', - (WidgetTester tester) async { + testWidgets('handles debounced clicks on semantic link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - home: WebLinkDelegate( - semanticsIdentifier: 'test-link-71', - TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: WebLinkDelegate( + semanticsIdentifier: 'test-link-71', + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return GestureDetector( + onTap: () {}, + child: const Text('My Link'), + ); + }, + ), ), ), - )); + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = - html.document.createElement('flt-semantics-host'); + final html.Element semanticsHost = html.document.createElement( + '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); @@ -1025,37 +1142,42 @@ void main() { }); // Regression test for: https://github.com/flutter/flutter/issues/162927 - testWidgets('prevents navigation with debounced clicks on semantic link', - (WidgetTester tester) async { + testWidgets('prevents navigation with debounced clicks on semantic link', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('https://flutter.dev'); - await tester.pumpWidget(MaterialApp( - home: WebLinkDelegate( - semanticsIdentifier: 'test-link-71', - TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: WebLinkDelegate( + semanticsIdentifier: 'test-link-71', + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + return GestureDetector( + onTap: () {}, + child: const Text('My Link'), + ); + }, + ), ), ), - )); + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = - html.document.createElement('flt-semantics-host'); + final html.Element semanticsHost = html.document.createElement( + '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); @@ -1076,37 +1198,45 @@ void main() { // TODO(mdebbar): Remove this test after the engine PR [1] makes it to stable. // [1] https://github.com/flutter/engine/pull/52720 - testWidgets('handles clicks on (old) semantic link with a button', - (WidgetTester tester) async { + testWidgets('handles clicks on (old) semantic link with a button', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return const SizedBox(width: 100, height: 100); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return const SizedBox(width: 100, height: 100); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = - html.document.createElement('flt-semantics-host'); + final html.Element semanticsHost = html.document.createElement( + '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'); + final html.Element semanticsContainer = html.document.createElement( + 'flt-semantics-container', + ); semanticsAnchor.append(semanticsContainer); final html.Element semanticsButton = html.document.createElement('flt-semantics') @@ -1129,38 +1259,45 @@ void main() { // TODO(mdebbar): Remove this test after the engine PR [1] makes it to stable. // [1] https://github.com/flutter/engine/pull/52720 - testWidgets('handles clicks on (old) semantic link with text', - (WidgetTester tester) async { + testWidgets('handles clicks on (old) semantic link with text', ( + WidgetTester tester, + ) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; - await tester.pumpWidget(MaterialApp( - routes: { - '/foobar': (BuildContext context) => const Text('Internal route'), - }, - home: WebLinkDelegate(TestLinkInfo( - uri: uri, - target: LinkTarget.blank, - builder: (BuildContext context, FollowLink? followLink) { - followLinkCallback = followLink; - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); + await tester.pumpWidget( + MaterialApp( + routes: { + '/foobar': (BuildContext context) => const Text('Internal route'), }, - )), - )); + home: WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.blank, + builder: (BuildContext context, FollowLink? followLink) { + followLinkCallback = followLink; + return GestureDetector( + onTap: () {}, + child: const Text('My Link'), + ); + }, + ), + ), + ), + ); // Platform view creation happens asynchronously. await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = - html.document.createElement('flt-semantics-host'); + final html.Element semanticsHost = html.document.createElement( + '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); @@ -1204,26 +1341,25 @@ html.MouseEvent _simulateClick(html.Element target, {bool metaKey = false}) { // }.toJS); final html.MouseEvent mouseEvent = html.MouseEvent( 'click', - html.MouseEventInit( - bubbles: true, - cancelable: true, - metaKey: metaKey, - ), + html.MouseEventInit(bubbles: true, cancelable: true, metaKey: metaKey), ); LinkViewController.handleGlobalClick(event: mouseEvent, target: target); return mouseEvent; } -html.KeyboardEvent _simulateKeydown(html.Element target, - {bool metaKey = false}) { +html.KeyboardEvent _simulateKeydown( + html.Element target, { + bool metaKey = false, +}) { final html.KeyboardEvent keydownEvent = html.KeyboardEvent( - 'keydown', - html.KeyboardEventInit( - bubbles: true, - cancelable: true, - metaKey: metaKey, - // code: 'Space', - )); + 'keydown', + html.KeyboardEventInit( + bubbles: true, + cancelable: true, + metaKey: metaKey, + // code: 'Space', + ), + ); LinkViewController.handleGlobalKeydown(event: keydownEvent); return keydownEvent; } diff --git a/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart b/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart index 00b74cd6f59..30173a6e77e 100644 --- a/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart +++ b/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart @@ -50,7 +50,8 @@ void main() { when(mockWindow.open(any, any, any)).thenReturn(jsMockWindow); when(mockNavigator.userAgent).thenReturn( - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'); + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', + ); plugin = UrlLauncherPlugin(debugWindow: jsMockWindow); }); @@ -66,7 +67,9 @@ void main() { testWidgets('"mailto" URLs -> true', (WidgetTester _) async { expect( - plugin.canLaunch('mailto:name@mydomain.com'), completion(isTrue)); + plugin.canLaunch('mailto:name@mydomain.com'), + completion(isTrue), + ); }); testWidgets('"tel" URLs -> true', (WidgetTester _) async { @@ -74,8 +77,10 @@ void main() { }); testWidgets('"sms" URLs -> true', (WidgetTester _) async { - expect(plugin.canLaunch('sms:+19725551212?body=hello%20there'), - completion(isTrue)); + expect( + plugin.canLaunch('sms:+19725551212?body=hello%20there'), + completion(isTrue), + ); }); testWidgets('"javascript" URLs -> false', (WidgetTester _) async { @@ -85,190 +90,251 @@ void main() { group('launch', () { testWidgets('launching a URL returns true', (WidgetTester _) async { - expect( - plugin.launch( - 'https://www.google.com', - ), - completion(isTrue)); + expect(plugin.launch('https://www.google.com'), completion(isTrue)); }); testWidgets('launching a "mailto" returns true', (WidgetTester _) async { - expect( - plugin.launch( - 'mailto:name@mydomain.com', - ), - completion(isTrue)); + expect(plugin.launch('mailto:name@mydomain.com'), completion(isTrue)); }); testWidgets('launching a "tel" returns true', (WidgetTester _) async { - expect( - plugin.launch( - 'tel:5551234567', - ), - completion(isTrue)); + expect(plugin.launch('tel:5551234567'), completion(isTrue)); }); testWidgets('launching a "sms" returns true', (WidgetTester _) async { expect( - plugin.launch( - 'sms:+19725551212?body=hello%20there', - ), - completion(isTrue)); + plugin.launch('sms:+19725551212?body=hello%20there'), + completion(isTrue), + ); }); - testWidgets('launching a "javascript" returns false', - (WidgetTester _) async { + testWidgets('launching a "javascript" returns false', ( + WidgetTester _, + ) async { expect(plugin.launch('javascript:alert("1")'), completion(isFalse)); }); - testWidgets('launching a unknown sceheme returns true', - (WidgetTester _) async { - expect( - plugin.launch( - 'foo:bar', - ), - completion(isTrue)); + testWidgets('launching a unknown sceheme returns true', ( + WidgetTester _, + ) async { + expect(plugin.launch('foo:bar'), completion(isTrue)); }); }); group('openNewWindow', () { - testWidgets('http urls should be launched in a new window', - (WidgetTester _) async { + testWidgets('http urls should be launched in a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('http://www.google.com'); - verify(mockWindow.open( - 'http://www.google.com', '', 'noopener,noreferrer')); + verify( + mockWindow.open('http://www.google.com', '', 'noopener,noreferrer'), + ); }); - testWidgets('https urls should be launched in a new window', - (WidgetTester _) async { + testWidgets('https urls should be launched in a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('https://www.google.com'); - verify(mockWindow.open( - 'https://www.google.com', '', 'noopener,noreferrer')); + verify( + mockWindow.open('https://www.google.com', '', 'noopener,noreferrer'), + ); }); - testWidgets('mailto urls should be launched on a new window', - (WidgetTester _) async { + testWidgets('mailto urls should be launched on a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('mailto:name@mydomain.com'); - verify(mockWindow.open( - 'mailto:name@mydomain.com', '', 'noopener,noreferrer')); + verify( + mockWindow.open( + 'mailto:name@mydomain.com', + '', + 'noopener,noreferrer', + ), + ); }); - testWidgets('tel urls should be launched on a new window', - (WidgetTester _) async { + testWidgets('tel urls should be launched on a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('tel:5551234567'); verify(mockWindow.open('tel:5551234567', '', 'noopener,noreferrer')); }); - testWidgets('sms urls should be launched on a new window', - (WidgetTester _) async { + testWidgets('sms urls should be launched on a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('sms:+19725551212?body=hello%20there'); - verify(mockWindow.open( - 'sms:+19725551212?body=hello%20there', '', 'noopener,noreferrer')); + verify( + mockWindow.open( + 'sms:+19725551212?body=hello%20there', + '', + 'noopener,noreferrer', + ), + ); }); testWidgets( - 'setting webOnlyLinkTarget as _self opens the url in the same tab', - (WidgetTester _) async { - plugin.openNewWindow('https://www.google.com', - webOnlyWindowName: '_self'); - verify(mockWindow.open( - 'https://www.google.com', '_self', 'noopener,noreferrer')); - }); + 'setting webOnlyLinkTarget as _self opens the url in the same tab', + (WidgetTester _) async { + plugin.openNewWindow( + 'https://www.google.com', + webOnlyWindowName: '_self', + ); + verify( + mockWindow.open( + 'https://www.google.com', + '_self', + 'noopener,noreferrer', + ), + ); + }, + ); testWidgets( - 'setting webOnlyLinkTarget as _blank opens the url in a new tab', - (WidgetTester _) async { - plugin.openNewWindow('https://www.google.com', - webOnlyWindowName: '_blank'); - verify(mockWindow.open( - 'https://www.google.com', '_blank', 'noopener,noreferrer')); - }); + 'setting webOnlyLinkTarget as _blank opens the url in a new tab', + (WidgetTester _) async { + plugin.openNewWindow( + 'https://www.google.com', + webOnlyWindowName: '_blank', + ); + verify( + mockWindow.open( + 'https://www.google.com', + '_blank', + 'noopener,noreferrer', + ), + ); + }, + ); group('Safari', () { setUp(() { when(mockNavigator.userAgent).thenReturn( - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.1 Safari/605.1.15'); + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.1 Safari/605.1.15', + ); // Recreate the plugin, so it grabs the overrides from this group plugin = UrlLauncherPlugin(debugWindow: jsMockWindow); }); - testWidgets('http urls should be launched in a new window', - (WidgetTester _) async { + testWidgets('http urls should be launched in a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('http://www.google.com'); - verify(mockWindow.open( - 'http://www.google.com', '', 'noopener,noreferrer')); + verify( + mockWindow.open('http://www.google.com', '', 'noopener,noreferrer'), + ); }); - testWidgets('https urls should be launched in a new window', - (WidgetTester _) async { + testWidgets('https urls should be launched in a new window', ( + WidgetTester _, + ) async { plugin.openNewWindow('https://www.google.com'); - verify(mockWindow.open( - 'https://www.google.com', '', 'noopener,noreferrer')); + verify( + mockWindow.open( + 'https://www.google.com', + '', + 'noopener,noreferrer', + ), + ); }); - testWidgets('mailto urls should be launched on the same window', - (WidgetTester _) async { + testWidgets('mailto urls should be launched on the same window', ( + WidgetTester _, + ) async { plugin.openNewWindow('mailto:name@mydomain.com'); - verify(mockWindow.open( - 'mailto:name@mydomain.com', '_top', 'noopener,noreferrer')); + verify( + mockWindow.open( + 'mailto:name@mydomain.com', + '_top', + 'noopener,noreferrer', + ), + ); }); - testWidgets('tel urls should be launched on the same window', - (WidgetTester _) async { + testWidgets('tel urls should be launched on the same window', ( + WidgetTester _, + ) async { plugin.openNewWindow('tel:5551234567'); verify( - mockWindow.open('tel:5551234567', '_top', 'noopener,noreferrer')); + mockWindow.open('tel:5551234567', '_top', 'noopener,noreferrer'), + ); }); - testWidgets('sms urls should be launched on the same window', - (WidgetTester _) async { + testWidgets('sms urls should be launched on the same window', ( + WidgetTester _, + ) async { plugin.openNewWindow('sms:+19725551212?body=hello%20there'); - verify(mockWindow.open('sms:+19725551212?body=hello%20there', '_top', - 'noopener,noreferrer')); + verify( + mockWindow.open( + 'sms:+19725551212?body=hello%20there', + '_top', + 'noopener,noreferrer', + ), + ); }); testWidgets( - 'mailto urls should use _blank if webOnlyWindowName is set as _blank', - (WidgetTester _) async { - plugin.openNewWindow('mailto:name@mydomain.com', - webOnlyWindowName: '_blank'); - verify(mockWindow.open( - 'mailto:name@mydomain.com', '_blank', 'noopener,noreferrer')); - }); + 'mailto urls should use _blank if webOnlyWindowName is set as _blank', + (WidgetTester _) async { + plugin.openNewWindow( + 'mailto:name@mydomain.com', + webOnlyWindowName: '_blank', + ); + verify( + mockWindow.open( + 'mailto:name@mydomain.com', + '_blank', + 'noopener,noreferrer', + ), + ); + }, + ); }); }); group('supportsMode', () { testWidgets('returns true for platformDefault', (WidgetTester _) async { - expect(plugin.supportsMode(PreferredLaunchMode.platformDefault), - completion(isTrue)); + expect( + plugin.supportsMode(PreferredLaunchMode.platformDefault), + completion(isTrue), + ); }); testWidgets('returns false for other modes', (WidgetTester _) async { - expect(plugin.supportsMode(PreferredLaunchMode.externalApplication), - completion(isFalse)); expect( - plugin.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication), - completion(isFalse)); - expect(plugin.supportsMode(PreferredLaunchMode.inAppBrowserView), - completion(isFalse)); - expect(plugin.supportsMode(PreferredLaunchMode.inAppWebView), - completion(isFalse)); + plugin.supportsMode(PreferredLaunchMode.externalApplication), + completion(isFalse), + ); + expect( + plugin.supportsMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + completion(isFalse), + ); + expect( + plugin.supportsMode(PreferredLaunchMode.inAppBrowserView), + completion(isFalse), + ); + expect( + plugin.supportsMode(PreferredLaunchMode.inAppWebView), + completion(isFalse), + ); }); }); testWidgets('supportsCloseForMode returns false', (WidgetTester _) async { - expect(plugin.supportsCloseForMode(PreferredLaunchMode.platformDefault), - completion(isFalse)); + expect( + plugin.supportsCloseForMode(PreferredLaunchMode.platformDefault), + completion(isFalse), + ); }); }); } diff --git a/packages/url_launcher/url_launcher_web/example/pubspec.yaml b/packages/url_launcher/url_launcher_web/example/pubspec.yaml index b734fade0f7..586ae6e6fa1 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 c24d47876ec..f28ca254f29 100644 --- a/packages/url_launcher/url_launcher_web/lib/src/link.dart +++ b/packages/url_launcher/url_launcher_web/lib/src/link.dart @@ -111,9 +111,7 @@ class WebLinkDelegateState extends State { fit: StackFit.passthrough, children: [ _buildChild(context), - Positioned.fill( - child: _buildPlatformView(context), - ), + Positioned.fill(child: _buildPlatformView(context)), ], ); } @@ -136,18 +134,22 @@ class WebLinkDelegateState extends State { child: PlatformViewLink( viewType: linkViewType, onCreatePlatformView: (PlatformViewCreationParams params) { - _controller = - LinkViewController.fromParams(params, _semanticsIdentifier); + _controller = LinkViewController.fromParams( + params, + _semanticsIdentifier, + ); return _controller ..setUri(widget.link.uri) ..setTarget(widget.link.target); }, - surfaceFactory: - (BuildContext context, PlatformViewController controller) { + surfaceFactory: ( + BuildContext context, + PlatformViewController controller, + ) { return PlatformViewSurface( controller: controller, - gestureRecognizers: const >{}, + gestureRecognizers: + const >{}, hitTestBehavior: PlatformViewHitTestBehavior.transparent, ); }, @@ -160,8 +162,8 @@ class WebLinkDelegateState extends State { final JSAny _useCapture = {'capture': true}.jsify()!; /// Signature for the function that triggers a link. -typedef TriggerLinkCallback = void Function( - int viewId, html.MouseEvent? mouseEvent); +typedef TriggerLinkCallback = + void Function(int viewId, html.MouseEvent? mouseEvent); /// Keeps track of the signals required to trigger a link. /// @@ -184,10 +186,7 @@ typedef TriggerLinkCallback = void Function( class LinkTriggerSignals { /// Creates a [LinkTriggerSignals] instance that calls [triggerLink] when all /// the signals are received within a [staleTimeout] duration. - LinkTriggerSignals({ - required this.triggerLink, - required this.staleTimeout, - }); + LinkTriggerSignals({required this.triggerLink, required this.staleTimeout}); /// The function to be called when all signals have been received and the link /// is ready to be triggered. @@ -349,8 +348,10 @@ class LinkViewController extends PlatformViewController { String semanticsIdentifier, ) { final int viewId = params.id; - final LinkViewController controller = - LinkViewController(viewId, semanticsIdentifier); + final LinkViewController controller = LinkViewController( + viewId, + semanticsIdentifier, + ); controller._initialize().then((_) { /// Because _initialize is async, it can happen that [LinkViewController.dispose] /// may get called before this `then` callback. @@ -464,10 +465,7 @@ class LinkViewController extends PlatformViewController { } static void _onGlobalClick(html.MouseEvent event) { - handleGlobalClick( - event: event, - target: event.target as html.Element?, - ); + handleGlobalClick(event: event, target: event.target as html.Element?); } /// Global click handler that's called for every click event on the window. @@ -491,10 +489,7 @@ class LinkViewController extends PlatformViewController { return; } - _triggerSignals.onMouseEvent( - viewId: viewIdFromTarget, - mouseEvent: event, - ); + _triggerSignals.onMouseEvent(viewId: viewIdFromTarget, mouseEvent: event); _triggerSignals.triggerLinkIfReady(); } @@ -629,8 +624,9 @@ class LinkViewController extends PlatformViewController { return null; } - final String? semanticsIdentifier = - semanticsLink.getAttribute('flt-semantics-identifier'); + final String? semanticsIdentifier = semanticsLink.getAttribute( + 'flt-semantics-identifier', + ); if (semanticsIdentifier == null) { return null; } diff --git a/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart b/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart index b3de107d436..7ecf359071b 100644 --- a/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart +++ b/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart @@ -13,20 +13,14 @@ import 'package:web/web.dart' as html; import 'src/link.dart'; -const Set _safariTargetTopSchemes = { - 'mailto', - 'tel', - 'sms', -}; +const Set _safariTargetTopSchemes = {'mailto', 'tel', 'sms'}; String? _getUrlScheme(String url) => Uri.tryParse(url)?.scheme; bool _isSafariTargetTopScheme(String? scheme) => _safariTargetTopSchemes.contains(scheme); // The set of schemes that are explicitly disallowed by the plugin. -const Set _disallowedSchemes = { - 'javascript', -}; +const Set _disallowedSchemes = {'javascript'}; bool _isDisallowedScheme(String? scheme) => _disallowedSchemes.contains(scheme); bool _navigatorIsSafari(html.Navigator navigator) => @@ -39,7 +33,7 @@ bool _navigatorIsSafari(html.Navigator navigator) => class UrlLauncherPlugin extends UrlLauncherPlatform { /// A constructor that allows tests to override the window object used by the plugin. UrlLauncherPlugin({@visibleForTesting html.Window? debugWindow}) - : _window = debugWindow ?? html.window { + : _window = debugWindow ?? html.window { _isSafari = _navigatorIsSafari(_window.navigator); } @@ -55,8 +49,11 @@ class UrlLauncherPlugin extends UrlLauncherPlatform { /// Registers this class as the default instance of [UrlLauncherPlatform]. static void registerWith(Registrar registrar) { UrlLauncherPlatform.instance = UrlLauncherPlugin(); - ui_web.platformViewRegistry - .registerViewFactory(linkViewType, linkViewFactory, isVisible: false); + ui_web.platformViewRegistry.registerViewFactory( + linkViewType, + linkViewFactory, + isVisible: false, + ); } @override @@ -83,7 +80,8 @@ class UrlLauncherPlugin extends UrlLauncherPlatform { } // Some schemes need to be opened on the _top window context on Safari. // See https://github.com/flutter/flutter/issues/51461 - final String target = webOnlyWindowName ?? + final String target = + webOnlyWindowName ?? ((_isSafari && _isSafariTargetTopScheme(scheme)) ? '_top' : ''); _window.open(url, target, 'noopener,noreferrer'); diff --git a/packages/url_launcher/url_launcher_web/pubspec.yaml b/packages/url_launcher/url_launcher_web/pubspec.yaml index 0335a62f5ab..820e20f349d 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_windows/CHANGELOG.md b/packages/url_launcher/url_launcher_windows/CHANGELOG.md index 5ca8a7aabb1..9e49e72706e 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 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 739d09d00c4..432569a6676 100644 --- a/packages/url_launcher/url_launcher_windows/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_windows/example/lib/main.dart @@ -19,9 +19,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', - theme: ThemeData( - primarySwatch: Colors.blue, - ), + theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'URL Launcher'), ); } @@ -66,9 +64,7 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: ListView( children: [ Column( @@ -79,9 +75,10 @@ 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 7ae139e30e3..5b558573268 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.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 f076f3ecc99..a3cf71a5a10 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 @@ -26,11 +26,12 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : __pigeon_binaryMessenger = binaryMessenger, - __pigeon_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + UrlLauncherApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : __pigeon_binaryMessenger = binaryMessenger, + __pigeon_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -42,10 +43,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_windows.UrlLauncherApi.canLaunchUrl$__pigeon_messageChannelSuffix'; final BasicMessageChannel __pigeon_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); + __pigeon_channelName, + pigeonChannelCodec, + binaryMessenger: __pigeon_binaryMessenger, + ); final List? __pigeon_replyList = await __pigeon_channel.send([url]) as List?; if (__pigeon_replyList == null) { @@ -71,10 +72,10 @@ class UrlLauncherApi { 'dev.flutter.pigeon.url_launcher_windows.UrlLauncherApi.launchUrl$__pigeon_messageChannelSuffix'; final BasicMessageChannel __pigeon_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); + __pigeon_channelName, + pigeonChannelCodec, + binaryMessenger: __pigeon_binaryMessenger, + ); final List? __pigeon_replyList = await __pigeon_channel.send([url]) as List?; if (__pigeon_replyList == null) { diff --git a/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart b/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart index 8ba77dc391a..2807071d505 100644 --- a/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart +++ b/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart @@ -11,9 +11,8 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for Windows. class UrlLauncherWindows extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherWindows({ - @visibleForTesting UrlLauncherApi? api, - }) : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherWindows({@visibleForTesting UrlLauncherApi? api}) + : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; diff --git a/packages/url_launcher/url_launcher_windows/pigeons/messages.dart b/packages/url_launcher/url_launcher_windows/pigeons/messages.dart index 28152e45b88..197495ad1aa 100644 --- a/packages/url_launcher/url_launcher_windows/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_windows/pigeons/messages.dart @@ -4,13 +4,15 @@ import 'package:pigeon/pigeon.dart'; -@ConfigurePigeon(PigeonOptions( - dartOut: 'lib/src/messages.g.dart', - cppOptions: CppOptions(namespace: 'url_launcher_windows'), - cppHeaderOut: 'windows/messages.g.h', - cppSourceOut: 'windows/messages.g.cpp', - copyrightHeader: 'pigeons/copyright.txt', -)) +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/messages.g.dart', + cppOptions: CppOptions(namespace: 'url_launcher_windows'), + cppHeaderOut: 'windows/messages.g.h', + cppSourceOut: 'windows/messages.g.cpp', + copyrightHeader: 'pigeons/copyright.txt', + ), +) @HostApi(dartHostTestHandler: 'TestUrlLauncherApi') abstract class UrlLauncherApi { bool canLaunchUrl(String url); diff --git a/packages/url_launcher/url_launcher_windows/pubspec.yaml b/packages/url_launcher/url_launcher_windows/pubspec.yaml index ae08dc7eb81..53671a8ade0 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart b/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart index 5d8efc0316b..e5926fcdb47 100644 --- a/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart +++ b/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart @@ -47,16 +47,17 @@ void main() { api.canLaunch = true; expect( - await plugin.launch( - 'http://example.com/', - useSafariVC: true, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - true); + await plugin.launch( + 'http://example.com/', + useSafariVC: true, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + true, + ); expect(api.argument, 'http://example.com/'); }); @@ -64,16 +65,17 @@ void main() { api.canLaunch = false; expect( - await plugin.launch( - 'http://example.com/', - useSafariVC: true, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - false); + await plugin.launch( + 'http://example.com/', + useSafariVC: true, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + false, + ); expect(api.argument, 'http://example.com/'); }); @@ -81,16 +83,17 @@ void main() { api.throwError = true; await expectLater( - plugin.launch( - 'http://example.com/', - useSafariVC: true, - useWebView: false, - enableJavaScript: false, - enableDomStorage: false, - universalLinksOnly: false, - headers: const {}, - ), - throwsA(isA())); + plugin.launch( + 'http://example.com/', + useSafariVC: true, + useWebView: false, + enableJavaScript: false, + enableDomStorage: false, + universalLinksOnly: false, + headers: const {}, + ), + throwsA(isA()), + ); expect(api.argument, 'http://example.com/'); }); }); @@ -98,40 +101,51 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherWindows launcher = UrlLauncherWindows(api: api); - expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true); + expect( + await launcher.supportsMode(PreferredLaunchMode.platformDefault), + true, + ); }); test('returns true for external application', () async { final UrlLauncherWindows launcher = UrlLauncherWindows(api: api); expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true); + await launcher.supportsMode(PreferredLaunchMode.externalApplication), + true, + ); }); test('returns false for other modes', () async { final UrlLauncherWindows launcher = UrlLauncherWindows(api: api); expect( - await launcher - .supportsMode(PreferredLaunchMode.externalNonBrowserApplication), - false); - expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false); + await launcher.supportsMode( + PreferredLaunchMode.externalNonBrowserApplication, + ), + false, + ); + expect( + await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), + false, + ); expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); + await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + false, + ); }); }); test('supportsCloseForMode returns false', () async { final UrlLauncherWindows launcher = UrlLauncherWindows(api: api); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.platformDefault), - false); + await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), + false, + ); expect( - await launcher - .supportsCloseForMode(PreferredLaunchMode.externalApplication), - false); + await launcher.supportsCloseForMode( + PreferredLaunchMode.externalApplication, + ), + false, + ); }); } diff --git a/packages/web_benchmarks/CHANGELOG.md b/packages/web_benchmarks/CHANGELOG.md index c814675f9e4..3a529e23eea 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.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 4.0.0 diff --git a/packages/web_benchmarks/README.md b/packages/web_benchmarks/README.md index 9b63bf815d4..020d921d7e1 100644 --- a/packages/web_benchmarks/README.md +++ b/packages/web_benchmarks/README.md @@ -31,20 +31,25 @@ import 'dart:io'; import 'package:web_benchmarks/analysis.dart'; void main() { - final BenchmarkResults baselineResults = - _benchmarkResultsFromFile('/path/to/benchmark_baseline.json'); - final BenchmarkResults testResults1 = - _benchmarkResultsFromFile('/path/to/benchmark_test_1.json'); - final BenchmarkResults testResults2 = - _benchmarkResultsFromFile('/path/to/benchmark_test_2.json'); + final BenchmarkResults baselineResults = _benchmarkResultsFromFile( + '/path/to/benchmark_baseline.json', + ); + final BenchmarkResults testResults1 = _benchmarkResultsFromFile( + '/path/to/benchmark_test_1.json', + ); + final BenchmarkResults testResults2 = _benchmarkResultsFromFile( + '/path/to/benchmark_test_2.json', + ); // Compute the delta between [baselineResults] and [testResults1]. final BenchmarkResults delta = computeDelta(baselineResults, testResults1); stdout.writeln(delta.toJson()); // Compute the average of [testResults] and [testResults2]. - final BenchmarkResults average = - computeAverage([testResults1, testResults2]); + final BenchmarkResults average = computeAverage([ + testResults1, + testResults2, + ]); stdout.writeln(average.toJson()); } @@ -54,4 +59,5 @@ BenchmarkResults _benchmarkResultsFromFile(String path) { jsonDecode(file.readAsStringSync()) as Map; return BenchmarkResults.parse(fileContentAsJson); } + ``` diff --git a/packages/web_benchmarks/example/analyze_example.dart b/packages/web_benchmarks/example/analyze_example.dart index bf2721ac594..d261ab2a48f 100644 --- a/packages/web_benchmarks/example/analyze_example.dart +++ b/packages/web_benchmarks/example/analyze_example.dart @@ -9,20 +9,25 @@ import 'dart:io'; import 'package:web_benchmarks/analysis.dart'; void main() { - final BenchmarkResults baselineResults = - _benchmarkResultsFromFile('/path/to/benchmark_baseline.json'); - final BenchmarkResults testResults1 = - _benchmarkResultsFromFile('/path/to/benchmark_test_1.json'); - final BenchmarkResults testResults2 = - _benchmarkResultsFromFile('/path/to/benchmark_test_2.json'); + final BenchmarkResults baselineResults = _benchmarkResultsFromFile( + '/path/to/benchmark_baseline.json', + ); + final BenchmarkResults testResults1 = _benchmarkResultsFromFile( + '/path/to/benchmark_test_1.json', + ); + final BenchmarkResults testResults2 = _benchmarkResultsFromFile( + '/path/to/benchmark_test_2.json', + ); // Compute the delta between [baselineResults] and [testResults1]. final BenchmarkResults delta = computeDelta(baselineResults, testResults1); stdout.writeln(delta.toJson()); // Compute the average of [testResults] and [testResults2]. - final BenchmarkResults average = - computeAverage([testResults1, testResults2]); + final BenchmarkResults average = computeAverage([ + testResults1, + testResults2, + ]); stdout.writeln(average.toJson()); } @@ -32,4 +37,5 @@ BenchmarkResults _benchmarkResultsFromFile(String path) { jsonDecode(file.readAsStringSync()) as Map; return BenchmarkResults.parse(fileContentAsJson); } + // #enddocregion analyze diff --git a/packages/web_benchmarks/lib/analysis.dart b/packages/web_benchmarks/lib/analysis.dart index 73b5d6e78c5..8d5d411577f 100644 --- a/packages/web_benchmarks/lib/analysis.dart +++ b/packages/web_benchmarks/lib/analysis.dart @@ -26,8 +26,10 @@ BenchmarkResults computeAverage(List results) { for (int i = 0; i < scoresForBenchmark.length; i++) { final BenchmarkScore score = scoresForBenchmark[i]; final double averageValue = score.value / results.length; - average.scores[benchmark]![i] = - BenchmarkScore(metric: score.metric, value: averageValue); + average.scores[benchmark]![i] = BenchmarkScore( + metric: score.metric, + value: averageValue, + ); } } return average; @@ -45,17 +47,19 @@ 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); } @@ -91,21 +95,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(); + // 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 fc427473e0d..574d31c649c 100644 --- a/packages/web_benchmarks/lib/client.dart +++ b/packages/web_benchmarks/lib/client.dart @@ -58,7 +58,8 @@ Future runBenchmarks( if (nextBenchmark == LocalBenchmarkServerClient.kManualFallback) { _fallbackToManual( - 'The server did not tell us which benchmark to run next.'); + 'The server did not tell us which benchmark to run next.', + ); return; } @@ -67,13 +68,14 @@ 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( @@ -93,14 +95,15 @@ 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) { @@ -154,12 +157,13 @@ void _fallbackToManual(String error) { // Find the button elements added above. final Element button = document.querySelector('#$benchmarkName')!; button.addEventListener( - 'click', - (JSAny? arg) { - final Element? manualPanel = document.querySelector('#manual-panel'); - manualPanel?.remove(); - _runBenchmark(benchmarkName); - }.toJS); + 'click', + (JSAny? arg) { + final Element? manualPanel = document.querySelector('#manual-panel'); + manualPanel?.remove(); + _runBenchmark(benchmarkName); + }.toJS, + ); } } @@ -194,7 +198,8 @@ class TimeseriesVisualization { // The amount of vertical space available on the chart. Because some // outliers can be huge they can dwarf all the useful values. So we // limit it to 1.5 x the biggest non-outlier. - _maxValueChartRange = 1.5 * + _maxValueChartRange = + 1.5 * _stats.samples .where((AnnotatedSample sample) => !sample.isOutlier) .map((AnnotatedSample sample) => sample.magnitude) @@ -260,13 +265,21 @@ class TimeseriesVisualization { // Draw a horizontal solid line corresponding to the average. _ctx.lineWidth = 1; - drawLine(0, _normalized(_stats.average), _screenWidth, - _normalized(_stats.average)); + drawLine( + 0, + _normalized(_stats.average), + _screenWidth, + _normalized(_stats.average), + ); // Draw a horizontal dashed line corresponding to the outlier cut off. _ctx.setLineDash([5.toJS, 5.toJS].toJS); - drawLine(0, _normalized(_stats.outlierCutOff), _screenWidth, - _normalized(_stats.outlierCutOff)); + drawLine( + 0, + _normalized(_stats.outlierCutOff), + _screenWidth, + _normalized(_stats.outlierCutOff), + ); // Draw a light red band that shows the noise (1 stddev in each direction). _ctx.fillStyle = 'rgba(255,50,50,0.3)'.toJS; @@ -361,8 +374,10 @@ class LocalBenchmarkServerClient { sendData: json.encode(profile.toJson()), ); if (request.status != 200) { - throw Exception('Failed to report profile data to benchmark server. ' - 'The server responded with status code ${request.status}.'); + throw Exception( + 'Failed to report profile data to benchmark server. ' + 'The server responded with status code ${request.status}.', + ); } } diff --git a/packages/web_benchmarks/lib/src/benchmark_result.dart b/packages/web_benchmarks/lib/src/benchmark_result.dart index ac80c747345..317378200dc 100644 --- a/packages/web_benchmarks/lib/src/benchmark_result.dart +++ b/packages/web_benchmarks/lib/src/benchmark_result.dart @@ -7,11 +7,7 @@ class BenchmarkScore { /// Creates a benchmark score. /// /// [metric] and [value] must not be null. - BenchmarkScore({ - required this.metric, - required this.value, - this.delta, - }); + BenchmarkScore({required this.metric, required this.value, this.delta}); /// Deserializes a JSON object to create a [BenchmarkScore] object. factory BenchmarkScore.parse(Map json) { @@ -80,8 +76,10 @@ class BenchmarkResults { /// Serializes benchmark metrics to JSON. Map>> toJson() { - return scores.map>>( - (String benchmarkName, List scores) { + return scores.map>>(( + String benchmarkName, + List scores, + ) { return MapEntry>>( benchmarkName, scores.map((BenchmarkScore score) => score.toJson()).toList(), diff --git a/packages/web_benchmarks/lib/src/browser.dart b/packages/web_benchmarks/lib/src/browser.dart index 272a41d7b2b..d06a1f2c0b7 100644 --- a/packages/web_benchmarks/lib/src/browser.dart +++ b/packages/web_benchmarks/lib/src/browser.dart @@ -59,8 +59,12 @@ typedef ChromeErrorCallback = void Function(String); /// Manages a single Chrome process. class Chrome { - Chrome._(this._chromeProcess, this._onError, this._debugConnection, - bool headless) { + Chrome._( + this._chromeProcess, + this._onError, + this._debugConnection, + bool headless, + ) { if (headless) { // In headless mode, if the Chrome process quits before it was asked to // quit, notify the error listener. If it's not running headless, the @@ -69,7 +73,8 @@ class Chrome { _chromeProcess.exitCode.then((int exitCode) { if (!_isStopped) { _onError( - 'Chrome process exited prematurely with exit code $exitCode'); + 'Chrome process exited prematurely with exit code $exitCode', + ); } }); } @@ -80,11 +85,16 @@ class Chrome { /// The [onError] callback is called with an error message when the Chrome /// process encounters an error. In particular, [onError] is called when the /// Chrome process exits prematurely, i.e. before [stop] is called. - static Future launch(ChromeOptions options, - {String? workingDirectory, required ChromeErrorCallback onError}) async { + static Future launch( + ChromeOptions options, { + String? workingDirectory, + required ChromeErrorCallback onError, + }) async { if (!io.Platform.isWindows) { final io.ProcessResult versionResult = io.Process.runSync( - _findSystemChromeExecutable(), const ['--version']); + _findSystemChromeExecutable(), + const ['--version'], + ); print('Launching ${versionResult.stdout}'); } else { print('Launching Chrome...'); @@ -119,8 +129,10 @@ class Chrome { WipConnection? debugConnection; final int? debugPort = options.debugPort; if (debugPort != null) { - debugConnection = - await _connectToChromeDebugPort(chromeProcess, debugPort); + debugConnection = await _connectToChromeDebugPort( + chromeProcess, + debugPort, + ); } return Chrome._(chromeProcess, onError, debugConnection, options.headless); @@ -144,16 +156,18 @@ class Chrome { Future beginRecordingPerformance(String? label) async { if (_tracingCompleter != null) { throw StateError( - 'Cannot start a new performance trace. A tracing session labeled ' - '"$label" is already in progress.'); + 'Cannot start a new performance trace. A tracing session labeled ' + '"$label" is already in progress.', + ); } _tracingCompleter = Completer(); _tracingData = >[]; // Subscribe to tracing events prior to calling "Tracing.start". Otherwise, // we'll miss tracing data. - _tracingSubscription = - _debugConnection?.onNotification.listen((WipEvent event) { + _tracingSubscription = _debugConnection?.onNotification.listen(( + WipEvent event, + ) { // We receive data as a sequence of "Tracing.dataCollected" followed by // "Tracing.tracingComplete" at the end. Until "Tracing.tracingComplete" // is received, the data may be incomplete. @@ -165,11 +179,14 @@ class Chrome { final dynamic value = event.params!['value']; if (value is! List) { throw FormatException( - '"Tracing.dataCollected" returned malformed data. ' - 'Expected a List but got: ${value.runtimeType}'); + '"Tracing.dataCollected" returned malformed data. ' + 'Expected a List but got: ${value.runtimeType}', + ); } - _tracingData?.addAll((event.params!['value'] as List) - .cast>()); + _tracingData?.addAll( + (event.params!['value'] as List) + .cast>(), + ); } }); await _debugConnection?.sendCommand('Tracing.start', { @@ -226,8 +243,9 @@ String _findSystemChromeExecutable() { } if (io.Platform.isLinux) { - final io.ProcessResult which = - io.Process.runSync('which', ['google-chrome']); + final io.ProcessResult which = io.Process.runSync('which', [ + 'google-chrome', + ]); if (which.exitCode != 0) { throw Exception('Failed to locate system Chrome installation.'); @@ -245,7 +263,7 @@ String _findSystemChromeExecutable() { io.Platform.environment['PROGRAMFILES'], io.Platform.environment['PROGRAMFILES(X86)'], ]) - if (item != null) item + if (item != null) item, ]; final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) { @@ -255,38 +273,48 @@ String _findSystemChromeExecutable() { return path.join(windowsPrefix, kWindowsExecutable); } else { throw Exception( - 'Web benchmarks cannot run on ${io.Platform.operatingSystem}.'); + 'Web benchmarks cannot run on ${io.Platform.operatingSystem}.', + ); } } /// Waits for Chrome to print DevTools URI and connects to it. Future _connectToChromeDebugPort( - io.Process chromeProcess, int port) async { + io.Process chromeProcess, + int port, +) async { chromeProcess.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { - print('[CHROME]: $line'); - }); + print('[CHROME]: $line'); + }); await chromeProcess.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .map((String line) { - print('[CHROME]: $line'); - return line; - }).firstWhere((String line) => line.startsWith('DevTools listening'), - orElse: () { - throw Exception('Expected Chrome to print "DevTools listening" string ' - 'with DevTools URL, but the string was never printed.'); - }); + print('[CHROME]: $line'); + return line; + }) + .firstWhere( + (String line) => line.startsWith('DevTools listening'), + orElse: () { + throw Exception( + 'Expected Chrome to print "DevTools listening" string ' + 'with DevTools URL, but the string was never printed.', + ); + }, + ); - final Uri devtoolsUri = - await _getRemoteDebuggerUrl(Uri.parse('http://localhost:$port')); + final Uri devtoolsUri = await _getRemoteDebuggerUrl( + Uri.parse('http://localhost:$port'), + ); print('Connecting to DevTools: $devtoolsUri'); final ChromeConnection chromeConnection = ChromeConnection('localhost', port); - final Iterable tabs = - (await chromeConnection.getTabs()).where((ChromeTab tab) { + final Iterable tabs = (await chromeConnection.getTabs()).where(( + ChromeTab tab, + ) { return tab.url.startsWith('http://localhost'); }); final ChromeTab tab = tabs.single; @@ -298,8 +326,9 @@ Future _connectToChromeDebugPort( /// Gets the Chrome debugger URL for the web page being benchmarked. Future _getRemoteDebuggerUrl(Uri base) async { final io.HttpClient client = io.HttpClient(); - final io.HttpClientRequest request = - await client.getUrl(base.resolve('/json/list')); + final io.HttpClientRequest request = await client.getUrl( + base.resolve('/json/list'), + ); final io.HttpClientResponse response = await request.close(); final List? jsonObject = await json.fuse(utf8).decoder.bind(response).single as List?; @@ -315,24 +344,23 @@ class BlinkTraceSummary { required this.averageBeginFrameTime, required this.averageUpdateLifecyclePhasesTime, }) : averageTotalUIFrameTime = - averageBeginFrameTime + averageUpdateLifecyclePhasesTime; + averageBeginFrameTime + averageUpdateLifecyclePhasesTime; /// Summarizes Blink trace from the raw JSON trace. static BlinkTraceSummary? fromJson(List> traceJson) { try { // Convert raw JSON data to BlinkTraceEvent objects sorted by timestamp. - List events = traceJson - .map(BlinkTraceEvent.fromJson) - .toList() - ..sort((BlinkTraceEvent a, BlinkTraceEvent b) => a.ts - b.ts); + List events = + traceJson.map(BlinkTraceEvent.fromJson).toList() + ..sort((BlinkTraceEvent a, BlinkTraceEvent b) => a.ts - b.ts); Exception noMeasuredFramesFound() => Exception( - 'No measured frames found in benchmark tracing data. This likely ' - 'indicates a bug in the benchmark. For example, the benchmark failed ' - "to pump enough frames. It may also indicate a change in Chrome's " - 'tracing data format. Check if Chrome version changed recently and ' - 'adjust the parsing code accordingly.', - ); + 'No measured frames found in benchmark tracing data. This likely ' + 'indicates a bug in the benchmark. For example, the benchmark failed ' + "to pump enough frames. It may also indicate a change in Chrome's " + 'tracing data format. Check if Chrome version changed recently and ' + 'adjust the parsing code accordingly.', + ); // Use the pid from the first "measured_frame" event since the event is // emitted by the script running on the process we're interested in. @@ -348,9 +376,10 @@ 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 = []; @@ -383,21 +412,27 @@ class BlinkTraceSummary { // Compute averages and summarize. return BlinkTraceSummary._( - averageBeginFrameTime: _computeAverageDuration(frames - .map((BlinkFrame frame) => frame.beginFrame) - .whereType() - .toList()), - averageUpdateLifecyclePhasesTime: _computeAverageDuration(frames - .map((BlinkFrame frame) => frame.updateAllLifecyclePhases) - .whereType() - .toList()), + averageBeginFrameTime: _computeAverageDuration( + frames + .map((BlinkFrame frame) => frame.beginFrame) + .whereType() + .toList(), + ), + averageUpdateLifecyclePhasesTime: _computeAverageDuration( + frames + .map((BlinkFrame frame) => frame.updateAllLifecyclePhases) + .whereType() + .toList(), + ), ); } catch (_) { final io.File traceFile = io.File('./chrome-trace.json'); io.stderr.writeln( - 'Failed to interpret the Chrome trace contents. The trace was saved in ${traceFile.path}'); + 'Failed to interpret the Chrome trace contents. The trace was saved in ${traceFile.path}', + ); traceFile.writeAsStringSync( - const JsonEncoder.withIndent(' ').convert(traceJson)); + const JsonEncoder.withIndent(' ').convert(traceJson), + ); rethrow; } } @@ -423,7 +458,8 @@ class BlinkTraceSummary { final Duration averageTotalUIFrameTime; @override - String toString() => '$BlinkTraceSummary(' + String toString() => + '$BlinkTraceSummary(' 'averageBeginFrameTime: ${averageBeginFrameTime.inMicroseconds / 1000}ms, ' 'averageUpdateLifecyclePhasesTime: ${averageUpdateLifecyclePhasesTime.inMicroseconds / 1000}ms)'; } @@ -450,12 +486,12 @@ Duration _computeAverageDuration(List events) { final double sum = events .skip(math.max(events.length - kMeasuredSampleCount, 0)) .fold(0.0, (double previousValue, BlinkTraceEvent event) { - final int? threadClockDuration = event.tdur; - if (threadClockDuration == null) { - throw FormatException('Trace event lacks "tdur" field: $event'); - } - return previousValue + threadClockDuration; - }); + final int? threadClockDuration = event.tdur; + if (threadClockDuration == null) { + throw FormatException('Trace event lacks "tdur" field: $event'); + } + return previousValue + threadClockDuration; + }); final int sampleCount = math.min(events.length, kMeasuredSampleCount); return Duration(microseconds: sum ~/ sampleCount); } @@ -588,7 +624,8 @@ class BlinkTraceEvent { bool get isEndMeasuredFrame => ph == 'e' && name == 'measured_frame'; @override - String toString() => '$BlinkTraceEvent(' + String toString() => + '$BlinkTraceEvent(' 'args: ${json.encode(args)}, ' 'cat: $cat, ' 'name: $name, ' diff --git a/packages/web_benchmarks/lib/src/computations.dart b/packages/web_benchmarks/lib/src/computations.dart index 99ffcfbc38d..0545b7d8c90 100644 --- a/packages/web_benchmarks/lib/src/computations.dart +++ b/packages/web_benchmarks/lib/src/computations.dart @@ -21,7 +21,7 @@ class Timeseries { /// /// [name], [isReported], and [useCustomWarmUp] must not be null. Timeseries(this.name, this.isReported, {this.useCustomWarmUp = false}) - : _warmUpFrameCount = useCustomWarmUp ? 0 : null; + : _warmUpFrameCount = useCustomWarmUp ? 0 : null; /// The label of this timeseries used for debugging and result inspection. final String name; @@ -65,12 +65,15 @@ class Timeseries { assert(finalWarmUpFrameCount >= 0 && finalWarmUpFrameCount < count); // The first few values we simply discard and never look at. They're from the warm-up phase. - final List warmUpValues = - _allValues.sublist(0, finalWarmUpFrameCount); + final List warmUpValues = _allValues.sublist( + 0, + finalWarmUpFrameCount, + ); // Values we analyze. - final List candidateValues = - _allValues.sublist(finalWarmUpFrameCount); + final List candidateValues = _allValues.sublist( + finalWarmUpFrameCount, + ); // The average that includes outliers. final double dirtyAverage = _computeAverage(name, candidateValues); @@ -83,17 +86,21 @@ class Timeseries { final double outlierCutOff = dirtyAverage + dirtyStandardDeviation; // Candidates with outliers removed. - final Iterable cleanValues = - candidateValues.where((double value) => value <= outlierCutOff); + final Iterable cleanValues = candidateValues.where( + (double value) => value <= outlierCutOff, + ); // Outlier candidates. - final Iterable outliers = - candidateValues.where((double value) => value > outlierCutOff); + final Iterable outliers = candidateValues.where( + (double value) => value > outlierCutOff, + ); // Final statistics. final double cleanAverage = _computeAverage(name, cleanValues); - final double standardDeviation = - _computeStandardDeviationForPopulation(name, cleanValues); + final double standardDeviation = _computeStandardDeviationForPopulation( + name, + cleanValues, + ); final double noise = cleanAverage > 0.0 ? standardDeviation / cleanAverage : 0.0; @@ -228,9 +235,10 @@ 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() { @@ -282,7 +290,8 @@ class AnnotatedSample { double _computeAverage(String label, Iterable values) { if (values.isEmpty) { throw StateError( - '$label: attempted to compute an average of an empty value list.'); + '$label: attempted to compute an average of an empty value list.', + ); } final double sum = values.reduce((double a, double b) => a + b); @@ -297,10 +306,13 @@ double _computeAverage(String label, Iterable values) { /// /// * https://en.wikipedia.org/wiki/Standard_deviation double _computeStandardDeviationForPopulation( - String label, Iterable population) { + String label, + Iterable population, +) { if (population.isEmpty) { throw StateError( - '$label: attempted to compute the standard deviation of empty population.'); + '$label: attempted to compute the standard deviation of empty population.', + ); } final double mean = _computeAverage(label, population); final double sumOfSquaredDeltas = population.fold( @@ -338,12 +350,15 @@ Map computePercentiles( } } - final List sorted = - values.sorted((double a, double b) => a.compareTo(b)); + final List sorted = values.sorted( + (double a, double b) => a.compareTo(b), + ); final Map computed = {}; for (final double percentile in percentiles) { - final int percentileIndex = - (sorted.length * percentile).round().clamp(0, sorted.length - 1); + final int percentileIndex = (sorted.length * percentile).round().clamp( + 0, + sorted.length - 1, + ); computed[percentile] = sorted[percentileIndex]; } diff --git a/packages/web_benchmarks/lib/src/metrics.dart b/packages/web_benchmarks/lib/src/metrics.dart index 5145d73baff..9fb6f3d6ffd 100644 --- a/packages/web_benchmarks/lib/src/metrics.dart +++ b/packages/web_benchmarks/lib/src/metrics.dart @@ -59,17 +59,20 @@ sealed class BenchmarkMetricComputation { /// The name for the computed value tracking the average value of the measured /// samples without outliers. - static const NamedMetricComputation average = - NamedMetricComputation._('average'); + static const NamedMetricComputation average = NamedMetricComputation._( + 'average', + ); /// The name for the computed value tracking the average of outlier samples. - static const NamedMetricComputation outlierAverage = - NamedMetricComputation._('outlierAverage'); + static const NamedMetricComputation outlierAverage = NamedMetricComputation._( + 'outlierAverage', + ); /// The name for the computed value tracking the outlier average divided by /// the clean average. - static const NamedMetricComputation outlierRatio = - NamedMetricComputation._('outlierRatio'); + static const NamedMetricComputation outlierRatio = NamedMetricComputation._( + 'outlierRatio', + ); /// The name for the computed value tracking the noise as a multiple of the /// [average] value takes from clean samples. @@ -77,30 +80,36 @@ sealed class BenchmarkMetricComputation { /// The name for the computed value tracking the 50th percentile value from /// the samples with outliers. - static const PercentileMetricComputation p50 = - PercentileMetricComputation._('p50', 0.5); + static const PercentileMetricComputation p50 = PercentileMetricComputation._( + 'p50', + 0.5, + ); /// The name for the computed value tracking the 90th percentile value from /// the samples with outliers. - static const PercentileMetricComputation p90 = - PercentileMetricComputation._('p90', 0.9); + static const PercentileMetricComputation p90 = PercentileMetricComputation._( + 'p90', + 0.9, + ); /// The name for the computed value tracking the 95th percentile value from /// the samples with outliers. - static const PercentileMetricComputation p95 = - PercentileMetricComputation._('p95', 0.95); + static const PercentileMetricComputation p95 = PercentileMetricComputation._( + 'p95', + 0.95, + ); /// All of the computed vales for each [BenchmarkMetric]. static const List values = [ - average, - outlierAverage, - outlierRatio, - noise, - p50, - p90, - p95, - ]; + average, + outlierAverage, + outlierRatio, + noise, + p50, + p90, + p95, + ]; } /// A [BenchmarkMetricComputation] with a descriptive name. @@ -111,7 +120,7 @@ final class NamedMetricComputation extends BenchmarkMetricComputation { /// A [BenchmarkMetricComputation] describing a percentile (p50, p90, etc.). final class PercentileMetricComputation extends BenchmarkMetricComputation { const PercentileMetricComputation._(super.name, this.percentile) - : assert(percentile >= 0.0 && percentile <= 1.0); + : assert(percentile >= 0.0 && percentile <= 1.0); /// The percentile value as a double. /// @@ -122,15 +131,16 @@ final class PercentileMetricComputation extends BenchmarkMetricComputation { /// metric. static const List values = [ - BenchmarkMetricComputation.p50, - BenchmarkMetricComputation.p90, - BenchmarkMetricComputation.p95, - ]; + BenchmarkMetricComputation.p50, + BenchmarkMetricComputation.p90, + BenchmarkMetricComputation.p95, + ]; /// 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 92a710dbc8b..0b00436ab03 100644 --- a/packages/web_benchmarks/lib/src/recorder.dart +++ b/packages/web_benchmarks/lib/src/recorder.dart @@ -247,8 +247,10 @@ abstract class SceneBuilderRecorder extends Recorder { _profile.record('sceneBuildDuration', () { final Scene scene = sceneBuilder.build(); _profile.record('windowRenderDuration', () { - assert(view != null, - 'Cannot profile windowRenderDuration on a null View.'); + assert( + view != null, + 'Cannot profile windowRenderDuration on a null View.', + ); view!.render(scene); }, reported: false); }, reported: false); @@ -340,10 +342,8 @@ abstract class WidgetRecorder extends Recorder implements FrameRecorder { /// benchmark implementation instead of using a built-in strategy. The /// benchmark is expected to call [Profile.stopWarmingUp] to signal that /// the warm-up phase is finished. - WidgetRecorder({ - required String name, - this.useCustomWarmUp = false, - }) : super._(name, true); + WidgetRecorder({required String name, this.useCustomWarmUp = false}) + : super._(name, true); /// Creates a widget to be benchmarked. /// @@ -411,16 +411,18 @@ abstract class WidgetRecorder extends Recorder implements FrameRecorder { _RecordingWidgetsBinding.ensureInitialized(); final Widget widget = createWidget(); - registerEngineBenchmarkValueListener(BenchmarkMetric.prerollFrame.label, - (num value) { + registerEngineBenchmarkValueListener(BenchmarkMetric.prerollFrame.label, ( + num value, + ) { localProfile.addDataPoint( BenchmarkMetric.prerollFrame.label, Duration(microseconds: value.toInt()), reported: false, ); }); - registerEngineBenchmarkValueListener(BenchmarkMetric.applyFrame.label, - (num value) { + registerEngineBenchmarkValueListener(BenchmarkMetric.applyFrame.label, ( + num value, + ) { localProfile.addDataPoint( BenchmarkMetric.applyFrame.label, Duration(microseconds: value.toInt()), @@ -430,25 +432,26 @@ abstract class WidgetRecorder extends Recorder implements FrameRecorder { late void Function(List frameTimings) frameTimingsCallback; binding.addTimingsCallback( - frameTimingsCallback = (List frameTimings) { - for (final FrameTiming frameTiming in frameTimings) { - localProfile.addDataPoint( - BenchmarkMetric.flutterFrameTotalTime.label, - frameTiming.totalSpan, - reported: false, - ); - localProfile.addDataPoint( - BenchmarkMetric.flutterFrameBuildTime.label, - frameTiming.buildDuration, - reported: false, - ); - localProfile.addDataPoint( - BenchmarkMetric.flutterFrameRasterTime.label, - frameTiming.rasterDuration, - reported: false, - ); - } - }); + frameTimingsCallback = (List frameTimings) { + for (final FrameTiming frameTiming in frameTimings) { + localProfile.addDataPoint( + BenchmarkMetric.flutterFrameTotalTime.label, + frameTiming.totalSpan, + reported: false, + ); + localProfile.addDataPoint( + BenchmarkMetric.flutterFrameBuildTime.label, + frameTiming.buildDuration, + reported: false, + ); + localProfile.addDataPoint( + BenchmarkMetric.flutterFrameRasterTime.label, + frameTiming.rasterDuration, + reported: false, + ); + } + }, + ); binding._beginRecording(this, widget); @@ -591,9 +594,7 @@ class _WidgetBuildRecorderHostState extends State<_WidgetBuildRecorderHost> { @override Widget build(BuildContext context) { - return SizedBox.expand( - child: widget.recorder._getWidgetForFrame(), - ); + return SizedBox.expand(child: widget.recorder._getWidgetForFrame()); } } @@ -603,7 +604,7 @@ class Profile { /// /// [name] and [useCustomWarmUp] must not be null. Profile({required this.name, this.useCustomWarmUp = false}) - : _isWarmingUp = useCustomWarmUp; + : _isWarmingUp = useCustomWarmUp; /// The name of the benchmark that produced this profile. final String name; @@ -624,7 +625,8 @@ class Profile { void stopWarmingUp() { if (!useCustomWarmUp) { throw Exception( - '`stopWarmingUp` should be used only when `useCustomWarmUp` is true.'); + '`stopWarmingUp` should be used only when `useCustomWarmUp` is true.', + ); } else if (!_isWarmingUp) { throw Exception('Warm-up already stopped.'); } else { @@ -677,8 +679,9 @@ class Profile { // We have recorded something, but do we have enough samples? If every // timeseries has collected enough samples, stop the benchmark. - return !scoreData.keys - .every((String key) => scoreData[key]!.count >= kTotalSampleCount); + return !scoreData.keys.every( + (String key) => scoreData[key]!.count >= kTotalSampleCount, + ); } /// Returns a JSON representation of the profile that will be sent to the @@ -925,7 +928,8 @@ void startMeasureFrame(Profile profile) { void endMeasureFrame() { if (!_calledStartMeasureFrame) { throw Exception( - '`startMeasureFrame` has not been called before calling `endMeasureFrame`'); + '`startMeasureFrame` has not been called before calling `endMeasureFrame`', + ); } _calledStartMeasureFrame = false; diff --git a/packages/web_benchmarks/lib/src/runner.dart b/packages/web_benchmarks/lib/src/runner.dart index 9a1eb231fe5..fff7e9f3902 100644 --- a/packages/web_benchmarks/lib/src/runner.dart +++ b/packages/web_benchmarks/lib/src/runner.dart @@ -113,13 +113,10 @@ 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 { @@ -128,33 +125,30 @@ class BenchmarkServer { if (!_processManager.canRun('flutter')) { throw Exception( - "flutter executable is not runnable. Make sure it's in the PATH."); + "flutter executable is not runnable. Make sure it's in the PATH.", + ); } final DateTime startTime = DateTime.now(); print('Building Flutter web app $compilationOptions...'); - final io.ProcessResult buildResult = await _processManager.run( - [ - 'flutter', - 'build', - 'web', - if (compilationOptions.useWasm) ...[ - '--wasm', - '--no-strip-wasm', - ], - '--dart-define=FLUTTER_WEB_ENABLE_PROFILING=true', - if (!treeShakeIcons) '--no-tree-shake-icons', - '--profile', - '-t', - entryPoint, - ], - workingDirectory: benchmarkAppDirectory.path, - ); - - final int buildTime = Duration( - milliseconds: DateTime.now().millisecondsSinceEpoch - - startTime.millisecondsSinceEpoch, - ).inSeconds; + final io.ProcessResult buildResult = await _processManager.run([ + 'flutter', + 'build', + 'web', + if (compilationOptions.useWasm) ...['--wasm', '--no-strip-wasm'], + '--dart-define=FLUTTER_WEB_ENABLE_PROFILING=true', + if (!treeShakeIcons) '--no-tree-shake-icons', + '--profile', + '-t', + entryPoint, + ], workingDirectory: benchmarkAppDirectory.path); + + final int buildTime = + Duration( + milliseconds: + DateTime.now().millisecondsSinceEpoch - + startTime.millisecondsSinceEpoch, + ).inSeconds; print('Build took ${buildTime}s to complete.'); if (buildResult.exitCode != 0) { @@ -194,10 +188,12 @@ class BenchmarkServer { cascade = cascade.add((Request request) async { final Response response = await buildFolderHandler(request); if (response.mimeType == 'text/html') { - return response.change(headers: { - 'Cross-Origin-Opener-Policy': 'same-origin', - 'Cross-Origin-Embedder-Policy': 'require-corp', - }); + return response.change( + headers: { + 'Cross-Origin-Opener-Policy': 'same-origin', + 'Cross-Origin-Embedder-Policy': 'require-corp', + }, + ); } return response; }); @@ -212,18 +208,21 @@ class BenchmarkServer { json.decode(await request.readAsString()) as Map; final String? benchmarkName = profile['name'] as String?; if (benchmarkName != benchmarkIterator.current) { - profileData.completeError(Exception( - 'Browser returned benchmark results from a wrong benchmark.\n' - 'Requested to run benchmark ${benchmarkIterator.current}, but ' - 'got results for $benchmarkName.', - )); + profileData.completeError( + Exception( + 'Browser returned benchmark results from a wrong benchmark.\n' + 'Requested to run benchmark ${benchmarkIterator.current}, but ' + 'got results for $benchmarkName.', + ), + ); unawaited(server.close()); } // Trace data is null when the benchmark is not frame-based, such as RawRecorder. if (latestPerformanceTrace != null) { - final BlinkTraceSummary? traceSummary = - BlinkTraceSummary.fromJson(latestPerformanceTrace!); + final BlinkTraceSummary? traceSummary = BlinkTraceSummary.fromJson( + latestPerformanceTrace!, + ); profile[totalUiFrameAverage] = traceSummary?.averageTotalUIFrameTime.inMicroseconds; profile['scoreKeys'] ??= @@ -233,14 +232,17 @@ class BenchmarkServer { } collectedProfiles.add(profile); return Response.ok('Profile received'); - } else if (request.requestedUri.path - .endsWith('/start-performance-tracing')) { + } else if (request.requestedUri.path.endsWith( + '/start-performance-tracing', + )) { latestPerformanceTrace = null; await chrome!.beginRecordingPerformance( - request.requestedUri.queryParameters['label']); + request.requestedUri.queryParameters['label'], + ); return Response.ok('Started performance tracing'); - } else if (request.requestedUri.path - .endsWith('/stop-performance-tracing')) { + } else if (request.requestedUri.path.endsWith( + '/stop-performance-tracing', + )) { latestPerformanceTrace = await chrome!.endRecordingPerformance(); return Response.ok('Stopped performance tracing'); } else if (request.requestedUri.path.endsWith('/on-error')) { @@ -280,7 +282,8 @@ class BenchmarkServer { return Response.ok('Reported.'); } else { return Response.notFound( - 'This request is not handled by the profile-data handler.'); + 'This request is not handled by the profile-data handler.', + ); } } catch (error, stackTrace) { if (!profileData.isCompleted) { @@ -315,11 +318,14 @@ class BenchmarkServer { try { shelf_io.serveRequests(server, cascade.handler); - final String dartToolDirectory = - path.join(benchmarkAppDirectory.path, '.dart_tool'); - final String userDataDir = io.Directory(dartToolDirectory) - .createTempSync('chrome_user_data_') - .path; + final String dartToolDirectory = path.join( + benchmarkAppDirectory.path, + '.dart_tool', + ); + final String userDataDir = + io.Directory( + dartToolDirectory, + ).createTempSync('chrome_user_data_').path; final ChromeOptions options = ChromeOptions( url: _benchmarkAppUrl, @@ -353,16 +359,18 @@ class BenchmarkServer { throw StateError('Benchmark name is empty'); } - final List scoreKeys = - List.from(profile['scoreKeys'] as Iterable); + final List scoreKeys = List.from( + profile['scoreKeys'] as Iterable, + ); if (scoreKeys.isEmpty) { throw StateError('No score keys in benchmark "$benchmarkName"'); } for (final String scoreKey in scoreKeys) { if (scoreKey.isEmpty) { throw StateError( - 'Score key is empty in benchmark "$benchmarkName". ' - 'Received [${scoreKeys.join(', ')}]'); + 'Score key is empty in benchmark "$benchmarkName". ' + 'Received [${scoreKeys.join(', ')}]', + ); } } @@ -371,10 +379,7 @@ class BenchmarkServer { if (key == 'name' || key == 'scoreKeys') { continue; } - scores.add(BenchmarkScore( - metric: key, - value: profile[key] as num, - )); + scores.add(BenchmarkScore(metric: key, value: profile[key] as num)); } results[benchmarkName] = scores; } diff --git a/packages/web_benchmarks/pubspec.yaml b/packages/web_benchmarks/pubspec.yaml index 422836628cb..e842a9b9f11 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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: collection: ^1.18.0 diff --git a/packages/web_benchmarks/test/src/analysis_test.dart b/packages/web_benchmarks/test/src/analysis_test.dart index c584f58085c..309eb5ea432 100644 --- a/packages/web_benchmarks/test/src/analysis_test.dart +++ b/packages/web_benchmarks/test/src/analysis_test.dart @@ -30,20 +30,19 @@ void main() { ], }, ); - final BenchmarkResults average = - computeAverage([result1, result2]); - expect( - average.toJson(), - >>{ - 'foo': >[ - {'metric': 'foo.bar', 'value': 5}, - {'metric': 'foo.baz', 'value': 10}, - ], - 'bar': >[ - {'metric': 'bar.foo', 'value': 1.7999999999999998}, - ], - }, - ); + final BenchmarkResults average = computeAverage([ + result1, + result2, + ]); + expect(average.toJson(), >>{ + 'foo': >[ + {'metric': 'foo.bar', 'value': 5}, + {'metric': 'foo.baz', 'value': 10}, + ], + 'bar': >[ + {'metric': 'bar.foo', 'value': 1.7999999999999998}, + ], + }); }); test('fails for mismatched benchmark names', () { @@ -57,12 +56,9 @@ void main() { 'foo1': [BenchmarkScore(metric: 'foo.bar', value: 4)], }, ); - expect( - () { - computeAverage([result1, result2]); - }, - throwsException, - ); + expect(() { + computeAverage([result1, result2]); + }, throwsException); }); test('fails for mismatched benchmark metrics', () { @@ -76,27 +72,26 @@ void main() { 'foo': [BenchmarkScore(metric: 'foo.boo', value: 4)], }, ); - expect( - () { - computeAverage([result1, result2]); - }, - throwsException, - ); + expect(() { + computeAverage([result1, result2]); + }, throwsException); }); }); test('computeDelta', () { - final BenchmarkResults benchmark1 = - BenchmarkResults.parse(testBenchmarkResults1); - final BenchmarkResults benchmark2 = - BenchmarkResults.parse(testBenchmarkResults2); + final BenchmarkResults benchmark1 = BenchmarkResults.parse( + testBenchmarkResults1, + ); + final BenchmarkResults benchmark2 = BenchmarkResults.parse( + testBenchmarkResults2, + ); final BenchmarkResults delta = computeDelta(benchmark1, benchmark2); expect(delta.toJson(), expectedBenchmarkDelta); }); } -final Map>> testBenchmarkResults1 = - >>{ +final Map>> +testBenchmarkResults1 = >>{ 'foo': >[ {'metric': 'preroll_frame.average', 'value': 60.5}, {'metric': 'preroll_frame.outlierAverage', 'value': 1400}, @@ -141,8 +136,8 @@ final Map>> testBenchmarkResults1 = ], }; -final Map>> testBenchmarkResults2 = - >>{ +final Map>> +testBenchmarkResults2 = >>{ 'foo': >[ {'metric': 'preroll_frame.average', 'value': 65.5}, {'metric': 'preroll_frame.outlierAverage', 'value': 1410}, @@ -155,11 +150,11 @@ final Map>> testBenchmarkResults2 = {'metric': 'drawFrameDuration.average', 'value': 2000.0}, { 'metric': 'drawFrameDuration.outlierAverage', - 'value': 20000 + 'value': 20000, }, { 'metric': 'drawFrameDuration.outlierRatio', - 'value': 11.05 + 'value': 11.05, }, {'metric': 'drawFrameDuration.noise', 'value': 1.34}, {'metric': 'totalUiFrame.average', 'value': 4150}, @@ -176,11 +171,11 @@ final Map>> testBenchmarkResults2 = {'metric': 'drawFrameDuration.average', 'value': 2000.0}, { 'metric': 'drawFrameDuration.outlierAverage', - 'value': 20000 + 'value': 20000, }, { 'metric': 'drawFrameDuration.outlierRatio', - 'value': 11.05 + 'value': 11.05, }, {'metric': 'drawFrameDuration.noise', 'value': 1.34}, {'metric': 'totalUiFrame.average', 'value': 4150}, @@ -189,138 +184,138 @@ final Map>> testBenchmarkResults2 = final Map>> expectedBenchmarkDelta = >>{ - 'foo': >[ - { - 'metric': 'preroll_frame.average', - 'value': 65.5, - 'delta': 5.0 - }, - { - 'metric': 'preroll_frame.outlierAverage', - 'value': 1410.0, - 'delta': 10.0, - }, - { - 'metric': 'preroll_frame.outlierRatio', - 'value': 20.0, - 'delta': -0.1999999999999993, - }, - { - 'metric': 'preroll_frame.noise', - 'value': 1.5, - 'delta': 0.65, - }, - { - 'metric': 'apply_frame.average', - 'value': 50.0, - 'delta': -30.0, - }, - { - 'metric': 'apply_frame.outlierAverage', - 'value': 100.0, - 'delta': -100.6, - }, - { - 'metric': 'apply_frame.outlierRatio', - 'value': 2.55, - 'delta': 0.04999999999999982, - }, - { - 'metric': 'apply_frame.noise', - 'value': 0.9, - 'delta': 0.5, - }, - { - 'metric': 'drawFrameDuration.average', - 'value': 2000.0, - 'delta': -58.90000000000009, - }, - { - 'metric': 'drawFrameDuration.outlierAverage', - 'value': 20000.0, - 'delta': -4000.0, - }, - { - 'metric': 'drawFrameDuration.outlierRatio', - 'value': 11.05, - 'delta': -1.0, - }, - { - 'metric': 'drawFrameDuration.noise', - 'value': 1.34, - 'delta': 1.0, - }, - { - 'metric': 'totalUiFrame.average', - 'value': 4150.0, - 'delta': -16.0, - }, - ], - 'bar': >[ - { - 'metric': 'preroll_frame.average', - 'value': 65.5, - 'delta': 5.0, - }, - { - 'metric': 'preroll_frame.outlierAverage', - 'value': 1410.0, - 'delta': 10.0, - }, - { - 'metric': 'preroll_frame.outlierRatio', - 'value': 20.0, - 'delta': -0.1999999999999993, - }, - { - 'metric': 'preroll_frame.noise', - 'value': 1.5, - 'delta': 0.65, - }, - { - 'metric': 'apply_frame.average', - 'value': 50.0, - 'delta': -30.0, - }, - { - 'metric': 'apply_frame.outlierAverage', - 'value': 100.0, - 'delta': -100.6, - }, - { - 'metric': 'apply_frame.outlierRatio', - 'value': 2.55, - 'delta': 0.04999999999999982, - }, - { - 'metric': 'apply_frame.noise', - 'value': 0.9, - 'delta': 0.5, - }, - { - 'metric': 'drawFrameDuration.average', - 'value': 2000.0, - 'delta': -58.90000000000009, - }, - { - 'metric': 'drawFrameDuration.outlierAverage', - 'value': 20000.0, - 'delta': -4000.0, - }, - { - 'metric': 'drawFrameDuration.outlierRatio', - 'value': 11.05, - 'delta': -1.0, - }, - { - 'metric': 'drawFrameDuration.noise', - 'value': 1.34, - 'delta': 1.0, - }, - { - 'metric': 'totalUiFrame.average', - 'value': 4150.0, - 'delta': -16.0, - }, - ], -}; + 'foo': >[ + { + 'metric': 'preroll_frame.average', + 'value': 65.5, + 'delta': 5.0, + }, + { + 'metric': 'preroll_frame.outlierAverage', + 'value': 1410.0, + 'delta': 10.0, + }, + { + 'metric': 'preroll_frame.outlierRatio', + 'value': 20.0, + 'delta': -0.1999999999999993, + }, + { + 'metric': 'preroll_frame.noise', + 'value': 1.5, + 'delta': 0.65, + }, + { + 'metric': 'apply_frame.average', + 'value': 50.0, + 'delta': -30.0, + }, + { + 'metric': 'apply_frame.outlierAverage', + 'value': 100.0, + 'delta': -100.6, + }, + { + 'metric': 'apply_frame.outlierRatio', + 'value': 2.55, + 'delta': 0.04999999999999982, + }, + { + 'metric': 'apply_frame.noise', + 'value': 0.9, + 'delta': 0.5, + }, + { + 'metric': 'drawFrameDuration.average', + 'value': 2000.0, + 'delta': -58.90000000000009, + }, + { + 'metric': 'drawFrameDuration.outlierAverage', + 'value': 20000.0, + 'delta': -4000.0, + }, + { + 'metric': 'drawFrameDuration.outlierRatio', + 'value': 11.05, + 'delta': -1.0, + }, + { + 'metric': 'drawFrameDuration.noise', + 'value': 1.34, + 'delta': 1.0, + }, + { + 'metric': 'totalUiFrame.average', + 'value': 4150.0, + 'delta': -16.0, + }, + ], + 'bar': >[ + { + 'metric': 'preroll_frame.average', + 'value': 65.5, + 'delta': 5.0, + }, + { + 'metric': 'preroll_frame.outlierAverage', + 'value': 1410.0, + 'delta': 10.0, + }, + { + 'metric': 'preroll_frame.outlierRatio', + 'value': 20.0, + 'delta': -0.1999999999999993, + }, + { + 'metric': 'preroll_frame.noise', + 'value': 1.5, + 'delta': 0.65, + }, + { + 'metric': 'apply_frame.average', + 'value': 50.0, + 'delta': -30.0, + }, + { + 'metric': 'apply_frame.outlierAverage', + 'value': 100.0, + 'delta': -100.6, + }, + { + 'metric': 'apply_frame.outlierRatio', + 'value': 2.55, + 'delta': 0.04999999999999982, + }, + { + 'metric': 'apply_frame.noise', + 'value': 0.9, + 'delta': 0.5, + }, + { + 'metric': 'drawFrameDuration.average', + 'value': 2000.0, + 'delta': -58.90000000000009, + }, + { + 'metric': 'drawFrameDuration.outlierAverage', + 'value': 20000.0, + 'delta': -4000.0, + }, + { + 'metric': 'drawFrameDuration.outlierRatio', + 'value': 11.05, + 'delta': -1.0, + }, + { + 'metric': 'drawFrameDuration.noise', + 'value': 1.34, + 'delta': 1.0, + }, + { + 'metric': 'totalUiFrame.average', + 'value': 4150.0, + 'delta': -16.0, + }, + ], + }; diff --git a/packages/web_benchmarks/test/src/benchmark_result_test.dart b/packages/web_benchmarks/test/src/benchmark_result_test.dart index 65adee8556a..19ccf1a1abc 100644 --- a/packages/web_benchmarks/test/src/benchmark_result_test.dart +++ b/packages/web_benchmarks/test/src/benchmark_result_test.dart @@ -15,7 +15,7 @@ void main() { ], 'bar': >[ {'metric': 'bar.foo', 'value': 1.23}, - ] + ], }; final BenchmarkResults benchmarkResults = BenchmarkResults.parse(data); diff --git a/packages/web_benchmarks/test/src/browser_test.dart b/packages/web_benchmarks/test/src/browser_test.dart index a9239978388..7f61f841f82 100644 --- a/packages/web_benchmarks/test/src/browser_test.dart +++ b/packages/web_benchmarks/test/src/browser_test.dart @@ -11,14 +11,17 @@ import 'browser_test_json_samples.dart'; void main() { group('BlinkTraceEvent works with Chrome 89+', () { // Used to test 'false' results - final BlinkTraceEvent unrelatedPhX = - BlinkTraceEvent.fromJson(unrelatedPhXJson); - final BlinkTraceEvent anotherUnrelated = - BlinkTraceEvent.fromJson(anotherUnrelatedJson); + final BlinkTraceEvent unrelatedPhX = BlinkTraceEvent.fromJson( + unrelatedPhXJson, + ); + final BlinkTraceEvent anotherUnrelated = BlinkTraceEvent.fromJson( + anotherUnrelatedJson, + ); test('isBeginFrame', () { - final BlinkTraceEvent event = - BlinkTraceEvent.fromJson(beginMainFrameJson_89plus); + final BlinkTraceEvent event = BlinkTraceEvent.fromJson( + beginMainFrameJson_89plus, + ); expect(event.isBeginFrame, isTrue); expect(unrelatedPhX.isBeginFrame, isFalse); @@ -26,8 +29,9 @@ void main() { }); test('isUpdateAllLifecyclePhases', () { - final BlinkTraceEvent event = - BlinkTraceEvent.fromJson(updateLifecycleJson_89plus); + final BlinkTraceEvent event = BlinkTraceEvent.fromJson( + updateLifecycleJson_89plus, + ); expect(event.isUpdateAllLifecyclePhases, isTrue); expect(unrelatedPhX.isUpdateAllLifecyclePhases, isFalse); @@ -35,8 +39,9 @@ void main() { }); test('isBeginMeasuredFrame', () { - final BlinkTraceEvent event = - BlinkTraceEvent.fromJson(beginMeasuredFrameJson_89plus); + final BlinkTraceEvent event = BlinkTraceEvent.fromJson( + beginMeasuredFrameJson_89plus, + ); expect(event.isBeginMeasuredFrame, isTrue); expect(unrelatedPhX.isBeginMeasuredFrame, isFalse); @@ -44,8 +49,9 @@ void main() { }); test('isEndMeasuredFrame', () { - final BlinkTraceEvent event = - BlinkTraceEvent.fromJson(endMeasuredFrameJson_89plus); + final BlinkTraceEvent event = BlinkTraceEvent.fromJson( + endMeasuredFrameJson_89plus, + ); expect(event.isEndMeasuredFrame, isTrue); expect(unrelatedPhX.isEndMeasuredFrame, isFalse); diff --git a/packages/web_benchmarks/test/src/browser_test_json_samples.dart b/packages/web_benchmarks/test/src/browser_test_json_samples.dart index aa6c56e4d8c..cf34fd8a7cd 100644 --- a/packages/web_benchmarks/test/src/browser_test_json_samples.dart +++ b/packages/web_benchmarks/test/src/browser_test_json_samples.dart @@ -8,7 +8,8 @@ import 'dart:convert' show jsonDecode; // integration tests of this package that dumped all the data as captured. /// To test isBeginFrame. (Sampled from Chrome 89+) -final Map beginMainFrameJson_89plus = jsonDecode(''' +final Map beginMainFrameJson_89plus = + jsonDecode(''' { "args": { "frameTime": 2338687248768 @@ -23,10 +24,12 @@ final Map beginMainFrameJson_89plus = jsonDecode(''' "ts": 2338687258440, "tts": 375499 } -''') as Map; +''') + as Map; /// To test isUpdateAllLifecyclePhases. (Sampled from Chrome 89+) -final Map updateLifecycleJson_89plus = jsonDecode(''' +final Map updateLifecycleJson_89plus = + jsonDecode(''' { "args": {}, "cat": "blink", @@ -39,10 +42,12 @@ final Map updateLifecycleJson_89plus = jsonDecode(''' "ts": 2338687265284, "tts": 375900 } -''') as Map; +''') + as Map; /// To test isBeginMeasuredFrame. (Sampled from Chrome 89+) -final Map beginMeasuredFrameJson_89plus = jsonDecode(''' +final Map beginMeasuredFrameJson_89plus = + jsonDecode(''' { "args": {}, "cat": "blink.user_timing", @@ -54,10 +59,12 @@ final Map beginMeasuredFrameJson_89plus = jsonDecode(''' "tid": 1, "ts": 2338687265932 } -''') as Map; +''') + as Map; /// To test isEndMeasuredFrame. (Sampled from Chrome 89+) -final Map endMeasuredFrameJson_89plus = jsonDecode(''' +final Map endMeasuredFrameJson_89plus = + jsonDecode(''' { "args": {}, "cat": "blink.user_timing", @@ -69,10 +76,12 @@ final Map endMeasuredFrameJson_89plus = jsonDecode(''' "tid": 1, "ts": 2338687440485 } -''') as Map; +''') + as Map; /// An unrelated data frame to test negative cases. -final Map unrelatedPhXJson = jsonDecode(''' +final Map unrelatedPhXJson = + jsonDecode(''' { "args": {}, "cat": "blink,rail", @@ -85,10 +94,12 @@ final Map unrelatedPhXJson = jsonDecode(''' "ts": 2338691143317, "tts": 1685405 } -''') as Map; +''') + as Map; /// Another unrelated data frame to test negative cases. -final Map anotherUnrelatedJson = jsonDecode(''' +final Map anotherUnrelatedJson = + jsonDecode(''' { "args": { "sort_index": -1 @@ -100,4 +111,5 @@ final Map anotherUnrelatedJson = jsonDecode(''' "tid": 1, "ts": 2338692906482 } -''') as Map; +''') + as Map; diff --git a/packages/web_benchmarks/test/src/computations_test.dart b/packages/web_benchmarks/test/src/computations_test.dart index 94fe4407943..3b9f3fe5719 100644 --- a/packages/web_benchmarks/test/src/computations_test.dart +++ b/packages/web_benchmarks/test/src/computations_test.dart @@ -8,11 +8,13 @@ import 'package:web_benchmarks/src/computations.dart'; void main() { group('computations', () { test('computePercentiles', () { - final Map computed = computePercentiles( - 'test', - [0.0, 0.5, 0.9, 0.95, 1.0], - List.generate(100, (int i) => i.toDouble()), - ); + final Map computed = computePercentiles('test', [ + 0.0, + 0.5, + 0.9, + 0.95, + 1.0, + ], List.generate(100, (int i) => i.toDouble())); expect(computed.length, 5); expect(computed[0.0], 0.0); expect(computed[0.5], 50.0); diff --git a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/automator.dart b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/automator.dart index 9484a544144..26a627e908b 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/automator.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/automator.dart @@ -92,8 +92,9 @@ class Automator { } Future _handleAppScroll() async { - final ScrollableState scrollable = - Scrollable.of(find.byKey(textKey).evaluate().single); + final ScrollableState scrollable = Scrollable.of( + find.byKey(textKey).evaluate().single, + ); await scrollable.position.animateTo( 30000, curve: Curves.linear, @@ -120,8 +121,9 @@ class Automator { void _handleSimpleBenchmarkPathCheck() { // Record whether the URL contains the expected path so we can verify the // behavior of setting the `benchmarkPath` on the benchmark server. - final bool containsExpectedPath = - window.location.toString().contains(testBenchmarkPath); + final bool containsExpectedPath = window.location.toString().contains( + testBenchmarkPath, + ); profile.extraData['expectedUrl'] = containsExpectedPath ? 1 : 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 2887ba9b7c2..11c0a22cc92 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 @@ -8,14 +8,12 @@ import '../common.dart'; 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), - }, - ); + await runBenchmarks({ + 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 f8f54492c3e..d125a70e14c 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 @@ -8,12 +8,9 @@ import '../common.dart'; import '../recorder.dart'; Future main() async { - await runBenchmarks( - { - BenchmarkName.simpleBenchmarkPathCheck.name: () => TestAppRecorder( - benchmark: BenchmarkName.simpleBenchmarkPathCheck, - ), - }, - benchmarkPath: testBenchmarkPath, - ); + await runBenchmarks({ + 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 301ca2111e7..fd58c8f7dd4 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 @@ -8,11 +8,8 @@ import '../common.dart'; import '../recorder.dart'; Future main() async { - await runBenchmarks( - { - BenchmarkName.simpleCompilationCheck.name: () => TestAppRecorder( - benchmark: BenchmarkName.simpleCompilationCheck, - ), - }, - ); + await runBenchmarks({ + BenchmarkName.simpleCompilationCheck.name: + () => TestAppRecorder(benchmark: BenchmarkName.simpleCompilationCheck), + }); } diff --git a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/common.dart b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/common.dart index 8045852f64d..4e592473a55 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/common.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/common.dart @@ -11,5 +11,5 @@ enum BenchmarkName { appScroll, appTap, simpleBenchmarkPathCheck, - simpleCompilationCheck; + simpleCompilationCheck, } diff --git a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/recorder.dart b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/recorder.dart index 8b0abd0d125..f1d095efe05 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/recorder.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/recorder.dart @@ -11,7 +11,7 @@ import 'common.dart'; /// A recorder that measures frame building durations for the test app. class TestAppRecorder extends WidgetRecorder { TestAppRecorder({required this.benchmark}) - : super(name: benchmark.name, useCustomWarmUp: true); + : super(name: benchmark.name, useCustomWarmUp: true); /// The name of the benchmark to be run. /// 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 6a299084647..0141f9c9e0e 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 @@ -14,20 +14,16 @@ import 'package:web_benchmarks/src/common.dart'; import 'test_infra/common.dart'; Future main() async { - test( - 'Can run a web benchmark', - () async { - await _runBenchmarks( - benchmarkNames: [ - BenchmarkName.appNavigate.name, - BenchmarkName.appScroll.name, - BenchmarkName.appTap.name, - ], - entryPoint: 'benchmark/test_infra/client/app_client.dart', - ); - }, - timeout: Timeout.none, - ); + test('Can run a web benchmark', () async { + await _runBenchmarks( + benchmarkNames: [ + BenchmarkName.appNavigate.name, + BenchmarkName.appScroll.name, + BenchmarkName.appTap.name, + ], + entryPoint: 'benchmark/test_infra/client/app_client.dart', + ); + }, timeout: Timeout.none); test( 'Can run a web benchmark with an alternate benchmarkPath', @@ -46,35 +42,32 @@ Future main() async { // The runner puts an `expectedUrl` metric in the results so that we can // verify the initial page value that should be passed on initial load // and on reloads. - final BenchmarkScore expectedUrlScore = scores! - .firstWhere((BenchmarkScore score) => score.metric == 'expectedUrl'); + final BenchmarkScore expectedUrlScore = scores!.firstWhere( + (BenchmarkScore score) => score.metric == 'expectedUrl', + ); expect(expectedUrlScore.value, 1); }, timeout: Timeout.none, ); - test( - 'Can run a web benchmark with wasm', - () async { - final BenchmarkResults results = await _runBenchmarks( - benchmarkNames: [BenchmarkName.simpleCompilationCheck.name], - entryPoint: - 'benchmark/test_infra/client/simple_compilation_client.dart', - compilationOptions: const CompilationOptions.wasm(), - ); + test('Can run a web benchmark with wasm', () async { + final BenchmarkResults results = await _runBenchmarks( + benchmarkNames: [BenchmarkName.simpleCompilationCheck.name], + entryPoint: 'benchmark/test_infra/client/simple_compilation_client.dart', + compilationOptions: const CompilationOptions.wasm(), + ); - // The runner puts an `isWasm` metric in the results so that we can verify - // we are running with the correct compiler and renderer. - final List? scores = - results.scores[BenchmarkName.simpleCompilationCheck.name]; - expect(scores, isNotNull); + // The runner puts an `isWasm` metric in the results so that we can verify + // we are running with the correct compiler and renderer. + final List? scores = + results.scores[BenchmarkName.simpleCompilationCheck.name]; + expect(scores, isNotNull); - final BenchmarkScore isWasmScore = scores! - .firstWhere((BenchmarkScore score) => score.metric == 'isWasm'); - expect(isWasmScore.value, 1); - }, - timeout: Timeout.none, - ); + final BenchmarkScore isWasmScore = scores!.firstWhere( + (BenchmarkScore score) => score.metric == 'isWasm', + ); + expect(isWasmScore.value, 1); + }, timeout: Timeout.none); } Future _runBenchmarks({ @@ -92,25 +85,30 @@ Future _runBenchmarks({ ); final List expectedMetrics = - expectedBenchmarkMetrics(useWasm: compilationOptions.useWasm) - .map((BenchmarkMetric metric) => metric.label) - .toList(); + expectedBenchmarkMetrics( + useWasm: compilationOptions.useWasm, + ).map((BenchmarkMetric metric) => metric.label).toList(); for (final String benchmarkName in benchmarkNames) { for (final String metricName in expectedMetrics) { for (final BenchmarkMetricComputation computation in BenchmarkMetricComputation.values) { expect( - taskResult.scores[benchmarkName]!.where((BenchmarkScore score) => - score.metric == '$metricName.${computation.name}'), - hasLength(1), - reason: 'Expected to find a metric named ' - '$metricName.${computation.name}'); + taskResult.scores[benchmarkName]!.where( + (BenchmarkScore score) => + score.metric == '$metricName.${computation.name}', + ), + hasLength(1), + reason: + 'Expected to find a metric named ' + '$metricName.${computation.name}', + ); } } expect( - taskResult.scores[benchmarkName]! - .where((BenchmarkScore score) => score.metric == totalUiFrameAverage), + taskResult.scores[benchmarkName]!.where( + (BenchmarkScore score) => score.metric == totalUiFrameAverage, + ), hasLength(1), ); } diff --git a/packages/web_benchmarks/testing/test_app/lib/main.dart b/packages/web_benchmarks/testing/test_app/lib/main.dart index 172abba3288..542875c0c46 100644 --- a/packages/web_benchmarks/testing/test_app/lib/main.dart +++ b/packages/web_benchmarks/testing/test_app/lib/main.dart @@ -20,10 +20,7 @@ final GoRouter _router = GoRouter( path: '/', builder: (_, __) => const HomePage(title: 'Flutter Demo Home Page'), ), - GoRoute( - path: '/about', - builder: (_, __) => const AboutPage(), - ), + GoRoute(path: '/about', builder: (_, __) => const AboutPage()), ], ); diff --git a/packages/web_benchmarks/testing/test_app/pubspec.yaml b/packages/web_benchmarks/testing/test_app/pubspec.yaml index d6b2aa9bd67..8b8bdc3aacf 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.6.0 + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/web_benchmarks/tool/run_tests.dart b/packages/web_benchmarks/tool/run_tests.dart index 3e0fb093442..2205fff0f5f 100644 --- a/packages/web_benchmarks/tool/run_tests.dart +++ b/packages/web_benchmarks/tool/run_tests.dart @@ -24,31 +24,26 @@ Future main(List args) async { final Directory packageDir = Directory(p.dirname(Platform.script.path)).parent; - final String testingAppDirPath = - p.join(packageDir.path, 'testing', 'test_app'); + final String testingAppDirPath = p.join( + packageDir.path, + 'testing', + 'test_app', + ); // Fetch the test app's dependencies. - int status = await _runProcess( - 'flutter', - [ - 'pub', - 'get', - ], - workingDirectory: testingAppDirPath, - ); + int status = await _runProcess('flutter', [ + 'pub', + 'get', + ], workingDirectory: testingAppDirPath); if (status != 0) { exit(status); } // Run the tests. - status = await _runProcess( - 'flutter', - [ - 'test', - 'testing', - ], - workingDirectory: packageDir.path, - ); + status = await _runProcess('flutter', [ + 'test', + 'testing', + ], workingDirectory: packageDir.path); exit(status); } @@ -67,10 +62,8 @@ Future _runProcess( List arguments, { String? workingDirectory, }) async { - final Process process = await _streamOutput(Process.start( - command, - arguments, - workingDirectory: workingDirectory, - )); + final Process process = await _streamOutput( + Process.start(command, arguments, workingDirectory: workingDirectory), + ); return process.exitCode; } diff --git a/packages/webview_flutter/webview_flutter/CHANGELOG.md b/packages/webview_flutter/webview_flutter/CHANGELOG.md index 50311c69cfc..237a1b3f7f8 100644 --- a/packages/webview_flutter/webview_flutter/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 4.13.0 * Adds support to respond to recoverable SSL certificate errors. See `NavigationDelegate(onSSlAuthError)`. diff --git a/packages/webview_flutter/webview_flutter/README.md b/packages/webview_flutter/webview_flutter/README.md index eaab72089d7..8bd3e087015 100644 --- a/packages/webview_flutter/webview_flutter/README.md +++ b/packages/webview_flutter/webview_flutter/README.md @@ -21,26 +21,27 @@ 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). @@ -54,6 +55,7 @@ Widget build(BuildContext context) { body: WebViewWidget(controller: controller), ); } + ``` See the Dartdocs for [WebViewController](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewController-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 6307f311b19..59838e3dda1 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 @@ -22,41 +22,50 @@ import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; Future main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - final HttpServer server = - await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - unawaited(server.forEach((HttpRequest request) { - if (request.uri.path == '/hello.txt') { - request.response.writeln('Hello, world.'); - } else if (request.uri.path == '/secondary.txt') { - request.response.writeln('How are you today?'); - } else if (request.uri.path == '/headers') { - request.response.writeln('${request.headers}'); - } else if (request.uri.path == '/favicon.ico') { - request.response.statusCode = HttpStatus.notFound; - } else if (request.uri.path == '/http-basic-authentication') { - final List? authHeader = - request.headers[HttpHeaders.authorizationHeader]; - if (authHeader != null) { - final String encodedCredential = authHeader.first.split(' ')[1]; - final String credential = - String.fromCharCodes(base64Decode(encodedCredential)); - if (credential == 'user:password') { - request.response.writeln('Authorized'); + final HttpServer server = await HttpServer.bind( + InternetAddress.loopbackIPv4, + 0, + ); + unawaited( + server.forEach((HttpRequest request) { + if (request.uri.path == '/hello.txt') { + request.response.writeln('Hello, world.'); + } else if (request.uri.path == '/secondary.txt') { + request.response.writeln('How are you today?'); + } else if (request.uri.path == '/headers') { + request.response.writeln('${request.headers}'); + } else if (request.uri.path == '/favicon.ico') { + request.response.statusCode = HttpStatus.notFound; + } else if (request.uri.path == '/http-basic-authentication') { + final List? authHeader = + request.headers[HttpHeaders.authorizationHeader]; + if (authHeader != null) { + final String encodedCredential = authHeader.first.split(' ')[1]; + final String credential = String.fromCharCodes( + base64Decode(encodedCredential), + ); + if (credential == 'user:password') { + request.response.writeln('Authorized'); + } else { + request.response.headers.add( + HttpHeaders.wwwAuthenticateHeader, + 'Basic realm="Test realm"', + ); + request.response.statusCode = HttpStatus.unauthorized; + } } else { request.response.headers.add( - HttpHeaders.wwwAuthenticateHeader, 'Basic realm="Test realm"'); + HttpHeaders.wwwAuthenticateHeader, + 'Basic realm="Test realm"', + ); request.response.statusCode = HttpStatus.unauthorized; } } else { - request.response.headers - .add(HttpHeaders.wwwAuthenticateHeader, 'Basic realm="Test realm"'); - request.response.statusCode = HttpStatus.unauthorized; + fail('unexpected request: ${request.method} ${request.uri}'); } - } else { - fail('unexpected request: ${request.method} ${request.uri}'); - } - request.response.close(); - })); + request.response.close(); + }), + ); final String prefixUrl = 'http://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; final String secondaryUrl = '$prefixUrl/secondary.txt'; @@ -101,7 +110,7 @@ Future main() async { testWidgets('loadRequest with headers', (WidgetTester tester) async { final Map headers = { - 'test_header': 'flutter_test_header' + 'test_header': 'flutter_test_header', }; final StreamController pageLoads = StreamController(); @@ -118,9 +127,11 @@ Future main() async { await pageLoads.stream.firstWhere((String url) => url == headersUrl); - final String content = await controller.runJavaScriptReturningResult( - 'document.documentElement.innerText', - ) as String; + final String content = + await controller.runJavaScriptReturningResult( + 'document.documentElement.innerText', + ) + as String; expect(content.contains('flutter_test_header'), isTrue); }); @@ -158,16 +169,18 @@ Future main() async { final Completer onPageFinished = Completer(); bool resizeButtonTapped = false; - await tester.pumpWidget(ResizableWebView( - onResize: () { - if (resizeButtonTapped) { - buttonTapResizeCompleter.complete(); - } else { - initialResizeCompleter.complete(); - } - }, - onPageFinished: () => onPageFinished.complete(), - )); + await tester.pumpWidget( + ResizableWebView( + onResize: () { + if (resizeButtonTapped) { + buttonTapResizeCompleter.complete(); + } else { + initialResizeCompleter.complete(); + } + }, + onPageFinished: () => onPageFinished.complete(), + ), + ); await onPageFinished.future; // Wait for a potential call to resize after page is loaded. @@ -189,9 +202,9 @@ Future main() async { final WebViewController controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); - await controller.setNavigationDelegate(NavigationDelegate( - onPageFinished: (_) => pageFinished.complete(), - )); + await controller.setNavigationDelegate( + NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), + ); await controller.setUserAgent('Custom_User_Agent1'); await controller.loadRequest(Uri.parse('about:blank')); @@ -203,136 +216,146 @@ Future main() async { expect(customUserAgent, 'Custom_User_Agent1'); }); - group('Video playback policy', () { - testWidgets('Auto media playback', (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); - Completer pageLoaded = Completer(); - - late PlatformWebViewControllerCreationParams params; - if (defaultTargetPlatform == TargetPlatform.iOS) { - params = WebKitWebViewControllerCreationParams( - mediaTypesRequiringUserAction: const {}, - ); - } else { - params = const PlatformWebViewControllerCreationParams(); - } + group( + 'Video playback policy', + () { + testWidgets('Auto media playback', (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + Completer pageLoaded = Completer(); + + late PlatformWebViewControllerCreationParams params; + if (defaultTargetPlatform == TargetPlatform.iOS) { + params = WebKitWebViewControllerCreationParams( + mediaTypesRequiringUserAction: const {}, + ); + } else { + params = const PlatformWebViewControllerCreationParams(); + } - WebViewController controller = - WebViewController.fromPlatformCreationParams(params); - await controller.setJavaScriptMode(JavaScriptMode.unrestricted); + WebViewController controller = + WebViewController.fromPlatformCreationParams(params); + await controller.setJavaScriptMode(JavaScriptMode.unrestricted); - await controller.setNavigationDelegate( - NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), - ); + await controller.setNavigationDelegate( + NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), + ); - if (controller.platform is AndroidWebViewController) { - await (controller.platform as AndroidWebViewController) - .setMediaPlaybackRequiresUserGesture(false); - } + if (controller.platform is AndroidWebViewController) { + await (controller.platform as AndroidWebViewController) + .setMediaPlaybackRequiresUserGesture(false); + } - await controller.loadRequest( - Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'), - ); + await controller.loadRequest( + Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'), + ); - await tester.pumpWidget(WebViewWidget(controller: controller)); + await tester.pumpWidget(WebViewWidget(controller: controller)); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - await pageLoaded.future; + await pageLoaded.future; - bool isPaused = - await controller.runJavaScriptReturningResult('isPaused();') as bool; - expect(isPaused, false); + bool isPaused = + await controller.runJavaScriptReturningResult('isPaused();') + as bool; + expect(isPaused, false); - pageLoaded = Completer(); - controller = WebViewController(); - await controller.setJavaScriptMode(JavaScriptMode.unrestricted); + pageLoaded = Completer(); + controller = WebViewController(); + await controller.setJavaScriptMode(JavaScriptMode.unrestricted); - await controller.setNavigationDelegate( - NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), - ); + await controller.setNavigationDelegate( + NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), + ); - await controller.loadRequest( - Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'), - ); + await controller.loadRequest( + Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'), + ); - await tester.pumpWidget(WebViewWidget(controller: controller)); + await tester.pumpWidget(WebViewWidget(controller: controller)); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - await pageLoaded.future; + await pageLoaded.future; - isPaused = - await controller.runJavaScriptReturningResult('isPaused();') as bool; - expect(isPaused, true); - }); + isPaused = + await controller.runJavaScriptReturningResult('isPaused();') + as bool; + expect(isPaused, true); + }); - testWidgets('Video plays inline', (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); - final Completer pageLoaded = Completer(); - final Completer videoPlaying = Completer(); + testWidgets('Video plays inline', (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + final Completer pageLoaded = Completer(); + final Completer videoPlaying = Completer(); + + late PlatformWebViewControllerCreationParams params; + if (defaultTargetPlatform == TargetPlatform.iOS) { + params = WebKitWebViewControllerCreationParams( + mediaTypesRequiringUserAction: const {}, + allowsInlineMediaPlayback: true, + ); + } else { + params = const PlatformWebViewControllerCreationParams(); + } + final WebViewController controller = + WebViewController.fromPlatformCreationParams(params); + await controller.setJavaScriptMode(JavaScriptMode.unrestricted); - late PlatformWebViewControllerCreationParams params; - if (defaultTargetPlatform == TargetPlatform.iOS) { - params = WebKitWebViewControllerCreationParams( - mediaTypesRequiringUserAction: const {}, - allowsInlineMediaPlayback: true, + await controller.setNavigationDelegate( + NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), ); - } else { - params = const PlatformWebViewControllerCreationParams(); - } - final WebViewController controller = - WebViewController.fromPlatformCreationParams(params); - await controller.setJavaScriptMode(JavaScriptMode.unrestricted); - await controller.setNavigationDelegate( - NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), - ); + await controller.addJavaScriptChannel( + 'VideoTestTime', + onMessageReceived: (JavaScriptMessage message) { + final double currentTime = double.parse(message.message); + // Let it play for at least 1 second to make sure the related video's properties are set. + if (currentTime > 1 && !videoPlaying.isCompleted) { + videoPlaying.complete(null); + } + }, + ); - await controller.addJavaScriptChannel( - 'VideoTestTime', - onMessageReceived: (JavaScriptMessage message) { - final double currentTime = double.parse(message.message); - // Let it play for at least 1 second to make sure the related video's properties are set. - if (currentTime > 1 && !videoPlaying.isCompleted) { - videoPlaying.complete(null); - } - }, - ); + if (controller.platform is AndroidWebViewController) { + await (controller.platform as AndroidWebViewController) + .setMediaPlaybackRequiresUserGesture(false); + } - if (controller.platform is AndroidWebViewController) { - await (controller.platform as AndroidWebViewController) - .setMediaPlaybackRequiresUserGesture(false); - } + await controller.loadRequest( + Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'), + ); - await controller.loadRequest( - Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'), - ); + await tester.pumpWidget(WebViewWidget(controller: controller)); + await tester.pumpAndSettle(); - await tester.pumpWidget(WebViewWidget(controller: controller)); - await tester.pumpAndSettle(); + await pageLoaded.future; - await pageLoaded.future; + // Makes sure we get the correct event that indicates the video is actually playing. + await videoPlaying.future; - // Makes sure we get the correct event that indicates the video is actually playing. - await videoPlaying.future; + final bool fullScreen = + await controller.runJavaScriptReturningResult('isFullScreen();') + as bool; + expect(fullScreen, false); + }); + }, + // TODO(bparrishMines): Stop skipping once https://github.com/flutter/flutter/issues/148487 is resolved + skip: true, + ); - final bool fullScreen = await controller - .runJavaScriptReturningResult('isFullScreen();') as bool; - expect(fullScreen, false); - }); - }, - // TODO(bparrishMines): Stop skipping once https://github.com/flutter/flutter/issues/148487 is resolved - skip: true); - - group('Audio playback policy', () { - late String audioTestBase64; - setUpAll(() async { - final ByteData audioData = - await rootBundle.load('assets/sample_audio.ogg'); - final String base64AudioData = - base64Encode(Uint8List.view(audioData.buffer)); - final String audioTest = ''' + group( + 'Audio playback policy', + () { + late String audioTestBase64; + setUpAll(() async { + final ByteData audioData = await rootBundle.load( + 'assets/sample_audio.ogg', + ); + final String base64AudioData = base64Encode( + Uint8List.view(audioData.buffer), + ); + final String audioTest = ''' Audio auto play '''; - final String iframeTestBase64 = - base64Encode(const Utf8Encoder().convert(iframe)); + final String iframeTestBase64 = base64Encode( + const Utf8Encoder().convert(iframe), + ); - final String openWindowTest = ''' + final String openWindowTest = ''' @@ -1384,48 +1471,52 @@ Future main() async { '''; - final String openWindowTestBase64 = - base64Encode(const Utf8Encoder().convert(openWindowTest)); + final String openWindowTestBase64 = base64Encode( + const Utf8Encoder().convert(openWindowTest), + ); - final Completer pageLoadCompleter = Completer(); + final Completer pageLoadCompleter = Completer(); - final PlatformWebViewController controller = PlatformWebViewController( - const PlatformWebViewControllerCreationParams(), - ); - await controller.setJavaScriptMode(JavaScriptMode.unrestricted); - final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams(), - ); - await delegate.setOnPageFinished((_) => pageLoadCompleter.complete()); - await controller.setPlatformNavigationDelegate(delegate); - await controller.loadRequest( - LoadRequestParams( - uri: Uri.parse( - 'data:text/html;charset=utf-8;base64,$openWindowTestBase64', - ), + final PlatformWebViewController controller = PlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); + await controller.setJavaScriptMode(JavaScriptMode.unrestricted); + final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + await delegate.setOnPageFinished((_) => pageLoadCompleter.complete()); + await controller.setPlatformNavigationDelegate(delegate); + await controller.loadRequest( + LoadRequestParams( + uri: Uri.parse( + 'data:text/html;charset=utf-8;base64,$openWindowTestBase64', ), - ); + ), + ); - await tester.pumpWidget(Builder( + await tester.pumpWidget( + Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, - )); + ), + ); - await pageLoadCompleter.future; + await pageLoadCompleter.future; - final bool iframeLoaded = - await controller.runJavaScriptReturningResult('iframeLoaded') as bool; - expect(iframeLoaded, true); + final bool iframeLoaded = + await controller.runJavaScriptReturningResult('iframeLoaded') as bool; + expect(iframeLoaded, true); - final String elementText = await controller.runJavaScriptReturningResult( - 'document.querySelector("p") && document.querySelector("p").textContent', - ) as String; - expect(elementText, 'null'); - }, - ); + final String elementText = + await controller.runJavaScriptReturningResult( + 'document.querySelector("p") && document.querySelector("p").textContent', + ) + as String; + expect(elementText, 'null'); + }); testWidgets( '`AndroidWebViewController` can be reused with a new `AndroidWebViewWidget`', @@ -1440,120 +1531,131 @@ Future main() async { ); await delegate.setOnPageFinished((_) => pageLoaded.complete()); await controller.setPlatformNavigationDelegate(delegate); - await controller - .loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); + await controller.loadRequest( + LoadRequestParams(uri: Uri.parse(primaryUrl)), + ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageLoaded.future; await tester.pumpWidget(Container()); await tester.pumpAndSettle(); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); pageLoaded = Completer(); await controller.loadRequest( LoadRequestParams(uri: Uri.parse(primaryUrl)), ); - await expectLater( - pageLoaded.future, - completes, - ); + await expectLater(pageLoaded.future, completes); }, ); - testWidgets('can receive JavaScript alert dialogs', - (WidgetTester tester) async { + testWidgets('can receive JavaScript alert dialogs', ( + WidgetTester tester, + ) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final Completer alertMessage = Completer(); - await controller.setOnJavaScriptAlertDialog( - (JavaScriptAlertDialogRequest request) async { - alertMessage.complete(request.message); - }, - ); + await controller.setOnJavaScriptAlertDialog(( + JavaScriptAlertDialogRequest request, + ) async { + alertMessage.complete(request.message); + }); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await controller.runJavaScript('alert("alert message")'); await expectLater(alertMessage.future, completion('alert message')); }); - testWidgets('can receive JavaScript confirm dialogs', - (WidgetTester tester) async { + testWidgets('can receive JavaScript confirm dialogs', ( + WidgetTester tester, + ) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final Completer confirmMessage = Completer(); - await controller.setOnJavaScriptConfirmDialog( - (JavaScriptConfirmDialogRequest request) async { - confirmMessage.complete(request.message); - return true; - }, - ); + await controller.setOnJavaScriptConfirmDialog(( + JavaScriptConfirmDialogRequest request, + ) async { + confirmMessage.complete(request.message); + return true; + }); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await controller.runJavaScript('confirm("confirm message")'); await expectLater(confirmMessage.future, completion('confirm message')); }); - testWidgets('can receive JavaScript prompt dialogs', - (WidgetTester tester) async { + testWidgets('can receive JavaScript prompt dialogs', ( + WidgetTester tester, + ) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); - await controller.setOnJavaScriptTextInputDialog( - (JavaScriptTextInputDialogRequest request) async { - return 'return message'; - }, - ); + await controller.setOnJavaScriptTextInputDialog(( + JavaScriptTextInputDialogRequest request, + ) async { + return 'return message'; + }); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); final Object promptResponse = await controller.runJavaScriptReturningResult( 'prompt("input message", "default text")', @@ -1562,8 +1664,9 @@ Future main() async { }); group('Logging', () { - testWidgets('can receive console log messages', - (WidgetTester tester) async { + testWidgets('can receive console log messages', ( + WidgetTester tester, + ) async { const String testPage = ''' @@ -1583,22 +1686,27 @@ Future main() async { await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setOnConsoleMessage((JavaScriptConsoleMessage message) { - debugMessageReceived - .complete('${message.level.name}:${message.message}'); + debugMessageReceived.complete( + '${message.level.name}:${message.message}', + ); }); await controller.loadHtmlString(testPage); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await expectLater( - debugMessageReceived.future, completion('debug:Debug message')); + debugMessageReceived.future, + completion('debug:Debug message'), + ); }); }); } @@ -1618,30 +1726,29 @@ class ResizableWebView extends StatefulWidget { } class ResizableWebViewState extends State { - late final PlatformWebViewController controller = PlatformWebViewController( - const PlatformWebViewControllerCreationParams(), - ) - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setPlatformNavigationDelegate( - PlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams(), - )..setOnPageFinished((_) => widget.onPageFinished()), - ) - ..addJavaScriptChannel( - JavaScriptChannelParams( - name: 'Resize', - onMessageReceived: (_) { - widget.onResize(); - }, - ), - ) - ..loadRequest( - LoadRequestParams( - uri: Uri.parse( - 'data:text/html;charset=utf-8;base64,${base64Encode(const Utf8Encoder().convert(resizePage))}', - ), - ), - ); + late final PlatformWebViewController controller = + PlatformWebViewController(const PlatformWebViewControllerCreationParams()) + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setPlatformNavigationDelegate( + PlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + )..setOnPageFinished((_) => widget.onPageFinished()), + ) + ..addJavaScriptChannel( + JavaScriptChannelParams( + name: 'Resize', + onMessageReceived: (_) { + widget.onResize(); + }, + ), + ) + ..loadRequest( + LoadRequestParams( + uri: Uri.parse( + 'data:text/html;charset=utf-8;base64,${base64Encode(const Utf8Encoder().convert(resizePage))}', + ), + ), + ); double webViewWidth = 200; double webViewHeight = 200; @@ -1708,16 +1815,15 @@ class CopyableObjectWithCallback class ClassWithCallbackClass { ClassWithCallbackClass() { callbackClass = CopyableObjectWithCallback( - withWeakReferenceTo( - this, - (WeakReference weakReference) { - return () { - // Weak reference to `this` in callback. - // ignore: unnecessary_statements - weakReference; - }; - }, - ), + withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return () { + // Weak reference to `this` in callback. + // ignore: unnecessary_statements + weakReference; + }; + }), ); } diff --git a/packages/webview_flutter/webview_flutter_android/example/integration_test/webview_flutter_test_legacy.dart b/packages/webview_flutter/webview_flutter_android/example/integration_test/webview_flutter_test_legacy.dart index 1bd1895b8b5..8dc094211ee 100644 --- a/packages/webview_flutter/webview_flutter_android/example/integration_test/webview_flutter_test_legacy.dart +++ b/packages/webview_flutter/webview_flutter_android/example/integration_test/webview_flutter_test_legacy.dart @@ -27,20 +27,22 @@ Future main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0); - unawaited(server.forEach((HttpRequest request) { - if (request.uri.path == '/hello.txt') { - request.response.writeln('Hello, world.'); - } else if (request.uri.path == '/secondary.txt') { - request.response.writeln('How are you today?'); - } else if (request.uri.path == '/headers') { - request.response.writeln('${request.headers}'); - } else if (request.uri.path == '/favicon.ico') { - request.response.statusCode = HttpStatus.notFound; - } else { - fail('unexpected request: ${request.method} ${request.uri}'); - } - request.response.close(); - })); + unawaited( + server.forEach((HttpRequest request) { + if (request.uri.path == '/hello.txt') { + request.response.writeln('Hello, world.'); + } else if (request.uri.path == '/secondary.txt') { + request.response.writeln('How are you today?'); + } else if (request.uri.path == '/headers') { + request.response.writeln('${request.headers}'); + } else if (request.uri.path == '/favicon.ico') { + request.response.statusCode = HttpStatus.notFound; + } else { + fail('unexpected request: ${request.method} ${request.uri}'); + } + request.response.close(); + }), + ); final String prefixUrl = 'http://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; final String secondaryUrl = '$prefixUrl/secondary.txt'; @@ -102,75 +104,77 @@ Future main() async { }); testWidgets( - 'withWeakRefenceTo allows encapsulating class to be garbage collected', - (WidgetTester tester) async { - final Completer gcCompleter = Completer(); - final android.PigeonInstanceManager instanceManager = - android.PigeonInstanceManager( - onWeakReferenceRemoved: gcCompleter.complete, - ); - - ClassWithCallbackClass? instance = ClassWithCallbackClass(); - instanceManager.addHostCreatedInstance(instance.callbackClass, 0); - instance = null; - - // Force garbage collection. - await IntegrationTestWidgetsFlutterBinding.instance - .watchPerformance(() async { - await tester.pumpAndSettle(); - }); + 'withWeakRefenceTo allows encapsulating class to be garbage collected', + (WidgetTester tester) async { + final Completer gcCompleter = Completer(); + final android.PigeonInstanceManager instanceManager = + android.PigeonInstanceManager( + onWeakReferenceRemoved: gcCompleter.complete, + ); + + ClassWithCallbackClass? instance = ClassWithCallbackClass(); + instanceManager.addHostCreatedInstance(instance.callbackClass, 0); + instance = null; + + // Force garbage collection. + await IntegrationTestWidgetsFlutterBinding.instance.watchPerformance( + () async { + await tester.pumpAndSettle(); + }, + ); - final int gcIdentifier = await gcCompleter.future; - expect(gcIdentifier, 0); - }, timeout: const Timeout(Duration(seconds: 10))); + final int gcIdentifier = await gcCompleter.future; + expect(gcIdentifier, 0); + }, + timeout: const Timeout(Duration(seconds: 10)), + ); // TODO(bparrishMines): This test is skipped because of // https://github.com/flutter/flutter/issues/123327 - testWidgets( - 'WebView is released by garbage collection', - (WidgetTester tester) async { - final Completer webViewGCCompleter = Completer(); - - late final android.PigeonInstanceManager instanceManager; - instanceManager = android.PigeonInstanceManager( - onWeakReferenceRemoved: (int identifier) { + testWidgets('WebView is released by garbage collection', ( + WidgetTester tester, + ) async { + final Completer webViewGCCompleter = Completer(); + + late final android.PigeonInstanceManager instanceManager; + instanceManager = android.PigeonInstanceManager( + onWeakReferenceRemoved: (int identifier) { final android.PigeonInternalProxyApiBaseClass instance = instanceManager.getInstanceWithWeakReference(identifier)!; if (instance is android.WebView && !webViewGCCompleter.isCompleted) { webViewGCCompleter.complete(); } - }); + }, + ); - // Continually recreate web views until one is disposed through garbage - // collection. - while (!webViewGCCompleter.isCompleted) { - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - return AndroidWebView(instanceManager: instanceManager).build( - context: context, - creationParams: CreationParams( - webSettings: WebSettings( - hasNavigationDelegate: false, - userAgent: const WebSetting.of('woeifj'), - ), - ), - javascriptChannelRegistry: JavascriptChannelRegistry( - {}, + // Continually recreate web views until one is disposed through garbage + // collection. + while (!webViewGCCompleter.isCompleted) { + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return AndroidWebView(instanceManager: instanceManager).build( + context: context, + creationParams: CreationParams( + webSettings: WebSettings( + hasNavigationDelegate: false, + userAgent: const WebSetting.of('woeifj'), ), - webViewPlatformCallbacksHandler: TestPlatformCallbacksHandler(), - ); - }, - ), - ); - await tester.pumpAndSettle(); + ), + javascriptChannelRegistry: JavascriptChannelRegistry( + {}, + ), + webViewPlatformCallbacksHandler: TestPlatformCallbacksHandler(), + ); + }, + ), + ); + await tester.pumpAndSettle(); - await tester.pumpWidget(Container()); - await tester.pumpAndSettle(); - } - }, - skip: true, - ); + await tester.pumpWidget(Container()); + await tester.pumpAndSettle(); + } + }, skip: true); testWidgets('evaluateJavascript', (WidgetTester tester) async { final Completer controllerCompleter = @@ -219,15 +223,16 @@ Future main() async { ); final WebViewController controller = await controllerCompleter.future; final Map headers = { - 'test_header': 'flutter_test_header' + 'test_header': 'flutter_test_header', }; await controller.loadUrl(headersUrl, headers: headers); await pageStarts.stream.firstWhere((String url) => url == headersUrl); await pageLoads.stream.firstWhere((String url) => url == headersUrl); - final String content = await controller - .runJavascriptReturningResult('document.documentElement.innerText'); + final String content = await controller.runJavascriptReturningResult( + 'document.documentElement.innerText', + ); expect(content.contains('flutter_test_header'), isTrue); }); @@ -282,16 +287,18 @@ Future main() async { final Completer onPageFinished = Completer(); bool resizeButtonTapped = false; - await tester.pumpWidget(ResizableWebView( - onResize: (_) { - if (resizeButtonTapped) { - buttonTapResizeCompleter.complete(); - } else { - initialResizeCompleter.complete(); - } - }, - onPageFinished: () => onPageFinished.complete(), - )); + await tester.pumpWidget( + ResizableWebView( + onResize: (_) { + if (resizeButtonTapped) { + buttonTapResizeCompleter.complete(); + } else { + initialResizeCompleter.complete(); + } + }, + onPageFinished: () => onPageFinished.complete(), + ), + ); await onPageFinished.future; // Wait for a potential call to resize after page is loaded. await initialResizeCompleter.future.timeout( @@ -343,8 +350,9 @@ Future main() async { expect(customUserAgent2, 'Custom_User_Agent2'); }); - testWidgets('use default platform userAgent after webView is rebuilt', - (WidgetTester tester) async { + testWidgets('use default platform userAgent after webView is rebuilt', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); final GlobalKey globalKey = GlobalKey(); @@ -397,10 +405,12 @@ Future main() async { group('Video playback policy', () { late String videoTestBase64; setUpAll(() async { - final ByteData videoData = - await rootBundle.load('assets/sample_video.mp4'); - final String base64VideoData = - base64Encode(Uint8List.view(videoData.buffer)); + final ByteData videoData = await rootBundle.load( + 'assets/sample_video.mp4', + ); + final String base64VideoData = base64Encode( + Uint8List.view(videoData.buffer), + ); final String videoTest = ''' Video auto play @@ -459,8 +469,9 @@ Future main() async { WebViewController controller = await controllerCompleter.future; await pageLoaded.future; - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); expect(isPaused, _webviewBool(false)); controllerCompleter = Completer(); @@ -491,8 +502,9 @@ Future main() async { expect(isPaused, _webviewBool(true)); }); - testWidgets('Changes to initialMediaPlaybackPolicy are ignored', - (WidgetTester tester) async { + testWidgets('Changes to initialMediaPlaybackPolicy are ignored', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); Completer pageLoaded = Completer(); @@ -518,8 +530,9 @@ Future main() async { final WebViewController controller = await controllerCompleter.future; await pageLoaded.future; - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); expect(isPaused, _webviewBool(false)); pageLoaded = Completer(); @@ -549,8 +562,9 @@ Future main() async { expect(isPaused, _webviewBool(false)); }); - testWidgets('Video plays inline when allowsInlineMediaPlayback is true', - (WidgetTester tester) async { + testWidgets('Video plays inline when allowsInlineMediaPlayback is true', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); final Completer pageLoaded = Completer(); @@ -594,8 +608,9 @@ Future main() async { // Makes sure we get the correct event that indicates the video is actually playing. await videoPlaying.future; - final String fullScreen = - await controller.runJavascriptReturningResult('isFullScreen();'); + final String fullScreen = await controller.runJavascriptReturningResult( + 'isFullScreen();', + ); expect(fullScreen, _webviewBool(false)); }); }); @@ -603,10 +618,12 @@ Future main() async { group('Audio playback policy', () { late String audioTestBase64; setUpAll(() async { - final ByteData audioData = - await rootBundle.load('assets/sample_audio.ogg'); - final String base64AudioData = - base64Encode(Uint8List.view(audioData.buffer)); + final ByteData audioData = await rootBundle.load( + 'assets/sample_audio.ogg', + ); + final String base64AudioData = base64Encode( + Uint8List.view(audioData.buffer), + ); final String audioTest = ''' Audio auto play @@ -661,8 +678,9 @@ Future main() async { await pageStarted.future; await pageLoaded.future; - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); expect(isPaused, _webviewBool(false)); controllerCompleter = Completer(); @@ -698,8 +716,9 @@ Future main() async { expect(isPaused, _webviewBool(true)); }); - testWidgets('Changes to initialMediaPlaybackPolicy are ignored', - (WidgetTester tester) async { + testWidgets('Changes to initialMediaPlaybackPolicy are ignored', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); Completer pageStarted = Completer(); @@ -730,8 +749,9 @@ Future main() async { await pageStarted.future; await pageLoaded.future; - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); expect(isPaused, _webviewBool(false)); pageStarted = Completer(); @@ -776,8 +796,9 @@ Future main() async { '''; - final String getTitleTestBase64 = - base64Encode(const Utf8Encoder().convert(getTitleTest)); + final String getTitleTestBase64 = base64Encode( + const Utf8Encoder().convert(getTitleTest), + ); final Completer pageStarted = Completer(); final Completer pageLoaded = Completer(); final Completer controllerCompleter = @@ -832,8 +853,9 @@ Future main() async { '''; - final String scrollTestPageBase64 = - base64Encode(const Utf8Encoder().convert(scrollTestPage)); + final String scrollTestPageBase64 = base64Encode( + const Utf8Encoder().convert(scrollTestPage), + ); final Completer pageLoaded = Completer(); final Completer controllerCompleter = @@ -918,8 +940,9 @@ Future main() async { '''; - final String scrollTestPageBase64 = - base64Encode(const Utf8Encoder().convert(scrollTestPage)); + final String scrollTestPageBase64 = base64Encode( + const Utf8Encoder().convert(scrollTestPage), + ); final Completer pageLoaded = Completer(); final Completer controllerCompleter = @@ -964,8 +987,9 @@ Future main() async { expect(Y_SCROLL * 2, scrollPosY); }); - testWidgets('inputs are scrolled into view when focused', - (WidgetTester tester) async { + testWidgets('inputs are scrolled into view when focused', ( + WidgetTester tester, + ) async { const String scrollTestPage = ''' @@ -990,8 +1014,9 @@ Future main() async { '''; - final String scrollTestPageBase64 = - base64Encode(const Utf8Encoder().convert(scrollTestPage)); + final String scrollTestPageBase64 = base64Encode( + const Utf8Encoder().convert(scrollTestPage), + ); final Completer pageLoaded = Completer(); final Completer controllerCompleter = @@ -1025,12 +1050,16 @@ Future main() async { final WebViewController controller = await controllerCompleter.future; await pageLoaded.future; final String viewportRectJSON = await _runJavaScriptReturningResult( - controller, 'JSON.stringify(viewport.getBoundingClientRect())'); + controller, + 'JSON.stringify(viewport.getBoundingClientRect())', + ); final Map viewportRectRelativeToViewport = jsonDecode(viewportRectJSON) as Map; num getDomRectComponent( - Map rectAsJson, String component) { + Map rectAsJson, + String component, + ) { return rectAsJson[component]! as num; } @@ -1038,15 +1067,20 @@ Future main() async { final String initialInputClientRectJSON = await _runJavaScriptReturningResult( - controller, 'JSON.stringify(inputEl.getBoundingClientRect())'); + controller, + 'JSON.stringify(inputEl.getBoundingClientRect())', + ); final Map initialInputClientRectRelativeToViewport = jsonDecode(initialInputClientRectJSON) as Map; expect( - getDomRectComponent( - initialInputClientRectRelativeToViewport, 'bottom') <= - getDomRectComponent(viewportRectRelativeToViewport, 'bottom'), - isFalse); + getDomRectComponent( + initialInputClientRectRelativeToViewport, + 'bottom', + ) <= + getDomRectComponent(viewportRectRelativeToViewport, 'bottom'), + isFalse, + ); await controller.runJavascript('inputEl.focus()'); @@ -1054,34 +1088,40 @@ Future main() async { final String lastInputClientRectJSON = await _runJavaScriptReturningResult( - controller, 'JSON.stringify(inputEl.getBoundingClientRect())'); + controller, + 'JSON.stringify(inputEl.getBoundingClientRect())', + ); final Map lastInputClientRectRelativeToViewport = jsonDecode(lastInputClientRectJSON) as Map; expect( - getDomRectComponent(lastInputClientRectRelativeToViewport, 'top') >= - getDomRectComponent(viewportRectRelativeToViewport, 'top'), - isTrue); + getDomRectComponent(lastInputClientRectRelativeToViewport, 'top') >= + getDomRectComponent(viewportRectRelativeToViewport, 'top'), + isTrue, + ); expect( - getDomRectComponent( - lastInputClientRectRelativeToViewport, 'bottom') <= - getDomRectComponent(viewportRectRelativeToViewport, 'bottom'), - isTrue); + getDomRectComponent(lastInputClientRectRelativeToViewport, 'bottom') <= + getDomRectComponent(viewportRectRelativeToViewport, 'bottom'), + isTrue, + ); expect( - getDomRectComponent(lastInputClientRectRelativeToViewport, 'left') >= - getDomRectComponent(viewportRectRelativeToViewport, 'left'), - isTrue); + getDomRectComponent(lastInputClientRectRelativeToViewport, 'left') >= + getDomRectComponent(viewportRectRelativeToViewport, 'left'), + isTrue, + ); expect( - getDomRectComponent(lastInputClientRectRelativeToViewport, 'right') <= - getDomRectComponent(viewportRectRelativeToViewport, 'right'), - isTrue); + getDomRectComponent(lastInputClientRectRelativeToViewport, 'right') <= + getDomRectComponent(viewportRectRelativeToViewport, 'right'), + isTrue, + ); }); }); group('NavigationDelegate', () { const String blankPage = ''; - final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,' + final String blankPageEncoded = + 'data:text/html;charset=utf-8;base64,' '${base64Encode(const Utf8Encoder().convert(blankPage))}'; testWidgets('can allow requests', (WidgetTester tester) async { @@ -1140,11 +1180,14 @@ Future main() async { expect(error.errorType, isNotNull); expect( - error.failingUrl?.startsWith('https://www.notawebsite..com'), isTrue); + error.failingUrl?.startsWith('https://www.notawebsite..com'), + isTrue, + ); }); - testWidgets('onWebResourceError is not called with valid url', - (WidgetTester tester) async { + testWidgets('onWebResourceError is not called with valid url', ( + WidgetTester tester, + ) async { final Completer errorCompleter = Completer(); final Completer pageFinishCompleter = Completer(); @@ -1168,10 +1211,10 @@ Future main() async { await pageFinishCompleter.future; }); - testWidgets( - 'onWebResourceError only called for main frame', - (WidgetTester tester) async { - const String iframeTest = ''' + testWidgets('onWebResourceError only called for main frame', ( + WidgetTester tester, + ) async { + const String iframeTest = ''' @@ -1182,32 +1225,31 @@ Future main() async { '''; - final String iframeTestBase64 = - base64Encode(const Utf8Encoder().convert(iframeTest)); + final String iframeTestBase64 = base64Encode( + const Utf8Encoder().convert(iframeTest), + ); - final Completer errorCompleter = - Completer(); - final Completer pageFinishCompleter = Completer(); + final Completer errorCompleter = + Completer(); + final Completer pageFinishCompleter = Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - initialUrl: - 'data:text/html;charset=utf-8;base64,$iframeTestBase64', - onWebResourceError: (WebResourceError error) { - errorCompleter.complete(error); - }, - onPageFinished: (_) => pageFinishCompleter.complete(), - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + initialUrl: 'data:text/html;charset=utf-8;base64,$iframeTestBase64', + onWebResourceError: (WebResourceError error) { + errorCompleter.complete(error); + }, + onPageFinished: (_) => pageFinishCompleter.complete(), ), - ); + ), + ); - expect(errorCompleter.future, doesNotComplete); - await pageFinishCompleter.future; - }, - ); + expect(errorCompleter.future, doesNotComplete); + await pageFinishCompleter.future; + }); testWidgets('can block requests', (WidgetTester tester) async { final Completer controllerCompleter = @@ -1236,14 +1278,17 @@ Future main() async { await pageLoads.stream.first; // Wait for initial page load. final WebViewController controller = await controllerCompleter.future; - await controller - .runJavascript('location.href = "https://www.youtube.com/"'); + await controller.runJavascript( + 'location.href = "https://www.youtube.com/"', + ); // There should never be any second page load, since our new URL is // blocked. Still wait for a potential page change for some time in order // to give the test a chance to fail. - await pageLoads.stream.first - .timeout(const Duration(milliseconds: 500), onTimeout: () => ''); + await pageLoads.stream.first.timeout( + const Duration(milliseconds: 500), + onTimeout: () => '', + ); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, isNot(contains('youtube.com'))); }); @@ -1266,8 +1311,9 @@ Future main() async { navigationDelegate: (NavigationRequest request) async { NavigationDecision decision = NavigationDecision.prevent; decision = await Future.delayed( - const Duration(milliseconds: 10), - () => NavigationDecision.navigate); + const Duration(milliseconds: 10), + () => NavigationDecision.navigate, + ); return decision; }, onPageFinished: (String url) => pageLoads.add(url), @@ -1285,8 +1331,9 @@ Future main() async { }); }); - testWidgets('launches with gestureNavigationEnabled on iOS', - (WidgetTester tester) async { + testWidgets('launches with gestureNavigationEnabled on iOS', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); await tester.pumpWidget( @@ -1311,8 +1358,9 @@ Future main() async { expect(currentUrl, primaryUrl); }); - testWidgets('target _blank opens in same window', - (WidgetTester tester) async { + testWidgets('target _blank opens in same window', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); final Completer pageLoaded = Completer(); @@ -1338,49 +1386,46 @@ Future main() async { expect(currentUrl, primaryUrl); }); - testWidgets( - 'can open new window and go back', - (WidgetTester tester) async { - final Completer controllerCompleter = - Completer(); - Completer pageLoaded = Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - onPageFinished: (String url) { - pageLoaded.complete(); - }, - initialUrl: primaryUrl, - ), + testWidgets('can open new window and go back', (WidgetTester tester) async { + final Completer controllerCompleter = + Completer(); + Completer pageLoaded = Completer(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (String url) { + pageLoaded.complete(); + }, + initialUrl: primaryUrl, ), - ); - final WebViewController controller = await controllerCompleter.future; - expect(controller.currentUrl(), completion(primaryUrl)); - await pageLoaded.future; - pageLoaded = Completer(); + ), + ); + final WebViewController controller = await controllerCompleter.future; + expect(controller.currentUrl(), completion(primaryUrl)); + await pageLoaded.future; + pageLoaded = Completer(); - await controller.runJavascript('window.open("$secondaryUrl")'); - await pageLoaded.future; - pageLoaded = Completer(); - expect(controller.currentUrl(), completion(secondaryUrl)); + await controller.runJavascript('window.open("$secondaryUrl")'); + await pageLoaded.future; + pageLoaded = Completer(); + expect(controller.currentUrl(), completion(secondaryUrl)); - expect(controller.canGoBack(), completion(true)); - await controller.goBack(); - await pageLoaded.future; - await expectLater(controller.currentUrl(), completion(primaryUrl)); - }, - ); + expect(controller.canGoBack(), completion(true)); + await controller.goBack(); + await pageLoaded.future; + await expectLater(controller.currentUrl(), completion(primaryUrl)); + }); - testWidgets( - 'JavaScript does not run in parent window', - (WidgetTester tester) async { - const String iframe = ''' + testWidgets('JavaScript does not run in parent window', ( + WidgetTester tester, + ) async { + const String iframe = ''' '''; - final String iframeTestBase64 = - base64Encode(const Utf8Encoder().convert(iframe)); + final String iframeTestBase64 = base64Encode( + const Utf8Encoder().convert(iframe), + ); - final String openWindowTest = ''' + final String openWindowTest = ''' @@ -1408,86 +1454,86 @@ Future main() async { '''; - final String openWindowTestBase64 = - base64Encode(const Utf8Encoder().convert(openWindowTest)); - final Completer controllerCompleter = - Completer(); - final Completer pageLoadCompleter = Completer(); + final String openWindowTestBase64 = base64Encode( + const Utf8Encoder().convert(openWindowTest), + ); + final Completer controllerCompleter = + Completer(); + final Completer pageLoadCompleter = Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - initialUrl: - 'data:text/html;charset=utf-8;base64,$openWindowTestBase64', - onPageFinished: (String url) { - pageLoadCompleter.complete(); - }, - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + initialUrl: + 'data:text/html;charset=utf-8;base64,$openWindowTestBase64', + onPageFinished: (String url) { + pageLoadCompleter.complete(); + }, ), - ); + ), + ); - final WebViewController controller = await controllerCompleter.future; - await pageLoadCompleter.future; + final WebViewController controller = await controllerCompleter.future; + await pageLoadCompleter.future; - final String iframeLoaded = - await controller.runJavascriptReturningResult('iframeLoaded'); - expect(iframeLoaded, 'true'); + final String iframeLoaded = await controller.runJavascriptReturningResult( + 'iframeLoaded', + ); + expect(iframeLoaded, 'true'); - final String elementText = await controller.runJavascriptReturningResult( - 'document.querySelector("p") && document.querySelector("p").textContent', - ); - expect(elementText, 'null'); - }, - ); + final String elementText = await controller.runJavascriptReturningResult( + 'document.querySelector("p") && document.querySelector("p").textContent', + ); + expect(elementText, 'null'); + }); - testWidgets( - 'clearCache should clear local storage', - (WidgetTester tester) async { - final Completer controllerCompleter = - Completer(); + testWidgets('clearCache should clear local storage', ( + WidgetTester tester, + ) async { + final Completer controllerCompleter = + Completer(); - Completer pageLoadCompleter = Completer(); + Completer pageLoadCompleter = Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - initialUrl: primaryUrl, - javascriptMode: JavascriptMode.unrestricted, - onPageFinished: (_) => pageLoadCompleter.complete(), - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + initialUrl: primaryUrl, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (_) => pageLoadCompleter.complete(), + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, ), - ); + ), + ); - await pageLoadCompleter.future; - pageLoadCompleter = Completer(); + await pageLoadCompleter.future; + pageLoadCompleter = Completer(); - final WebViewController controller = await controllerCompleter.future; - await controller.runJavascript('localStorage.setItem("myCat", "Tom");'); - final String myCatItem = await controller.runJavascriptReturningResult( - 'localStorage.getItem("myCat");', - ); - expect(myCatItem, '"Tom"'); + final WebViewController controller = await controllerCompleter.future; + await controller.runJavascript('localStorage.setItem("myCat", "Tom");'); + final String myCatItem = await controller.runJavascriptReturningResult( + 'localStorage.getItem("myCat");', + ); + expect(myCatItem, '"Tom"'); - await controller.clearCache(); - await pageLoadCompleter.future; + await controller.clearCache(); + await pageLoadCompleter.future; - final String nullItem = await controller.runJavascriptReturningResult( - 'localStorage.getItem("myCat");', - ); - expect(nullItem, 'null'); - }, - ); + final String nullItem = await controller.runJavascriptReturningResult( + 'localStorage.getItem("myCat");', + ); + expect(nullItem, 'null'); + }); } // JavaScript booleans evaluate to different string values on Android and iOS. @@ -1549,8 +1595,9 @@ class ResizableWebViewState extends State { @override Widget build(BuildContext context) { - final String resizeTestBase64 = - base64Encode(const Utf8Encoder().convert(resizePage)); + final String resizeTestBase64 = base64Encode( + const Utf8Encoder().convert(resizePage), + ); return Directionality( textDirection: TextDirection.ltr, child: Column( @@ -1603,16 +1650,15 @@ class CopyableObjectWithCallback class ClassWithCallbackClass { ClassWithCallbackClass() { callbackClass = CopyableObjectWithCallback( - withWeakReferenceTo( - this, - (WeakReference weakReference) { - return () { - // Weak reference to `this` in callback. - // ignore: unnecessary_statements - weakReference; - }; - }, - ), + withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return () { + // Weak reference to `this` in callback. + // ignore: unnecessary_statements + weakReference; + }; + }), ); } diff --git a/packages/webview_flutter/webview_flutter_android/example/lib/legacy/web_view.dart b/packages/webview_flutter/webview_flutter_android/example/lib/legacy/web_view.dart index 909056f4ea9..77a2483c458 100644 --- a/packages/webview_flutter/webview_flutter_android/example/lib/legacy/web_view.dart +++ b/packages/webview_flutter/webview_flutter_android/example/lib/legacy/web_view.dart @@ -26,8 +26,8 @@ typedef WebViewCreatedCallback = void Function(WebViewController controller); /// `navigation` should be handled. /// /// See also: [WebView.navigationDelegate]. -typedef NavigationDelegate = FutureOr Function( - NavigationRequest navigation); +typedef NavigationDelegate = + FutureOr Function(NavigationRequest navigation); /// Signature for when a [WebView] has started loading a page. typedef PageStartedCallback = void Function(String url); @@ -261,8 +261,9 @@ class _WebViewState extends State { void initState() { super.initState(); _platformCallbacksHandler = _PlatformCallbacksHandler(widget); - _javascriptChannelRegistry = - JavascriptChannelRegistry(widget.javascriptChannels); + _javascriptChannelRegistry = JavascriptChannelRegistry( + widget.javascriptChannels, + ); } @override @@ -277,8 +278,9 @@ class _WebViewState extends State { Widget build(BuildContext context) { return WebView.platform.build( context: context, - onWebViewPlatformCreated: - (WebViewPlatformController? webViewPlatformController) { + onWebViewPlatformCreated: ( + WebViewPlatformController? webViewPlatformController, + ) { final WebViewController controller = WebViewController( widget, webViewPlatformController!, @@ -400,10 +402,7 @@ class WebViewController { /// The [baseUrl] parameter is used when resolving relative URLs within the /// HTML string. Future loadHtmlString(String html, {String? baseUrl}) { - return _webViewPlatformController.loadHtmlString( - html, - baseUrl: baseUrl, - ); + return _webViewPlatformController.loadHtmlString(html, baseUrl: baseUrl); } /// Loads the specified URL. @@ -414,10 +413,7 @@ class WebViewController { /// `url` must not be null. /// /// Throws an ArgumentError if `url` is not a valid URL string. - Future loadUrl( - String url, { - Map? headers, - }) async { + Future loadUrl(String url, {Map? headers}) async { _validateUrlString(url); return _webViewPlatformController.loadUrl(url, headers); } @@ -493,28 +489,35 @@ class WebViewController { _widget = widget; await _updateSettings(_webSettingsFromWidget(widget)); await _updateJavascriptChannels( - _javascriptChannelRegistry.channels.values.toSet()); + _javascriptChannelRegistry.channels.values.toSet(), + ); } Future _updateSettings(WebSettings newSettings) { - final WebSettings update = - _clearUnchangedWebSettings(_settings, newSettings); + final WebSettings update = _clearUnchangedWebSettings( + _settings, + newSettings, + ); _settings = newSettings; return _webViewPlatformController.updateSettings(update); } Future _updateJavascriptChannels( - Set? newChannels) async { + Set? newChannels, + ) async { final Set currentChannels = _javascriptChannelRegistry.channels.keys.toSet(); final Set newChannelNames = _extractChannelNames(newChannels); - final Set channelsToAdd = - newChannelNames.difference(currentChannels); - final Set channelsToRemove = - currentChannels.difference(newChannelNames); + final Set channelsToAdd = newChannelNames.difference( + currentChannels, + ); + final Set channelsToRemove = currentChannels.difference( + newChannelNames, + ); if (channelsToRemove.isNotEmpty) { - await _webViewPlatformController - .removeJavascriptChannels(channelsToRemove); + await _webViewPlatformController.removeJavascriptChannels( + channelsToRemove, + ); } if (channelsToAdd.isNotEmpty) { await _webViewPlatformController.addJavascriptChannels(channelsToAdd); @@ -526,8 +529,11 @@ class WebViewController { // ignore: public_member_api_docs Future evaluateJavascript(String javascriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { - return Future.error(FlutterError( - 'JavaScript mode must be enabled/unrestricted when calling evaluateJavascript.')); + return Future.error( + FlutterError( + 'JavaScript mode must be enabled/unrestricted when calling evaluateJavascript.', + ), + ); } return _webViewPlatformController.evaluateJavascript(javascriptString); } @@ -541,8 +547,11 @@ class WebViewController { // embedded in the main frame HTML has been loaded. Future runJavascript(String javaScriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { - return Future.error(FlutterError( - 'Javascript mode must be enabled/unrestricted when calling runJavascript.')); + return Future.error( + FlutterError( + 'Javascript mode must be enabled/unrestricted when calling runJavascript.', + ), + ); } return _webViewPlatformController.runJavascript(javaScriptString); } @@ -557,11 +566,15 @@ class WebViewController { /// embedded in the main frame HTML has been loaded. Future runJavascriptReturningResult(String javaScriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { - return Future.error(FlutterError( - 'Javascript mode must be enabled/unrestricted when calling runJavascriptReturningResult.')); + return Future.error( + FlutterError( + 'Javascript mode must be enabled/unrestricted when calling runJavascriptReturningResult.', + ), + ); } - return _webViewPlatformController - .runJavascriptReturningResult(javaScriptString); + return _webViewPlatformController.runJavascriptReturningResult( + javaScriptString, + ); } /// Returns the title of the currently loaded page. @@ -599,7 +612,9 @@ class WebViewController { // This method assumes that no fields in `currentValue` are null. WebSettings _clearUnchangedWebSettings( - WebSettings currentValue, WebSettings newValue) { + WebSettings currentValue, + WebSettings newValue, + ) { assert(currentValue.javascriptMode != null); assert(currentValue.hasNavigationDelegate != null); assert(currentValue.hasProgressTracking != null); @@ -645,9 +660,10 @@ class WebViewController { } Set _extractChannelNames(Set? channels) { - final Set channelNames = channels == null - ? {} - : channels.map((JavascriptChannel channel) => channel.name).toSet(); + final Set channelNames = + channels == null + ? {} + : channels.map((JavascriptChannel channel) => channel.name).toSet(); return channelNames; } @@ -688,7 +704,8 @@ class WebViewCookieManager extends WebViewCookieManagerPlatform { WebViewCookieManagerPlatform.instance = WebViewAndroidCookieManager(); } else { throw AssertionError( - 'This platform is currently unsupported for webview_flutter_android.'); + 'This platform is currently unsupported for webview_flutter_android.', + ); } } return WebViewCookieManagerPlatform.instance!; diff --git a/packages/webview_flutter/webview_flutter_android/example/lib/main.dart b/packages/webview_flutter/webview_flutter_android/example/lib/main.dart index 6608c7bebbd..64a1f3d3c20 100644 --- a/packages/webview_flutter/webview_flutter_android/example/lib/main.dart +++ b/packages/webview_flutter/webview_flutter_android/example/lib/main.dart @@ -175,31 +175,30 @@ class _WebViewExampleState extends State { void initState() { super.initState(); - _controller = PlatformWebViewController( - AndroidWebViewControllerCreationParams(), - ) - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setBackgroundColor(const Color(0x80000000)) - ..setPlatformNavigationDelegate( - PlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams(), - ) - ..setOnProgress((int progress) { - debugPrint('WebView is loading (progress : $progress%)'); - }) - ..setOnPageStarted((String url) { - debugPrint('Page started loading: $url'); - }) - ..setOnPageFinished((String url) { - debugPrint('Page finished loading: $url'); - }) - ..setOnHttpError((HttpResponseError error) { - debugPrint( - 'HTTP error occured on page: ${error.response?.statusCode}', - ); - }) - ..setOnWebResourceError((WebResourceError error) { - debugPrint(''' + _controller = + PlatformWebViewController(AndroidWebViewControllerCreationParams()) + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setBackgroundColor(const Color(0x80000000)) + ..setPlatformNavigationDelegate( + PlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ) + ..setOnProgress((int progress) { + debugPrint('WebView is loading (progress : $progress%)'); + }) + ..setOnPageStarted((String url) { + debugPrint('Page started loading: $url'); + }) + ..setOnPageFinished((String url) { + debugPrint('Page finished loading: $url'); + }) + ..setOnHttpError((HttpResponseError error) { + debugPrint( + 'HTTP error occured on page: ${error.response?.statusCode}', + ); + }) + ..setOnWebResourceError((WebResourceError error) { + debugPrint(''' Page resource error: code: ${error.errorCode} description: ${error.description} @@ -207,47 +206,49 @@ Page resource error: isForMainFrame: ${error.isForMainFrame} url: ${error.url} '''); + }) + ..setOnNavigationRequest((NavigationRequest request) { + if (request.url.contains('pub.dev')) { + debugPrint('blocking navigation to ${request.url}'); + return NavigationDecision.prevent; + } + debugPrint('allowing navigation to ${request.url}'); + return NavigationDecision.navigate; + }) + ..setOnUrlChange((UrlChange change) { + debugPrint('url change to ${change.url}'); + }) + ..setOnHttpAuthRequest((HttpAuthRequest request) { + openDialog(request); + }) + ..setOnSSlAuthError((PlatformSslAuthError error) { + debugPrint( + 'SSL error from ${(error as AndroidSslAuthError).url}', + ); + error.cancel(); + }), + ) + ..addJavaScriptChannel( + JavaScriptChannelParams( + name: 'Toaster', + onMessageReceived: (JavaScriptMessage message) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message.message))); + }, + ), + ) + ..setOnPlatformPermissionRequest(( + PlatformWebViewPermissionRequest request, + ) { + debugPrint( + 'requesting permissions for ${request.types.map((WebViewPermissionResourceType type) => type.name)}', + ); + request.grant(); }) - ..setOnNavigationRequest((NavigationRequest request) { - if (request.url.contains('pub.dev')) { - debugPrint('blocking navigation to ${request.url}'); - return NavigationDecision.prevent; - } - debugPrint('allowing navigation to ${request.url}'); - return NavigationDecision.navigate; - }) - ..setOnUrlChange((UrlChange change) { - debugPrint('url change to ${change.url}'); - }) - ..setOnHttpAuthRequest((HttpAuthRequest request) { - openDialog(request); - }) - ..setOnSSlAuthError((PlatformSslAuthError error) { - debugPrint('SSL error from ${(error as AndroidSslAuthError).url}'); - error.cancel(); - }), - ) - ..addJavaScriptChannel(JavaScriptChannelParams( - name: 'Toaster', - onMessageReceived: (JavaScriptMessage message) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(message.message)), + ..loadRequest( + LoadRequestParams(uri: Uri.parse('https://flutter.dev')), ); - }, - )) - ..setOnPlatformPermissionRequest( - (PlatformWebViewPermissionRequest request) { - debugPrint( - 'requesting permissions for ${request.types.map((WebViewPermissionResourceType type) => type.name)}', - ); - request.grant(); - }, - ) - ..loadRequest( - LoadRequestParams( - uri: Uri.parse('https://flutter.dev'), - ), - ); } @override @@ -277,9 +278,9 @@ Page resource error: onPressed: () async { final String? url = await _controller.currentUrl(); if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Favorited $url')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Favorited $url'))); } }, child: const Icon(Icons.favorite), @@ -357,10 +358,11 @@ class SampleMenu extends StatelessWidget { super.key, required this.webViewController, PlatformWebViewCookieManager? cookieManager, - }) : cookieManager = cookieManager ?? - PlatformWebViewCookieManager( - const PlatformWebViewCookieManagerCreationParams(), - ); + }) : cookieManager = + cookieManager ?? + PlatformWebViewCookieManager( + const PlatformWebViewCookieManagerCreationParams(), + ); final PlatformWebViewController webViewController; late final PlatformWebViewCookieManager cookieManager; @@ -409,81 +411,82 @@ class SampleMenu extends StatelessWidget { _onViewportMetaExample(); } }, - itemBuilder: (BuildContext context) => >[ - const PopupMenuItem( - value: MenuOptions.showUserAgent, - child: Text('Show user agent'), - ), - const PopupMenuItem( - value: MenuOptions.listCookies, - child: Text('List cookies'), - ), - const PopupMenuItem( - value: MenuOptions.clearCookies, - child: Text('Clear cookies'), - ), - const PopupMenuItem( - value: MenuOptions.addToCache, - child: Text('Add to cache'), - ), - const PopupMenuItem( - value: MenuOptions.listCache, - child: Text('List cache'), - ), - const PopupMenuItem( - value: MenuOptions.clearCache, - child: Text('Clear cache'), - ), - const PopupMenuItem( - value: MenuOptions.navigationDelegate, - child: Text('Navigation Delegate example'), - ), - const PopupMenuItem( - value: MenuOptions.doPostRequest, - child: Text('Post Request'), - ), - const PopupMenuItem( - value: MenuOptions.loadHtmlString, - child: Text('Load HTML string'), - ), - const PopupMenuItem( - value: MenuOptions.loadLocalFile, - child: Text('Load local file'), - ), - const PopupMenuItem( - value: MenuOptions.loadFlutterAsset, - child: Text('Load Flutter Asset'), - ), - const PopupMenuItem( - value: MenuOptions.setCookie, - child: Text('Set cookie'), - ), - const PopupMenuItem( - key: ValueKey('ShowTransparentBackgroundExample'), - value: MenuOptions.transparentBackground, - child: Text('Transparent background example'), - ), - const PopupMenuItem( - value: MenuOptions.logExample, - child: Text('Log example'), - ), - const PopupMenuItem( - value: MenuOptions.videoExample, - child: Text('Video example'), - ), - const PopupMenuItem( - value: MenuOptions.basicAuthentication, - child: Text('Basic Authentication Example'), - ), - const PopupMenuItem( - value: MenuOptions.javaScriptAlert, - child: Text('JavaScript Alert Example'), - ), - const PopupMenuItem( - value: MenuOptions.viewportMeta, - child: Text('Viewport meta example'), - ), - ], + itemBuilder: + (BuildContext context) => >[ + const PopupMenuItem( + value: MenuOptions.showUserAgent, + child: Text('Show user agent'), + ), + const PopupMenuItem( + value: MenuOptions.listCookies, + child: Text('List cookies'), + ), + const PopupMenuItem( + value: MenuOptions.clearCookies, + child: Text('Clear cookies'), + ), + const PopupMenuItem( + value: MenuOptions.addToCache, + child: Text('Add to cache'), + ), + const PopupMenuItem( + value: MenuOptions.listCache, + child: Text('List cache'), + ), + const PopupMenuItem( + value: MenuOptions.clearCache, + child: Text('Clear cache'), + ), + const PopupMenuItem( + value: MenuOptions.navigationDelegate, + child: Text('Navigation Delegate example'), + ), + const PopupMenuItem( + value: MenuOptions.doPostRequest, + child: Text('Post Request'), + ), + const PopupMenuItem( + value: MenuOptions.loadHtmlString, + child: Text('Load HTML string'), + ), + const PopupMenuItem( + value: MenuOptions.loadLocalFile, + child: Text('Load local file'), + ), + const PopupMenuItem( + value: MenuOptions.loadFlutterAsset, + child: Text('Load Flutter Asset'), + ), + const PopupMenuItem( + value: MenuOptions.setCookie, + child: Text('Set cookie'), + ), + const PopupMenuItem( + key: ValueKey('ShowTransparentBackgroundExample'), + value: MenuOptions.transparentBackground, + child: Text('Transparent background example'), + ), + const PopupMenuItem( + value: MenuOptions.logExample, + child: Text('Log example'), + ), + const PopupMenuItem( + value: MenuOptions.videoExample, + child: Text('Video example'), + ), + const PopupMenuItem( + value: MenuOptions.basicAuthentication, + child: Text('Basic Authentication Example'), + ), + const PopupMenuItem( + value: MenuOptions.javaScriptAlert, + child: Text('JavaScript Alert Example'), + ), + const PopupMenuItem( + value: MenuOptions.viewportMeta, + child: Text('Viewport meta example'), + ), + ], ); } @@ -496,19 +499,19 @@ class SampleMenu extends StatelessWidget { } Future _onListCookies(BuildContext context) async { - final String cookies = await webViewController - .runJavaScriptReturningResult('document.cookie') as String; + final String cookies = + await webViewController.runJavaScriptReturningResult('document.cookie') + as String; if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar( - content: Column( - mainAxisAlignment: MainAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - const Text('Cookies:'), - _getCookieList(cookies), - ], + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Column( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [const Text('Cookies:'), _getCookieList(cookies)], + ), ), - )); + ); } } @@ -517,26 +520,28 @@ class SampleMenu extends StatelessWidget { 'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";', ); if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar( - content: Text('Added a test entry to cache.'), - )); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Added a test entry to cache.')), + ); } } Future _onListCache() { - return webViewController.runJavaScript('caches.keys()' - // ignore: missing_whitespace_between_adjacent_strings - '.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))' - '.then((caches) => Toaster.postMessage(caches))'); + return webViewController.runJavaScript( + 'caches.keys()' + // ignore: missing_whitespace_between_adjacent_strings + '.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))' + '.then((caches) => Toaster.postMessage(caches))', + ); } Future _onClearCache(BuildContext context) async { await webViewController.clearCache(); await webViewController.clearLocalStorage(); if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar( - content: Text('Cache cleared.'), - )); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Cache cleared.'))); } } @@ -547,9 +552,9 @@ class SampleMenu extends StatelessWidget { message = 'There are no cookies.'; } if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar( - content: Text(message), - )); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message))); } } @@ -558,9 +563,7 @@ class SampleMenu extends StatelessWidget { const Utf8Encoder().convert(kNavigationExamplePage), ); return webViewController.loadRequest( - LoadRequestParams( - uri: Uri.parse('data:text/html;base64,$contentBase64'), - ), + LoadRequestParams(uri: Uri.parse('data:text/html;base64,$contentBase64')), ); } @@ -573,9 +576,9 @@ class SampleMenu extends StatelessWidget { path: '/anything', ), ); - await webViewController.loadRequest(LoadRequestParams( - uri: Uri.parse('https://httpbin.org/anything'), - )); + await webViewController.loadRequest( + LoadRequestParams(uri: Uri.parse('https://httpbin.org/anything')), + ); } Future _onVideoExample(BuildContext context) { @@ -584,10 +587,12 @@ class SampleMenu extends StatelessWidget { // #docregion fullscreen_example androidController.setCustomWidgetCallbacks( onShowCustomWidget: (Widget widget, OnHideCustomWidgetCallback callback) { - Navigator.of(context).push(MaterialPageRoute( - builder: (BuildContext context) => widget, - fullscreenDialog: true, - )); + Navigator.of(context).push( + MaterialPageRoute( + builder: (BuildContext context) => widget, + fullscreenDialog: true, + ), + ); }, onHideCustomWidget: () { Navigator.of(context).pop(); @@ -603,15 +608,17 @@ class SampleMenu extends StatelessWidget { } Future _onDoPostRequest() { - return webViewController.loadRequest(LoadRequestParams( - uri: Uri.parse('https://httpbin.org/post'), - method: LoadRequestMethod.post, - headers: const { - 'foo': 'bar', - 'Content-Type': 'text/plain', - }, - body: Uint8List.fromList('Test Body'.codeUnits), - )); + return webViewController.loadRequest( + LoadRequestParams( + uri: Uri.parse('https://httpbin.org/post'), + method: LoadRequestMethod.post, + headers: const { + 'foo': 'bar', + 'Content-Type': 'text/plain', + }, + body: Uint8List.fromList('Test Body'.codeUnits), + ), + ); } Future _onLoadLocalFileExample() async { @@ -632,21 +639,27 @@ class SampleMenu extends StatelessWidget { } Future _onJavaScriptAlertExample(BuildContext context) { - webViewController.setOnJavaScriptAlertDialog( - (JavaScriptAlertDialogRequest request) async { + webViewController.setOnJavaScriptAlertDialog(( + JavaScriptAlertDialogRequest request, + ) async { await _showAlert(context, request.message); }); - webViewController.setOnJavaScriptConfirmDialog( - (JavaScriptConfirmDialogRequest request) async { + webViewController.setOnJavaScriptConfirmDialog(( + JavaScriptConfirmDialogRequest request, + ) async { final bool result = await _showConfirm(context, request.message); return result; }); - webViewController.setOnJavaScriptTextInputDialog( - (JavaScriptTextInputDialogRequest request) async { - final String result = - await _showTextInput(context, request.message, request.defaultText); + webViewController.setOnJavaScriptTextInputDialog(( + JavaScriptTextInputDialogRequest request, + ) async { + final String result = await _showTextInput( + context, + request.message, + request.defaultText, + ); return result; }); @@ -658,8 +671,9 @@ class SampleMenu extends StatelessWidget { return Container(); } final List cookieList = cookies.split(';'); - final Iterable cookieWidgets = - cookieList.map((String cookie) => Text(cookie)); + final Iterable cookieWidgets = cookieList.map( + (String cookie) => Text(cookie), + ); return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, @@ -670,7 +684,8 @@ class SampleMenu extends StatelessWidget { static Future _prepareLocalFile() async { final String tmpDir = (await getTemporaryDirectory()).path; final File indexFile = File( - {tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator)); + {tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator), + ); await indexFile.create(recursive: true); await indexFile.writeAsString(kLocalExamplePage); @@ -679,10 +694,12 @@ class SampleMenu extends StatelessWidget { } Future _onLogExample() { - webViewController - .setOnConsoleMessage((JavaScriptConsoleMessage consoleMessage) { + webViewController.setOnConsoleMessage(( + JavaScriptConsoleMessage consoleMessage, + ) { debugPrint( - '== JS == ${consoleMessage.level.name}: ${consoleMessage.message}'); + '== JS == ${consoleMessage.level.name}: ${consoleMessage.message}', + ); }); return webViewController.loadHtmlString(kLogExamplePage); } @@ -706,9 +723,7 @@ class SampleMenu extends StatelessWidget { if (urlTextController.text.isNotEmpty) { final Uri? uri = Uri.tryParse(urlTextController.text); if (uri != null && uri.scheme.isNotEmpty) { - webViewController.loadRequest( - LoadRequestParams(uri: uri), - ); + webViewController.loadRequest(LoadRequestParams(uri: uri)); Navigator.pop(context); } } @@ -723,60 +738,70 @@ class SampleMenu extends StatelessWidget { Future _showAlert(BuildContext context, String message) async { return showDialog( - context: context, - builder: (BuildContext ctx) { - return AlertDialog( - content: Text(message), - actions: [ - TextButton( - onPressed: () { - Navigator.of(ctx).pop(); - }, - child: const Text('OK')) - ], - ); - }); + context: context, + builder: (BuildContext ctx) { + return AlertDialog( + content: Text(message), + actions: [ + TextButton( + onPressed: () { + Navigator.of(ctx).pop(); + }, + child: const Text('OK'), + ), + ], + ); + }, + ); } Future _showConfirm(BuildContext context, String message) async { return await showDialog( - context: context, - builder: (BuildContext ctx) { - return AlertDialog( - content: Text(message), - actions: [ - TextButton( - onPressed: () { - Navigator.of(ctx).pop(false); - }, - child: const Text('Cancel')), - TextButton( - onPressed: () { - Navigator.of(ctx).pop(true); - }, - child: const Text('OK')), - ], - ); - }) ?? + context: context, + builder: (BuildContext ctx) { + return AlertDialog( + content: Text(message), + actions: [ + TextButton( + onPressed: () { + Navigator.of(ctx).pop(false); + }, + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + Navigator.of(ctx).pop(true); + }, + child: const Text('OK'), + ), + ], + ); + }, + ) ?? false; } Future _showTextInput( - BuildContext context, String message, String? defaultText) async { + BuildContext context, + String message, + String? defaultText, + ) async { return await showDialog( - context: context, - builder: (BuildContext ctx) { - return AlertDialog( - content: Text(message), - actions: [ - TextButton( - onPressed: () { - Navigator.of(ctx).pop('Text test'); - }, - child: const Text('Enter')), - ], - ); - }) ?? + context: context, + builder: (BuildContext ctx) { + return AlertDialog( + content: Text(message), + actions: [ + TextButton( + onPressed: () { + Navigator.of(ctx).pop('Text test'); + }, + child: const Text('Enter'), + ), + ], + ); + }, + ) ?? ''; } diff --git a/packages/webview_flutter/webview_flutter_android/example/lib/readme_excerpts.dart b/packages/webview_flutter/webview_flutter_android/example/lib/readme_excerpts.dart index dc2d799c3bf..92390fbabe5 100644 --- a/packages/webview_flutter/webview_flutter_android/example/lib/readme_excerpts.dart +++ b/packages/webview_flutter/webview_flutter_android/example/lib/readme_excerpts.dart @@ -7,8 +7,9 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte /// Example function for README demonstration of Payment Request API. Future enablePaymentRequest() async { - final PlatformWebViewController controller = - PlatformWebViewController(AndroidWebViewControllerCreationParams()); + final PlatformWebViewController controller = PlatformWebViewController( + AndroidWebViewControllerCreationParams(), + ); final AndroidWebViewController androidController = controller as AndroidWebViewController; // #docregion payment_request_example diff --git a/packages/webview_flutter/webview_flutter_android/example/pubspec.yaml b/packages/webview_flutter/webview_flutter_android/example/pubspec.yaml index 53d3c68df62..93141e0cfce 100644 --- a/packages/webview_flutter/webview_flutter_android/example/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the webview_flutter_android plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart index 12c460f4129..d704216640b 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart @@ -32,20 +32,17 @@ class AndroidWebViewProxy { /// Constructs [WebView]. final WebView Function({ - void Function( - WebView, - int left, - int top, - int oldLeft, - int oldTop, - )? onScrollChanged, - }) newWebView; + void Function(WebView, int left, int top, int oldLeft, int oldTop)? + onScrollChanged, + }) + newWebView; /// Constructs [JavaScriptChannel]. final JavaScriptChannel Function({ required String channelName, required void Function(JavaScriptChannel, String) postMessage, - }) newJavaScriptChannel; + }) + newJavaScriptChannel; /// Constructs [WebViewClient]. final WebViewClient Function({ @@ -56,73 +53,50 @@ class AndroidWebViewProxy { WebView, WebResourceRequest, WebResourceResponse, - )? onReceivedHttpError, - void Function( - WebViewClient, - WebView, - WebResourceRequest, - WebResourceError, - )? onReceivedRequestError, + )? + onReceivedHttpError, + void Function(WebViewClient, WebView, WebResourceRequest, WebResourceError)? + onReceivedRequestError, void Function( WebViewClient, WebView, WebResourceRequest, WebResourceErrorCompat, - )? onReceivedRequestErrorCompat, + )? + onReceivedRequestErrorCompat, void Function(WebViewClient, WebView, int, String, String)? onReceivedError, void Function(WebViewClient, WebView, WebResourceRequest)? requestLoading, void Function(WebViewClient, WebView, String)? urlLoading, void Function(WebViewClient, WebView, String, bool)? doUpdateVisitedHistory, void Function(WebViewClient, WebView, HttpAuthHandler, String, String)? - onReceivedHttpAuthRequest, - void Function( - WebViewClient, - WebView, - AndroidMessage, - AndroidMessage, - )? onFormResubmission, - void Function( - WebViewClient, - WebView, - String, - )? onLoadResource, - void Function( - WebViewClient, - WebView, - String, - )? onPageCommitVisible, - void Function( - WebViewClient, - WebView, - ClientCertRequest, - )? onReceivedClientCertRequest, - void Function( - WebViewClient, - WebView, - String, - String?, - String, - )? onReceivedLoginRequest, - void Function( - WebViewClient, - WebView, - SslErrorHandler, - SslError, - )? onReceivedSslError, - void Function( - WebViewClient, - WebView, - double, - double, - )? onScaleChanged, - }) newWebViewClient; + onReceivedHttpAuthRequest, + void Function(WebViewClient, WebView, AndroidMessage, AndroidMessage)? + onFormResubmission, + void Function(WebViewClient, WebView, String)? onLoadResource, + void Function(WebViewClient, WebView, String)? onPageCommitVisible, + void Function(WebViewClient, WebView, ClientCertRequest)? + onReceivedClientCertRequest, + void Function(WebViewClient, WebView, String, String?, String)? + onReceivedLoginRequest, + void Function(WebViewClient, WebView, SslErrorHandler, SslError)? + onReceivedSslError, + void Function(WebViewClient, WebView, double, double)? onScaleChanged, + }) + newWebViewClient; /// Constructs [DownloadListener]. final DownloadListener Function({ required void Function( - DownloadListener, String, String, String, String, int) - onDownloadStart, - }) newDownloadListener; + DownloadListener, + String, + String, + String, + String, + int, + ) + onDownloadStart, + }) + newDownloadListener; /// Constructs [WebChromeClient]. final WebChromeClient Function({ @@ -131,32 +105,22 @@ class AndroidWebViewProxy { WebChromeClient, WebView, FileChooserParams, - ) onShowFileChooser, + ) + onShowFileChooser, void Function(WebChromeClient, PermissionRequest)? onPermissionRequest, void Function(WebChromeClient, View, CustomViewCallback)? onShowCustomView, void Function(WebChromeClient)? onHideCustomView, - void Function( - WebChromeClient, - String, - GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, + void Function(WebChromeClient, String, GeolocationPermissionsCallback)? + onGeolocationPermissionsShowPrompt, void Function(WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function(WebChromeClient, ConsoleMessage)? onConsoleMessage, Future Function(WebChromeClient, WebView, String, String)? onJsAlert, - required Future Function( - WebChromeClient, - WebView, - String, - String, - ) onJsConfirm, - Future Function( - WebChromeClient, - WebView, - String, - String, - String, - )? onJsPrompt, - }) newWebChromeClient; + required Future Function(WebChromeClient, WebView, String, String) + onJsConfirm, + Future Function(WebChromeClient, WebView, String, String, String)? + onJsPrompt, + }) + newWebChromeClient; /// Calls to [WebView.setWebContentsDebuggingEnabled]. final Future Function(bool) setWebContentsDebuggingEnabledWebView; diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart index 12f7d30aa5f..0117cc86e63 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart @@ -20,8 +20,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse( - {Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -43,7 +46,7 @@ abstract class PigeonInternalProxyApiBaseClass { this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -114,7 +117,7 @@ class PigeonInstanceManager { // HashMap). final Expando _identifiers = Expando(); final Map> - _weakInstances = >{}; + _weakInstances = >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -136,70 +139,102 @@ class PigeonInstanceManager { }, ); _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager); + instanceManager: instanceManager, + ); WebResourceRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebResourceResponse.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebResourceError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebResourceErrorCompat.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebViewPoint.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ConsoleMessage.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); CookieManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebView.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); JavaScriptChannel.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebViewClient.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); DownloadListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebChromeClient.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); FlutterAssetManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebStorage.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); FileChooserParams.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); PermissionRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); CustomViewCallback.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); View.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); GeolocationPermissionsCallback.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); HttpAuthHandler.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); AndroidMessage.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); ClientCertRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); PrivateKey.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); X509Certificate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); SslErrorHandler.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); SslError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); SslCertificateDName.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); SslCertificate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); Certificate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebSettingsCompat.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); WebViewFeature.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager); + pigeon_instanceManager: instanceManager, + ); return instanceManager; } @@ -216,8 +251,9 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = - WeakReference(instance); + _weakInstances[identifier] = WeakReference( + instance, + ); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -279,7 +315,8 @@ class PigeonInstanceManager { /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. T? getInstanceWithWeakReference( - int identifier) { + int identifier, + ) { final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; @@ -314,7 +351,9 @@ class PigeonInstanceManager { /// Throws assertion error if the instance or its identifier has already been /// added. void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, int identifier) { + PigeonInternalProxyApiBaseClass instance, + int identifier, + ) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -343,7 +382,7 @@ class PigeonInstanceManager { class _PigeonInternalInstanceManagerApi { /// Constructor for [_PigeonInternalInstanceManagerApi]. _PigeonInternalInstanceManagerApi({BinaryMessenger? binaryMessenger}) - : pigeonVar_binaryMessenger = binaryMessenger; + : pigeonVar_binaryMessenger = binaryMessenger; final BinaryMessenger? pigeonVar_binaryMessenger; @@ -355,31 +394,37 @@ class _PigeonInternalInstanceManagerApi { PigeonInstanceManager? instanceManager, }) { { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference was null.', + ); final List args = (message as List?)!; final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.'); + assert( + arg_identifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', + ); try { - (instanceManager ?? PigeonInstanceManager.instance) - .remove(arg_identifier!); + (instanceManager ?? PigeonInstanceManager.instance).remove( + arg_identifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -391,12 +436,13 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.removeStrongReference'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [identifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([identifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -420,10 +466,10 @@ class _PigeonInternalInstanceManagerApi { 'dev.flutter.pigeon.webview_flutter_android.PigeonInternalInstanceManager.clear'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -458,8 +504,9 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager - .getInstanceWithWeakReference(readValue(buffer)! as int); + return instanceManager.getInstanceWithWeakReference( + readValue(buffer)! as int, + ); default: return super.readValueOfType(type, buffer); } @@ -691,72 +738,88 @@ class WebResourceRequest extends PigeonInternalProxyApiBaseClass { bool hasGesture, String method, Map? requestHeaders, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_url = (args[1] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null String.', + ); final bool? arg_isForMainFrame = (args[2] as bool?); - assert(arg_isForMainFrame != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_isForMainFrame != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null bool.', + ); final bool? arg_isRedirect = (args[3] as bool?); final bool? arg_hasGesture = (args[4] as bool?); - assert(arg_hasGesture != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_hasGesture != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null bool.', + ); final String? arg_method = (args[5] as String?); - assert(arg_method != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_method != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance was null, expected non-null String.', + ); final Map? arg_requestHeaders = (args[6] as Map?)?.cast(); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_url!, - arg_isForMainFrame!, - arg_isRedirect, - arg_hasGesture!, - arg_method!, - arg_requestHeaders) ?? - WebResourceRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - url: arg_url!, - isForMainFrame: arg_isForMainFrame!, - isRedirect: arg_isRedirect, - hasGesture: arg_hasGesture!, - method: arg_method!, - requestHeaders: arg_requestHeaders, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_url!, + arg_isForMainFrame!, + arg_isRedirect, + arg_hasGesture!, + arg_method!, + arg_requestHeaders, + ) ?? + WebResourceRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + url: arg_url!, + isForMainFrame: arg_isForMainFrame!, + isRedirect: arg_isRedirect, + hasGesture: arg_hasGesture!, + method: arg_method!, + requestHeaders: arg_requestHeaders, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -804,45 +867,53 @@ class WebResourceResponse extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_statusCode = (args[1] as int?); - assert(arg_statusCode != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_statusCode != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_statusCode!) ?? - WebResourceResponse.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - statusCode: arg_statusCode!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_statusCode!) ?? + WebResourceResponse.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + statusCode: arg_statusCode!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -886,56 +957,64 @@ class WebResourceError extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - WebResourceError Function( - int errorCode, - String description, - )? pigeon_newInstance, + WebResourceError Function(int errorCode, String description)? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_errorCode = (args[1] as int?); - assert(arg_errorCode != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_errorCode != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_description = (args[2] as String?); - assert(arg_description != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_description != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? - WebResourceError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - errorCode: arg_errorCode!, - description: arg_description!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? + WebResourceError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: arg_errorCode!, + description: arg_description!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -980,56 +1059,64 @@ class WebResourceErrorCompat extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - WebResourceErrorCompat Function( - int errorCode, - String description, - )? pigeon_newInstance, + WebResourceErrorCompat Function(int errorCode, String description)? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_errorCode = (args[1] as int?); - assert(arg_errorCode != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_errorCode != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_description = (args[2] as String?); - assert(arg_description != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_description != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? - WebResourceErrorCompat.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - errorCode: arg_errorCode!, - description: arg_description!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? + WebResourceErrorCompat.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: arg_errorCode!, + description: arg_description!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1071,56 +1158,63 @@ class WebViewPoint extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - WebViewPoint Function( - int x, - int y, - )? pigeon_newInstance, + WebViewPoint Function(int x, int y)? pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_x = (args[1] as int?); - assert(arg_x != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_x != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_y = (args[2] as int?); - assert(arg_y != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_y != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_x!, arg_y!) ?? - WebViewPoint.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - x: arg_x!, - y: arg_y!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_x!, arg_y!) ?? + WebViewPoint.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + x: arg_x!, + y: arg_y!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1173,63 +1267,82 @@ class ConsoleMessage extends PigeonInternalProxyApiBaseClass { String message, ConsoleMessageLevel level, String sourceId, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null int.', + ); final int? arg_lineNumber = (args[1] as int?); - assert(arg_lineNumber != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_lineNumber != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null int.', + ); final String? arg_message = (args[2] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null String.', + ); final ConsoleMessageLevel? arg_level = (args[3] as ConsoleMessageLevel?); - assert(arg_level != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null ConsoleMessageLevel.'); + assert( + arg_level != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null ConsoleMessageLevel.', + ); final String? arg_sourceId = (args[4] as String?); - assert(arg_sourceId != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_sourceId != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_lineNumber!, arg_message!, - arg_level!, arg_sourceId!) ?? - ConsoleMessage.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - lineNumber: arg_lineNumber!, - message: arg_message!, - level: arg_level!, - sourceId: arg_sourceId!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_lineNumber!, + arg_message!, + arg_level!, + arg_sourceId!, + ) ?? + ConsoleMessage.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + lineNumber: arg_lineNumber!, + message: arg_message!, + level: arg_level!, + sourceId: arg_sourceId!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1276,41 +1389,47 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CookieManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + CookieManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1330,12 +1449,13 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.CookieManager.instance'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1354,10 +1474,7 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { } /// Sets a single cookie (key-value pair) for the given URL. - Future setCookie( - String url, - String value, - ) async { + Future setCookie(String url, String value) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCookieManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1365,12 +1482,13 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.CookieManager.setCookie'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, url, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, url, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1395,12 +1513,13 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.CookieManager.removeAllCookies'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1422,10 +1541,7 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { } /// Sets whether the `WebView` should allow third party cookies to be set. - Future setAcceptThirdPartyCookies( - WebView webView, - bool accept, - ) async { + Future setAcceptThirdPartyCookies(WebView webView, bool accept) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCookieManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1433,12 +1549,13 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.CookieManager.setAcceptThirdPartyCookies'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, webView, accept], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, webView, accept]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1472,8 +1589,8 @@ class WebView extends View { super.pigeon_instanceManager, this.onScrollChanged, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1481,12 +1598,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1544,7 +1662,8 @@ class WebView extends View { int top, int oldLeft, int oldTop, - )? onScrollChanged; + )? + onScrollChanged; /// The WebSettings object used to control the settings for this WebView. late final WebSettings settings = pigeonVar_settings(); @@ -1560,92 +1679,113 @@ class WebView extends View { int top, int oldLeft, int oldTop, - )? onScrollChanged, + )? + onScrollChanged, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebView.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + WebView.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null.', + ); final List args = (message as List?)!; final WebView? arg_pigeon_instance = (args[0] as WebView?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null WebView.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null WebView.', + ); final int? arg_left = (args[1] as int?); - assert(arg_left != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.'); + assert( + arg_left != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.', + ); final int? arg_top = (args[2] as int?); - assert(arg_top != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.'); + assert( + arg_top != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.', + ); final int? arg_oldLeft = (args[3] as int?); - assert(arg_oldLeft != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.'); + assert( + arg_oldLeft != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.', + ); final int? arg_oldTop = (args[4] as int?); - assert(arg_oldTop != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.'); + assert( + arg_oldTop != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebView.onScrollChanged was null, expected non-null int.', + ); try { (onScrollChanged ?? arg_pigeon_instance!.onScrollChanged)?.call( - arg_pigeon_instance!, - arg_left!, - arg_top!, - arg_oldLeft!, - arg_oldTop!); + arg_pigeon_instance!, + arg_left!, + arg_top!, + arg_oldLeft!, + arg_oldTop!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1660,19 +1800,20 @@ class WebView extends View { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(pigeonVar_instance); () async { const String pigeonVar_channelName = 'dev.flutter.pigeon.webview_flutter_android.WebView.settings'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1691,11 +1832,7 @@ class WebView extends View { } /// Loads the given data into this WebView using a 'data' scheme URL. - Future loadData( - String data, - String? mimeType, - String? encoding, - ) async { + Future loadData(String data, String? mimeType, String? encoding) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1703,12 +1840,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.loadData'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, data, mimeType, encoding], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, data, mimeType, encoding]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1740,12 +1878,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.loadDataWithBaseUrl'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, baseUrl, data, mimeType, encoding, historyUrl], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([this, baseUrl, data, mimeType, encoding, historyUrl]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1762,10 +1901,7 @@ class WebView extends View { } /// Loads the given URL. - Future loadUrl( - String url, - Map headers, - ) async { + Future loadUrl(String url, Map headers) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1773,12 +1909,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.loadUrl'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, url, headers], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, url, headers]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1795,10 +1932,7 @@ class WebView extends View { } /// Loads the URL with postData using "POST" method into this WebView. - Future postUrl( - String url, - Uint8List data, - ) async { + Future postUrl(String url, Uint8List data) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1806,12 +1940,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.postUrl'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, url, data], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, url, data]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1836,12 +1971,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.getUrl'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1866,12 +2002,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.canGoBack'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1901,12 +2038,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.canGoForward'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1936,12 +2074,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.goBack'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1966,12 +2105,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.goForward'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1996,12 +2136,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.reload'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2026,12 +2167,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.clearCache'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, includeDiskFiles], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, includeDiskFiles]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2057,12 +2199,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.evaluateJavascript'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, javascriptString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, javascriptString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2087,12 +2230,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.getTitle'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2117,18 +2261,20 @@ class WebView extends View { }) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.webview_flutter_android.WebView.setWebContentsDebuggingEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2154,12 +2300,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.setWebViewClient'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, client], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, client]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2184,12 +2331,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.addJavaScriptChannel'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, channel], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, channel]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2214,12 +2362,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.removeJavaScriptChannel'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, name], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, name]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2245,12 +2394,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.setDownloadListener'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, listener], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, listener]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2275,12 +2425,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.setWebChromeClient'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, client], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, client]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2305,12 +2456,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.setBackgroundColor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, color], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, color]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2335,12 +2487,13 @@ class WebView extends View { 'dev.flutter.pigeon.webview_flutter_android.WebView.destroy'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2391,41 +2544,47 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + WebSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -2441,12 +2600,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setDomStorageEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, flag], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, flag]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2471,12 +2631,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setJavaScriptCanOpenWindowsAutomatically'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, flag], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, flag]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2501,12 +2662,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setSupportMultipleWindows'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, support], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, support]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2531,12 +2693,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setJavaScriptEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, flag], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, flag]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2561,12 +2724,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setUserAgentString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, userAgentString], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, userAgentString]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2591,12 +2755,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setMediaPlaybackRequiresUserGesture'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, require], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, require]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2622,12 +2787,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setSupportZoom'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, support], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, support]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2653,12 +2819,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setLoadWithOverviewMode'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, overview], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, overview]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2684,12 +2851,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setUseWideViewPort'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, use], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, use]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2715,12 +2883,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setDisplayZoomControls'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2746,12 +2915,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setBuiltInZoomControls'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2776,12 +2946,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setAllowFileAccess'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2806,12 +2977,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setAllowContentAccess'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2836,12 +3008,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setGeolocationEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2866,12 +3039,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setTextZoom'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, textZoom], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, textZoom]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2896,12 +3070,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.getUserAgentString'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2931,12 +3106,13 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebSettings.setMixedContentMode'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, mode], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, mode]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2972,8 +3148,8 @@ class JavaScriptChannel extends PigeonInternalProxyApiBaseClass { required this.channelName, required this.postMessage, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecJavaScriptChannel; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -2981,12 +3157,13 @@ class JavaScriptChannel extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, channelName], ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([pigeonVar_instanceIdentifier, channelName]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3017,8 +3194,9 @@ class JavaScriptChannel extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecJavaScriptChannel = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecJavaScriptChannel = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); final String channelName; @@ -3041,54 +3219,60 @@ class JavaScriptChannel extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - JavaScriptChannel pigeon_instance, - String message, - ) postMessage; + final void Function(JavaScriptChannel pigeon_instance, String message) + postMessage; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - JavaScriptChannel pigeon_instance, - String message, - )? postMessage, + void Function(JavaScriptChannel pigeon_instance, String message)? + postMessage, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage was null.', + ); final List args = (message as List?)!; final JavaScriptChannel? arg_pigeon_instance = (args[0] as JavaScriptChannel?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage was null, expected non-null JavaScriptChannel.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage was null, expected non-null JavaScriptChannel.', + ); final String? arg_message = (args[1] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.postMessage was null, expected non-null String.', + ); try { - (postMessage ?? arg_pigeon_instance!.postMessage) - .call(arg_pigeon_instance!, arg_message!); + (postMessage ?? arg_pigeon_instance!.postMessage).call( + arg_pigeon_instance!, + arg_message!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -3131,8 +3315,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { this.onReceivedSslError, this.onScaleChanged, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebViewClient; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3140,12 +3324,13 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -3216,7 +3401,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebViewClient pigeon_instance, WebView webView, String url, - )? onPageStarted; + )? + onPageStarted; /// Notify the host application that a page has finished loading. /// @@ -3241,7 +3427,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebViewClient pigeon_instance, WebView webView, String url, - )? onPageFinished; + )? + onPageFinished; /// Notify the host application that an HTTP error has been received from the /// server while loading a resource. @@ -3268,7 +3455,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView webView, WebResourceRequest request, WebResourceResponse response, - )? onReceivedHttpError; + )? + onReceivedHttpError; /// Report web resource loading error to the host application. /// @@ -3294,7 +3482,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView webView, WebResourceRequest request, WebResourceError error, - )? onReceivedRequestError; + )? + onReceivedRequestError; /// Report web resource loading error to the host application. /// @@ -3320,7 +3509,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView webView, WebResourceRequest request, WebResourceErrorCompat error, - )? onReceivedRequestErrorCompat; + )? + onReceivedRequestErrorCompat; /// Report an error to the host application. /// @@ -3347,7 +3537,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { int errorCode, String description, String failingUrl, - )? onReceivedError; + )? + onReceivedError; /// Give the host application a chance to take control when a URL is about to /// be loaded in the current WebView. @@ -3373,7 +3564,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebViewClient pigeon_instance, WebView webView, WebResourceRequest request, - )? requestLoading; + )? + requestLoading; /// Give the host application a chance to take control when a URL is about to /// be loaded in the current WebView. @@ -3399,7 +3591,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebViewClient pigeon_instance, WebView webView, String url, - )? urlLoading; + )? + urlLoading; /// Notify the host application to update its visited links database. /// @@ -3425,7 +3618,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView webView, String url, bool isReload, - )? doUpdateVisitedHistory; + )? + doUpdateVisitedHistory; /// Notifies the host application that the WebView received an HTTP /// authentication request. @@ -3453,7 +3647,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { HttpAuthHandler handler, String host, String realm, - )? onReceivedHttpAuthRequest; + )? + onReceivedHttpAuthRequest; /// Ask the host application if the browser should resend data as the /// requested page was a result of a POST. @@ -3480,7 +3675,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView view, AndroidMessage dontResend, AndroidMessage resend, - )? onFormResubmission; + )? + onFormResubmission; /// Notify the host application that the WebView will load the resource /// specified by the given url. @@ -3502,11 +3698,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - WebViewClient pigeon_instance, - WebView view, - String url, - )? onLoadResource; + final void Function(WebViewClient pigeon_instance, WebView view, String url)? + onLoadResource; /// Notify the host application that WebView content left over from previous /// page navigations will no longer be drawn. @@ -3528,11 +3721,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - WebViewClient pigeon_instance, - WebView view, - String url, - )? onPageCommitVisible; + final void Function(WebViewClient pigeon_instance, WebView view, String url)? + onPageCommitVisible; /// Notify the host application to handle a SSL client certificate request. /// @@ -3557,7 +3747,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebViewClient pigeon_instance, WebView view, ClientCertRequest request, - )? onReceivedClientCertRequest; + )? + onReceivedClientCertRequest; /// Notify the host application that a request to automatically log in the /// user has been processed. @@ -3585,7 +3776,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { String realm, String? account, String args, - )? onReceivedLoginRequest; + )? + onReceivedLoginRequest; /// Notifies the host application that an SSL error occurred while loading a /// resource. @@ -3612,7 +3804,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView view, SslErrorHandler handler, SslError error, - )? onReceivedSslError; + )? + onReceivedSslError; /// Notify the host application that the scale applied to the WebView has /// changed. @@ -3639,681 +3832,860 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { WebView view, double oldScale, double newScale, - )? onScaleChanged; + )? + onScaleChanged; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, WebViewClient Function()? pigeon_newInstance, - void Function( - WebViewClient pigeon_instance, - WebView webView, - String url, - )? onPageStarted, - void Function( - WebViewClient pigeon_instance, - WebView webView, - String url, - )? onPageFinished, + void Function(WebViewClient pigeon_instance, WebView webView, String url)? + onPageStarted, + void Function(WebViewClient pigeon_instance, WebView webView, String url)? + onPageFinished, void Function( WebViewClient pigeon_instance, WebView webView, WebResourceRequest request, WebResourceResponse response, - )? onReceivedHttpError, + )? + onReceivedHttpError, void Function( WebViewClient pigeon_instance, WebView webView, WebResourceRequest request, WebResourceError error, - )? onReceivedRequestError, + )? + onReceivedRequestError, void Function( WebViewClient pigeon_instance, WebView webView, WebResourceRequest request, WebResourceErrorCompat error, - )? onReceivedRequestErrorCompat, + )? + onReceivedRequestErrorCompat, void Function( WebViewClient pigeon_instance, WebView webView, int errorCode, String description, String failingUrl, - )? onReceivedError, + )? + onReceivedError, void Function( WebViewClient pigeon_instance, WebView webView, WebResourceRequest request, - )? requestLoading, - void Function( - WebViewClient pigeon_instance, - WebView webView, - String url, - )? urlLoading, + )? + requestLoading, + void Function(WebViewClient pigeon_instance, WebView webView, String url)? + urlLoading, void Function( WebViewClient pigeon_instance, WebView webView, String url, bool isReload, - )? doUpdateVisitedHistory, + )? + doUpdateVisitedHistory, void Function( WebViewClient pigeon_instance, WebView webView, HttpAuthHandler handler, String host, String realm, - )? onReceivedHttpAuthRequest, + )? + onReceivedHttpAuthRequest, void Function( WebViewClient pigeon_instance, WebView view, AndroidMessage dontResend, AndroidMessage resend, - )? onFormResubmission, - void Function( - WebViewClient pigeon_instance, - WebView view, - String url, - )? onLoadResource, - void Function( - WebViewClient pigeon_instance, - WebView view, - String url, - )? onPageCommitVisible, + )? + onFormResubmission, + void Function(WebViewClient pigeon_instance, WebView view, String url)? + onLoadResource, + void Function(WebViewClient pigeon_instance, WebView view, String url)? + onPageCommitVisible, void Function( WebViewClient pigeon_instance, WebView view, ClientCertRequest request, - )? onReceivedClientCertRequest, + )? + onReceivedClientCertRequest, void Function( WebViewClient pigeon_instance, WebView view, String realm, String? account, String args, - )? onReceivedLoginRequest, + )? + onReceivedLoginRequest, void Function( WebViewClient pigeon_instance, WebView view, SslErrorHandler handler, SslError error, - )? onReceivedSslError, + )? + onReceivedSslError, void Function( WebViewClient pigeon_instance, WebView view, double oldScale, double newScale, - )? onScaleChanged, + )? + onScaleChanged, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebViewClient.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + WebViewClient.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageStarted was null, expected non-null String.', + ); try { - (onPageStarted ?? arg_pigeon_instance!.onPageStarted) - ?.call(arg_pigeon_instance!, arg_webView!, arg_url!); + (onPageStarted ?? arg_pigeon_instance!.onPageStarted)?.call( + arg_pigeon_instance!, + arg_webView!, + arg_url!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageFinished was null, expected non-null String.', + ); try { - (onPageFinished ?? arg_pigeon_instance!.onPageFinished) - ?.call(arg_pigeon_instance!, arg_webView!, arg_url!); + (onPageFinished ?? arg_pigeon_instance!.onPageFinished)?.call( + arg_pigeon_instance!, + arg_webView!, + arg_url!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebView.', + ); final WebResourceRequest? arg_request = (args[2] as WebResourceRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebResourceRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebResourceRequest.', + ); final WebResourceResponse? arg_response = (args[3] as WebResourceResponse?); - assert(arg_response != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebResourceResponse.'); + assert( + arg_response != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpError was null, expected non-null WebResourceResponse.', + ); try { (onReceivedHttpError ?? arg_pigeon_instance!.onReceivedHttpError) - ?.call(arg_pigeon_instance!, arg_webView!, arg_request!, - arg_response!); + ?.call( + arg_pigeon_instance!, + arg_webView!, + arg_request!, + arg_response!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebView.', + ); final WebResourceRequest? arg_request = (args[2] as WebResourceRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebResourceRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebResourceRequest.', + ); final WebResourceError? arg_error = (args[3] as WebResourceError?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebResourceError.'); + assert( + arg_error != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestError was null, expected non-null WebResourceError.', + ); try { (onReceivedRequestError ?? arg_pigeon_instance!.onReceivedRequestError) - ?.call(arg_pigeon_instance!, arg_webView!, arg_request!, - arg_error!); + ?.call( + arg_pigeon_instance!, + arg_webView!, + arg_request!, + arg_error!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebView.', + ); final WebResourceRequest? arg_request = (args[2] as WebResourceRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebResourceRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebResourceRequest.', + ); final WebResourceErrorCompat? arg_error = (args[3] as WebResourceErrorCompat?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebResourceErrorCompat.'); + assert( + arg_error != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedRequestErrorCompat was null, expected non-null WebResourceErrorCompat.', + ); try { (onReceivedRequestErrorCompat ?? arg_pigeon_instance!.onReceivedRequestErrorCompat) - ?.call(arg_pigeon_instance!, arg_webView!, arg_request!, - arg_error!); + ?.call( + arg_pigeon_instance!, + arg_webView!, + arg_request!, + arg_error!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null WebView.', + ); final int? arg_errorCode = (args[2] as int?); - assert(arg_errorCode != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null int.'); + assert( + arg_errorCode != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null int.', + ); final String? arg_description = (args[3] as String?); - assert(arg_description != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null String.'); + assert( + arg_description != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null String.', + ); final String? arg_failingUrl = (args[4] as String?); - assert(arg_failingUrl != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null String.'); + assert( + arg_failingUrl != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedError was null, expected non-null String.', + ); try { (onReceivedError ?? arg_pigeon_instance!.onReceivedError)?.call( - arg_pigeon_instance!, - arg_webView!, - arg_errorCode!, - arg_description!, - arg_failingUrl!); + arg_pigeon_instance!, + arg_webView!, + arg_errorCode!, + arg_description!, + arg_failingUrl!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null, expected non-null WebView.', + ); final WebResourceRequest? arg_request = (args[2] as WebResourceRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null, expected non-null WebResourceRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.requestLoading was null, expected non-null WebResourceRequest.', + ); try { - (requestLoading ?? arg_pigeon_instance!.requestLoading) - ?.call(arg_pigeon_instance!, arg_webView!, arg_request!); + (requestLoading ?? arg_pigeon_instance!.requestLoading)?.call( + arg_pigeon_instance!, + arg_webView!, + arg_request!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.urlLoading was null, expected non-null String.', + ); try { - (urlLoading ?? arg_pigeon_instance!.urlLoading) - ?.call(arg_pigeon_instance!, arg_webView!, arg_url!); + (urlLoading ?? arg_pigeon_instance!.urlLoading)?.call( + arg_pigeon_instance!, + arg_webView!, + arg_url!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null String.', + ); final bool? arg_isReload = (args[3] as bool?); - assert(arg_isReload != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null bool.'); + assert( + arg_isReload != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.doUpdateVisitedHistory was null, expected non-null bool.', + ); try { (doUpdateVisitedHistory ?? arg_pigeon_instance!.doUpdateVisitedHistory) - ?.call(arg_pigeon_instance!, arg_webView!, arg_url!, - arg_isReload!); + ?.call( + arg_pigeon_instance!, + arg_webView!, + arg_url!, + arg_isReload!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null WebViewClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null WebView.', + ); final HttpAuthHandler? arg_handler = (args[2] as HttpAuthHandler?); - assert(arg_handler != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null HttpAuthHandler.'); + assert( + arg_handler != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null HttpAuthHandler.', + ); final String? arg_host = (args[3] as String?); - assert(arg_host != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null String.'); + assert( + arg_host != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null String.', + ); final String? arg_realm = (args[4] as String?); - assert(arg_realm != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null String.'); + assert( + arg_realm != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedHttpAuthRequest was null, expected non-null String.', + ); try { (onReceivedHttpAuthRequest ?? arg_pigeon_instance!.onReceivedHttpAuthRequest) - ?.call(arg_pigeon_instance!, arg_webView!, arg_handler!, - arg_host!, arg_realm!); + ?.call( + arg_pigeon_instance!, + arg_webView!, + arg_handler!, + arg_host!, + arg_realm!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null WebView.', + ); final AndroidMessage? arg_dontResend = (args[2] as AndroidMessage?); - assert(arg_dontResend != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null AndroidMessage.'); + assert( + arg_dontResend != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null AndroidMessage.', + ); final AndroidMessage? arg_resend = (args[3] as AndroidMessage?); - assert(arg_resend != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null AndroidMessage.'); + assert( + arg_resend != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null AndroidMessage.', + ); try { (onFormResubmission ?? arg_pigeon_instance!.onFormResubmission) - ?.call(arg_pigeon_instance!, arg_view!, arg_dontResend!, - arg_resend!); + ?.call( + arg_pigeon_instance!, + arg_view!, + arg_dontResend!, + arg_resend!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null String.', + ); try { - (onLoadResource ?? arg_pigeon_instance!.onLoadResource) - ?.call(arg_pigeon_instance!, arg_view!, arg_url!); + (onLoadResource ?? arg_pigeon_instance!.onLoadResource)?.call( + arg_pigeon_instance!, + arg_view!, + arg_url!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null String.', + ); try { (onPageCommitVisible ?? arg_pigeon_instance!.onPageCommitVisible) ?.call(arg_pigeon_instance!, arg_view!, arg_url!); @@ -4322,37 +4694,46 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null WebView.', + ); final ClientCertRequest? arg_request = (args[2] as ClientCertRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null ClientCertRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null ClientCertRequest.', + ); try { (onReceivedClientCertRequest ?? arg_pigeon_instance!.onReceivedClientCertRequest) @@ -4362,134 +4743,181 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null WebView.', + ); final String? arg_realm = (args[2] as String?); - assert(arg_realm != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null String.'); + assert( + arg_realm != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null String.', + ); final String? arg_account = (args[3] as String?); final String? arg_args = (args[4] as String?); - assert(arg_args != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null String.'); + assert( + arg_args != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null String.', + ); try { (onReceivedLoginRequest ?? arg_pigeon_instance!.onReceivedLoginRequest) - ?.call(arg_pigeon_instance!, arg_view!, arg_realm!, arg_account, - arg_args!); + ?.call( + arg_pigeon_instance!, + arg_view!, + arg_realm!, + arg_account, + arg_args!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null WebView.', + ); final SslErrorHandler? arg_handler = (args[2] as SslErrorHandler?); - assert(arg_handler != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null SslErrorHandler.'); + assert( + arg_handler != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null SslErrorHandler.', + ); final SslError? arg_error = (args[3] as SslError?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null SslError.'); + assert( + arg_error != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null SslError.', + ); try { (onReceivedSslError ?? arg_pigeon_instance!.onReceivedSslError) ?.call( - arg_pigeon_instance!, arg_view!, arg_handler!, arg_error!); + arg_pigeon_instance!, + arg_view!, + arg_handler!, + arg_error!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null.', + ); final List args = (message as List?)!; final WebViewClient? arg_pigeon_instance = (args[0] as WebViewClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null WebViewClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null WebViewClient.', + ); final WebView? arg_view = (args[1] as WebView?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null WebView.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null WebView.', + ); final double? arg_oldScale = (args[2] as double?); - assert(arg_oldScale != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null double.'); + assert( + arg_oldScale != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null double.', + ); final double? arg_newScale = (args[3] as double?); - assert(arg_newScale != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null double.'); + assert( + arg_newScale != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null double.', + ); try { (onScaleChanged ?? arg_pigeon_instance!.onScaleChanged)?.call( - arg_pigeon_instance!, arg_view!, arg_oldScale!, arg_newScale!); + arg_pigeon_instance!, + arg_view!, + arg_oldScale!, + arg_newScale!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4509,7 +4937,8 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { /// /// Defaults to false. Future setSynchronousReturnValueForShouldOverrideUrlLoading( - bool value) async { + bool value, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebViewClient; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4517,12 +4946,13 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.setSynchronousReturnValueForShouldOverrideUrlLoading'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4573,8 +5003,8 @@ class DownloadListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onDownloadStart, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDownloadListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4582,12 +5012,13 @@ class DownloadListener extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.DownloadListener.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4645,7 +5076,8 @@ class DownloadListener extends PigeonInternalProxyApiBaseClass { String contentDisposition, String mimetype, int contentLength, - ) onDownloadStart; + ) + onDownloadStart; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4658,59 +5090,77 @@ class DownloadListener extends PigeonInternalProxyApiBaseClass { String contentDisposition, String mimetype, int contentLength, - )? onDownloadStart, + )? + onDownloadStart, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null.', + ); final List args = (message as List?)!; final DownloadListener? arg_pigeon_instance = (args[0] as DownloadListener?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null DownloadListener.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null DownloadListener.', + ); final String? arg_url = (args[1] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.', + ); final String? arg_userAgent = (args[2] as String?); - assert(arg_userAgent != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.'); + assert( + arg_userAgent != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.', + ); final String? arg_contentDisposition = (args[3] as String?); - assert(arg_contentDisposition != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.'); + assert( + arg_contentDisposition != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.', + ); final String? arg_mimetype = (args[4] as String?); - assert(arg_mimetype != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.'); + assert( + arg_mimetype != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null String.', + ); final int? arg_contentLength = (args[5] as int?); - assert(arg_contentLength != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null int.'); + assert( + arg_contentLength != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListener.onDownloadStart was null, expected non-null int.', + ); try { (onDownloadStart ?? arg_pigeon_instance!.onDownloadStart).call( - arg_pigeon_instance!, - arg_url!, - arg_userAgent!, - arg_contentDisposition!, - arg_mimetype!, - arg_contentLength!); + arg_pigeon_instance!, + arg_url!, + arg_userAgent!, + arg_contentDisposition!, + arg_mimetype!, + arg_contentLength!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -4747,8 +5197,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { required this.onJsConfirm, this.onJsPrompt, }) { - final int pigeonVar_instanceIdentifier = - pigeon_instanceManager.addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager + .addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebChromeClient; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4756,12 +5206,13 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_defaultConstructor'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -4826,7 +5277,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebChromeClient pigeon_instance, WebView webView, int progress, - )? onProgressChanged; + )? + onProgressChanged; /// Tell the client to show a file chooser. /// @@ -4851,7 +5303,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebChromeClient pigeon_instance, WebView webView, FileChooserParams params, - ) onShowFileChooser; + ) + onShowFileChooser; /// Notify the host application that web content is requesting permission to /// access the specified resources and the permission currently isn't granted @@ -4877,7 +5330,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { final void Function( WebChromeClient pigeon_instance, PermissionRequest request, - )? onPermissionRequest; + )? + onPermissionRequest; /// Callback to Dart function `WebChromeClient.onShowCustomView`. /// @@ -4902,7 +5356,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebChromeClient pigeon_instance, View view, CustomViewCallback callback, - )? onShowCustomView; + )? + onShowCustomView; /// Notify the host application that the current page has entered full screen /// mode. @@ -4951,7 +5406,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebChromeClient pigeon_instance, String origin, GeolocationPermissionsCallback callback, - )? onGeolocationPermissionsShowPrompt; + )? + onGeolocationPermissionsShowPrompt; /// Notify the host application that a request for Geolocation permissions, /// made with a previous call to `onGeolocationPermissionsShowPrompt` has been @@ -4975,7 +5431,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final void Function(WebChromeClient pigeon_instance)? - onGeolocationPermissionsHidePrompt; + onGeolocationPermissionsHidePrompt; /// Report a JavaScript console message to the host application. /// @@ -4996,10 +5452,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - WebChromeClient pigeon_instance, - ConsoleMessage message, - )? onConsoleMessage; + final void Function(WebChromeClient pigeon_instance, ConsoleMessage message)? + onConsoleMessage; /// Notify the host application that the web page wants to display a /// JavaScript `alert()` dialog. @@ -5026,7 +5480,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebView webView, String url, String message, - )? onJsAlert; + )? + onJsAlert; /// Notify the host application that the web page wants to display a /// JavaScript `confirm()` dialog. @@ -5053,7 +5508,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebView webView, String url, String message, - ) onJsConfirm; + ) + onJsConfirm; /// Notify the host application that the web page wants to display a /// JavaScript `prompt()` dialog. @@ -5081,7 +5537,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { String url, String message, String defaultValue, - )? onJsPrompt; + )? + onJsPrompt; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5091,119 +5548,143 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebChromeClient pigeon_instance, WebView webView, int progress, - )? onProgressChanged, + )? + onProgressChanged, Future> Function( WebChromeClient pigeon_instance, WebView webView, FileChooserParams params, - )? onShowFileChooser, - void Function( - WebChromeClient pigeon_instance, - PermissionRequest request, - )? onPermissionRequest, + )? + onShowFileChooser, + void Function(WebChromeClient pigeon_instance, PermissionRequest request)? + onPermissionRequest, void Function( WebChromeClient pigeon_instance, View view, CustomViewCallback callback, - )? onShowCustomView, + )? + onShowCustomView, void Function(WebChromeClient pigeon_instance)? onHideCustomView, void Function( WebChromeClient pigeon_instance, String origin, GeolocationPermissionsCallback callback, - )? onGeolocationPermissionsShowPrompt, + )? + onGeolocationPermissionsShowPrompt, void Function(WebChromeClient pigeon_instance)? - onGeolocationPermissionsHidePrompt, - void Function( - WebChromeClient pigeon_instance, - ConsoleMessage message, - )? onConsoleMessage, + onGeolocationPermissionsHidePrompt, + void Function(WebChromeClient pigeon_instance, ConsoleMessage message)? + onConsoleMessage, Future Function( WebChromeClient pigeon_instance, WebView webView, String url, String message, - )? onJsAlert, + )? + onJsAlert, Future Function( WebChromeClient pigeon_instance, WebView webView, String url, String message, - )? onJsConfirm, + )? + onJsConfirm, Future Function( WebChromeClient pigeon_instance, WebView webView, String url, String message, String defaultValue, - )? onJsPrompt, + )? + onJsPrompt, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null, expected non-null WebChromeClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null, expected non-null WebView.', + ); final int? arg_progress = (args[2] as int?); - assert(arg_progress != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null, expected non-null int.'); + assert( + arg_progress != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null, expected non-null int.', + ); try { - (onProgressChanged ?? arg_pigeon_instance!.onProgressChanged) - ?.call(arg_pigeon_instance!, arg_webView!, arg_progress!); + (onProgressChanged ?? arg_pigeon_instance!.onProgressChanged)?.call( + arg_pigeon_instance!, + arg_webView!, + arg_progress!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null WebChromeClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null WebView.', + ); final FileChooserParams? arg_params = (args[2] as FileChooserParams?); - assert(arg_params != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null FileChooserParams.'); + assert( + arg_params != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null FileChooserParams.', + ); try { final List output = await (onShowFileChooser ?? arg_pigeon_instance!.onShowFileChooser) @@ -5213,34 +5694,41 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest was null, expected non-null WebChromeClient.', + ); final PermissionRequest? arg_request = (args[1] as PermissionRequest?); - assert(arg_request != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest was null, expected non-null PermissionRequest.'); + assert( + arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onPermissionRequest was null, expected non-null PermissionRequest.', + ); try { (onPermissionRequest ?? arg_pigeon_instance!.onPermissionRequest) ?.call(arg_pigeon_instance!, arg_request!); @@ -5249,108 +5737,135 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null, expected non-null WebChromeClient.', + ); final View? arg_view = (args[1] as View?); - assert(arg_view != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null, expected non-null View.'); + assert( + arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null, expected non-null View.', + ); final CustomViewCallback? arg_callback = (args[2] as CustomViewCallback?); - assert(arg_callback != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null, expected non-null CustomViewCallback.'); + assert( + arg_callback != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowCustomView was null, expected non-null CustomViewCallback.', + ); try { - (onShowCustomView ?? arg_pigeon_instance!.onShowCustomView) - ?.call(arg_pigeon_instance!, arg_view!, arg_callback!); + (onShowCustomView ?? arg_pigeon_instance!.onShowCustomView)?.call( + arg_pigeon_instance!, + arg_view!, + arg_callback!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onHideCustomView', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onHideCustomView', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onHideCustomView was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onHideCustomView was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onHideCustomView was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onHideCustomView was null, expected non-null WebChromeClient.', + ); try { - (onHideCustomView ?? arg_pigeon_instance!.onHideCustomView) - ?.call(arg_pigeon_instance!); + (onHideCustomView ?? arg_pigeon_instance!.onHideCustomView)?.call( + arg_pigeon_instance!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null, expected non-null WebChromeClient.', + ); final String? arg_origin = (args[1] as String?); - assert(arg_origin != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null, expected non-null String.'); + assert( + arg_origin != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null, expected non-null String.', + ); final GeolocationPermissionsCallback? arg_callback = (args[2] as GeolocationPermissionsCallback?); - assert(arg_callback != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null, expected non-null GeolocationPermissionsCallback.'); + assert( + arg_callback != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsShowPrompt was null, expected non-null GeolocationPermissionsCallback.', + ); try { (onGeolocationPermissionsShowPrompt ?? arg_pigeon_instance!.onGeolocationPermissionsShowPrompt) @@ -5360,30 +5875,35 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsHidePrompt', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsHidePrompt', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsHidePrompt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsHidePrompt was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsHidePrompt was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onGeolocationPermissionsHidePrompt was null, expected non-null WebChromeClient.', + ); try { (onGeolocationPermissionsHidePrompt ?? arg_pigeon_instance!.onGeolocationPermissionsHidePrompt) @@ -5393,174 +5913,228 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage was null, expected non-null WebChromeClient.', + ); final ConsoleMessage? arg_message = (args[1] as ConsoleMessage?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage was null, expected non-null ConsoleMessage.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onConsoleMessage was null, expected non-null ConsoleMessage.', + ); try { - (onConsoleMessage ?? arg_pigeon_instance!.onConsoleMessage) - ?.call(arg_pigeon_instance!, arg_message!); + (onConsoleMessage ?? arg_pigeon_instance!.onConsoleMessage)?.call( + arg_pigeon_instance!, + arg_message!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null WebChromeClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null String.', + ); final String? arg_message = (args[3] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsAlert was null, expected non-null String.', + ); try { await (onJsAlert ?? arg_pigeon_instance!.onJsAlert)?.call( - arg_pigeon_instance!, arg_webView!, arg_url!, arg_message!); + arg_pigeon_instance!, + arg_webView!, + arg_url!, + arg_message!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null WebChromeClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null String.', + ); final String? arg_message = (args[3] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null String.', + ); try { final bool output = await (onJsConfirm ?? arg_pigeon_instance!.onJsConfirm).call( - arg_pigeon_instance!, arg_webView!, arg_url!, arg_message!); + arg_pigeon_instance!, + arg_webView!, + arg_url!, + arg_message!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null.', + ); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); - assert(arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null WebChromeClient.'); + assert( + arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null WebChromeClient.', + ); final WebView? arg_webView = (args[1] as WebView?); - assert(arg_webView != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null WebView.'); + assert( + arg_webView != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null WebView.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null String.', + ); final String? arg_message = (args[3] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null String.', + ); final String? arg_defaultValue = (args[4] as String?); - assert(arg_defaultValue != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null String.'); + assert( + arg_defaultValue != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsPrompt was null, expected non-null String.', + ); try { final String? output = await (onJsPrompt ?? arg_pigeon_instance!.onJsPrompt)?.call( - arg_pigeon_instance!, - arg_webView!, - arg_url!, - arg_message!, - arg_defaultValue!); + arg_pigeon_instance!, + arg_webView!, + arg_url!, + arg_message!, + arg_defaultValue!, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5590,12 +6164,13 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.setSynchronousReturnValueForOnShowFileChooser'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5632,12 +6207,13 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.setSynchronousReturnValueForOnConsoleMessage'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5674,12 +6250,13 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.setSynchronousReturnValueForOnJsAlert'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5716,12 +6293,13 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.setSynchronousReturnValueForOnJsConfirm'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5758,12 +6336,13 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.setSynchronousReturnValueForOnJsPrompt'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, value], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5814,8 +6393,9 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecFlutterAssetManager = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecFlutterAssetManager = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); /// The global instance of the `FlutterAssetManager`. static final FlutterAssetManager instance = pigeonVar_instance(); @@ -5828,41 +6408,47 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - FlutterAssetManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + FlutterAssetManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -5883,12 +6469,13 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.instance'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5917,12 +6504,13 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.list'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, path], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, path]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5958,12 +6546,13 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.getAssetFilePathByName'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, name], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, name]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6021,41 +6610,47 @@ class WebStorage extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebStorage.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + WebStorage.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6075,12 +6670,13 @@ class WebStorage extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebStorage.instance'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([pigeonVar_instanceIdentifier]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6107,12 +6703,13 @@ class WebStorage extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.WebStorage.deleteAllData'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6176,61 +6773,78 @@ class FileChooserParams extends PigeonInternalProxyApiBaseClass { List acceptTypes, FileChooserMode mode, String? filenameHint, - )? pigeon_newInstance, + )? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null int.', + ); final bool? arg_isCaptureEnabled = (args[1] as bool?); - assert(arg_isCaptureEnabled != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null bool.'); + assert( + arg_isCaptureEnabled != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null bool.', + ); final List? arg_acceptTypes = (args[2] as List?)?.cast(); - assert(arg_acceptTypes != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_acceptTypes != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null List.', + ); final FileChooserMode? arg_mode = (args[3] as FileChooserMode?); - assert(arg_mode != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null FileChooserMode.'); + assert( + arg_mode != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance was null, expected non-null FileChooserMode.', + ); final String? arg_filenameHint = (args[4] as String?); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_isCaptureEnabled!, arg_acceptTypes!, - arg_mode!, arg_filenameHint) ?? - FileChooserParams.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - isCaptureEnabled: arg_isCaptureEnabled!, - acceptTypes: arg_acceptTypes!, - mode: arg_mode!, - filenameHint: arg_filenameHint, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call( + arg_isCaptureEnabled!, + arg_acceptTypes!, + arg_mode!, + arg_filenameHint, + ) ?? + FileChooserParams.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + isCaptureEnabled: arg_isCaptureEnabled!, + acceptTypes: arg_acceptTypes!, + mode: arg_mode!, + filenameHint: arg_filenameHint, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6267,8 +6881,9 @@ class PermissionRequest extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecPermissionRequest = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecPermissionRequest = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); final List resources; @@ -6280,46 +6895,54 @@ class PermissionRequest extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance was null, expected non-null int.', + ); final List? arg_resources = (args[1] as List?)?.cast(); - assert(arg_resources != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance was null, expected non-null List.'); + assert( + arg_resources != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance was null, expected non-null List.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_resources!) ?? - PermissionRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resources: arg_resources!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_resources!) ?? + PermissionRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resources: arg_resources!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6336,12 +6959,13 @@ class PermissionRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.PermissionRequest.grant'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, resources], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, resources]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6366,12 +6990,13 @@ class PermissionRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.PermissionRequest.deny'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6413,8 +7038,9 @@ class CustomViewCallback extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCustomViewCallback = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecCustomViewCallback = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -6424,41 +7050,47 @@ class CustomViewCallback extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CustomViewCallback.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + CustomViewCallback.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6474,12 +7106,13 @@ class CustomViewCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.onCustomViewHidden'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6530,41 +7163,47 @@ class View extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - View.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + View.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6572,10 +7211,7 @@ class View extends PigeonInternalProxyApiBaseClass { } /// Set the scrolled position of your view. - Future scrollTo( - int x, - int y, - ) async { + Future scrollTo(int x, int y) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6583,12 +7219,13 @@ class View extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.View.scrollTo'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, x, y], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, x, y]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6605,10 +7242,7 @@ class View extends PigeonInternalProxyApiBaseClass { } /// Move the scrolled position of your view. - Future scrollBy( - int x, - int y, - ) async { + Future scrollBy(int x, int y) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6616,12 +7250,13 @@ class View extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.View.scrollBy'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, x, y], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, x, y]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6646,12 +7281,13 @@ class View extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.View.getScrollPosition'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6683,12 +7319,13 @@ class View extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.View.setVerticalScrollBarEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6715,12 +7352,13 @@ class View extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.View.setHorizontalScrollBarEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6745,12 +7383,13 @@ class View extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.View.setOverScrollMode'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, mode], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, mode]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6791,7 +7430,7 @@ class GeolocationPermissionsCallback extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecGeolocationPermissionsCallback = + _pigeonVar_codecGeolocationPermissionsCallback = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ @@ -6802,41 +7441,47 @@ class GeolocationPermissionsCallback extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - GeolocationPermissionsCallback.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + GeolocationPermissionsCallback.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6844,11 +7489,7 @@ class GeolocationPermissionsCallback extends PigeonInternalProxyApiBaseClass { } /// Sets the Geolocation permission state for the supplied origin. - Future invoke( - String origin, - bool allow, - bool retain, - ) async { + Future invoke(String origin, bool allow, bool retain) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecGeolocationPermissionsCallback; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6856,12 +7497,13 @@ class GeolocationPermissionsCallback extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.invoke'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, origin, allow, retain], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, origin, allow, retain]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6911,41 +7553,47 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - HttpAuthHandler.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + HttpAuthHandler.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -6963,12 +7611,13 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.useHttpAuthUsernamePassword'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6998,12 +7647,13 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.cancel'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7021,10 +7671,7 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { /// Instructs the WebView to proceed with the authentication with the given /// credentials. - Future proceed( - String username, - String password, - ) async { + Future proceed(String username, String password) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecHttpAuthHandler; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -7032,12 +7679,13 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.proceed'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, username, password], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, username, password]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7088,41 +7736,47 @@ class AndroidMessage extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AndroidMessage.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + AndroidMessage.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7141,12 +7795,13 @@ class AndroidMessage extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.AndroidMessage.sendToTarget'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7187,8 +7842,9 @@ class ClientCertRequest extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecClientCertRequest = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecClientCertRequest = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -7198,41 +7854,47 @@ class ClientCertRequest extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ClientCertRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + ClientCertRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7248,12 +7910,13 @@ class ClientCertRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.cancel'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7278,12 +7941,13 @@ class ClientCertRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.ignore'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7311,12 +7975,13 @@ class ClientCertRequest extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.proceed'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, privateKey, chain], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, privateKey, chain]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7366,41 +8031,47 @@ class PrivateKey extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - PrivateKey.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + PrivateKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7441,41 +8112,47 @@ class X509Certificate extends Certificate { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - X509Certificate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + X509Certificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7516,41 +8193,47 @@ class SslErrorHandler extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - SslErrorHandler.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + SslErrorHandler.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7567,12 +8250,13 @@ class SslErrorHandler extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.cancel'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7598,12 +8282,13 @@ class SslErrorHandler extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.proceed'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7658,56 +8343,64 @@ class SslError extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - SslError Function( - SslCertificate certificate, - String url, - )? pigeon_newInstance, + SslError Function(SslCertificate certificate, String url)? + pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null int.', + ); final SslCertificate? arg_certificate = (args[1] as SslCertificate?); - assert(arg_certificate != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null SslCertificate.'); + assert( + arg_certificate != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null SslCertificate.', + ); final String? arg_url = (args[2] as String?); - assert(arg_url != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null String.'); + assert( + arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null String.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call(arg_certificate!, arg_url!) ?? - SslError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - certificate: arg_certificate!, - url: arg_url!, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call(arg_certificate!, arg_url!) ?? + SslError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + certificate: arg_certificate!, + url: arg_url!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7723,12 +8416,13 @@ class SslError extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslError.getPrimaryError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7758,12 +8452,13 @@ class SslError extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslError.hasError'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this, error], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this, error]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7813,8 +8508,9 @@ class SslCertificateDName extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecSslCertificateDName = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecSslCertificateDName = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -7824,41 +8520,47 @@ class SslCertificateDName extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - SslCertificateDName.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + SslCertificateDName.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -7874,12 +8576,13 @@ class SslCertificateDName extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getCName'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7909,12 +8612,13 @@ class SslCertificateDName extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getDName'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7944,12 +8648,13 @@ class SslCertificateDName extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getOName'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7979,12 +8684,13 @@ class SslCertificateDName extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getUName'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8039,41 +8745,47 @@ class SslCertificate extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - SslCertificate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + SslCertificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -8089,12 +8801,13 @@ class SslCertificate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getIssuedBy'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8119,12 +8832,13 @@ class SslCertificate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getIssuedTo'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8150,12 +8864,13 @@ class SslCertificate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getValidNotAfterMsSinceEpoch'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8181,12 +8896,13 @@ class SslCertificate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getValidNotBeforeMsSinceEpoch'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8214,12 +8930,13 @@ class SslCertificate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getX509Certificate'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8269,41 +8986,47 @@ class Certificate extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.Certificate.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.Certificate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.Certificate.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.Certificate.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.Certificate.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.Certificate.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - Certificate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + Certificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -8319,12 +9042,13 @@ class Certificate extends PigeonInternalProxyApiBaseClass { 'dev.flutter.pigeon.webview_flutter_android.Certificate.getEncoded'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [this], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([this]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8369,8 +9093,9 @@ class WebSettingsCompat extends PigeonInternalProxyApiBaseClass { }); late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecWebSettingsCompat = - _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + _pigeonVar_codecWebSettingsCompat = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager, + ); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -8380,41 +9105,47 @@ class WebSettingsCompat extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebSettingsCompat.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + WebSettingsCompat.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -8429,18 +9160,20 @@ class WebSettingsCompat extends PigeonInternalProxyApiBaseClass { }) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.webview_flutter_android.WebSettingsCompat.setPaymentRequestEnabled'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [webSettings, enabled], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([webSettings, enabled]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8490,41 +9223,47 @@ class WebViewFeature extends PigeonInternalProxyApiBaseClass { }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebViewFeature.pigeon_newInstance', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.webview_flutter_android.WebViewFeature.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFeature.pigeon_newInstance was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFeature.pigeon_newInstance was null.', + ); final List args = (message as List?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFeature.pigeon_newInstance was null, expected non-null int.'); + assert( + arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFeature.pigeon_newInstance was null, expected non-null int.', + ); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebViewFeature.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + pigeon_newInstance?.call() ?? + WebViewFeature.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -8538,18 +9277,20 @@ class WebViewFeature extends PigeonInternalProxyApiBaseClass { }) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance); + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const String pigeonVar_channelName = 'dev.flutter.pigeon.webview_flutter_android.WebViewFeature.isFeatureSupported'; final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [feature], ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([feature]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart index 50f233181cc..e4a686dbe79 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart @@ -27,10 +27,11 @@ base class AndroidLoadFileParams extends LoadFileParams { required String absoluteFilePath, this.headers = const {}, }) : super( - absoluteFilePath: absoluteFilePath.startsWith('file://') - ? absoluteFilePath - : Uri.file(absoluteFilePath).toString(), - ); + absoluteFilePath: + absoluteFilePath.startsWith('file://') + ? absoluteFilePath + : Uri.file(absoluteFilePath).toString(), + ); /// Constructs a [AndroidLoadFileParams] using a [LoadFileParams]. factory AndroidLoadFileParams.fromLoadFileParams( @@ -65,9 +66,9 @@ class AndroidWebViewControllerCreationParams AndroidWebViewControllerCreationParams({ @visibleForTesting this.androidWebViewProxy = const AndroidWebViewProxy(), @visibleForTesting android_webview.WebStorage? androidWebStorage, - }) : androidWebStorage = - androidWebStorage ?? android_webview.WebStorage.instance, - super(); + }) : androidWebStorage = + androidWebStorage ?? android_webview.WebStorage.instance, + super(); /// Creates a [AndroidWebViewControllerCreationParams] instance based on [PlatformWebViewControllerCreationParams]. factory AndroidWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams( @@ -114,10 +115,13 @@ class AndroidWebViewPermissionResourceType class AndroidWebViewController extends PlatformWebViewController { /// Creates a new [AndroidWebViewController]. AndroidWebViewController(PlatformWebViewControllerCreationParams params) - : super.implementation(params is AndroidWebViewControllerCreationParams + : super.implementation( + params is AndroidWebViewControllerCreationParams ? params - : AndroidWebViewControllerCreationParams - .fromPlatformWebViewControllerCreationParams(params)) { + : AndroidWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams( + params, + ), + ) { _webView.settings.setDomStorageEnabled(true); _webView.settings.setJavaScriptCanOpenWindowsAutomatically(true); _webView.settings.setSupportMultipleWindows(true); @@ -133,227 +137,264 @@ class AndroidWebViewController extends PlatformWebViewController { params as AndroidWebViewControllerCreationParams; /// The native [android_webview.WebView] being controlled. - late final android_webview.WebView _webView = - _androidWebViewParams.androidWebViewProxy.newWebView( - onScrollChanged: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, int left, int top, int oldLeft, int oldTop) async { - final void Function(ScrollPositionChange)? callback = - weakReference.target?._onScrollPositionChangedCallback; - callback?.call(ScrollPositionChange(left.toDouble(), top.toDouble())); - }; - })); + late final android_webview.WebView _webView = _androidWebViewParams + .androidWebViewProxy + .newWebView( + onScrollChanged: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, int left, int top, int oldLeft, int oldTop) async { + final void Function(ScrollPositionChange)? callback = + weakReference.target?._onScrollPositionChangedCallback; + callback?.call( + ScrollPositionChange(left.toDouble(), top.toDouble()), + ); + }; + }), + ); late final android_webview.WebChromeClient _webChromeClient = _androidWebViewParams.androidWebViewProxy.newWebChromeClient( - onProgressChanged: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, android_webview.WebView webView, int progress) { - if (weakReference.target?._currentNavigationDelegate?._onProgress != - null) { - weakReference - .target!._currentNavigationDelegate!._onProgress!(progress); - } - }; - }), - onGeolocationPermissionsShowPrompt: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, String origin, - android_webview.GeolocationPermissionsCallback callback) async { - final OnGeolocationPermissionsShowPrompt? onShowPrompt = - weakReference.target?._onGeolocationPermissionsShowPrompt; - if (onShowPrompt != null) { - final GeolocationPermissionsResponse response = await onShowPrompt( - GeolocationPermissionsRequestParams(origin: origin), - ); - return callback.invoke(origin, response.allow, response.retain); - } else { - // default don't allow - return callback.invoke(origin, false, false); - } - }; - }), - onGeolocationPermissionsHidePrompt: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (android_webview.WebChromeClient instance) { - final OnGeolocationPermissionsHidePrompt? onHidePrompt = - weakReference.target?._onGeolocationPermissionsHidePrompt; - if (onHidePrompt != null) { - onHidePrompt(); - } - }; - }), - onShowCustomView: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, android_webview.View view, - android_webview.CustomViewCallback callback) { - final AndroidWebViewController? webViewController = - weakReference.target; - if (webViewController == null) { - callback.onCustomViewHidden(); - return; - } - final OnShowCustomWidgetCallback? onShowCallback = - webViewController._onShowCustomWidgetCallback; - if (onShowCallback == null) { - callback.onCustomViewHidden(); - return; - } - onShowCallback( - AndroidCustomViewWidget.private( - controller: webViewController, - customView: view, - // ignore: invalid_use_of_protected_member - instanceManager: view.pigeon_instanceManager, - ), - () => callback.onCustomViewHidden(), - ); - }; - }), - onHideCustomView: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (android_webview.WebChromeClient instance) { - final OnHideCustomWidgetCallback? onHideCustomViewCallback = - weakReference.target?._onHideCustomWidgetCallback; - if (onHideCustomViewCallback != null) { - onHideCustomViewCallback(); - } - }; - }), - onShowFileChooser: withWeakReferenceTo( - this, - (WeakReference weakReference) { - return (_, android_webview.WebView webView, - android_webview.FileChooserParams params) async { - if (weakReference.target?._onShowFileSelectorCallback != null) { - return weakReference.target!._onShowFileSelectorCallback!( - FileSelectorParams._fromFileChooserParams(params), + onProgressChanged: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, android_webview.WebView webView, int progress) { + if (weakReference.target?._currentNavigationDelegate?._onProgress != + null) { + weakReference.target!._currentNavigationDelegate!._onProgress!( + progress, + ); + } + }; + }), + onGeolocationPermissionsShowPrompt: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return ( + _, + String origin, + android_webview.GeolocationPermissionsCallback callback, + ) async { + final OnGeolocationPermissionsShowPrompt? onShowPrompt = + weakReference.target?._onGeolocationPermissionsShowPrompt; + if (onShowPrompt != null) { + final GeolocationPermissionsResponse response = + await onShowPrompt( + GeolocationPermissionsRequestParams(origin: origin), + ); + return callback.invoke(origin, response.allow, response.retain); + } else { + // default don't allow + return callback.invoke(origin, false, false); + } + }; + }), + onGeolocationPermissionsHidePrompt: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (android_webview.WebChromeClient instance) { + final OnGeolocationPermissionsHidePrompt? onHidePrompt = + weakReference.target?._onGeolocationPermissionsHidePrompt; + if (onHidePrompt != null) { + onHidePrompt(); + } + }; + }), + onShowCustomView: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return ( + _, + android_webview.View view, + android_webview.CustomViewCallback callback, + ) { + final AndroidWebViewController? webViewController = + weakReference.target; + if (webViewController == null) { + callback.onCustomViewHidden(); + return; + } + final OnShowCustomWidgetCallback? onShowCallback = + webViewController._onShowCustomWidgetCallback; + if (onShowCallback == null) { + callback.onCustomViewHidden(); + return; + } + onShowCallback( + AndroidCustomViewWidget.private( + controller: webViewController, + customView: view, + // ignore: invalid_use_of_protected_member + instanceManager: view.pigeon_instanceManager, + ), + () => callback.onCustomViewHidden(), ); - } - return []; - }; - }, - ), - onConsoleMessage: withWeakReferenceTo( - this, - (WeakReference weakReference) { - return (android_webview.WebChromeClient webChromeClient, - android_webview.ConsoleMessage consoleMessage) async { - final void Function(JavaScriptConsoleMessage)? callback = - weakReference.target?._onConsoleLogCallback; - if (callback != null) { - JavaScriptLogLevel logLevel; - switch (consoleMessage.level) { - // Android maps `console.debug` to `MessageLevel.TIP`, it seems - // `MessageLevel.DEBUG` if not being used. - case android_webview.ConsoleMessageLevel.debug: - case android_webview.ConsoleMessageLevel.tip: - logLevel = JavaScriptLogLevel.debug; - case android_webview.ConsoleMessageLevel.error: - logLevel = JavaScriptLogLevel.error; - case android_webview.ConsoleMessageLevel.warning: - logLevel = JavaScriptLogLevel.warning; - case android_webview.ConsoleMessageLevel.unknown: - case android_webview.ConsoleMessageLevel.log: - logLevel = JavaScriptLogLevel.log; + }; + }), + onHideCustomView: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (android_webview.WebChromeClient instance) { + final OnHideCustomWidgetCallback? onHideCustomViewCallback = + weakReference.target?._onHideCustomWidgetCallback; + if (onHideCustomViewCallback != null) { + onHideCustomViewCallback(); } - - callback(JavaScriptConsoleMessage( - level: logLevel, - message: consoleMessage.message, - )); - } - }; - }, - ), - onPermissionRequest: withWeakReferenceTo( - this, - (WeakReference weakReference) { - return (_, android_webview.PermissionRequest request) async { - final void Function(PlatformWebViewPermissionRequest)? callback = - weakReference.target?._onPermissionRequestCallback; - if (callback == null) { - return request.deny(); - } else { - final Set types = - request.resources.nonNulls - .map((String type) { - switch (type) { - case PermissionRequestConstants.videoCapture: - return WebViewPermissionResourceType.camera; - case PermissionRequestConstants.audioCapture: - return WebViewPermissionResourceType.microphone; - case PermissionRequestConstants.midiSysex: - return AndroidWebViewPermissionResourceType.midiSysex; - case PermissionRequestConstants.protectedMediaId: - return AndroidWebViewPermissionResourceType - .protectedMediaId; - } - - // Type not supported. - return null; - }) - .whereType() - .toSet(); - - // If the request didn't contain any permissions recognized by the - // implementation, deny by default. - if (types.isEmpty) { + }; + }), + onShowFileChooser: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return ( + _, + android_webview.WebView webView, + android_webview.FileChooserParams params, + ) async { + if (weakReference.target?._onShowFileSelectorCallback != null) { + return weakReference.target!._onShowFileSelectorCallback!( + FileSelectorParams._fromFileChooserParams(params), + ); + } + return []; + }; + }), + onConsoleMessage: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return ( + android_webview.WebChromeClient webChromeClient, + android_webview.ConsoleMessage consoleMessage, + ) async { + final void Function(JavaScriptConsoleMessage)? callback = + weakReference.target?._onConsoleLogCallback; + if (callback != null) { + JavaScriptLogLevel logLevel; + switch (consoleMessage.level) { + // Android maps `console.debug` to `MessageLevel.TIP`, it seems + // `MessageLevel.DEBUG` if not being used. + case android_webview.ConsoleMessageLevel.debug: + case android_webview.ConsoleMessageLevel.tip: + logLevel = JavaScriptLogLevel.debug; + case android_webview.ConsoleMessageLevel.error: + logLevel = JavaScriptLogLevel.error; + case android_webview.ConsoleMessageLevel.warning: + logLevel = JavaScriptLogLevel.warning; + case android_webview.ConsoleMessageLevel.unknown: + case android_webview.ConsoleMessageLevel.log: + logLevel = JavaScriptLogLevel.log; + } + + callback( + JavaScriptConsoleMessage( + level: logLevel, + message: consoleMessage.message, + ), + ); + } + }; + }), + onPermissionRequest: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, android_webview.PermissionRequest request) async { + final void Function(PlatformWebViewPermissionRequest)? callback = + weakReference.target?._onPermissionRequestCallback; + if (callback == null) { return request.deny(); + } else { + final Set types = + request.resources.nonNulls + .map((String type) { + switch (type) { + case PermissionRequestConstants.videoCapture: + return WebViewPermissionResourceType.camera; + case PermissionRequestConstants.audioCapture: + return WebViewPermissionResourceType.microphone; + case PermissionRequestConstants.midiSysex: + return AndroidWebViewPermissionResourceType + .midiSysex; + case PermissionRequestConstants.protectedMediaId: + return AndroidWebViewPermissionResourceType + .protectedMediaId; + } + + // Type not supported. + return null; + }) + .whereType() + .toSet(); + + // If the request didn't contain any permissions recognized by the + // implementation, deny by default. + if (types.isEmpty) { + return request.deny(); + } + + callback( + AndroidWebViewPermissionRequest._( + types: types, + request: request, + ), + ); } - - callback(AndroidWebViewPermissionRequest._( - types: types, - request: request, - )); - } - }; - }, - ), - onJsAlert: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, __, String url, String message) async { - final Future Function(JavaScriptAlertDialogRequest)? callback = - weakReference.target?._onJavaScriptAlert; - if (callback != null) { - final JavaScriptAlertDialogRequest request = - JavaScriptAlertDialogRequest(message: message, url: url); - - await callback.call(request); - } - return; - }; - }), - onJsConfirm: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, __, String url, String message) async { - final Future Function(JavaScriptConfirmDialogRequest)? callback = - weakReference.target?._onJavaScriptConfirm; - if (callback != null) { - final JavaScriptConfirmDialogRequest request = - JavaScriptConfirmDialogRequest(message: message, url: url); - final bool result = await callback.call(request); - return result; - } - return false; - }; - }), - onJsPrompt: withWeakReferenceTo(this, - (WeakReference weakReference) { - return (_, __, String url, String message, String defaultValue) async { - final Future Function(JavaScriptTextInputDialogRequest)? + }; + }), + onJsAlert: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, String url, String message) async { + final Future Function(JavaScriptAlertDialogRequest)? + callback = weakReference.target?._onJavaScriptAlert; + if (callback != null) { + final JavaScriptAlertDialogRequest request = + JavaScriptAlertDialogRequest(message: message, url: url); + + await callback.call(request); + } + return; + }; + }), + onJsConfirm: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, String url, String message) async { + final Future Function(JavaScriptConfirmDialogRequest)? + callback = weakReference.target?._onJavaScriptConfirm; + if (callback != null) { + final JavaScriptConfirmDialogRequest request = + JavaScriptConfirmDialogRequest(message: message, url: url); + final bool result = await callback.call(request); + return result; + } + return false; + }; + }), + onJsPrompt: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return ( + _, + __, + String url, + String message, + String defaultValue, + ) async { + final Future Function(JavaScriptTextInputDialogRequest)? callback = weakReference.target?._onJavaScriptPrompt; - if (callback != null) { - final JavaScriptTextInputDialogRequest request = - JavaScriptTextInputDialogRequest( - message: message, url: url, defaultText: defaultValue); - final String result = await callback.call(request); - return result; - } - return ''; - }; - }), - ); + if (callback != null) { + final JavaScriptTextInputDialogRequest request = + JavaScriptTextInputDialogRequest( + message: message, + url: url, + defaultText: defaultValue, + ); + final String result = await callback.call(request); + return result; + } + return ''; + }; + }), + ); /// The native [android_webview.FlutterAssetManager] allows managing assets. late final android_webview.FlutterAssetManager _flutterAssetManager = @@ -365,7 +406,7 @@ class AndroidWebViewController extends PlatformWebViewController { AndroidNavigationDelegate? _currentNavigationDelegate; Future> Function(FileSelectorParams)? - _onShowFileSelectorCallback; + _onShowFileSelectorCallback; OnGeolocationPermissionsShowPrompt? _onGeolocationPermissionsShowPrompt; @@ -380,14 +421,14 @@ class AndroidWebViewController extends PlatformWebViewController { void Function(JavaScriptConsoleMessage consoleMessage)? _onConsoleLogCallback; Future Function(JavaScriptAlertDialogRequest request)? - _onJavaScriptAlert; + _onJavaScriptAlert; Future Function(JavaScriptConfirmDialogRequest request)? - _onJavaScriptConfirm; + _onJavaScriptConfirm; Future Function(JavaScriptTextInputDialogRequest request)? - _onJavaScriptPrompt; + _onJavaScriptPrompt; void Function(ScrollPositionChange scrollPositionChange)? - _onScrollPositionChangedCallback; + _onScrollPositionChangedCallback; /// Sets the file access permission for the web view. /// @@ -418,20 +459,14 @@ class AndroidWebViewController extends PlatformWebViewController { _webView.pigeon_instanceManager.getIdentifier(_webView)!; @override - Future loadFile( - String absoluteFilePath, - ) { + Future loadFile(String absoluteFilePath) { return loadFileWithParams( - AndroidLoadFileParams( - absoluteFilePath: absoluteFilePath, - ), + AndroidLoadFileParams(absoluteFilePath: absoluteFilePath), ); } @override - Future loadFileWithParams( - LoadFileParams params, - ) async { + Future loadFileWithParams(LoadFileParams params) async { switch (params) { case final AndroidLoadFileParams params: await Future.wait(>[ @@ -447,21 +482,17 @@ class AndroidWebViewController extends PlatformWebViewController { } @override - Future loadFlutterAsset( - String key, - ) async { - final String assetFilePath = - await _flutterAssetManager.getAssetFilePathByName(key); + Future loadFlutterAsset(String key) async { + final String assetFilePath = await _flutterAssetManager + .getAssetFilePathByName(key); final List pathElements = assetFilePath.split('/'); final String fileName = pathElements.removeLast(); - final List paths = - await _flutterAssetManager.list(pathElements.join('/')); + final List paths = await _flutterAssetManager.list( + pathElements.join('/'), + ); if (!paths.contains(fileName)) { - throw ArgumentError( - 'Asset for key "$key" not found.', - 'key', - ); + throw ArgumentError('Asset for key "$key" not found.', 'key'); } return _webView.loadUrl( @@ -471,23 +502,12 @@ class AndroidWebViewController extends PlatformWebViewController { } @override - Future loadHtmlString( - String html, { - String? baseUrl, - }) { - return _webView.loadDataWithBaseUrl( - baseUrl, - html, - 'text/html', - null, - null, - ); + Future loadHtmlString(String html, {String? baseUrl}) { + return _webView.loadDataWithBaseUrl(baseUrl, html, 'text/html', null, null); } @override - Future loadRequest( - LoadRequestParams params, - ) { + Future loadRequest(LoadRequestParams params) { if (!params.uri.hasScheme) { throw ArgumentError('WebViewRequest#uri is required to have a scheme.'); } @@ -496,7 +516,9 @@ class AndroidWebViewController extends PlatformWebViewController { return _webView.loadUrl(params.uri.toString(), params.headers); case LoadRequestMethod.post: return _webView.postUrl( - params.uri.toString(), params.body ?? Uint8List(0)); + params.uri.toString(), + params.body ?? Uint8List(0), + ); } // The enum comes from a different package, which could get a new value at // any time, so a fallback case is necessary. Since there is no reasonable @@ -505,9 +527,10 @@ class AndroidWebViewController extends PlatformWebViewController { // so that the linter will flag the switch as needing an update. // ignore: dead_code throw UnimplementedError( - 'This version of `AndroidWebViewController` currently has no ' - 'implementation for HTTP method ${params.method.serialize()} in ' - 'loadRequest.'); + 'This version of `AndroidWebViewController` currently has no ' + 'implementation for HTTP method ${params.method.serialize()} in ' + 'loadRequest.', + ); } @override @@ -537,7 +560,8 @@ class AndroidWebViewController extends PlatformWebViewController { @override Future setPlatformNavigationDelegate( - covariant AndroidNavigationDelegate handler) async { + covariant AndroidNavigationDelegate handler, + ) async { _currentNavigationDelegate = handler; await Future.wait(>[ handler.setOnLoadRequest(loadRequest), @@ -574,7 +598,8 @@ class AndroidWebViewController extends PlatformWebViewController { javaScriptChannelParams is AndroidJavaScriptChannelParams ? javaScriptChannelParams : AndroidJavaScriptChannelParams.fromJavaScriptChannelParams( - javaScriptChannelParams); + javaScriptChannelParams, + ); // When JavaScript channel with the same name exists make sure to remove it // before registering the new channel. @@ -585,8 +610,9 @@ class AndroidWebViewController extends PlatformWebViewController { _javaScriptChannelParams[androidJavaScriptParams.name] = androidJavaScriptParams; - return _webView - .addJavaScriptChannel(androidJavaScriptParams._javaScriptChannel); + return _webView.addJavaScriptChannel( + androidJavaScriptParams._javaScriptChannel, + ); } @override @@ -626,9 +652,9 @@ class AndroidWebViewController extends PlatformWebViewController { _webView.setBackgroundColor(color.value); @override - Future setJavaScriptMode(JavaScriptMode javaScriptMode) => - _webView.settings - .setJavaScriptEnabled(javaScriptMode == JavaScriptMode.unrestricted); + Future setJavaScriptMode(JavaScriptMode javaScriptMode) => _webView + .settings + .setJavaScriptEnabled(javaScriptMode == JavaScriptMode.unrestricted); @override Future setUserAgent(String? userAgent) => @@ -636,8 +662,9 @@ class AndroidWebViewController extends PlatformWebViewController { @override Future setOnScrollPositionChange( - void Function(ScrollPositionChange scrollPositionChange)? - onScrollPositionChange) async { + void Function(ScrollPositionChange scrollPositionChange)? + onScrollPositionChange, + ) async { _onScrollPositionChangedCallback = onScrollPositionChange; } @@ -675,7 +702,7 @@ class AndroidWebViewController extends PlatformWebViewController { /// selector. Future setOnShowFileSelector( Future> Function(FileSelectorParams params)? - onShowFileSelector, + onShowFileSelector, ) { _onShowFileSelectorCallback = onShowFileSelector; return _webChromeClient.setSynchronousReturnValueForOnShowFileChooser( @@ -689,9 +716,7 @@ class AndroidWebViewController extends PlatformWebViewController { /// Only invoked on Android versions 21+. @override Future setOnPlatformPermissionRequest( - void Function( - PlatformWebViewPermissionRequest request, - ) onPermissionRequest, + void Function(PlatformWebViewPermissionRequest request) onPermissionRequest, ) async { _onPermissionRequestCallback = onPermissionRequest; } @@ -757,12 +782,13 @@ class AndroidWebViewController extends PlatformWebViewController { /// written to the JavaScript console. @override Future setOnConsoleMessage( - void Function(JavaScriptConsoleMessage consoleMessage) - onConsoleMessage) async { + void Function(JavaScriptConsoleMessage consoleMessage) onConsoleMessage, + ) async { _onConsoleLogCallback = onConsoleMessage; return _webChromeClient.setSynchronousReturnValueForOnConsoleMessage( - _onConsoleLogCallback != null); + _onConsoleLogCallback != null, + ); } @override @@ -770,24 +796,27 @@ class AndroidWebViewController extends PlatformWebViewController { @override Future setOnJavaScriptAlertDialog( - Future Function(JavaScriptAlertDialogRequest request) - onJavaScriptAlertDialog) async { + Future Function(JavaScriptAlertDialogRequest request) + onJavaScriptAlertDialog, + ) async { _onJavaScriptAlert = onJavaScriptAlertDialog; return _webChromeClient.setSynchronousReturnValueForOnJsAlert(true); } @override Future setOnJavaScriptConfirmDialog( - Future Function(JavaScriptConfirmDialogRequest request) - onJavaScriptConfirmDialog) async { + Future Function(JavaScriptConfirmDialogRequest request) + onJavaScriptConfirmDialog, + ) async { _onJavaScriptConfirm = onJavaScriptConfirmDialog; return _webChromeClient.setSynchronousReturnValueForOnJsConfirm(true); } @override Future setOnJavaScriptTextInputDialog( - Future Function(JavaScriptTextInputDialogRequest request) - onJavaScriptTextInputDialog) async { + Future Function(JavaScriptTextInputDialogRequest request) + onJavaScriptTextInputDialog, + ) async { _onJavaScriptPrompt = onJavaScriptTextInputDialog; return _webChromeClient.setSynchronousReturnValueForOnJsPrompt(true); } @@ -807,14 +836,14 @@ class AndroidWebViewController extends PlatformWebViewController { Future setOverScrollMode(WebViewOverScrollMode mode) { return switch (mode) { WebViewOverScrollMode.always => _webView.setOverScrollMode( - android_webview.OverScrollMode.always, - ), + android_webview.OverScrollMode.always, + ), WebViewOverScrollMode.ifContentScrolls => _webView.setOverScrollMode( - android_webview.OverScrollMode.ifContentScrolls, - ), + android_webview.OverScrollMode.ifContentScrolls, + ), WebViewOverScrollMode.never => _webView.setOverScrollMode( - android_webview.OverScrollMode.never, - ), + android_webview.OverScrollMode.never, + ), // This prevents future additions from causing a breaking change. // ignore: unreachable_switch_case _ => throw UnsupportedError('Android does not support $mode.'), @@ -845,8 +874,9 @@ class AndroidWebViewController extends PlatformWebViewController { WebViewFeatureType.paymentRequest => WebViewFeatureConstants.paymentRequest, }; - return _androidWebViewParams.androidWebViewProxy - .isWebViewFeatureSupported(feature); + return _androidWebViewParams.androidWebViewProxy.isWebViewFeatureSupported( + feature, + ); } /// Sets whether the WebView should enable the Payment Request API. @@ -878,23 +908,24 @@ class AndroidWebViewPermissionRequest extends PlatformWebViewPermissionRequest { @override Future grant() { - return _request - .grant(types.map((WebViewPermissionResourceType type) { - switch (type) { - case WebViewPermissionResourceType.camera: - return PermissionRequestConstants.videoCapture; - case WebViewPermissionResourceType.microphone: - return PermissionRequestConstants.audioCapture; - case AndroidWebViewPermissionResourceType.midiSysex: - return PermissionRequestConstants.midiSysex; - case AndroidWebViewPermissionResourceType.protectedMediaId: - return PermissionRequestConstants.protectedMediaId; - } - - throw UnsupportedError( - 'Resource of type `${type.name}` is not supported.', - ); - }).toList()); + return _request.grant( + types.map((WebViewPermissionResourceType type) { + switch (type) { + case WebViewPermissionResourceType.camera: + return PermissionRequestConstants.videoCapture; + case WebViewPermissionResourceType.microphone: + return PermissionRequestConstants.audioCapture; + case AndroidWebViewPermissionResourceType.midiSysex: + return PermissionRequestConstants.midiSysex; + case AndroidWebViewPermissionResourceType.protectedMediaId: + return PermissionRequestConstants.protectedMediaId; + } + + throw UnsupportedError( + 'Resource of type `${type.name}` is not supported.', + ); + }).toList(), + ); } @override @@ -904,16 +935,17 @@ class AndroidWebViewPermissionRequest extends PlatformWebViewPermissionRequest { } /// Signature for the `setGeolocationPermissionsPromptCallbacks` callback responsible for request the Geolocation API. -typedef OnGeolocationPermissionsShowPrompt - = Future Function( - GeolocationPermissionsRequestParams request); +typedef OnGeolocationPermissionsShowPrompt = + Future Function( + GeolocationPermissionsRequestParams request, + ); /// Signature for the `setGeolocationPermissionsPromptCallbacks` callback responsible for request the Geolocation API is cancel. typedef OnGeolocationPermissionsHidePrompt = void Function(); /// Signature for the `setCustomWidgetCallbacks` callback responsible for showing the custom view. -typedef OnShowCustomWidgetCallback = void Function( - Widget widget, void Function() onCustomWidgetHidden); +typedef OnShowCustomWidgetCallback = + void Function(Widget widget, void Function() onCustomWidgetHidden); /// Signature for the `setCustomWidgetCallbacks` callback responsible for hiding the custom view. typedef OnHideCustomWidgetCallback = void Function(); @@ -922,9 +954,7 @@ typedef OnHideCustomWidgetCallback = void Function(); @immutable class GeolocationPermissionsRequestParams { /// [origin]: The origin for which permissions are set. - const GeolocationPermissionsRequestParams({ - required this.origin, - }); + const GeolocationPermissionsRequestParams({required this.origin}); /// [origin]: The origin for which permissions are set. final String origin; @@ -1063,22 +1093,19 @@ class AndroidJavaScriptChannelParams extends JavaScriptChannelParams { required super.onMessageReceived, @visibleForTesting AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(), - }) : assert(name.isNotEmpty), - _javaScriptChannel = webViewProxy.newJavaScriptChannel( - channelName: name, - postMessage: withWeakReferenceTo( - onMessageReceived, - (WeakReference weakReference) { - return (_, String message) { - if (weakReference.target != null) { - weakReference.target!( - JavaScriptMessage(message: message), - ); - } - }; - }, - ), - ); + }) : assert(name.isNotEmpty), + _javaScriptChannel = webViewProxy.newJavaScriptChannel( + channelName: name, + postMessage: withWeakReferenceTo(onMessageReceived, ( + WeakReference weakReference, + ) { + return (_, String message) { + if (weakReference.target != null) { + weakReference.target!(JavaScriptMessage(message: message)); + } + }; + }), + ); /// Constructs a [AndroidJavaScriptChannelParams] using a /// [JavaScriptChannelParams]. @@ -1087,10 +1114,10 @@ class AndroidJavaScriptChannelParams extends JavaScriptChannelParams { @visibleForTesting AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(), }) : this( - name: params.name, - onMessageReceived: params.onMessageReceived, - webViewProxy: webViewProxy, - ); + name: params.name, + onMessageReceived: params.onMessageReceived, + webViewProxy: webViewProxy, + ); final android_webview.JavaScriptChannel _javaScriptChannel; } @@ -1114,7 +1141,7 @@ class AndroidWebViewWidgetCreationParams @visibleForTesting this.platformViewsServiceProxy = const PlatformViewsServiceProxy(), }) : instanceManager = - instanceManager ?? android_webview.PigeonInstanceManager.instance; + instanceManager ?? android_webview.PigeonInstanceManager.instance; /// Constructs a [WebKitWebViewWidgetCreationParams] using a /// [PlatformWebViewWidgetCreationParams]. @@ -1122,17 +1149,18 @@ class AndroidWebViewWidgetCreationParams PlatformWebViewWidgetCreationParams params, { bool displayWithHybridComposition = false, @visibleForTesting android_webview.PigeonInstanceManager? instanceManager, - @visibleForTesting PlatformViewsServiceProxy platformViewsServiceProxy = + @visibleForTesting + PlatformViewsServiceProxy platformViewsServiceProxy = const PlatformViewsServiceProxy(), }) : this( - key: params.key, - controller: params.controller, - layoutDirection: params.layoutDirection, - gestureRecognizers: params.gestureRecognizers, - displayWithHybridComposition: displayWithHybridComposition, - instanceManager: instanceManager, - platformViewsServiceProxy: platformViewsServiceProxy, - ); + key: params.key, + controller: params.controller, + layoutDirection: params.layoutDirection, + gestureRecognizers: params.gestureRecognizers, + displayWithHybridComposition: displayWithHybridComposition, + instanceManager: instanceManager, + platformViewsServiceProxy: platformViewsServiceProxy, + ); /// Maintains instances used to communicate with the native objects they /// represent. @@ -1163,12 +1191,12 @@ class AndroidWebViewWidgetCreationParams @override int get hashCode => Object.hash( - controller, - layoutDirection, - displayWithHybridComposition, - platformViewsServiceProxy, - instanceManager, - ); + controller, + layoutDirection, + displayWithHybridComposition, + platformViewsServiceProxy, + instanceManager, + ); @override bool operator ==(Object other) { @@ -1185,12 +1213,13 @@ class AndroidWebViewWidgetCreationParams class AndroidWebViewWidget extends PlatformWebViewWidget { /// Constructs a [WebKitWebViewWidget]. AndroidWebViewWidget(PlatformWebViewWidgetCreationParams params) - : super.implementation( - params is AndroidWebViewWidgetCreationParams - ? params - : AndroidWebViewWidgetCreationParams - .fromPlatformWebViewWidgetCreationParams(params), - ); + : super.implementation( + params is AndroidWebViewWidgetCreationParams + ? params + : AndroidWebViewWidgetCreationParams.fromPlatformWebViewWidgetCreationParams( + params, + ), + ); AndroidWebViewWidgetCreationParams get _androidParams => params as AndroidWebViewWidgetCreationParams; @@ -1201,9 +1230,11 @@ class AndroidWebViewWidget extends PlatformWebViewWidget { return PlatformViewLink( // Setting a default key using `params` ensures the `PlatformViewLink` // recreates the PlatformView when changes are made. - key: _androidParams.key ?? + key: + _androidParams.key ?? ValueKey( - params as AndroidWebViewWidgetCreationParams), + params as AndroidWebViewWidgetCreationParams, + ), viewType: 'plugins.flutter.io/webview', surfaceFactory: ( BuildContext context, @@ -1217,15 +1248,16 @@ class AndroidWebViewWidget extends PlatformWebViewWidget { }, onCreatePlatformView: (PlatformViewCreationParams params) { return _initAndroidView( - params, - displayWithHybridComposition: - _androidParams.displayWithHybridComposition, - platformViewsServiceProxy: _androidParams.platformViewsServiceProxy, - view: - (_androidParams.controller as AndroidWebViewController)._webView, - instanceManager: _androidParams.instanceManager, - layoutDirection: _androidParams.layoutDirection, - ) + params, + displayWithHybridComposition: + _androidParams.displayWithHybridComposition, + platformViewsServiceProxy: _androidParams.platformViewsServiceProxy, + view: + (_androidParams.controller as AndroidWebViewController) + ._webView, + instanceManager: _androidParams.instanceManager, + layoutDirection: _androidParams.layoutDirection, + ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, @@ -1240,12 +1272,16 @@ class AndroidWebViewWidget extends PlatformWebViewWidget { if (controller._onShowCustomWidgetCallback == null) { controller.setCustomWidgetCallbacks( - onShowCustomWidget: - (Widget widget, OnHideCustomWidgetCallback callback) { - Navigator.of(context).push(MaterialPageRoute( - builder: (BuildContext context) => widget, - fullscreenDialog: true, - )); + onShowCustomWidget: ( + Widget widget, + OnHideCustomWidgetCallback callback, + ) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (BuildContext context) => widget, + fullscreenDialog: true, + ), + ); }, onHideCustomWidget: () { Navigator.of(context).pop(); @@ -1282,7 +1318,7 @@ class AndroidCustomViewWidget extends StatelessWidget { @visibleForTesting this.platformViewsServiceProxy = const PlatformViewsServiceProxy(), }) : instanceManager = - instanceManager ?? android_webview.PigeonInstanceManager.instance; + instanceManager ?? android_webview.PigeonInstanceManager.instance; /// The reference to the Android native view that should be shown. final android_webview.View customView; @@ -1322,12 +1358,12 @@ class AndroidCustomViewWidget extends StatelessWidget { }, onCreatePlatformView: (PlatformViewCreationParams params) { return _initAndroidView( - params, - displayWithHybridComposition: false, - platformViewsServiceProxy: platformViewsServiceProxy, - view: customView, - instanceManager: instanceManager, - ) + params, + displayWithHybridComposition: false, + platformViewsServiceProxy: platformViewsServiceProxy, + view: customView, + instanceManager: instanceManager, + ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, @@ -1377,10 +1413,8 @@ class AndroidWebResourceError extends WebResourceError { required super.description, super.isForMainFrame, super.url, - }) : failingUrl = url, - super( - errorType: _errorCodeToErrorType(errorCode), - ); + }) : failingUrl = url, + super(errorType: _errorCodeToErrorType(errorCode)); /// Gets the URL for which the failing resource request was made. @Deprecated('Please use `url`.') @@ -1474,216 +1508,234 @@ class AndroidUrlChange extends UrlChange { class AndroidNavigationDelegate extends PlatformNavigationDelegate { /// Creates a new [AndroidNavigationDelegate]. AndroidNavigationDelegate(PlatformNavigationDelegateCreationParams params) - : super.implementation(params is AndroidNavigationDelegateCreationParams + : super.implementation( + params is AndroidNavigationDelegateCreationParams ? params - : AndroidNavigationDelegateCreationParams - .fromPlatformNavigationDelegateCreationParams(params)) { + : AndroidNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams( + params, + ), + ) { final WeakReference weakThis = WeakReference(this); _webViewClient = (this.params as AndroidNavigationDelegateCreationParams) .androidWebViewProxy .newWebViewClient( - onPageFinished: (_, android_webview.WebView webView, String url) { - final PageEventCallback? callback = weakThis.target?._onPageFinished; - if (callback != null) { - callback(url); - } - }, - onPageStarted: (_, android_webview.WebView webView, String url) { - final PageEventCallback? callback = weakThis.target?._onPageStarted; - if (callback != null) { - callback(url); - } - }, - onReceivedHttpError: ( - _, - android_webview.WebView webView, - android_webview.WebResourceRequest request, - android_webview.WebResourceResponse response, - ) { - if (weakThis.target?._onHttpError != null) { - weakThis.target!._onHttpError!( - HttpResponseError( - request: WebResourceRequest( - uri: Uri.parse(request.url), - ), - response: WebResourceResponse( - uri: null, - statusCode: response.statusCode, - ), - ), - ); - } - }, - onReceivedRequestError: ( - _, - android_webview.WebView webView, - android_webview.WebResourceRequest request, - android_webview.WebResourceError error, - ) { - final WebResourceErrorCallback? callback = - weakThis.target?._onWebResourceError; - if (callback != null) { - callback(AndroidWebResourceError._( - errorCode: error.errorCode, - description: error.description, - url: request.url, - isForMainFrame: request.isForMainFrame, - )); - } - }, - onReceivedRequestErrorCompat: ( - _, - android_webview.WebView webView, - android_webview.WebResourceRequest request, - android_webview.WebResourceErrorCompat error, - ) { - final WebResourceErrorCallback? callback = - weakThis.target?._onWebResourceError; - if (callback != null) { - callback(AndroidWebResourceError._( - errorCode: error.errorCode, - description: error.description, - url: request.url, - isForMainFrame: request.isForMainFrame, - )); - } - }, - onReceivedError: ( - _, - android_webview.WebView webView, - int errorCode, - String description, - String failingUrl, - ) { - final WebResourceErrorCallback? callback = - weakThis.target?._onWebResourceError; - if (callback != null) { - callback(AndroidWebResourceError._( - errorCode: errorCode, - description: description, - url: failingUrl, - isForMainFrame: true, - )); - } - }, - requestLoading: ( - _, - android_webview.WebView webView, - android_webview.WebResourceRequest request, - ) { - weakThis.target?._handleNavigation( - request.url, - headers: request.requestHeaders?.map( - (String? key, String? value) { - return MapEntry(key!, value!); - }, - ) ?? - {}, - isForMainFrame: request.isForMainFrame, - ); - }, - urlLoading: (_, android_webview.WebView webView, String url) { - weakThis.target?._handleNavigation(url, isForMainFrame: true); - }, - doUpdateVisitedHistory: ( - _, - android_webview.WebView webView, - String url, - bool isReload, - ) { - final UrlChangeCallback? callback = weakThis.target?._onUrlChange; - if (callback != null) { - callback(AndroidUrlChange(url: url, isReload: isReload)); - } - }, - onReceivedHttpAuthRequest: ( - _, - android_webview.WebView webView, - android_webview.HttpAuthHandler httpAuthHandler, - String host, - String realm, - ) { - final void Function(HttpAuthRequest)? callback = - weakThis.target?._onHttpAuthRequest; - if (callback != null) { - callback( - HttpAuthRequest( - onProceed: (WebViewCredential credential) { - httpAuthHandler.proceed(credential.user, credential.password); - }, - onCancel: () { - httpAuthHandler.cancel(); - }, - host: host, - realm: realm, - ), - ); - } else { - httpAuthHandler.cancel(); - } - }, - onFormResubmission: - (_, __, android_webview.AndroidMessage dontResend, ___) { - dontResend.sendToTarget(); - }, - onReceivedClientCertRequest: ( - _, - __, - android_webview.ClientCertRequest request, - ) { - request.cancel(); - }, - onReceivedSslError: ( - _, - __, - android_webview.SslErrorHandler handler, - android_webview.SslError error, - ) async { - final void Function(PlatformSslAuthError)? callback = - weakThis.target?._onSslAuthError; - - if (callback != null) { - final AndroidSslAuthError authError = - await AndroidSslAuthError.fromNativeCallback( - error: error, - handler: handler, - ); + onPageFinished: (_, android_webview.WebView webView, String url) { + final PageEventCallback? callback = + weakThis.target?._onPageFinished; + if (callback != null) { + callback(url); + } + }, + onPageStarted: (_, android_webview.WebView webView, String url) { + final PageEventCallback? callback = weakThis.target?._onPageStarted; + if (callback != null) { + callback(url); + } + }, + onReceivedHttpError: ( + _, + android_webview.WebView webView, + android_webview.WebResourceRequest request, + android_webview.WebResourceResponse response, + ) { + if (weakThis.target?._onHttpError != null) { + weakThis.target!._onHttpError!( + HttpResponseError( + request: WebResourceRequest(uri: Uri.parse(request.url)), + response: WebResourceResponse( + uri: null, + statusCode: response.statusCode, + ), + ), + ); + } + }, + onReceivedRequestError: ( + _, + android_webview.WebView webView, + android_webview.WebResourceRequest request, + android_webview.WebResourceError error, + ) { + final WebResourceErrorCallback? callback = + weakThis.target?._onWebResourceError; + if (callback != null) { + callback( + AndroidWebResourceError._( + errorCode: error.errorCode, + description: error.description, + url: request.url, + isForMainFrame: request.isForMainFrame, + ), + ); + } + }, + onReceivedRequestErrorCompat: ( + _, + android_webview.WebView webView, + android_webview.WebResourceRequest request, + android_webview.WebResourceErrorCompat error, + ) { + final WebResourceErrorCallback? callback = + weakThis.target?._onWebResourceError; + if (callback != null) { + callback( + AndroidWebResourceError._( + errorCode: error.errorCode, + description: error.description, + url: request.url, + isForMainFrame: request.isForMainFrame, + ), + ); + } + }, + onReceivedError: ( + _, + android_webview.WebView webView, + int errorCode, + String description, + String failingUrl, + ) { + final WebResourceErrorCallback? callback = + weakThis.target?._onWebResourceError; + if (callback != null) { + callback( + AndroidWebResourceError._( + errorCode: errorCode, + description: description, + url: failingUrl, + isForMainFrame: true, + ), + ); + } + }, + requestLoading: ( + _, + android_webview.WebView webView, + android_webview.WebResourceRequest request, + ) { + weakThis.target?._handleNavigation( + request.url, + headers: + request.requestHeaders?.map(( + String? key, + String? value, + ) { + return MapEntry(key!, value!); + }) ?? + {}, + isForMainFrame: request.isForMainFrame, + ); + }, + urlLoading: (_, android_webview.WebView webView, String url) { + weakThis.target?._handleNavigation(url, isForMainFrame: true); + }, + doUpdateVisitedHistory: ( + _, + android_webview.WebView webView, + String url, + bool isReload, + ) { + final UrlChangeCallback? callback = weakThis.target?._onUrlChange; + if (callback != null) { + callback(AndroidUrlChange(url: url, isReload: isReload)); + } + }, + onReceivedHttpAuthRequest: ( + _, + android_webview.WebView webView, + android_webview.HttpAuthHandler httpAuthHandler, + String host, + String realm, + ) { + final void Function(HttpAuthRequest)? callback = + weakThis.target?._onHttpAuthRequest; + if (callback != null) { + callback( + HttpAuthRequest( + onProceed: (WebViewCredential credential) { + httpAuthHandler.proceed( + credential.user, + credential.password, + ); + }, + onCancel: () { + httpAuthHandler.cancel(); + }, + host: host, + realm: realm, + ), + ); + } else { + httpAuthHandler.cancel(); + } + }, + onFormResubmission: ( + _, + __, + android_webview.AndroidMessage dontResend, + ___, + ) { + dontResend.sendToTarget(); + }, + onReceivedClientCertRequest: ( + _, + __, + android_webview.ClientCertRequest request, + ) { + request.cancel(); + }, + onReceivedSslError: ( + _, + __, + android_webview.SslErrorHandler handler, + android_webview.SslError error, + ) async { + final void Function(PlatformSslAuthError)? callback = + weakThis.target?._onSslAuthError; + + if (callback != null) { + final AndroidSslAuthError authError = + await AndroidSslAuthError.fromNativeCallback( + error: error, + handler: handler, + ); - callback(authError); - } else { - await handler.cancel(); - } - }, - ); + callback(authError); + } else { + await handler.cancel(); + } + }, + ); _downloadListener = (this.params as AndroidNavigationDelegateCreationParams) .androidWebViewProxy .newDownloadListener( - onDownloadStart: ( - _, - String url, - String userAgent, - String contentDisposition, - String mimetype, - int contentLength, - ) { - if (weakThis.target != null) { - weakThis.target?._handleNavigation(url, isForMainFrame: true); - } - }, - ); + onDownloadStart: ( + _, + String url, + String userAgent, + String contentDisposition, + String mimetype, + int contentLength, + ) { + if (weakThis.target != null) { + weakThis.target?._handleNavigation(url, isForMainFrame: true); + } + }, + ); } AndroidNavigationDelegateCreationParams get _androidParams => params as AndroidNavigationDelegateCreationParams; - late final android_webview.WebChromeClient _webChromeClient = - _androidParams.androidWebViewProxy.newWebChromeClient( - onJsConfirm: (_, __, ___, ____) async => false, - onShowFileChooser: (_, __, ___) async => [], - ); + late final android_webview.WebChromeClient _webChromeClient = _androidParams + .androidWebViewProxy + .newWebChromeClient( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ); /// Gets the native [android_webview.WebChromeClient] that is bridged by this [AndroidNavigationDelegate]. /// @@ -1737,34 +1789,25 @@ class AndroidNavigationDelegate extends PlatformNavigationDelegate { } final FutureOr returnValue = onNavigationRequest( - NavigationRequest( - url: url, - isMainFrame: isForMainFrame, - ), + NavigationRequest(url: url, isMainFrame: isForMainFrame), ); if (returnValue is NavigationDecision && returnValue == NavigationDecision.navigate) { - onLoadRequest(LoadRequestParams( - uri: Uri.parse(url), - headers: headers, - )); + onLoadRequest(LoadRequestParams(uri: Uri.parse(url), headers: headers)); } else if (returnValue is Future) { returnValue.then((NavigationDecision shouldLoadUrl) { if (shouldLoadUrl == NavigationDecision.navigate) { - onLoadRequest(LoadRequestParams( - uri: Uri.parse(url), - headers: headers, - )); + onLoadRequest( + LoadRequestParams(uri: Uri.parse(url), headers: headers), + ); } }); } } /// Invoked when loading the url after a navigation request is approved. - Future setOnLoadRequest( - LoadRequestCallback onLoadRequest, - ) async { + Future setOnLoadRequest(LoadRequestCallback onLoadRequest) async { _onLoadRequest = onLoadRequest; } @@ -1773,35 +1816,28 @@ class AndroidNavigationDelegate extends PlatformNavigationDelegate { NavigationRequestCallback onNavigationRequest, ) async { _onNavigationRequest = onNavigationRequest; - return _webViewClient - .setSynchronousReturnValueForShouldOverrideUrlLoading(true); + return _webViewClient.setSynchronousReturnValueForShouldOverrideUrlLoading( + true, + ); } @override - Future setOnPageStarted( - PageEventCallback onPageStarted, - ) async { + Future setOnPageStarted(PageEventCallback onPageStarted) async { _onPageStarted = onPageStarted; } @override - Future setOnPageFinished( - PageEventCallback onPageFinished, - ) async { + Future setOnPageFinished(PageEventCallback onPageFinished) async { _onPageFinished = onPageFinished; } @override - Future setOnHttpError( - HttpResponseErrorCallback onHttpError, - ) async { + Future setOnHttpError(HttpResponseErrorCallback onHttpError) async { _onHttpError = onHttpError; } @override - Future setOnProgress( - ProgressCallback onProgress, - ) async { + Future setOnProgress(ProgressCallback onProgress) async { _onProgress = onProgress; } diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart index 4c8db3e16e3..9c8a24e1bbf 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart @@ -25,7 +25,8 @@ class AndroidWebViewCookieManagerCreationParams /// Creates a [AndroidWebViewCookieManagerCreationParams] instance based on [PlatformWebViewCookieManagerCreationParams]. factory AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( - PlatformWebViewCookieManagerCreationParams params) { + PlatformWebViewCookieManagerCreationParams params, + ) { return AndroidWebViewCookieManagerCreationParams._(params); } } @@ -36,13 +37,14 @@ class AndroidWebViewCookieManager extends PlatformWebViewCookieManager { AndroidWebViewCookieManager( PlatformWebViewCookieManagerCreationParams params, { CookieManager? cookieManager, - }) : _cookieManager = cookieManager ?? CookieManager.instance, - super.implementation( - params is AndroidWebViewCookieManagerCreationParams - ? params - : AndroidWebViewCookieManagerCreationParams - .fromPlatformWebViewCookieManagerCreationParams(params), - ); + }) : _cookieManager = cookieManager ?? CookieManager.instance, + super.implementation( + params is AndroidWebViewCookieManagerCreationParams + ? params + : AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( + params, + ), + ); final CookieManager _cookieManager; @@ -55,7 +57,8 @@ class AndroidWebViewCookieManager extends PlatformWebViewCookieManager { Future setCookie(WebViewCookie cookie) { if (!_isValidPath(cookie.path)) { throw ArgumentError( - 'The path property for the provided cookie was not given a legal value.'); + 'The path property for the provided cookie was not given a legal value.', + ); } return _cookieManager.setCookie( cookie.domain, @@ -81,8 +84,10 @@ class AndroidWebViewCookieManager extends PlatformWebViewCookieManager { bool accept, ) { // ignore: invalid_use_of_protected_member - final WebView webView = _cookieManager.pigeon_instanceManager - .getInstanceWithWeakReference(controller.webViewIdentifier)!; + final WebView webView = + _cookieManager.pigeon_instanceManager.getInstanceWithWeakReference( + controller.webViewIdentifier, + )!; return _cookieManager.setAcceptThirdPartyCookies(webView, accept); } } diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android.dart b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android.dart index cbfeadad5aa..819cdd65340 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android.dart @@ -22,7 +22,7 @@ import 'webview_android_widget.dart'; class AndroidWebView implements WebViewPlatform { /// Constructs an [AndroidWebView]. AndroidWebView({@visibleForTesting PigeonInstanceManager? instanceManager}) - : instanceManager = instanceManager ?? PigeonInstanceManager.instance; + : instanceManager = instanceManager ?? PigeonInstanceManager.instance; /// Maintains instances used to communicate with the native objects they /// represent. @@ -75,7 +75,8 @@ class AndroidWebView implements WebViewPlatform { Future clearCookies() { if (WebViewCookieManagerPlatform.instance == null) { throw Exception( - 'Could not clear cookies as no implementation for WebViewCookieManagerPlatform has been registered.'); + 'Could not clear cookies as no implementation for WebViewCookieManagerPlatform has been registered.', + ); } return WebViewCookieManagerPlatform.instance!.clearCookies(); } diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_cookie_manager.dart b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_cookie_manager.dart index a65605c87a3..cfb42965091 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_cookie_manager.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_cookie_manager.dart @@ -24,7 +24,8 @@ class WebViewAndroidCookieManager extends WebViewCookieManagerPlatform { Future setCookie(WebViewCookie cookie) { if (!_isValidPath(cookie.path)) { throw ArgumentError( - 'The path property for the provided cookie was not given a legal value.'); + 'The path property for the provided cookie was not given a legal value.', + ); } return _cookieManager.setCookie( cookie.domain, diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart index b9b311a1abc..a9bb5a05108 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart @@ -27,7 +27,7 @@ class WebViewAndroidWidget extends StatefulWidget { @visibleForTesting android_webview.FlutterAssetManager? flutterAssetManager, @visibleForTesting this.webStorage, }) : flutterAssetManager = - flutterAssetManager ?? android_webview.FlutterAssetManager.instance; + flutterAssetManager ?? android_webview.FlutterAssetManager.instance; /// Initial parameters used to setup the WebView. final CreationParams creationParams; @@ -50,7 +50,7 @@ class WebViewAndroidWidget extends StatefulWidget { /// Callback to build a widget once [android_webview.WebView] has been initialized. final Widget Function(WebViewAndroidPlatformController controller) - onBuildWidget; + onBuildWidget; /// Manages the JavaScript storage APIs. final android_webview.WebStorage? webStorage; @@ -91,11 +91,11 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { @visibleForTesting this.webViewProxy = const WebViewProxy(), @visibleForTesting android_webview.FlutterAssetManager? flutterAssetManager, @visibleForTesting android_webview.WebStorage? webStorage, - }) : webStorage = webStorage ?? android_webview.WebStorage.instance, - flutterAssetManager = - flutterAssetManager ?? android_webview.FlutterAssetManager.instance, - assert(creationParams.webSettings?.hasNavigationDelegate != null), - super(callbacksHandler) { + }) : webStorage = webStorage ?? android_webview.WebStorage.instance, + flutterAssetManager = + flutterAssetManager ?? android_webview.FlutterAssetManager.instance, + assert(creationParams.webSettings?.hasNavigationDelegate != null), + super(callbacksHandler) { webView = webViewProxy.createWebView(); webView.settings.setDomStorageEnabled(true); @@ -120,101 +120,101 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { final Map _javaScriptChannels = {}; - late final android_webview.WebViewClient _webViewClient = - webViewProxy.createWebViewClient( - onPageStarted: withWeakReferenceTo(this, ( - WeakReference weakReference, - ) { - return (_, __, String url) { - weakReference.target?.callbacksHandler.onPageStarted(url); - }; - }), - onPageFinished: withWeakReferenceTo(this, ( - WeakReference weakReference, - ) { - return (_, __, String url) { - weakReference.target?.callbacksHandler.onPageFinished(url); - }; - }), - onReceivedError: withWeakReferenceTo(this, ( - WeakReference weakReference, - ) { - return ( - _, - __, - int errorCode, - String description, - String failingUrl, - ) { - weakReference.target?.callbacksHandler - .onWebResourceError(WebResourceError( - errorCode: errorCode, - description: description, - failingUrl: failingUrl, - errorType: _errorCodeToErrorType(errorCode), - )); - }; - }), - onReceivedRequestError: withWeakReferenceTo(this, ( - WeakReference weakReference, - ) { - return ( - _, - __, - android_webview.WebResourceRequest request, - android_webview.WebResourceError error, - ) { - if (request.isForMainFrame) { - weakReference.target?.callbacksHandler - .onWebResourceError(WebResourceError( - errorCode: error.errorCode, - description: error.description, - failingUrl: request.url, - errorType: _errorCodeToErrorType(error.errorCode), - )); - } - }; - }), - urlLoading: withWeakReferenceTo(this, ( - WeakReference weakReference, - ) { - return (_, __, String url) { - weakReference.target?._handleNavigationRequest( - url: url, - isForMainFrame: true, - ); - }; - }), - onFormResubmission: - (_, __, android_webview.AndroidMessage dontResend, ___) { - dontResend.sendToTarget(); - }, - onReceivedClientCertRequest: ( - _, - __, - android_webview.ClientCertRequest request, - ) { - request.cancel(); - }, - onReceivedSslError: ( - _, - __, - android_webview.SslErrorHandler handler, - ___, - ) { - handler.cancel(); - }, - requestLoading: withWeakReferenceTo(this, ( - WeakReference weakReference, - ) { - return (_, __, android_webview.WebResourceRequest request) { - weakReference.target?._handleNavigationRequest( - url: request.url, - isForMainFrame: request.isForMainFrame, - ); - }; - }), - ); + late final android_webview.WebViewClient _webViewClient = webViewProxy + .createWebViewClient( + onPageStarted: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, String url) { + weakReference.target?.callbacksHandler.onPageStarted(url); + }; + }), + onPageFinished: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, String url) { + weakReference.target?.callbacksHandler.onPageFinished(url); + }; + }), + onReceivedError: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, int errorCode, String description, String failingUrl) { + weakReference.target?.callbacksHandler.onWebResourceError( + WebResourceError( + errorCode: errorCode, + description: description, + failingUrl: failingUrl, + errorType: _errorCodeToErrorType(errorCode), + ), + ); + }; + }), + onReceivedRequestError: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return ( + _, + __, + android_webview.WebResourceRequest request, + android_webview.WebResourceError error, + ) { + if (request.isForMainFrame) { + weakReference.target?.callbacksHandler.onWebResourceError( + WebResourceError( + errorCode: error.errorCode, + description: error.description, + failingUrl: request.url, + errorType: _errorCodeToErrorType(error.errorCode), + ), + ); + } + }; + }), + urlLoading: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, String url) { + weakReference.target?._handleNavigationRequest( + url: url, + isForMainFrame: true, + ); + }; + }), + onFormResubmission: ( + _, + __, + android_webview.AndroidMessage dontResend, + ___, + ) { + dontResend.sendToTarget(); + }, + onReceivedClientCertRequest: ( + _, + __, + android_webview.ClientCertRequest request, + ) { + request.cancel(); + }, + onReceivedSslError: ( + _, + __, + android_webview.SslErrorHandler handler, + ___, + ) { + handler.cancel(); + }, + requestLoading: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, android_webview.WebResourceRequest request) { + weakReference.target?._handleNavigationRequest( + url: request.url, + isForMainFrame: request.isForMainFrame, + ); + }; + }), + ); bool _hasNavigationDelegate = false; bool _hasProgressTracking = false; @@ -242,45 +242,43 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { @visibleForTesting late final android_webview.DownloadListener downloadListener = android_webview.DownloadListener( - onDownloadStart: withWeakReferenceTo( - this, - (WeakReference weakReference) { - return ( - _, - String url, - String userAgent, - String contentDisposition, - String mimetype, - int contentLength, + onDownloadStart: withWeakReferenceTo(this, ( + WeakReference weakReference, ) { - weakReference.target?._handleNavigationRequest( - url: url, - isForMainFrame: true, - ); - }; - }, - ), - ); + return ( + _, + String url, + String userAgent, + String contentDisposition, + String mimetype, + int contentLength, + ) { + weakReference.target?._handleNavigationRequest( + url: url, + isForMainFrame: true, + ); + }; + }), + ); /// Handles JavaScript dialogs, favicons, titles, new windows, and the progress for [android_webview.WebView]. @visibleForTesting late final android_webview.WebChromeClient webChromeClient = android_webview.WebChromeClient( - onProgressChanged: withWeakReferenceTo( - this, - (WeakReference weakReference) { - return (_, __, int progress) { - final WebViewAndroidPlatformController? controller = - weakReference.target; - if (controller != null && controller._hasProgressTracking) { - controller.callbacksHandler.onProgress(progress); - } - }; - }, - ), - onJsConfirm: (_, __, ___, ____) async => false, - onShowFileChooser: (_, __, ___) async => [], - ); + onProgressChanged: withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return (_, __, int progress) { + final WebViewAndroidPlatformController? controller = + weakReference.target; + if (controller != null && controller._hasProgressTracking) { + controller.callbacksHandler.onProgress(progress); + } + }; + }), + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ); /// Manages the JavaScript storage APIs. final android_webview.WebStorage webStorage; @@ -296,9 +294,10 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { @override Future loadFile(String absoluteFilePath) { - final String url = absoluteFilePath.startsWith('file://') - ? absoluteFilePath - : 'file://$absoluteFilePath'; + final String url = + absoluteFilePath.startsWith('file://') + ? absoluteFilePath + : 'file://$absoluteFilePath'; webView.settings.setAllowFileAccess(true); return webView.loadUrl(url, {}); @@ -306,18 +305,16 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { @override Future loadFlutterAsset(String key) async { - final String assetFilePath = - await flutterAssetManager.getAssetFilePathByName(key); + final String assetFilePath = await flutterAssetManager + .getAssetFilePathByName(key); final List pathElements = assetFilePath.split('/'); final String fileName = pathElements.removeLast(); - final List paths = - await flutterAssetManager.list(pathElements.join('/')); + final List paths = await flutterAssetManager.list( + pathElements.join('/'), + ); if (!paths.contains(fileName)) { - throw ArgumentError( - 'Asset for key "$key" not found.', - 'key', - ); + throw ArgumentError('Asset for key "$key" not found.', 'key'); } return webView.loadUrl( @@ -327,19 +324,14 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { } @override - Future loadUrl( - String url, - Map? headers, - ) { + Future loadUrl(String url, Map? headers) { return webView.loadUrl(url, headers ?? {}); } /// When making a POST request, headers are ignored. As a workaround, make /// the request manually and load the response data using [loadHTMLString]. @override - Future loadRequest( - WebViewRequest request, - ) async { + Future loadRequest(WebViewRequest request) async { if (!request.uri.hasScheme) { throw ArgumentError('WebViewRequest#uri is required to have a scheme.'); } @@ -348,7 +340,9 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { return webView.loadUrl(request.uri.toString(), request.headers); case WebViewRequestMethod.post: return webView.postUrl( - request.uri.toString(), request.body ?? Uint8List(0)); + request.uri.toString(), + request.body ?? Uint8List(0), + ); } // The enum comes from a different package, which could get a new value at // any time, so a fallback case is necessary. Since there is no reasonable @@ -357,9 +351,10 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { // so that the linter will flag the switch as needing an update. // ignore: dead_code throw UnimplementedError( - 'This version of webview_android_widget currently has no ' - 'implementation for HTTP method ${request.method.serialize()} in ' - 'loadRequest.'); + 'This version of webview_android_widget currently has no ' + 'implementation for HTTP method ${request.method.serialize()} in ' + 'loadRequest.', + ); } @override @@ -419,39 +414,33 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { @override Future addJavascriptChannels(Set javascriptChannelNames) { return Future.wait( - javascriptChannelNames.where( - (String channelName) { - return !_javaScriptChannels.containsKey(channelName); - }, - ).map>( - (String channelName) { - final WebViewAndroidJavaScriptChannel javaScriptChannel = - WebViewAndroidJavaScriptChannel( - channelName: channelName, - javascriptChannelRegistry: javascriptChannelRegistry, - ); - _javaScriptChannels[channelName] = javaScriptChannel; - return webView.addJavaScriptChannel(javaScriptChannel); - }, - ), + javascriptChannelNames + .where((String channelName) { + return !_javaScriptChannels.containsKey(channelName); + }) + .map>((String channelName) { + final WebViewAndroidJavaScriptChannel javaScriptChannel = + WebViewAndroidJavaScriptChannel( + channelName: channelName, + javascriptChannelRegistry: javascriptChannelRegistry, + ); + _javaScriptChannels[channelName] = javaScriptChannel; + return webView.addJavaScriptChannel(javaScriptChannel); + }), ); } @override - Future removeJavascriptChannels( - Set javascriptChannelNames, - ) { + Future removeJavascriptChannels(Set javascriptChannelNames) { return Future.wait( - javascriptChannelNames.where( - (String channelName) { - return _javaScriptChannels.containsKey(channelName); - }, - ).map>( - (String channelName) { - _javaScriptChannels.remove(channelName); - return webView.removeJavaScriptChannel(channelName); - }, - ), + javascriptChannelNames + .where((String channelName) { + return _javaScriptChannels.containsKey(channelName); + }) + .map>((String channelName) { + _javaScriptChannels.remove(channelName); + return webView.removeJavaScriptChannel(channelName); + }), ); } @@ -498,8 +487,9 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { // https://github.com/flutter/flutter/issues/94224 WebViewCookieManagerPlatform.instance ??= WebViewAndroidCookieManager(); - creationParams.cookies - .forEach(WebViewCookieManagerPlatform.instance!.setCookie); + creationParams.cookies.forEach( + WebViewCookieManagerPlatform.instance!.setCookie, + ); } Future _setHasNavigationDelegate(bool hasNavigationDelegate) { @@ -609,18 +599,17 @@ class WebViewAndroidJavaScriptChannel required super.channelName, required this.javascriptChannelRegistry, }) : super( - postMessage: withWeakReferenceTo( - javascriptChannelRegistry, - (WeakReference weakReference) { - return (_, String message) { - weakReference.target?.onJavascriptChannelMessage( - channelName, - message, - ); - }; - }, - ), - ); + postMessage: withWeakReferenceTo(javascriptChannelRegistry, ( + WeakReference weakReference, + ) { + return (_, String message) { + weakReference.target?.onJavascriptChannelMessage( + channelName, + message, + ); + }; + }), + ); /// Manages named JavaScript channels and forwarding incoming messages on the correct channel. final JavascriptChannelRegistry javascriptChannelRegistry; @@ -645,52 +634,61 @@ class WebViewProxy { android_webview.WebViewClient, android_webview.WebView webView, String url, - )? onPageStarted, + )? + onPageStarted, void Function( android_webview.WebViewClient, android_webview.WebView webView, String url, - )? onPageFinished, + )? + onPageFinished, void Function( android_webview.WebViewClient, android_webview.WebView webView, android_webview.WebResourceRequest request, android_webview.WebResourceError error, - )? onReceivedRequestError, + )? + onReceivedRequestError, void Function( android_webview.WebViewClient, android_webview.WebView webView, int errorCode, String description, String failingUrl, - )? onReceivedError, + )? + onReceivedError, void Function( android_webview.WebViewClient, android_webview.WebView webView, android_webview.WebResourceRequest request, - )? requestLoading, + )? + requestLoading, void Function( android_webview.WebViewClient, android_webview.WebView, android_webview.AndroidMessage, android_webview.AndroidMessage, - )? onFormResubmission, + )? + onFormResubmission, void Function( android_webview.WebViewClient, android_webview.WebView, android_webview.ClientCertRequest, - )? onReceivedClientCertRequest, + )? + onReceivedClientCertRequest, void Function( android_webview.WebViewClient, android_webview.WebView, android_webview.SslErrorHandler, android_webview.SslError, - )? onReceivedSslError, + )? + onReceivedSslError, void Function( android_webview.WebViewClient, android_webview.WebView webView, String url, - )? urlLoading, + )? + urlLoading, }) { return android_webview.WebViewClient( onPageStarted: onPageStarted, diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_surface_android.dart b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_surface_android.dart index 7a0ac4c382c..45bb7e53aeb 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_surface_android.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_surface_android.dart @@ -55,7 +55,8 @@ class SurfaceAndroidWebView extends AndroidWebView { ) { return AndroidViewSurface( controller: controller as AndroidViewController, - gestureRecognizers: gestureRecognizers ?? + gestureRecognizers: + gestureRecognizers ?? const >{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); @@ -63,22 +64,22 @@ class SurfaceAndroidWebView extends AndroidWebView { onCreatePlatformView: (PlatformViewCreationParams params) { final Color? backgroundColor = creationParams.backgroundColor; return _createViewController( - // On some Android devices, transparent backgrounds can cause - // rendering issues on the non hybrid composition - // AndroidViewSurface. This switches the WebView to Hybrid - // Composition when the background color is not 100% opaque. - hybridComposition: - backgroundColor != null && backgroundColor.opacity < 1.0, - id: params.id, - viewType: 'plugins.flutter.io/webview', - // WebView content is not affected by the Android view's layout direction, - // we explicitly set it here so that the widget doesn't require an ambient - // directionality. - layoutDirection: - Directionality.maybeOf(context) ?? TextDirection.ltr, - webViewIdentifier: - instanceManager.getIdentifier(controller.webView)!, - ) + // On some Android devices, transparent backgrounds can cause + // rendering issues on the non hybrid composition + // AndroidViewSurface. This switches the WebView to Hybrid + // Composition when the background color is not 100% opaque. + hybridComposition: + backgroundColor != null && backgroundColor.opacity < 1.0, + id: params.id, + viewType: 'plugins.flutter.io/webview', + // WebView content is not affected by the Android view's layout direction, + // we explicitly set it here so that the widget doesn't require an ambient + // directionality. + layoutDirection: + Directionality.maybeOf(context) ?? TextDirection.ltr, + webViewIdentifier: + instanceManager.getIdentifier(controller.webView)!, + ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..addOnPlatformViewCreatedListener((int id) { if (onWebViewPlatformCreated != null) { diff --git a/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart b/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart index 9dadba738d8..c8dc41a8cb4 100644 --- a/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart +++ b/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart @@ -16,7 +16,6 @@ import 'package:pigeon/pigeon.dart'; ), ), ) - /// Mode of how to select files for a file chooser. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams. @@ -269,21 +268,15 @@ abstract class CookieManager { /// /// See https://developer.android.com/reference/android/webkit/WebView. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.webkit.WebView', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.webkit.WebView'), ) abstract class WebView extends View { WebView(); /// This is called in response to an internal scroll in this view (i.e., the /// view scrolled its own contents). - late void Function( - int left, - int top, - int oldLeft, - int oldTop, - )? onScrollChanged; + late void Function(int left, int top, int oldLeft, int oldTop)? + onScrollChanged; /// The WebSettings object used to control the settings for this WebView. @attached @@ -470,21 +463,24 @@ abstract class WebViewClient { WebView webView, WebResourceRequest request, WebResourceResponse response, - )? onReceivedHttpError; + )? + onReceivedHttpError; /// Report web resource loading error to the host application. late void Function( WebView webView, WebResourceRequest request, WebResourceError error, - )? onReceivedRequestError; + )? + onReceivedRequestError; /// Report web resource loading error to the host application. late void Function( WebView webView, WebResourceRequest request, WebResourceErrorCompat error, - )? onReceivedRequestErrorCompat; + )? + onReceivedRequestErrorCompat; /// Report an error to the host application. late void Function( @@ -492,25 +488,21 @@ abstract class WebViewClient { int errorCode, String description, String failingUrl, - )? onReceivedError; + )? + onReceivedError; /// Give the host application a chance to take control when a URL is about to /// be loaded in the current WebView. - late void Function( - WebView webView, - WebResourceRequest request, - )? requestLoading; + late void Function(WebView webView, WebResourceRequest request)? + requestLoading; /// Give the host application a chance to take control when a URL is about to /// be loaded in the current WebView. late void Function(WebView webView, String url)? urlLoading; /// Notify the host application to update its visited links database. - late void Function( - WebView webView, - String url, - bool isReload, - )? doUpdateVisitedHistory; + late void Function(WebView webView, String url, bool isReload)? + doUpdateVisitedHistory; /// Notifies the host application that the WebView received an HTTP /// authentication request. @@ -519,15 +511,13 @@ abstract class WebViewClient { HttpAuthHandler handler, String host, String realm, - )? onReceivedHttpAuthRequest; + )? + onReceivedHttpAuthRequest; /// Ask the host application if the browser should resend data as the /// requested page was a result of a POST. - void Function( - WebView view, - AndroidMessage dontResend, - AndroidMessage resend, - )? onFormResubmission; + void Function(WebView view, AndroidMessage dontResend, AndroidMessage resend)? + onFormResubmission; /// Notify the host application that the WebView will load the resource /// specified by the given url. @@ -538,27 +528,18 @@ abstract class WebViewClient { void Function(WebView view, String url)? onPageCommitVisible; /// Notify the host application to handle a SSL client certificate request. - void Function( - WebView view, - ClientCertRequest request, - )? onReceivedClientCertRequest; + void Function(WebView view, ClientCertRequest request)? + onReceivedClientCertRequest; /// Notify the host application that a request to automatically log in the /// user has been processed. - void Function( - WebView view, - String realm, - String? account, - String args, - )? onReceivedLoginRequest; + void Function(WebView view, String realm, String? account, String args)? + onReceivedLoginRequest; /// Notifies the host application that an SSL error occurred while loading a /// resource. - void Function( - WebView view, - SslErrorHandler handler, - SslError error, - )? onReceivedSslError; + void Function(WebView view, SslErrorHandler handler, SslError error)? + onReceivedSslError; /// Notify the host application that the scale applied to the WebView has /// changed. @@ -597,7 +578,8 @@ abstract class DownloadListener { String contentDisposition, String mimetype, int contentLength, - ) onDownloadStart; + ) + onDownloadStart; } /// Handles notification of JavaScript dialogs, favicons, titles, and the @@ -618,10 +600,8 @@ abstract class WebChromeClient { /// Tell the client to show a file chooser. @async - late List Function( - WebView webView, - FileChooserParams params, - ) onShowFileChooser; + late List Function(WebView webView, FileChooserParams params) + onShowFileChooser; /// Notify the host application that web content is requesting permission to /// access the specified resources and the permission currently isn't granted @@ -629,10 +609,7 @@ abstract class WebChromeClient { late void Function(PermissionRequest request)? onPermissionRequest; /// Callback to Dart function `WebChromeClient.onShowCustomView`. - late void Function( - View view, - CustomViewCallback callback, - )? onShowCustomView; + late void Function(View view, CustomViewCallback callback)? onShowCustomView; /// Notify the host application that the current page has entered full screen /// mode. @@ -641,10 +618,8 @@ abstract class WebChromeClient { /// Notify the host application that web content from the specified origin is /// attempting to use the Geolocation API, but no permission state is /// currently set for that origin. - late void Function( - String origin, - GeolocationPermissionsCallback callback, - )? onGeolocationPermissionsShowPrompt; + late void Function(String origin, GeolocationPermissionsCallback callback)? + onGeolocationPermissionsShowPrompt; /// Notify the host application that a request for Geolocation permissions, /// made with a previous call to `onGeolocationPermissionsShowPrompt` has been @@ -672,7 +647,8 @@ abstract class WebChromeClient { String url, String message, String defaultValue, - )? onJsPrompt; + )? + onJsPrompt; /// Sets the required synchronous return value for the Java method, /// `WebChromeClient.onShowFileChooser(...)`. @@ -858,9 +834,7 @@ abstract class CustomViewCallback { /// /// See https://developer.android.com/reference/android/view/View. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.view.View', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.view.View'), ) abstract class View { /// Set the scrolled position of your view. @@ -1102,10 +1076,7 @@ abstract class Certificate { ) abstract class WebSettingsCompat { @static - void setPaymentRequestEnabled( - WebSettings webSettings, - bool enabled, - ); + void setPaymentRequestEnabled(WebSettings webSettings, bool enabled); } /// Utility class for checking which WebView Support Library features are supported on the device. diff --git a/packages/webview_flutter/webview_flutter_android/pubspec.yaml b/packages/webview_flutter/webview_flutter_android/pubspec.yaml index 444894d8100..444bcf615ba 100644 --- a/packages/webview_flutter/webview_flutter_android/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_android/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 4.10.0 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart index 97ed60ae8fa..1271a2e9470 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart @@ -34,8 +34,9 @@ void main() { AndroidNavigationDelegate(_buildCreationParams()); late final String callbackUrl; - androidNavigationDelegate - .setOnPageFinished((String url) => callbackUrl = url); + androidNavigationDelegate.setOnPageFinished( + (String url) => callbackUrl = url, + ); CapturingWebViewClient.lastCreatedDelegate.onPageFinished!( CapturingWebViewClient(), @@ -51,8 +52,9 @@ void main() { AndroidNavigationDelegate(_buildCreationParams()); late final String callbackUrl; - androidNavigationDelegate - .setOnPageStarted((String url) => callbackUrl = url); + androidNavigationDelegate.setOnPageStarted( + (String url) => callbackUrl = url, + ); CapturingWebViewClient.lastCreatedDelegate.onPageStarted!( CapturingWebViewClient(), @@ -69,24 +71,26 @@ void main() { late final HttpResponseError callbackError; androidNavigationDelegate.setOnHttpError( - (HttpResponseError httpError) => callbackError = httpError); + (HttpResponseError httpError) => callbackError = httpError, + ); CapturingWebViewClient.lastCreatedDelegate.onReceivedHttpError!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: false, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - android_webview.WebResourceResponse.pigeon_detached( - statusCode: 401, - pigeon_instanceManager: TestInstanceManager(), - )); + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: false, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + android_webview.WebResourceResponse.pigeon_detached( + statusCode: 401, + pigeon_instanceManager: TestInstanceManager(), + ), + ); expect(callbackError.response?.statusCode, 401); }); @@ -97,7 +101,8 @@ void main() { late final WebResourceError callbackError; androidNavigationDelegate.setOnWebResourceError( - (WebResourceError error) => callbackError = error); + (WebResourceError error) => callbackError = error, + ); CapturingWebViewClient.lastCreatedDelegate.onReceivedRequestError!( CapturingWebViewClient(), @@ -130,7 +135,8 @@ void main() { late final WebResourceError callbackError; androidNavigationDelegate.setOnWebResourceError( - (WebResourceError error) => callbackError = error); + (WebResourceError error) => callbackError = error, + ); CapturingWebViewClient.lastCreatedDelegate.onReceivedError!( CapturingWebViewClient(), @@ -147,314 +153,334 @@ void main() { }); test( - 'onNavigationRequest from requestLoading should not be called when loadUrlCallback is not specified', - () { - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - NavigationRequest? callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); - - CapturingWebViewClient.lastCreatedDelegate.requestLoading!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: true, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - ); + 'onNavigationRequest from requestLoading should not be called when loadUrlCallback is not specified', + () { + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + NavigationRequest? callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + CapturingWebViewClient.lastCreatedDelegate.requestLoading!( + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: true, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + ); - expect(callbackNavigationRequest, isNull); - }); + expect(callbackNavigationRequest, isNull); + }, + ); test( - 'onNavigationRequest from requestLoading should be called when request is for main frame', - () { - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - NavigationRequest? callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); - - androidNavigationDelegate.setOnLoadRequest((_) async {}); - - CapturingWebViewClient.lastCreatedDelegate.requestLoading!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: true, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - ); + 'onNavigationRequest from requestLoading should be called when request is for main frame', + () { + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + NavigationRequest? callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + androidNavigationDelegate.setOnLoadRequest((_) async {}); + + CapturingWebViewClient.lastCreatedDelegate.requestLoading!( + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: true, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + ); - expect(callbackNavigationRequest, isNotNull); - }); + expect(callbackNavigationRequest, isNotNull); + }, + ); test( - 'onNavigationRequest from requestLoading should not be called when request is not for main frame', - () { - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - NavigationRequest? callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); - - androidNavigationDelegate.setOnLoadRequest((_) async {}); - - CapturingWebViewClient.lastCreatedDelegate.requestLoading!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: false, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - ); + 'onNavigationRequest from requestLoading should not be called when request is not for main frame', + () { + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + NavigationRequest? callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + androidNavigationDelegate.setOnLoadRequest((_) async {}); + + CapturingWebViewClient.lastCreatedDelegate.requestLoading!( + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: false, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + ); - expect(callbackNavigationRequest, isNull); - }); + expect(callbackNavigationRequest, isNull); + }, + ); test( - 'onLoadRequest from requestLoading should not be called when navigationRequestCallback is not specified', - () { - final Completer completer = Completer(); - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((_) { - completer.complete(); - return completer.future; - }); - - CapturingWebViewClient.lastCreatedDelegate.requestLoading!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: true, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - ); + 'onLoadRequest from requestLoading should not be called when navigationRequestCallback is not specified', + () { + final Completer completer = Completer(); + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((_) { + completer.complete(); + return completer.future; + }); + + CapturingWebViewClient.lastCreatedDelegate.requestLoading!( + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: true, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + ); - expect(completer.isCompleted, false); - }); + expect(completer.isCompleted, false); + }, + ); test( - 'onLoadRequest from requestLoading should not be called when onNavigationRequestCallback returns NavigationDecision.prevent', - () { - final Completer completer = Completer(); - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((_) { - completer.complete(); - return completer.future; - }); - - late final NavigationRequest callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); - - CapturingWebViewClient.lastCreatedDelegate.requestLoading!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: true, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - ); + 'onLoadRequest from requestLoading should not be called when onNavigationRequestCallback returns NavigationDecision.prevent', + () { + final Completer completer = Completer(); + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((_) { + completer.complete(); + return completer.future; + }); + + late final NavigationRequest callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + CapturingWebViewClient.lastCreatedDelegate.requestLoading!( + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: true, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + ); - expect(callbackNavigationRequest.isMainFrame, true); - expect(callbackNavigationRequest.url, 'https://www.google.com'); - expect(completer.isCompleted, false); - }); + expect(callbackNavigationRequest.isMainFrame, true); + expect(callbackNavigationRequest.url, 'https://www.google.com'); + expect(completer.isCompleted, false); + }, + ); test( - 'onLoadRequest from requestLoading should complete when onNavigationRequestCallback returns NavigationDecision.navigate', - () { - final Completer completer = Completer(); - late final LoadRequestParams loadRequestParams; - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) { - loadRequestParams = params; - completer.complete(); - return completer.future; - }); - - late final NavigationRequest callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.navigate; - }); - - CapturingWebViewClient.lastCreatedDelegate.requestLoading!( - CapturingWebViewClient(), - TestWebView(), - android_webview.WebResourceRequest.pigeon_detached( - url: 'https://www.google.com', - isForMainFrame: true, - isRedirect: true, - hasGesture: true, - method: 'GET', - requestHeaders: const {'X-Mock': 'mocking'}, - pigeon_instanceManager: TestInstanceManager(), - ), - ); + 'onLoadRequest from requestLoading should complete when onNavigationRequestCallback returns NavigationDecision.navigate', + () { + final Completer completer = Completer(); + late final LoadRequestParams loadRequestParams; + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) { + loadRequestParams = params; + completer.complete(); + return completer.future; + }); + + late final NavigationRequest callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.navigate; + }); + + CapturingWebViewClient.lastCreatedDelegate.requestLoading!( + CapturingWebViewClient(), + TestWebView(), + android_webview.WebResourceRequest.pigeon_detached( + url: 'https://www.google.com', + isForMainFrame: true, + isRedirect: true, + hasGesture: true, + method: 'GET', + requestHeaders: const {'X-Mock': 'mocking'}, + pigeon_instanceManager: TestInstanceManager(), + ), + ); - expect(loadRequestParams.uri.toString(), 'https://www.google.com'); - expect(loadRequestParams.headers, {'X-Mock': 'mocking'}); - expect(callbackNavigationRequest.isMainFrame, true); - expect(callbackNavigationRequest.url, 'https://www.google.com'); - expect(completer.isCompleted, true); - }); + expect(loadRequestParams.uri.toString(), 'https://www.google.com'); + expect(loadRequestParams.headers, { + 'X-Mock': 'mocking', + }); + expect(callbackNavigationRequest.isMainFrame, true); + expect(callbackNavigationRequest.url, 'https://www.google.com'); + expect(completer.isCompleted, true); + }, + ); test( - 'onNavigationRequest from urlLoading should not be called when loadUrlCallback is not specified', - () { - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - NavigationRequest? callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); - - CapturingWebViewClient.lastCreatedDelegate.urlLoading!( - CapturingWebViewClient(), - TestWebView(), - 'https://www.google.com', - ); + 'onNavigationRequest from urlLoading should not be called when loadUrlCallback is not specified', + () { + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + NavigationRequest? callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + CapturingWebViewClient.lastCreatedDelegate.urlLoading!( + CapturingWebViewClient(), + TestWebView(), + 'https://www.google.com', + ); - expect(callbackNavigationRequest, isNull); - }); + expect(callbackNavigationRequest, isNull); + }, + ); test( - 'onLoadRequest from urlLoading should not be called when navigationRequestCallback is not specified', - () { - final Completer completer = Completer(); - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((_) { - completer.complete(); - return completer.future; - }); - - CapturingWebViewClient.lastCreatedDelegate.urlLoading!( - CapturingWebViewClient(), - TestWebView(), - 'https://www.google.com', - ); + 'onLoadRequest from urlLoading should not be called when navigationRequestCallback is not specified', + () { + final Completer completer = Completer(); + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((_) { + completer.complete(); + return completer.future; + }); + + CapturingWebViewClient.lastCreatedDelegate.urlLoading!( + CapturingWebViewClient(), + TestWebView(), + 'https://www.google.com', + ); - expect(completer.isCompleted, false); - }); + expect(completer.isCompleted, false); + }, + ); test( - 'onLoadRequest from urlLoading should not be called when onNavigationRequestCallback returns NavigationDecision.prevent', - () { - final Completer completer = Completer(); - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((_) { - completer.complete(); - return completer.future; - }); - - late final NavigationRequest callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); - - CapturingWebViewClient.lastCreatedDelegate.urlLoading!( - CapturingWebViewClient(), - TestWebView(), - 'https://www.google.com', - ); + 'onLoadRequest from urlLoading should not be called when onNavigationRequestCallback returns NavigationDecision.prevent', + () { + final Completer completer = Completer(); + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((_) { + completer.complete(); + return completer.future; + }); + + late final NavigationRequest callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + CapturingWebViewClient.lastCreatedDelegate.urlLoading!( + CapturingWebViewClient(), + TestWebView(), + 'https://www.google.com', + ); - expect(callbackNavigationRequest.isMainFrame, true); - expect(callbackNavigationRequest.url, 'https://www.google.com'); - expect(completer.isCompleted, false); - }); + expect(callbackNavigationRequest.isMainFrame, true); + expect(callbackNavigationRequest.url, 'https://www.google.com'); + expect(completer.isCompleted, false); + }, + ); test( - 'onLoadRequest from urlLoading should complete when onNavigationRequestCallback returns NavigationDecision.navigate', - () { - final Completer completer = Completer(); - late final LoadRequestParams loadRequestParams; - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) { - loadRequestParams = params; - completer.complete(); - return completer.future; - }); - - late final NavigationRequest callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.navigate; - }); - - CapturingWebViewClient.lastCreatedDelegate.urlLoading!( - CapturingWebViewClient(), - TestWebView(), - 'https://www.google.com', - ); + 'onLoadRequest from urlLoading should complete when onNavigationRequestCallback returns NavigationDecision.navigate', + () { + final Completer completer = Completer(); + late final LoadRequestParams loadRequestParams; + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) { + loadRequestParams = params; + completer.complete(); + return completer.future; + }); + + late final NavigationRequest callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.navigate; + }); + + CapturingWebViewClient.lastCreatedDelegate.urlLoading!( + CapturingWebViewClient(), + TestWebView(), + 'https://www.google.com', + ); - expect(loadRequestParams.uri.toString(), 'https://www.google.com'); - expect(loadRequestParams.headers, {}); - expect(callbackNavigationRequest.isMainFrame, true); - expect(callbackNavigationRequest.url, 'https://www.google.com'); - expect(completer.isCompleted, true); - }); + expect(loadRequestParams.uri.toString(), 'https://www.google.com'); + expect(loadRequestParams.headers, {}); + expect(callbackNavigationRequest.isMainFrame, true); + expect(callbackNavigationRequest.url, 'https://www.google.com'); + expect(completer.isCompleted, true); + }, + ); test('setOnNavigationRequest should override URL loading', () { final AndroidNavigationDelegate androidNavigationDelegate = @@ -465,115 +491,120 @@ void main() { ); expect( - CapturingWebViewClient.lastCreatedDelegate - .synchronousReturnValueForShouldOverrideUrlLoading, - isTrue); - }); - - test( - 'onLoadRequest from onDownloadStart should not be called when navigationRequestCallback is not specified', - () { - final Completer completer = Completer(); - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((_) { - completer.complete(); - return completer.future; - }); - - CapturingDownloadListener.lastCreatedListener.onDownloadStart( - MockDownloadListener(), - '', - '', - '', - '', - 0, + CapturingWebViewClient + .lastCreatedDelegate + .synchronousReturnValueForShouldOverrideUrlLoading, + isTrue, ); - - expect(completer.isCompleted, false); }); test( - 'onLoadRequest from onDownloadStart should not be called when onNavigationRequestCallback returns NavigationDecision.prevent', - () { - final Completer completer = Completer(); - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((_) { - completer.complete(); - return completer.future; - }); - - late final NavigationRequest callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.prevent; - }); + 'onLoadRequest from onDownloadStart should not be called when navigationRequestCallback is not specified', + () { + final Completer completer = Completer(); + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((_) { + completer.complete(); + return completer.future; + }); + + CapturingDownloadListener.lastCreatedListener.onDownloadStart( + MockDownloadListener(), + '', + '', + '', + '', + 0, + ); - CapturingDownloadListener.lastCreatedListener.onDownloadStart( - MockDownloadListener(), - 'https://www.google.com', - '', - '', - '', - 0, - ); - - expect(callbackNavigationRequest.isMainFrame, true); - expect(callbackNavigationRequest.url, 'https://www.google.com'); - expect(completer.isCompleted, false); - }); + expect(completer.isCompleted, false); + }, + ); test( - 'onLoadRequest from onDownloadStart should complete when onNavigationRequestCallback returns NavigationDecision.navigate', - () { - final Completer completer = Completer(); - late final LoadRequestParams loadRequestParams; - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate(_buildCreationParams()); - - androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) { - loadRequestParams = params; - completer.complete(); - return completer.future; - }); + 'onLoadRequest from onDownloadStart should not be called when onNavigationRequestCallback returns NavigationDecision.prevent', + () { + final Completer completer = Completer(); + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((_) { + completer.complete(); + return completer.future; + }); + + late final NavigationRequest callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.prevent; + }); + + CapturingDownloadListener.lastCreatedListener.onDownloadStart( + MockDownloadListener(), + 'https://www.google.com', + '', + '', + '', + 0, + ); - late final NavigationRequest callbackNavigationRequest; - androidNavigationDelegate - .setOnNavigationRequest((NavigationRequest navigationRequest) { - callbackNavigationRequest = navigationRequest; - return NavigationDecision.navigate; - }); + expect(callbackNavigationRequest.isMainFrame, true); + expect(callbackNavigationRequest.url, 'https://www.google.com'); + expect(completer.isCompleted, false); + }, + ); - CapturingDownloadListener.lastCreatedListener.onDownloadStart( - MockDownloadListener(), - 'https://www.google.com', - '', - '', - '', - 0, - ); + test( + 'onLoadRequest from onDownloadStart should complete when onNavigationRequestCallback returns NavigationDecision.navigate', + () { + final Completer completer = Completer(); + late final LoadRequestParams loadRequestParams; + final AndroidNavigationDelegate androidNavigationDelegate = + AndroidNavigationDelegate(_buildCreationParams()); + + androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) { + loadRequestParams = params; + completer.complete(); + return completer.future; + }); + + late final NavigationRequest callbackNavigationRequest; + androidNavigationDelegate.setOnNavigationRequest(( + NavigationRequest navigationRequest, + ) { + callbackNavigationRequest = navigationRequest; + return NavigationDecision.navigate; + }); + + CapturingDownloadListener.lastCreatedListener.onDownloadStart( + MockDownloadListener(), + 'https://www.google.com', + '', + '', + '', + 0, + ); - expect(loadRequestParams.uri.toString(), 'https://www.google.com'); - expect(loadRequestParams.headers, {}); - expect(callbackNavigationRequest.isMainFrame, true); - expect(callbackNavigationRequest.url, 'https://www.google.com'); - expect(completer.isCompleted, true); - }); + expect(loadRequestParams.uri.toString(), 'https://www.google.com'); + expect(loadRequestParams.headers, {}); + expect(callbackNavigationRequest.isMainFrame, true); + expect(callbackNavigationRequest.url, 'https://www.google.com'); + expect(completer.isCompleted, true); + }, + ); test('onUrlChange', () { final AndroidNavigationDelegate androidNavigationDelegate = AndroidNavigationDelegate(_buildCreationParams()); late final AndroidUrlChange urlChange; - androidNavigationDelegate.setOnUrlChange( - (UrlChange change) { - urlChange = change as AndroidUrlChange; - }, - ); + androidNavigationDelegate.setOnUrlChange((UrlChange change) { + urlChange = change as AndroidUrlChange; + }); CapturingWebViewClient.lastCreatedDelegate.doUpdateVisitedHistory!( CapturingWebViewClient(), @@ -636,27 +667,28 @@ void main() { final Completer errorCompleter = Completer(); - await androidNavigationDelegate.setOnSSlAuthError( - (PlatformSslAuthError error) { - errorCompleter.complete(error); - }, - ); + await androidNavigationDelegate.setOnSSlAuthError(( + PlatformSslAuthError error, + ) { + errorCompleter.complete(error); + }); final Uint8List certificateData = Uint8List(0); const String url = 'https://google.com'; final MockSslError mockSslError = MockSslError(); when(mockSslError.url).thenReturn(url); - when(mockSslError.getPrimaryError()) - .thenAnswer((_) async => android_webview.SslErrorType.dateInvalid); + when( + mockSslError.getPrimaryError(), + ).thenAnswer((_) async => android_webview.SslErrorType.dateInvalid); final MockSslCertificate mockSslCertificate = MockSslCertificate(); final MockX509Certificate mockX509Certificate = MockX509Certificate(); - when(mockX509Certificate.getEncoded()).thenAnswer( - (_) async => certificateData, - ); - when(mockSslCertificate.getX509Certificate()).thenAnswer( - (_) async => mockX509Certificate, - ); + when( + mockX509Certificate.getEncoded(), + ).thenAnswer((_) async => certificateData); + when( + mockSslCertificate.getX509Certificate(), + ).thenAnswer((_) async => mockX509Certificate); when(mockSslError.certificate).thenReturn(mockSslCertificate); final MockSslErrorHandler mockSslErrorHandler = MockSslErrorHandler(); @@ -701,8 +733,7 @@ void main() { } AndroidNavigationDelegateCreationParams _buildCreationParams() { - return AndroidNavigationDelegateCreationParams - .fromPlatformNavigationDelegateCreationParams( + return AndroidNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams( const PlatformNavigationDelegateCreationParams(), androidWebViewProxy: const AndroidWebViewProxy( newWebChromeClient: CapturingWebChromeClient.new, @@ -734,8 +765,10 @@ class CapturingWebViewClient extends android_webview.WebViewClient { super.onReceivedSslError, super.onScaleChanged, }) : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {})) { + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ) { lastCreatedDelegate = this; } @@ -745,7 +778,8 @@ class CapturingWebViewClient extends android_webview.WebViewClient { @override Future setSynchronousReturnValueForShouldOverrideUrlLoading( - bool value) async { + bool value, + ) async { synchronousReturnValueForShouldOverrideUrlLoading = value; } } @@ -765,41 +799,44 @@ class CapturingWebChromeClient extends android_webview.WebChromeClient { required super.onJsConfirm, super.onJsPrompt, }) : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {})) { + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ) { lastCreatedDelegate = this; } static CapturingWebChromeClient lastCreatedDelegate = CapturingWebChromeClient( - onJsConfirm: (_, __, ___, ____) async => false, - onShowFileChooser: (_, __, ___) async => [], - ); + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ); } // Records the last created instance of itself. class CapturingDownloadListener extends android_webview.DownloadListener { - CapturingDownloadListener({ - required super.onDownloadStart, - }) : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {})) { + CapturingDownloadListener({required super.onDownloadStart}) + : super.pigeon_detached( + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ) { lastCreatedListener = this; } static CapturingDownloadListener lastCreatedListener = CapturingDownloadListener( - onDownloadStart: (_, __, ___, ____, _____, ______) {}, - ); + onDownloadStart: (_, __, ___, ____, _____, ______) {}, + ); } class TestWebView extends android_webview.WebView { TestWebView() - : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); + : super.pigeon_detached( + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); } class TestInstanceManager extends android_webview.PigeonInstanceManager { diff --git a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart index e72891b0254..ee1f6258fbf 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart @@ -26,78 +26,43 @@ import 'package:webview_flutter_android/src/android_webkit.g.dart' as _i2; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeHttpAuthHandler_1 extends _i1.SmartFake implements _i2.HttpAuthHandler { - _FakeHttpAuthHandler_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeHttpAuthHandler_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDownloadListener_2 extends _i1.SmartFake implements _i2.DownloadListener { - _FakeDownloadListener_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDownloadListener_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSslCertificate_3 extends _i1.SmartFake implements _i2.SslCertificate { - _FakeSslCertificate_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSslCertificate_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSslError_4 extends _i1.SmartFake implements _i2.SslError { - _FakeSslError_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSslError_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSslErrorHandler_5 extends _i1.SmartFake implements _i2.SslErrorHandler { - _FakeSslErrorHandler_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSslErrorHandler_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeX509Certificate_6 extends _i1.SmartFake implements _i2.X509Certificate { - _FakeX509Certificate_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeX509Certificate_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [HttpAuthHandler]. @@ -109,64 +74,52 @@ class MockHttpAuthHandler extends _i1.Mock implements _i2.HttpAuthHandler { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future useHttpAuthUsernamePassword() => (super.noSuchMethod( - Invocation.method( - #useHttpAuthUsernamePassword, - [], - ), - returnValue: _i3.Future.value(false), - ) as _i3.Future); + _i3.Future useHttpAuthUsernamePassword() => + (super.noSuchMethod( + Invocation.method(#useHttpAuthUsernamePassword, []), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); @override - _i3.Future cancel() => (super.noSuchMethod( - Invocation.method( - #cancel, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future cancel() => + (super.noSuchMethod( + Invocation.method(#cancel, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future proceed( - String? username, - String? password, - ) => + _i3.Future proceed(String? username, String? password) => (super.noSuchMethod( - Invocation.method( - #proceed, - [ - username, - password, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#proceed, [username, password]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.HttpAuthHandler pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeHttpAuthHandler_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.HttpAuthHandler); + _i2.HttpAuthHandler pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeHttpAuthHandler_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.HttpAuthHandler); } /// A class which mocks [DownloadListener]. @@ -178,55 +131,50 @@ class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener { } @override - void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) get onDownloadStart => (super.noSuchMethod( - Invocation.getter(#onDownloadStart), - returnValue: ( - _i2.DownloadListener pigeon_instance, - String url, - String userAgent, - String contentDisposition, - String mimetype, - int contentLength, - ) {}, - ) as void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - )); + void Function(_i2.DownloadListener, String, String, String, String, int) + get onDownloadStart => + (super.noSuchMethod( + Invocation.getter(#onDownloadStart), + returnValue: + ( + _i2.DownloadListener pigeon_instance, + String url, + String userAgent, + String contentDisposition, + String mimetype, + int contentLength, + ) {}, + ) + as void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + )); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i2.DownloadListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeDownloadListener_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.DownloadListener); + _i2.DownloadListener pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeDownloadListener_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.DownloadListener); } /// A class which mocks [SslCertificate]. @@ -238,73 +186,66 @@ class MockSslCertificate extends _i1.Mock implements _i2.SslCertificate { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future<_i2.SslCertificateDName?> getIssuedBy() => (super.noSuchMethod( - Invocation.method( - #getIssuedBy, - [], - ), - returnValue: _i3.Future<_i2.SslCertificateDName?>.value(), - ) as _i3.Future<_i2.SslCertificateDName?>); + _i3.Future<_i2.SslCertificateDName?> getIssuedBy() => + (super.noSuchMethod( + Invocation.method(#getIssuedBy, []), + returnValue: _i3.Future<_i2.SslCertificateDName?>.value(), + ) + as _i3.Future<_i2.SslCertificateDName?>); @override - _i3.Future<_i2.SslCertificateDName?> getIssuedTo() => (super.noSuchMethod( - Invocation.method( - #getIssuedTo, - [], - ), - returnValue: _i3.Future<_i2.SslCertificateDName?>.value(), - ) as _i3.Future<_i2.SslCertificateDName?>); + _i3.Future<_i2.SslCertificateDName?> getIssuedTo() => + (super.noSuchMethod( + Invocation.method(#getIssuedTo, []), + returnValue: _i3.Future<_i2.SslCertificateDName?>.value(), + ) + as _i3.Future<_i2.SslCertificateDName?>); @override - _i3.Future getValidNotAfterMsSinceEpoch() => (super.noSuchMethod( - Invocation.method( - #getValidNotAfterMsSinceEpoch, - [], - ), - returnValue: _i3.Future.value(), - ) as _i3.Future); + _i3.Future getValidNotAfterMsSinceEpoch() => + (super.noSuchMethod( + Invocation.method(#getValidNotAfterMsSinceEpoch, []), + returnValue: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future getValidNotBeforeMsSinceEpoch() => (super.noSuchMethod( - Invocation.method( - #getValidNotBeforeMsSinceEpoch, - [], - ), - returnValue: _i3.Future.value(), - ) as _i3.Future); + _i3.Future getValidNotBeforeMsSinceEpoch() => + (super.noSuchMethod( + Invocation.method(#getValidNotBeforeMsSinceEpoch, []), + returnValue: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future<_i2.X509Certificate?> getX509Certificate() => (super.noSuchMethod( - Invocation.method( - #getX509Certificate, - [], - ), - returnValue: _i3.Future<_i2.X509Certificate?>.value(), - ) as _i3.Future<_i2.X509Certificate?>); + _i3.Future<_i2.X509Certificate?> getX509Certificate() => + (super.noSuchMethod( + Invocation.method(#getX509Certificate, []), + returnValue: _i3.Future<_i2.X509Certificate?>.value(), + ) + as _i3.Future<_i2.X509Certificate?>); @override - _i2.SslCertificate pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeSslCertificate_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.SslCertificate); + _i2.SslCertificate pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeSslCertificate_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.SslCertificate); } /// A class which mocks [SslError]. @@ -316,65 +257,63 @@ class MockSslError extends _i1.Mock implements _i2.SslError { } @override - _i2.SslCertificate get certificate => (super.noSuchMethod( - Invocation.getter(#certificate), - returnValue: _FakeSslCertificate_3( - this, - Invocation.getter(#certificate), - ), - ) as _i2.SslCertificate); + _i2.SslCertificate get certificate => + (super.noSuchMethod( + Invocation.getter(#certificate), + returnValue: _FakeSslCertificate_3( + this, + Invocation.getter(#certificate), + ), + ) + as _i2.SslCertificate); @override - String get url => (super.noSuchMethod( - Invocation.getter(#url), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#url), - ), - ) as String); + String get url => + (super.noSuchMethod( + Invocation.getter(#url), + returnValue: _i4.dummyValue(this, Invocation.getter(#url)), + ) + as String); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future<_i2.SslErrorType> getPrimaryError() => (super.noSuchMethod( - Invocation.method( - #getPrimaryError, - [], - ), - returnValue: - _i3.Future<_i2.SslErrorType>.value(_i2.SslErrorType.dateInvalid), - ) as _i3.Future<_i2.SslErrorType>); + _i3.Future<_i2.SslErrorType> getPrimaryError() => + (super.noSuchMethod( + Invocation.method(#getPrimaryError, []), + returnValue: _i3.Future<_i2.SslErrorType>.value( + _i2.SslErrorType.dateInvalid, + ), + ) + as _i3.Future<_i2.SslErrorType>); @override - _i3.Future hasError(_i2.SslErrorType? error) => (super.noSuchMethod( - Invocation.method( - #hasError, - [error], - ), - returnValue: _i3.Future.value(false), - ) as _i3.Future); + _i3.Future hasError(_i2.SslErrorType? error) => + (super.noSuchMethod( + Invocation.method(#hasError, [error]), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); @override - _i2.SslError pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeSslError_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.SslError); + _i2.SslError pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeSslError_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.SslError); } /// A class which mocks [SslErrorHandler]. @@ -386,48 +325,44 @@ class MockSslErrorHandler extends _i1.Mock implements _i2.SslErrorHandler { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future cancel() => (super.noSuchMethod( - Invocation.method( - #cancel, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future cancel() => + (super.noSuchMethod( + Invocation.method(#cancel, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future proceed() => (super.noSuchMethod( - Invocation.method( - #proceed, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + _i3.Future proceed() => + (super.noSuchMethod( + Invocation.method(#proceed, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.SslErrorHandler pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeSslErrorHandler_5( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.SslErrorHandler); + _i2.SslErrorHandler pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeSslErrorHandler_5( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.SslErrorHandler); } /// A class which mocks [X509Certificate]. @@ -439,35 +374,32 @@ class MockX509Certificate extends _i1.Mock implements _i2.X509Certificate { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i2.X509Certificate pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeX509Certificate_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.X509Certificate); + _i2.X509Certificate pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeX509Certificate_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.X509Certificate); @override - _i3.Future<_i5.Uint8List> getEncoded() => (super.noSuchMethod( - Invocation.method( - #getEncoded, - [], - ), - returnValue: _i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), - ) as _i3.Future<_i5.Uint8List>); + _i3.Future<_i5.Uint8List> getEncoded() => + (super.noSuchMethod( + Invocation.method(#getEncoded, []), + returnValue: _i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), + ) + as _i3.Future<_i5.Uint8List>); } diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart index b7ca4ec92c8..d344c68d6ef 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart @@ -44,241 +44,315 @@ void main() { android_webview.JavaScriptChannel? mockJavaScriptChannel, android_webview.WebChromeClient Function({ void Function( - android_webview.WebChromeClient, android_webview.WebView, int)? - onProgressChanged, + android_webview.WebChromeClient, + android_webview.WebView, + int, + )? + onProgressChanged, required Future> Function( android_webview.WebChromeClient, android_webview.WebView, android_webview.FileChooserParams, - ) onShowFileChooser, - void Function(android_webview.WebChromeClient, - android_webview.PermissionRequest)? - onPermissionRequest, - void Function(android_webview.WebChromeClient, android_webview.View, - android_webview.CustomViewCallback)? - onShowCustomView, + ) + onShowFileChooser, + void Function( + android_webview.WebChromeClient, + android_webview.PermissionRequest, + )? + onPermissionRequest, + void Function( + android_webview.WebChromeClient, + android_webview.View, + android_webview.CustomViewCallback, + )? + onShowCustomView, void Function(android_webview.WebChromeClient)? onHideCustomView, void Function( android_webview.WebChromeClient, String, android_webview.GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, + )? + onGeolocationPermissionsShowPrompt, void Function(android_webview.WebChromeClient)? - onGeolocationPermissionsHidePrompt, + onGeolocationPermissionsHidePrompt, void Function( - android_webview.WebChromeClient, android_webview.ConsoleMessage)? - onConsoleMessage, - Future Function(android_webview.WebChromeClient, - android_webview.WebView, String, String)? - onJsAlert, + android_webview.WebChromeClient, + android_webview.ConsoleMessage, + )? + onConsoleMessage, + Future Function( + android_webview.WebChromeClient, + android_webview.WebView, + String, + String, + )? + onJsAlert, required Future Function( android_webview.WebChromeClient, android_webview.WebView, String, String, - ) onJsConfirm, + ) + onJsConfirm, Future Function( android_webview.WebChromeClient, android_webview.WebView, String, String, String, - )? onJsPrompt, - })? createWebChromeClient, + )? + onJsPrompt, + })? + createWebChromeClient, android_webview.WebView? mockWebView, android_webview.WebViewClient? mockWebViewClient, android_webview.WebStorage? mockWebStorage, android_webview.WebSettings? mockSettings, Future Function(String)? isWebViewFeatureSupported, Future Function(android_webview.WebSettings, bool)? - setPaymentRequestEnabled, + setPaymentRequestEnabled, }) { final android_webview.WebView nonNullMockWebView = mockWebView ?? MockWebView(); - final AndroidWebViewControllerCreationParams creationParams = - AndroidWebViewControllerCreationParams( - androidWebStorage: mockWebStorage ?? MockWebStorage(), - androidWebViewProxy: AndroidWebViewProxy( - newWebChromeClient: createWebChromeClient ?? - ({ - void Function(android_webview.WebChromeClient, - android_webview.WebView, int)? - onProgressChanged, - Future> Function( - android_webview.WebChromeClient, - android_webview.WebView, - android_webview.FileChooserParams, - )? onShowFileChooser, - void Function(android_webview.WebChromeClient, - android_webview.PermissionRequest)? - onPermissionRequest, - void Function( - android_webview.WebChromeClient, - android_webview.View, - android_webview.CustomViewCallback)? - onShowCustomView, - void Function(android_webview.WebChromeClient)? - onHideCustomView, - void Function( - android_webview.WebChromeClient, - String, - android_webview.GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, - void Function(android_webview.WebChromeClient)? - onGeolocationPermissionsHidePrompt, - void Function(android_webview.WebChromeClient, - android_webview.ConsoleMessage)? - onConsoleMessage, - Future Function(android_webview.WebChromeClient, - android_webview.WebView, String, String)? - onJsAlert, - Future Function( - android_webview.WebChromeClient, - android_webview.WebView, - String, - String, - )? onJsConfirm, - Future Function( - android_webview.WebChromeClient, - android_webview.WebView, - String, - String, - String, - )? onJsPrompt, - }) => - MockWebChromeClient(), - newWebView: ( - {dynamic Function(android_webview.WebView, int left, - int top, int oldLeft, int oldTop)? - onScrollChanged}) => - nonNullMockWebView, - newWebViewClient: ({ - void Function(android_webview.WebViewClient, - android_webview.WebView, String)? - onPageStarted, - void Function(android_webview.WebViewClient, - android_webview.WebView, String)? - onPageFinished, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.WebResourceRequest, - android_webview.WebResourceResponse, - )? onReceivedHttpError, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.WebResourceRequest, - android_webview.WebResourceError, - )? onReceivedRequestError, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.WebResourceRequest, - android_webview.WebResourceErrorCompat, - )? onReceivedRequestErrorCompat, - void Function(android_webview.WebViewClient, - android_webview.WebView, int, String, String)? - onReceivedError, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.WebResourceRequest)? - requestLoading, - void Function(android_webview.WebViewClient, - android_webview.WebView, String)? - urlLoading, - void Function(android_webview.WebViewClient, - android_webview.WebView, String, bool)? - doUpdateVisitedHistory, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.HttpAuthHandler, - String, - String)? - onReceivedHttpAuthRequest, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.AndroidMessage, - android_webview.AndroidMessage, - )? onFormResubmission, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - String, - )? onLoadResource, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - String, - )? onPageCommitVisible, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.ClientCertRequest, - )? onReceivedClientCertRequest, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - String, - String, - String, - )? onReceivedLoginRequest, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.SslErrorHandler, - android_webview.SslError, - )? onReceivedSslError, - void Function( - android_webview.WebViewClient, - android_webview.WebView, - double, - double, - )? onScaleChanged, - }) => - mockWebViewClient ?? MockWebViewClient(), - instanceFlutterAssetManager: () => - mockFlutterAssetManager ?? MockFlutterAssetManager(), - newJavaScriptChannel: ({ - required String channelName, - required void Function( - android_webview.JavaScriptChannel, String) - postMessage, - }) => - mockJavaScriptChannel ?? MockJavaScriptChannel(), - isWebViewFeatureSupported: - isWebViewFeatureSupported ?? (_) async => false, - setPaymentRequestEnabled: - setPaymentRequestEnabled ?? (_, __) async {}, - )); - - when(nonNullMockWebView.settings) - .thenReturn(mockSettings ?? MockWebSettings()); + final AndroidWebViewControllerCreationParams + creationParams = AndroidWebViewControllerCreationParams( + androidWebStorage: mockWebStorage ?? MockWebStorage(), + androidWebViewProxy: AndroidWebViewProxy( + newWebChromeClient: + createWebChromeClient ?? + ({ + void Function( + android_webview.WebChromeClient, + android_webview.WebView, + int, + )? + onProgressChanged, + Future> Function( + android_webview.WebChromeClient, + android_webview.WebView, + android_webview.FileChooserParams, + )? + onShowFileChooser, + void Function( + android_webview.WebChromeClient, + android_webview.PermissionRequest, + )? + onPermissionRequest, + void Function( + android_webview.WebChromeClient, + android_webview.View, + android_webview.CustomViewCallback, + )? + onShowCustomView, + void Function(android_webview.WebChromeClient)? onHideCustomView, + void Function( + android_webview.WebChromeClient, + String, + android_webview.GeolocationPermissionsCallback, + )? + onGeolocationPermissionsShowPrompt, + void Function(android_webview.WebChromeClient)? + onGeolocationPermissionsHidePrompt, + void Function( + android_webview.WebChromeClient, + android_webview.ConsoleMessage, + )? + onConsoleMessage, + Future Function( + android_webview.WebChromeClient, + android_webview.WebView, + String, + String, + )? + onJsAlert, + Future Function( + android_webview.WebChromeClient, + android_webview.WebView, + String, + String, + )? + onJsConfirm, + Future Function( + android_webview.WebChromeClient, + android_webview.WebView, + String, + String, + String, + )? + onJsPrompt, + }) => MockWebChromeClient(), + newWebView: + ({ + dynamic Function( + android_webview.WebView, + int left, + int top, + int oldLeft, + int oldTop, + )? + onScrollChanged, + }) => nonNullMockWebView, + newWebViewClient: + ({ + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? + onPageStarted, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? + onPageFinished, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.WebResourceRequest, + android_webview.WebResourceResponse, + )? + onReceivedHttpError, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.WebResourceRequest, + android_webview.WebResourceError, + )? + onReceivedRequestError, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.WebResourceRequest, + android_webview.WebResourceErrorCompat, + )? + onReceivedRequestErrorCompat, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + int, + String, + String, + )? + onReceivedError, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.WebResourceRequest, + )? + requestLoading, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? + urlLoading, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + bool, + )? + doUpdateVisitedHistory, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.HttpAuthHandler, + String, + String, + )? + onReceivedHttpAuthRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.AndroidMessage, + android_webview.AndroidMessage, + )? + onFormResubmission, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? + onLoadResource, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? + onPageCommitVisible, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.ClientCertRequest, + )? + onReceivedClientCertRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + String, + String, + )? + onReceivedLoginRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.SslErrorHandler, + android_webview.SslError, + )? + onReceivedSslError, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + double, + double, + )? + onScaleChanged, + }) => mockWebViewClient ?? MockWebViewClient(), + instanceFlutterAssetManager: + () => mockFlutterAssetManager ?? MockFlutterAssetManager(), + newJavaScriptChannel: + ({ + required String channelName, + required void Function(android_webview.JavaScriptChannel, String) + postMessage, + }) => mockJavaScriptChannel ?? MockJavaScriptChannel(), + isWebViewFeatureSupported: + isWebViewFeatureSupported ?? (_) async => false, + setPaymentRequestEnabled: setPaymentRequestEnabled ?? (_, __) async {}, + ), + ); + + when( + nonNullMockWebView.settings, + ).thenReturn(mockSettings ?? MockWebSettings()); return AndroidWebViewController(creationParams); } group('AndroidWebViewController', () { AndroidJavaScriptChannelParams - createAndroidJavaScriptChannelParamsWithMocks({ + createAndroidJavaScriptChannelParamsWithMocks({ String? name, MockJavaScriptChannel? mockJavaScriptChannel, }) { return AndroidJavaScriptChannelParams( - name: name ?? 'test', - onMessageReceived: (JavaScriptMessage message) {}, - webViewProxy: AndroidWebViewProxy( - newJavaScriptChannel: ({ - required String channelName, - required void Function(android_webview.JavaScriptChannel, String) - postMessage, - }) => - mockJavaScriptChannel ?? MockJavaScriptChannel(), - )); + name: name ?? 'test', + onMessageReceived: (JavaScriptMessage message) {}, + webViewProxy: AndroidWebViewProxy( + newJavaScriptChannel: + ({ + required String channelName, + required void Function( + android_webview.JavaScriptChannel, + String, + ) + postMessage, + }) => mockJavaScriptChannel ?? MockJavaScriptChannel(), + ), + ); } test('Initializing WebView settings on controller creation', () async { @@ -292,8 +366,9 @@ void main() { verify(mockWebSettings.setBuiltInZoomControls(true)).called(1); verify(mockWebSettings.setDisplayZoomControls(false)).called(1); verify(mockWebSettings.setDomStorageEnabled(true)).called(1); - verify(mockWebSettings.setJavaScriptCanOpenWindowsAutomatically(true)) - .called(1); + verify( + mockWebSettings.setJavaScriptCanOpenWindowsAutomatically(true), + ).called(1); verify(mockWebSettings.setLoadWithOverviewMode(true)).called(1); verify(mockWebSettings.setSupportMultipleWindows(true)).called(1); verify(mockWebSettings.setUseWideViewPort(false)).called(1); @@ -311,10 +386,9 @@ void main() { await controller.loadFile('/path/to/file.html'); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl('file:///path/to/file.html', {}), + ).called(1); }); test('Without file prefix and characters to be escaped', () async { @@ -328,10 +402,12 @@ void main() { await controller.loadFile('/path/to/?_<_>_.html'); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/%3F_%3C_%3E_.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/%3F_%3C_%3E_.html', + {}, + ), + ).called(1); }); test('With file prefix', () async { @@ -346,10 +422,9 @@ void main() { await controller.loadFile('file:///path/to/file.html'); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl('file:///path/to/file.html', {}), + ).called(1); }); }); @@ -368,10 +443,12 @@ void main() { ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/file.html', + {}, + ), + ).called(1); }); test('Without file prefix and characters to be escaped', () async { @@ -387,10 +464,12 @@ void main() { ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/%3F_%3C_%3E_.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/%3F_%3C_%3E_.html', + {}, + ), + ).called(1); }); test('With file prefix', () async { @@ -406,10 +485,12 @@ void main() { ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/file.html', + {}, + ), + ).called(1); }); }); @@ -427,10 +508,12 @@ void main() { ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/file.html', + {}, + ), + ).called(1); }); test('Without file prefix and characters to be escaped', () async { @@ -446,10 +529,12 @@ void main() { ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/%3F_%3C_%3E_.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/%3F_%3C_%3E_.html', + {}, + ), + ).called(1); }); test('With file prefix', () async { @@ -462,14 +547,17 @@ void main() { await controller.loadFileWithParams( AndroidLoadFileParams( - absoluteFilePath: 'file:///path/to/file.html'), + absoluteFilePath: 'file:///path/to/file.html', + ), ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )).called(1); + verify( + mockWebView.loadUrl( + 'file:///path/to/file.html', + {}, + ), + ).called(1); }); test('With additional headers', () async { @@ -492,14 +580,14 @@ void main() { ); verify(mockWebSettings.setAllowFileAccess(true)).called(1); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - const { - 'Authorization': 'Bearer test_token', - 'Cache-Control': 'no-cache', - 'X-Custom-Header': 'test-value', - }, - )).called(1); + verify( + mockWebView + .loadUrl('file:///path/to/file.html', const { + 'Authorization': 'Bearer test_token', + 'Cache-Control': 'no-cache', + 'X-Custom-Header': 'test-value', + }), + ).called(1); }); }); }); @@ -513,10 +601,12 @@ void main() { mockWebView: mockWebView, ); - when(mockAssetManager.getAssetFilePathByName('mock_key')) - .thenAnswer((_) => Future.value('')); - when(mockAssetManager.list('')) - .thenAnswer((_) => Future>.value([])); + when( + mockAssetManager.getAssetFilePathByName('mock_key'), + ).thenAnswer((_) => Future.value('')); + when( + mockAssetManager.list(''), + ).thenAnswer((_) => Future>.value([])); try { await controller.loadFlutterAsset('mock_key'); @@ -542,42 +632,55 @@ void main() { mockWebView: mockWebView, ); - when(mockAssetManager.getAssetFilePathByName('mock_key')) - .thenAnswer((_) => Future.value('www/mock_file.html')); + when( + mockAssetManager.getAssetFilePathByName('mock_key'), + ).thenAnswer((_) => Future.value('www/mock_file.html')); when(mockAssetManager.list('www')).thenAnswer( - (_) => Future>.value(['mock_file.html'])); + (_) => Future>.value(['mock_file.html']), + ); await controller.loadFlutterAsset('mock_key'); verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1); verify(mockAssetManager.list('www')).called(1); - verify(mockWebView.loadUrl( - 'file:///android_asset/www/mock_file.html', {})); + verify( + mockWebView.loadUrl( + 'file:///android_asset/www/mock_file.html', + {}, + ), + ); }); test( - 'loadFlutterAsset when asset name contains characters that should be escaped', - () async { - final MockWebView mockWebView = MockWebView(); - final MockFlutterAssetManager mockAssetManager = - MockFlutterAssetManager(); - final AndroidWebViewController controller = createControllerWithMocks( - mockFlutterAssetManager: mockAssetManager, - mockWebView: mockWebView, - ); + 'loadFlutterAsset when asset name contains characters that should be escaped', + () async { + final MockWebView mockWebView = MockWebView(); + final MockFlutterAssetManager mockAssetManager = + MockFlutterAssetManager(); + final AndroidWebViewController controller = createControllerWithMocks( + mockFlutterAssetManager: mockAssetManager, + mockWebView: mockWebView, + ); - when(mockAssetManager.getAssetFilePathByName('mock_key')) - .thenAnswer((_) => Future.value('www/?_<_>_.html')); - when(mockAssetManager.list('www')).thenAnswer( - (_) => Future>.value(['?_<_>_.html'])); + when( + mockAssetManager.getAssetFilePathByName('mock_key'), + ).thenAnswer((_) => Future.value('www/?_<_>_.html')); + when(mockAssetManager.list('www')).thenAnswer( + (_) => Future>.value(['?_<_>_.html']), + ); - await controller.loadFlutterAsset('mock_key'); + await controller.loadFlutterAsset('mock_key'); - verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1); - verify(mockAssetManager.list('www')).called(1); - verify(mockWebView.loadUrl( - 'file:///android_asset/www/%3F_%3C_%3E_.html', {})); - }); + verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1); + verify(mockAssetManager.list('www')).called(1); + verify( + mockWebView.loadUrl( + 'file:///android_asset/www/%3F_%3C_%3E_.html', + {}, + ), + ); + }, + ); test('loadHtmlString without baseUrl', () async { final MockWebView mockWebView = MockWebView(); @@ -587,13 +690,15 @@ void main() { await controller.loadHtmlString('

Hello Test!

'); - verify(mockWebView.loadDataWithBaseUrl( - null, - '

Hello Test!

', - 'text/html', - null, - null, - )).called(1); + verify( + mockWebView.loadDataWithBaseUrl( + null, + '

Hello Test!

', + 'text/html', + null, + null, + ), + ).called(1); }); test('loadHtmlString with baseUrl', () async { @@ -602,16 +707,20 @@ void main() { mockWebView: mockWebView, ); - await controller.loadHtmlString('

Hello Test!

', - baseUrl: 'https://flutter.dev'); - - verify(mockWebView.loadDataWithBaseUrl( - 'https://flutter.dev', + await controller.loadHtmlString( '

Hello Test!

', - 'text/html', - null, - null, - )).called(1); + baseUrl: 'https://flutter.dev', + ); + + verify( + mockWebView.loadDataWithBaseUrl( + 'https://flutter.dev', + '

Hello Test!

', + 'text/html', + null, + null, + ), + ).called(1); }); test('loadRequest without URI scheme', () async { @@ -648,10 +757,11 @@ void main() { await controller.loadRequest(requestParams); - verify(mockWebView.loadUrl( - 'https://flutter.dev', - {'X-Test': 'Testing'}, - )); + verify( + mockWebView.loadUrl('https://flutter.dev', { + 'X-Test': 'Testing', + }), + ); verifyNever(mockWebView.postUrl(any, any)); }); @@ -668,10 +778,7 @@ void main() { await controller.loadRequest(requestParams); - verify(mockWebView.postUrl( - 'https://flutter.dev', - Uint8List(0), - )); + verify(mockWebView.postUrl('https://flutter.dev', Uint8List(0))); verifyNever(mockWebView.loadUrl(any, any)); }); @@ -689,10 +796,12 @@ void main() { await controller.loadRequest(requestParams); - verify(mockWebView.postUrl( - 'https://flutter.dev', - Uint8List.fromList('{"message": "Hello World!"}'.codeUnits), - )); + verify( + mockWebView.postUrl( + 'https://flutter.dev', + Uint8List.fromList('{"message": "Hello World!"}'.codeUnits), + ), + ); verifyNever(mockWebView.loadUrl(any, any)); }); @@ -794,10 +903,12 @@ void main() { mockWebView: mockWebView, ); - when(mockNavigationDelegate.androidWebChromeClient) - .thenReturn(mockWebChromeClient); - when(mockNavigationDelegate.androidWebViewClient) - .thenReturn(mockWebViewClient); + when( + mockNavigationDelegate.androidWebChromeClient, + ).thenReturn(mockWebChromeClient); + when( + mockNavigationDelegate.androidWebViewClient, + ).thenReturn(mockWebViewClient); await controller.setPlatformNavigationDelegate(mockNavigationDelegate); @@ -806,10 +917,9 @@ void main() { }); test('onProgress', () { - final AndroidNavigationDelegate androidNavigationDelegate = - AndroidNavigationDelegate( - AndroidNavigationDelegateCreationParams - .fromPlatformNavigationDelegateCreationParams( + final AndroidNavigationDelegate + androidNavigationDelegate = AndroidNavigationDelegate( + AndroidNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams( const PlatformNavigationDelegateCreationParams(), androidWebViewProxy: const AndroidWebViewProxy( newWebViewClient: TestWebViewClient.new, @@ -820,8 +930,9 @@ void main() { ); late final int callbackProgress; - androidNavigationDelegate - .setOnProgress((int progress) => callbackProgress = progress); + androidNavigationDelegate.setOnProgress( + (int progress) => callbackProgress = progress, + ); final AndroidWebViewController controller = createControllerWithMocks( createWebChromeClient: CapturingWebChromeClient.new, @@ -862,7 +973,8 @@ void main() { android_webview.WebChromeClient, android_webview.WebView webView, android_webview.FileChooserParams params, - ) onShowFileChooserCallback; + ) + onShowFileChooserCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( createWebChromeClient: ({ @@ -871,7 +983,8 @@ void main() { android_webview.WebChromeClient, android_webview.WebView webView, android_webview.FileChooserParams params, - )? onShowFileChooser, + )? + onShowFileChooser, dynamic onGeolocationPermissionsShowPrompt, dynamic onGeolocationPermissionsHidePrompt, dynamic onPermissionRequest, @@ -888,12 +1001,10 @@ void main() { ); late final FileSelectorParams fileSelectorParams; - await controller.setOnShowFileSelector( - (FileSelectorParams params) async { - fileSelectorParams = params; - return []; - }, - ); + await controller.setOnShowFileSelector((FileSelectorParams params) async { + fileSelectorParams = params; + return []; + }); verify( mockWebChromeClient.setSynchronousReturnValueForOnShowFileChooser(true), @@ -919,12 +1030,13 @@ void main() { test('setGeolocationPermissionsPromptCallbacks', () async { late final Future Function( - android_webview.WebChromeClient, - String origin, - android_webview.GeolocationPermissionsCallback callback) - onGeoPermissionHandle; + android_webview.WebChromeClient, + String origin, + android_webview.GeolocationPermissionsCallback callback, + ) + onGeoPermissionHandle; late final void Function(android_webview.WebChromeClient instance) - onGeoPermissionHidePromptHandle; + onGeoPermissionHidePromptHandle; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( @@ -935,9 +1047,10 @@ void main() { android_webview.WebChromeClient, String origin, android_webview.GeolocationPermissionsCallback callback, - )? onGeolocationPermissionsShowPrompt, + )? + onGeolocationPermissionsShowPrompt, void Function(android_webview.WebChromeClient instance)? - onGeolocationPermissionsHidePrompt, + onGeolocationPermissionsHidePrompt, dynamic onPermissionRequest, dynamic onShowCustomView, dynamic onHideCustomView, @@ -947,11 +1060,12 @@ void main() { dynamic onJsPrompt, }) { onGeoPermissionHandle = - onGeolocationPermissionsShowPrompt! as Future Function( - android_webview.WebChromeClient, - String origin, - android_webview.GeolocationPermissionsCallback callback, - ); + onGeolocationPermissionsShowPrompt! + as Future Function( + android_webview.WebChromeClient, + String origin, + android_webview.GeolocationPermissionsCallback callback, + ); onGeoPermissionHidePromptHandle = onGeolocationPermissionsHidePrompt!; return mockWebChromeClient; }, @@ -965,8 +1079,10 @@ void main() { await controller.setGeolocationPermissionsPromptCallbacks( onShowPrompt: (GeolocationPermissionsRequestParams request) async { isAllow = request.origin == allowOrigin; - response = - GeolocationPermissionsResponse(allow: isAllow, retain: isAllow); + response = GeolocationPermissionsResponse( + allow: isAllow, + retain: isAllow, + ); return response; }, onHidePrompt: () { @@ -991,11 +1107,13 @@ void main() { test('setCustomViewCallbacks', () async { late final void Function( - android_webview.WebChromeClient instance, - android_webview.View view, - android_webview.CustomViewCallback callback) onShowCustomViewHandle; + android_webview.WebChromeClient instance, + android_webview.View view, + android_webview.CustomViewCallback callback, + ) + onShowCustomViewHandle; late final void Function(android_webview.WebChromeClient instance) - onHideCustomViewHandle; + onHideCustomViewHandle; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( @@ -1009,12 +1127,13 @@ void main() { dynamic onJsConfirm, dynamic onJsPrompt, void Function( - android_webview.WebChromeClient instance, - android_webview.View view, - android_webview.CustomViewCallback callback)? - onShowCustomView, + android_webview.WebChromeClient instance, + android_webview.View view, + android_webview.CustomViewCallback callback, + )? + onShowCustomView, void Function(android_webview.WebChromeClient instance)? - onHideCustomView, + onHideCustomView, dynamic onConsoleMessage, }) { onShowCustomViewHandle = onShowCustomView!; @@ -1023,16 +1142,16 @@ void main() { }, ); - final android_webview.View testView = - android_webview.View.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); + final android_webview.View testView = android_webview + .View.pigeon_detached(pigeon_instanceManager: testInstanceManager); bool showCustomViewCalled = false; bool hideCustomViewCalled = false; await controller.setCustomWidgetCallbacks( - onShowCustomWidget: - (Widget widget, OnHideCustomWidgetCallback callback) async { + onShowCustomWidget: ( + Widget widget, + OnHideCustomWidgetCallback callback, + ) async { showCustomViewCalled = true; }, onHideCustomWidget: () { @@ -1058,7 +1177,8 @@ void main() { late final void Function( android_webview.WebChromeClient instance, android_webview.PermissionRequest request, - ) onPermissionRequestCallback; + ) + onPermissionRequestCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( @@ -1070,7 +1190,8 @@ void main() { void Function( android_webview.WebChromeClient instance, android_webview.PermissionRequest request, - )? onPermissionRequest, + )? + onPermissionRequest, dynamic onShowCustomView, dynamic onHideCustomView, dynamic onConsoleMessage, @@ -1084,12 +1205,12 @@ void main() { ); late final PlatformWebViewPermissionRequest permissionRequest; - await controller.setOnPlatformPermissionRequest( - (PlatformWebViewPermissionRequest request) async { - permissionRequest = request; - await request.grant(); - }, - ); + await controller.setOnPlatformPermissionRequest(( + PlatformWebViewPermissionRequest request, + ) async { + permissionRequest = request; + await request.grant(); + }); final List permissionTypes = [ PermissionRequestConstants.audioCapture, @@ -1101,9 +1222,10 @@ void main() { onPermissionRequestCallback( android_webview.WebChromeClient.pigeon_detached( - onJsConfirm: (_, __, ___, ____) async => false, - onShowFileChooser: (_, __, ___) async => [], - pigeon_instanceManager: testInstanceManager), + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + pigeon_instanceManager: testInstanceManager, + ), mockPermissionRequest, ); @@ -1114,58 +1236,63 @@ void main() { }); test( - 'setOnPlatformPermissionRequest callback not invoked when type is not recognized', - () async { - late final void Function( - android_webview.WebChromeClient instance, - android_webview.PermissionRequest request, - ) onPermissionRequestCallback; + 'setOnPlatformPermissionRequest callback not invoked when type is not recognized', + () async { + late final void Function( + android_webview.WebChromeClient instance, + android_webview.PermissionRequest request, + ) + onPermissionRequestCallback; - final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); - final AndroidWebViewController controller = createControllerWithMocks( - createWebChromeClient: ({ - dynamic onProgressChanged, - dynamic onShowFileChooser, - dynamic onGeolocationPermissionsShowPrompt, - dynamic onGeolocationPermissionsHidePrompt, - void Function( - android_webview.WebChromeClient instance, - android_webview.PermissionRequest request, - )? onPermissionRequest, - dynamic onShowCustomView, - dynamic onHideCustomView, - dynamic onConsoleMessage, - dynamic onJsAlert, - dynamic onJsConfirm, - dynamic onJsPrompt, - }) { - onPermissionRequestCallback = onPermissionRequest!; - return mockWebChromeClient; - }, - ); + final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); + final AndroidWebViewController controller = createControllerWithMocks( + createWebChromeClient: ({ + dynamic onProgressChanged, + dynamic onShowFileChooser, + dynamic onGeolocationPermissionsShowPrompt, + dynamic onGeolocationPermissionsHidePrompt, + void Function( + android_webview.WebChromeClient instance, + android_webview.PermissionRequest request, + )? + onPermissionRequest, + dynamic onShowCustomView, + dynamic onHideCustomView, + dynamic onConsoleMessage, + dynamic onJsAlert, + dynamic onJsConfirm, + dynamic onJsPrompt, + }) { + onPermissionRequestCallback = onPermissionRequest!; + return mockWebChromeClient; + }, + ); - bool callbackCalled = false; - await controller.setOnPlatformPermissionRequest( - (PlatformWebViewPermissionRequest request) async { + bool callbackCalled = false; + await controller.setOnPlatformPermissionRequest(( + PlatformWebViewPermissionRequest request, + ) async { callbackCalled = true; - }, - ); + }); - final MockPermissionRequest mockPermissionRequest = - MockPermissionRequest(); - when(mockPermissionRequest.resources).thenReturn(['unknownType']); + final MockPermissionRequest mockPermissionRequest = + MockPermissionRequest(); + when( + mockPermissionRequest.resources, + ).thenReturn(['unknownType']); - onPermissionRequestCallback( - android_webview.WebChromeClient.pigeon_detached( - onJsConfirm: (_, __, ___, ____) async => false, - onShowFileChooser: (_, __, ___) async => [], - pigeon_instanceManager: testInstanceManager, - ), - mockPermissionRequest, - ); + onPermissionRequestCallback( + android_webview.WebChromeClient.pigeon_detached( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + pigeon_instanceManager: testInstanceManager, + ), + mockPermissionRequest, + ); - expect(callbackCalled, isFalse); - }); + expect(callbackCalled, isFalse); + }, + ); group('JavaScript Dialog', () { test('setOnJavaScriptAlertDialog', () async { @@ -1174,7 +1301,8 @@ void main() { android_webview.WebView, String url, String message, - ) onJsAlertCallback; + ) + onJsAlertCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); @@ -1187,9 +1315,13 @@ void main() { dynamic onPermissionRequest, dynamic onShowCustomView, dynamic onHideCustomView, - Future Function(android_webview.WebChromeClient, - android_webview.WebView, String url, String message)? - onJsAlert, + Future Function( + android_webview.WebChromeClient, + android_webview.WebView, + String url, + String message, + )? + onJsAlert, dynamic onJsConfirm, dynamic onJsPrompt, dynamic onConsoleMessage, @@ -1200,8 +1332,9 @@ void main() { ); late final String message; - await controller.setOnJavaScriptAlertDialog( - (JavaScriptAlertDialogRequest request) async { + await controller.setOnJavaScriptAlertDialog(( + JavaScriptAlertDialogRequest request, + ) async { message = request.message; return; }); @@ -1218,10 +1351,12 @@ void main() { test('setOnJavaScriptConfirmDialog', () async { late final Future Function( - android_webview.WebChromeClient, - android_webview.WebView, - String url, - String message) onJsConfirmCallback; + android_webview.WebChromeClient, + android_webview.WebView, + String url, + String message, + ) + onJsConfirmCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); @@ -1235,9 +1370,13 @@ void main() { dynamic onShowCustomView, dynamic onHideCustomView, dynamic onJsAlert, - Future Function(android_webview.WebChromeClient, - android_webview.WebView, String url, String message)? - onJsConfirm, + Future Function( + android_webview.WebChromeClient, + android_webview.WebView, + String url, + String message, + )? + onJsConfirm, dynamic onJsPrompt, dynamic onConsoleMessage, }) { @@ -1248,15 +1387,20 @@ void main() { late final String message; const bool callbackReturnValue = true; - await controller.setOnJavaScriptConfirmDialog( - (JavaScriptConfirmDialogRequest request) async { + await controller.setOnJavaScriptConfirmDialog(( + JavaScriptConfirmDialogRequest request, + ) async { message = request.message; return callbackReturnValue; }); const String callbackMessage = 'Message'; final bool returnValue = await onJsConfirmCallback( - MockWebChromeClient(), MockWebView(), '', callbackMessage); + MockWebChromeClient(), + MockWebView(), + '', + callbackMessage, + ); expect(message, callbackMessage); expect(returnValue, callbackReturnValue); @@ -1264,11 +1408,13 @@ void main() { test('setOnJavaScriptTextInputDialog', () async { late final Future Function( - android_webview.WebChromeClient, - android_webview.WebView, - String url, - String message, - String defaultValue) onJsPromptCallback; + android_webview.WebChromeClient, + android_webview.WebView, + String url, + String message, + String defaultValue, + ) + onJsPromptCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( @@ -1288,7 +1434,8 @@ void main() { String url, String message, String defaultText, - )? onJsPrompt, + )? + onJsPrompt, dynamic onConsoleMessage, }) { onJsPromptCallback = onJsPrompt!; @@ -1299,8 +1446,9 @@ void main() { late final String message; late final String? defaultText; const String callbackReturnValue = 'Return Value'; - await controller.setOnJavaScriptTextInputDialog( - (JavaScriptTextInputDialogRequest request) async { + await controller.setOnJavaScriptTextInputDialog(( + JavaScriptTextInputDialogRequest request, + ) async { message = request.message; defaultText = request.defaultText; return callbackReturnValue; @@ -1310,11 +1458,12 @@ void main() { const String callbackDefaultText = 'Default Text'; final String? returnValue = await onJsPromptCallback( - MockWebChromeClient(), - MockWebView(), - '', - callbackMessage, - callbackDefaultText); + MockWebChromeClient(), + MockWebView(), + '', + callbackMessage, + callbackDefaultText, + ); expect(message, callbackMessage); expect(defaultText, callbackDefaultText); @@ -1326,7 +1475,8 @@ void main() { late final void Function( android_webview.WebChromeClient instance, android_webview.ConsoleMessage message, - ) onConsoleMessageCallback; + ) + onConsoleMessageCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( @@ -1344,7 +1494,8 @@ void main() { void Function( android_webview.WebChromeClient, android_webview.ConsoleMessage, - )? onConsoleMessage, + )? + onConsoleMessage, }) { onConsoleMessageCallback = onConsoleMessage!; return mockWebChromeClient; @@ -1353,11 +1504,11 @@ void main() { final Map logs = {}; - await controller.setOnConsoleMessage( - (JavaScriptConsoleMessage message) async { - logs[message.message] = message.level; - }, - ); + await controller.setOnConsoleMessage(( + JavaScriptConsoleMessage message, + ) async { + logs[message.message] = message.level; + }); onConsoleMessageCallback( mockWebChromeClient, @@ -1402,11 +1553,12 @@ void main() { onConsoleMessageCallback( mockWebChromeClient, android_webview.ConsoleMessage.pigeon_detached( - lineNumber: 42, - message: 'Warning message', - level: android_webview.ConsoleMessageLevel.warning, - sourceId: 'source', - pigeon_instanceManager: testInstanceManager), + lineNumber: 42, + message: 'Warning message', + level: android_webview.ConsoleMessageLevel.warning, + sourceId: 'source', + pigeon_instanceManager: testInstanceManager, + ), ); onConsoleMessageCallback( mockWebChromeClient, @@ -1436,8 +1588,9 @@ void main() { await controller.runJavaScript('alert("This is a test.");'); - verify(mockWebView.evaluateJavascript('alert("This is a test.");')) - .called(1); + verify( + mockWebView.evaluateJavascript('alert("This is a test.");'), + ).called(1); }); test('runJavaScriptReturningResult with return value', () async { @@ -1446,11 +1599,15 @@ void main() { mockWebView: mockWebView, ); - when(mockWebView.evaluateJavascript('return "Hello" + " World!";')) - .thenAnswer((_) => Future.value('Hello World!')); + when( + mockWebView.evaluateJavascript('return "Hello" + " World!";'), + ).thenAnswer((_) => Future.value('Hello World!')); - final String message = await controller.runJavaScriptReturningResult( - 'return "Hello" + " World!";') as String; + final String message = + await controller.runJavaScriptReturningResult( + 'return "Hello" + " World!";', + ) + as String; expect(message, 'Hello World!'); }); @@ -1461,11 +1618,15 @@ void main() { mockWebView: mockWebView, ); - when(mockWebView.evaluateJavascript('alert("This is a test.");')) - .thenAnswer((_) => Future.value()); + when( + mockWebView.evaluateJavascript('alert("This is a test.");'), + ).thenAnswer((_) => Future.value()); - final String message = await controller - .runJavaScriptReturningResult('alert("This is a test.");') as String; + final String message = + await controller.runJavaScriptReturningResult( + 'alert("This is a test.");', + ) + as String; expect(message, ''); }); @@ -1476,11 +1637,15 @@ void main() { mockWebView: mockWebView, ); - when(mockWebView.evaluateJavascript('alert("This is a test.");')) - .thenAnswer((_) => Future.value('3.14')); + when( + mockWebView.evaluateJavascript('alert("This is a test.");'), + ).thenAnswer((_) => Future.value('3.14')); - final num message = await controller - .runJavaScriptReturningResult('alert("This is a test.");') as num; + final num message = + await controller.runJavaScriptReturningResult( + 'alert("This is a test.");', + ) + as num; expect(message, 3.14); }); @@ -1491,11 +1656,15 @@ void main() { mockWebView: mockWebView, ); - when(mockWebView.evaluateJavascript('alert("This is a test.");')) - .thenAnswer((_) => Future.value('true')); + when( + mockWebView.evaluateJavascript('alert("This is a test.");'), + ).thenAnswer((_) => Future.value('true')); - final bool message = await controller - .runJavaScriptReturningResult('alert("This is a test.");') as bool; + final bool message = + await controller.runJavaScriptReturningResult( + 'alert("This is a test.");', + ) + as bool; expect(message, true); }); @@ -1506,11 +1675,15 @@ void main() { mockWebView: mockWebView, ); - when(mockWebView.evaluateJavascript('alert("This is a test.");')) - .thenAnswer((_) => Future.value('false')); + when( + mockWebView.evaluateJavascript('alert("This is a test.");'), + ).thenAnswer((_) => Future.value('false')); - final bool message = await controller - .runJavaScriptReturningResult('alert("This is a test.");') as bool; + final bool message = + await controller.runJavaScriptReturningResult( + 'alert("This is a test.");', + ) + as bool; expect(message, false); }); @@ -1523,32 +1696,38 @@ void main() { final AndroidJavaScriptChannelParams paramsWithMock = createAndroidJavaScriptChannelParamsWithMocks(name: 'test'); await controller.addJavaScriptChannel(paramsWithMock); - verify(mockWebView.addJavaScriptChannel( - argThat(isA()))) - .called(1); + verify( + mockWebView.addJavaScriptChannel( + argThat(isA()), + ), + ).called(1); }); test( - 'addJavaScriptChannel add channel with same name should remove existing channel', - () async { - final MockWebView mockWebView = MockWebView(); - final AndroidWebViewController controller = createControllerWithMocks( - mockWebView: mockWebView, - ); - final AndroidJavaScriptChannelParams paramsWithMock = - createAndroidJavaScriptChannelParamsWithMocks(name: 'test'); - await controller.addJavaScriptChannel(paramsWithMock); - verify(mockWebView.addJavaScriptChannel( - argThat(isA()))) - .called(1); + 'addJavaScriptChannel add channel with same name should remove existing channel', + () async { + final MockWebView mockWebView = MockWebView(); + final AndroidWebViewController controller = createControllerWithMocks( + mockWebView: mockWebView, + ); + final AndroidJavaScriptChannelParams paramsWithMock = + createAndroidJavaScriptChannelParamsWithMocks(name: 'test'); + await controller.addJavaScriptChannel(paramsWithMock); + verify( + mockWebView.addJavaScriptChannel( + argThat(isA()), + ), + ).called(1); - await controller.addJavaScriptChannel(paramsWithMock); - verifyInOrder([ - mockWebView.removeJavaScriptChannel('test'), - mockWebView.addJavaScriptChannel( - argThat(isA())), - ]); - }); + await controller.addJavaScriptChannel(paramsWithMock); + verifyInOrder([ + mockWebView.removeJavaScriptChannel('test'), + mockWebView.addJavaScriptChannel( + argThat(isA()), + ), + ]); + }, + ); test('removeJavaScriptChannel when channel is not registered', () async { final MockWebView mockWebView = MockWebView(); @@ -1570,9 +1749,11 @@ void main() { // Make sure channel exists before removing it. await controller.addJavaScriptChannel(paramsWithMock); - verify(mockWebView.addJavaScriptChannel( - argThat(isA()))) - .called(1); + verify( + mockWebView.addJavaScriptChannel( + argThat(isA()), + ), + ).called(1); await controller.removeJavaScriptChannel('test'); verify(mockWebView.removeJavaScriptChannel('test')).called(1); @@ -1722,8 +1903,9 @@ void main() { const String userAgent = 'str'; - when(mockSettings.getUserAgentString()) - .thenAnswer((_) => Future.value(userAgent)); + when( + mockSettings.getUserAgentString(), + ).thenAnswer((_) => Future.value(userAgent)); expect(await controller.getUserAgent(), userAgent); }); @@ -1832,9 +2014,11 @@ void main() { await controller.setMixedContentMode(MixedContentMode.compatibilityMode); - verify(mockSettings.setMixedContentMode( - android_webview.MixedContentMode.compatibilityMode, - )).called(1); + verify( + mockSettings.setMixedContentMode( + android_webview.MixedContentMode.compatibilityMode, + ), + ).called(1); }); test('setOverScrollMode', () async { @@ -1846,9 +2030,7 @@ void main() { await controller.setOverScrollMode(WebViewOverScrollMode.always); verify( - mockWebView.setOverScrollMode( - android_webview.OverScrollMode.always, - ), + mockWebView.setOverScrollMode(android_webview.OverScrollMode.always), ).called(1); }); @@ -1856,9 +2038,7 @@ void main() { final MockWebView mockWebView = MockWebView(); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addHostCreatedInstance(mockWebView, 0); when(mockWebView.pigeon_instanceManager).thenReturn(instanceManager); @@ -1899,8 +2079,10 @@ void main() { final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockSettings, - setPaymentRequestEnabled: - (android_webview.WebSettings settings, bool enabled) async { + setPaymentRequestEnabled: ( + android_webview.WebSettings settings, + bool enabled, + ) async { capturedSettings = settings; capturedEnabled = enabled; }, @@ -1913,17 +2095,16 @@ void main() { }); group('AndroidWebViewWidget', () { - testWidgets('Builds Android view using supplied parameters', - (WidgetTester tester) async { + testWidgets('Builds Android view using supplied parameters', ( + WidgetTester tester, + ) async { final android_webview.WebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget( @@ -1934,25 +2115,26 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => webViewWidget.build(context), - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) => webViewWidget.build(context), + ), + ); expect(find.byType(PlatformViewLink), findsOneWidget); expect(find.byKey(const Key('test_web_view')), findsOneWidget); }); - testWidgets('displayWithHybridComposition is false', - (WidgetTester tester) async { + testWidgets('displayWithHybridComposition is false', ( + WidgetTester tester, + ) async { final android_webview.WebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final MockPlatformViewsServiceProxy mockPlatformViewsService = @@ -1978,9 +2160,11 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => webViewWidget.build(context), - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) => webViewWidget.build(context), + ), + ); await tester.pumpAndSettle(); verify( @@ -1995,17 +2179,16 @@ void main() { ); }); - testWidgets('displayWithHybridComposition is true', - (WidgetTester tester) async { + testWidgets('displayWithHybridComposition is true', ( + WidgetTester tester, + ) async { final android_webview.WebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final MockPlatformViewsServiceProxy mockPlatformViewsService = @@ -2032,9 +2215,11 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => webViewWidget.build(context), - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) => webViewWidget.build(context), + ), + ); await tester.pumpAndSettle(); verify( @@ -2049,21 +2234,21 @@ void main() { ); }); - testWidgets('default handling of custom views', - (WidgetTester tester) async { + testWidgets('default handling of custom views', ( + WidgetTester tester, + ) async { final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); void Function( - android_webview.WebChromeClient instance, - android_webview.View view, - android_webview.CustomViewCallback callback)? - onShowCustomViewCallback; + android_webview.WebChromeClient instance, + android_webview.View view, + android_webview.CustomViewCallback callback, + )? + onShowCustomViewCallback; final android_webview.WebView mockWebView = MockWebView(); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final AndroidWebViewController controller = createControllerWithMocks( @@ -2074,10 +2259,11 @@ void main() { dynamic onGeolocationPermissionsHidePrompt, dynamic onPermissionRequest, void Function( - android_webview.WebChromeClient instance, - android_webview.View view, - android_webview.CustomViewCallback callback)? - onShowCustomView, + android_webview.WebChromeClient instance, + android_webview.View view, + android_webview.CustomViewCallback callback, + )? + onShowCustomView, dynamic onHideCustomView, dynamic onConsoleMessage, dynamic onJsAlert, @@ -2137,13 +2323,12 @@ void main() { expect(find.byType(AndroidCustomViewWidget), findsOneWidget); }); - testWidgets('PlatformView is recreated when the controller changes', - (WidgetTester tester) async { + testWidgets('PlatformView is recreated when the controller changes', ( + WidgetTester tester, + ) async { final android_webview.WebView mockWebView = MockWebView(); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final MockPlatformViewsServiceProxy mockPlatformViewsService = @@ -2160,17 +2345,19 @@ void main() { ), ).thenReturn(MockSurfaceAndroidViewController()); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return AndroidWebViewWidget( - AndroidWebViewWidgetCreationParams( - controller: createControllerWithMocks(mockWebView: mockWebView), - platformViewsServiceProxy: mockPlatformViewsService, - instanceManager: instanceManager, - ), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return AndroidWebViewWidget( + AndroidWebViewWidgetCreationParams( + controller: createControllerWithMocks(mockWebView: mockWebView), + platformViewsServiceProxy: mockPlatformViewsService, + instanceManager: instanceManager, + ), + ).build(context); + }, + ), + ); await tester.pumpAndSettle(); verify( @@ -2184,17 +2371,19 @@ void main() { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return AndroidWebViewWidget( - AndroidWebViewWidgetCreationParams( - controller: createControllerWithMocks(mockWebView: mockWebView), - platformViewsServiceProxy: mockPlatformViewsService, - instanceManager: instanceManager, - ), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return AndroidWebViewWidget( + AndroidWebViewWidgetCreationParams( + controller: createControllerWithMocks(mockWebView: mockWebView), + platformViewsServiceProxy: mockPlatformViewsService, + instanceManager: instanceManager, + ), + ).build(context); + }, + ), + ); await tester.pumpAndSettle(); verify( @@ -2210,91 +2399,95 @@ void main() { }); testWidgets( - 'PlatformView does not rebuild when creation params stay the same', - (WidgetTester tester) async { - final android_webview.WebView mockWebView = MockWebView(); - final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - instanceManager.addDartCreatedInstance(mockWebView); - - final MockPlatformViewsServiceProxy mockPlatformViewsService = - MockPlatformViewsServiceProxy(); - - final AndroidWebViewController controller = createControllerWithMocks( - mockWebView: mockWebView, - ); + 'PlatformView does not rebuild when creation params stay the same', + (WidgetTester tester) async { + final android_webview.WebView mockWebView = MockWebView(); + final android_webview.PigeonInstanceManager instanceManager = + android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + instanceManager.addDartCreatedInstance(mockWebView); + + final MockPlatformViewsServiceProxy mockPlatformViewsService = + MockPlatformViewsServiceProxy(); - when( - mockPlatformViewsService.initSurfaceAndroidView( - id: anyNamed('id'), - viewType: anyNamed('viewType'), - layoutDirection: anyNamed('layoutDirection'), - creationParams: anyNamed('creationParams'), - creationParamsCodec: anyNamed('creationParamsCodec'), - onFocus: anyNamed('onFocus'), - ), - ).thenReturn(MockSurfaceAndroidViewController()); - - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return AndroidWebViewWidget( - AndroidWebViewWidgetCreationParams( - controller: controller, - platformViewsServiceProxy: mockPlatformViewsService, - instanceManager: instanceManager, - ), - ).build(context); - }, - )); - await tester.pumpAndSettle(); - - verify( - mockPlatformViewsService.initSurfaceAndroidView( - id: anyNamed('id'), - viewType: anyNamed('viewType'), - layoutDirection: anyNamed('layoutDirection'), - creationParams: anyNamed('creationParams'), - creationParamsCodec: anyNamed('creationParamsCodec'), - onFocus: anyNamed('onFocus'), - ), - ); + final AndroidWebViewController controller = createControllerWithMocks( + mockWebView: mockWebView, + ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return AndroidWebViewWidget( - AndroidWebViewWidgetCreationParams( - controller: controller, - platformViewsServiceProxy: mockPlatformViewsService, - instanceManager: instanceManager, - ), - ).build(context); - }, - )); - await tester.pumpAndSettle(); + when( + mockPlatformViewsService.initSurfaceAndroidView( + id: anyNamed('id'), + viewType: anyNamed('viewType'), + layoutDirection: anyNamed('layoutDirection'), + creationParams: anyNamed('creationParams'), + creationParamsCodec: anyNamed('creationParamsCodec'), + onFocus: anyNamed('onFocus'), + ), + ).thenReturn(MockSurfaceAndroidViewController()); + + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return AndroidWebViewWidget( + AndroidWebViewWidgetCreationParams( + controller: controller, + platformViewsServiceProxy: mockPlatformViewsService, + instanceManager: instanceManager, + ), + ).build(context); + }, + ), + ); + await tester.pumpAndSettle(); + + verify( + mockPlatformViewsService.initSurfaceAndroidView( + id: anyNamed('id'), + viewType: anyNamed('viewType'), + layoutDirection: anyNamed('layoutDirection'), + creationParams: anyNamed('creationParams'), + creationParamsCodec: anyNamed('creationParamsCodec'), + onFocus: anyNamed('onFocus'), + ), + ); - verifyNever( - mockPlatformViewsService.initSurfaceAndroidView( - id: anyNamed('id'), - viewType: anyNamed('viewType'), - layoutDirection: anyNamed('layoutDirection'), - creationParams: anyNamed('creationParams'), - creationParamsCodec: anyNamed('creationParamsCodec'), - onFocus: anyNamed('onFocus'), - ), - ); - }); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return AndroidWebViewWidget( + AndroidWebViewWidgetCreationParams( + controller: controller, + platformViewsServiceProxy: mockPlatformViewsService, + instanceManager: instanceManager, + ), + ).build(context); + }, + ), + ); + await tester.pumpAndSettle(); + + verifyNever( + mockPlatformViewsService.initSurfaceAndroidView( + id: anyNamed('id'), + viewType: anyNamed('viewType'), + layoutDirection: anyNamed('layoutDirection'), + creationParams: anyNamed('creationParams'), + creationParamsCodec: anyNamed('creationParamsCodec'), + onFocus: anyNamed('onFocus'), + ), + ); + }, + ); }); group('AndroidCustomViewWidget', () { - testWidgets('Builds Android custom view using supplied parameters', - (WidgetTester tester) async { + testWidgets('Builds Android custom view using supplied parameters', ( + WidgetTester tester, + ) async { final android_webview.WebView mockWebView = MockWebView(); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final AndroidWebViewController controller = createControllerWithMocks( @@ -2303,27 +2496,28 @@ void main() { final AndroidCustomViewWidget customViewWidget = AndroidCustomViewWidget.private( - key: const Key('test_custom_view'), - customView: mockWebView, - controller: controller, - instanceManager: instanceManager, - ); + key: const Key('test_custom_view'), + customView: mockWebView, + controller: controller, + instanceManager: instanceManager, + ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => customViewWidget.build(context), - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) => customViewWidget.build(context), + ), + ); expect(find.byType(PlatformViewLink), findsOneWidget); expect(find.byKey(const Key('test_custom_view')), findsOneWidget); }); - testWidgets('displayWithHybridComposition should be false', - (WidgetTester tester) async { + testWidgets('displayWithHybridComposition should be false', ( + WidgetTester tester, + ) async { final android_webview.WebView mockWebView = MockWebView(); final android_webview.PigeonInstanceManager instanceManager = - android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); instanceManager.addDartCreatedInstance(mockWebView); final AndroidWebViewController controller = createControllerWithMocks( @@ -2346,15 +2540,17 @@ void main() { final AndroidCustomViewWidget customViewWidget = AndroidCustomViewWidget.private( - controller: controller, - customView: mockWebView, - platformViewsServiceProxy: mockPlatformViewsService, - instanceManager: instanceManager, - ); + controller: controller, + customView: mockWebView, + platformViewsServiceProxy: mockPlatformViewsService, + instanceManager: instanceManager, + ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) => customViewWidget.build(context), - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) => customViewWidget.build(context), + ), + ); await tester.pumpAndSettle(); verify( @@ -2397,10 +2593,10 @@ class TestWebViewClient extends android_webview.WebViewClient { super.onReceivedSslError, super.onScaleChanged, }) : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); } class TestWebChromeClient extends android_webview.WebChromeClient { @@ -2417,18 +2613,17 @@ class TestWebChromeClient extends android_webview.WebChromeClient { required super.onJsConfirm, super.onJsPrompt, }) : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); } class TestDownloadListener extends android_webview.DownloadListener { - TestDownloadListener({ - required super.onDownloadStart, - }) : super.pigeon_detached( - pigeon_instanceManager: android_webview.PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); + TestDownloadListener({required super.onDownloadStart}) + : super.pigeon_detached( + pigeon_instanceManager: android_webview.PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); } diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart index 44b94ecd49f..4bf73f17a11 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart @@ -37,34 +37,19 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte class _FakeWebChromeClient_0 extends _i1.SmartFake implements _i2.WebChromeClient { - _FakeWebChromeClient_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebChromeClient_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewClient_1 extends _i1.SmartFake implements _i2.WebViewClient { - _FakeWebViewClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDownloadListener_2 extends _i1.SmartFake implements _i2.DownloadListener { - _FakeDownloadListener_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDownloadListener_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake @@ -72,10 +57,7 @@ class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake _FakePlatformNavigationDelegateCreationParams_3( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakePlatformWebViewControllerCreationParams_4 extends _i1.SmartFake @@ -83,125 +65,67 @@ class _FakePlatformWebViewControllerCreationParams_4 extends _i1.SmartFake _FakePlatformWebViewControllerCreationParams_4( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeObject_5 extends _i1.SmartFake implements Object { - _FakeObject_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOffset_6 extends _i1.SmartFake implements _i4.Offset { - _FakeOffset_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOffset_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebView_7 extends _i1.SmartFake implements _i2.WebView { - _FakeWebView_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebView_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeJavaScriptChannel_8 extends _i1.SmartFake implements _i2.JavaScriptChannel { - _FakeJavaScriptChannel_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeJavaScriptChannel_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCookieManager_9 extends _i1.SmartFake implements _i2.CookieManager { - _FakeCookieManager_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCookieManager_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFlutterAssetManager_10 extends _i1.SmartFake implements _i2.FlutterAssetManager { - _FakeFlutterAssetManager_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFlutterAssetManager_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebStorage_11 extends _i1.SmartFake implements _i2.WebStorage { - _FakeWebStorage_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebStorage_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePigeonInstanceManager_12 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformViewsServiceProxy_13 extends _i1.SmartFake implements _i5.PlatformViewsServiceProxy { - _FakePlatformViewsServiceProxy_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformViewsServiceProxy_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformWebViewController_14 extends _i1.SmartFake implements _i3.PlatformWebViewController { - _FakePlatformWebViewController_14( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformWebViewController_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSize_15 extends _i1.SmartFake implements _i4.Size { - _FakeSize_15( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSize_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeGeolocationPermissionsCallback_16 extends _i1.SmartFake @@ -209,21 +133,13 @@ class _FakeGeolocationPermissionsCallback_16 extends _i1.SmartFake _FakeGeolocationPermissionsCallback_16( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakePermissionRequest_17 extends _i1.SmartFake implements _i2.PermissionRequest { - _FakePermissionRequest_17( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePermissionRequest_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExpensiveAndroidViewController_18 extends _i1.SmartFake @@ -231,10 +147,7 @@ class _FakeExpensiveAndroidViewController_18 extends _i1.SmartFake _FakeExpensiveAndroidViewController_18( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeSurfaceAndroidViewController_19 extends _i1.SmartFake @@ -242,30 +155,17 @@ class _FakeSurfaceAndroidViewController_19 extends _i1.SmartFake _FakeSurfaceAndroidViewController_19( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeWebSettings_20 extends _i1.SmartFake implements _i2.WebSettings { - _FakeWebSettings_20( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebSettings_20(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewPoint_21 extends _i1.SmartFake implements _i2.WebViewPoint { - _FakeWebViewPoint_21( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewPoint_21(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AndroidNavigationDelegate]. @@ -274,172 +174,163 @@ class _FakeWebViewPoint_21 extends _i1.SmartFake implements _i2.WebViewPoint { class MockAndroidNavigationDelegate extends _i1.Mock implements _i7.AndroidNavigationDelegate { @override - _i2.WebChromeClient get androidWebChromeClient => (super.noSuchMethod( - Invocation.getter(#androidWebChromeClient), - returnValue: _FakeWebChromeClient_0( - this, - Invocation.getter(#androidWebChromeClient), - ), - returnValueForMissingStub: _FakeWebChromeClient_0( - this, - Invocation.getter(#androidWebChromeClient), - ), - ) as _i2.WebChromeClient); - - @override - _i2.WebViewClient get androidWebViewClient => (super.noSuchMethod( - Invocation.getter(#androidWebViewClient), - returnValue: _FakeWebViewClient_1( - this, - Invocation.getter(#androidWebViewClient), - ), - returnValueForMissingStub: _FakeWebViewClient_1( - this, - Invocation.getter(#androidWebViewClient), - ), - ) as _i2.WebViewClient); - - @override - _i2.DownloadListener get androidDownloadListener => (super.noSuchMethod( - Invocation.getter(#androidDownloadListener), - returnValue: _FakeDownloadListener_2( - this, - Invocation.getter(#androidDownloadListener), - ), - returnValueForMissingStub: _FakeDownloadListener_2( - this, - Invocation.getter(#androidDownloadListener), - ), - ) as _i2.DownloadListener); + _i2.WebChromeClient get androidWebChromeClient => + (super.noSuchMethod( + Invocation.getter(#androidWebChromeClient), + returnValue: _FakeWebChromeClient_0( + this, + Invocation.getter(#androidWebChromeClient), + ), + returnValueForMissingStub: _FakeWebChromeClient_0( + this, + Invocation.getter(#androidWebChromeClient), + ), + ) + as _i2.WebChromeClient); + + @override + _i2.WebViewClient get androidWebViewClient => + (super.noSuchMethod( + Invocation.getter(#androidWebViewClient), + returnValue: _FakeWebViewClient_1( + this, + Invocation.getter(#androidWebViewClient), + ), + returnValueForMissingStub: _FakeWebViewClient_1( + this, + Invocation.getter(#androidWebViewClient), + ), + ) + as _i2.WebViewClient); + + @override + _i2.DownloadListener get androidDownloadListener => + (super.noSuchMethod( + Invocation.getter(#androidDownloadListener), + returnValue: _FakeDownloadListener_2( + this, + Invocation.getter(#androidDownloadListener), + ), + returnValueForMissingStub: _FakeDownloadListener_2( + this, + Invocation.getter(#androidDownloadListener), + ), + ) + as _i2.DownloadListener); @override _i3.PlatformNavigationDelegateCreationParams get params => (super.noSuchMethod( - Invocation.getter(#params), - returnValue: _FakePlatformNavigationDelegateCreationParams_3( - this, - Invocation.getter(#params), - ), - returnValueForMissingStub: - _FakePlatformNavigationDelegateCreationParams_3( - this, - Invocation.getter(#params), - ), - ) as _i3.PlatformNavigationDelegateCreationParams); + Invocation.getter(#params), + returnValue: _FakePlatformNavigationDelegateCreationParams_3( + this, + Invocation.getter(#params), + ), + returnValueForMissingStub: + _FakePlatformNavigationDelegateCreationParams_3( + this, + Invocation.getter(#params), + ), + ) + as _i3.PlatformNavigationDelegateCreationParams); @override _i8.Future setOnLoadRequest(_i7.LoadRequestCallback? onLoadRequest) => (super.noSuchMethod( - Invocation.method( - #setOnLoadRequest, - [onLoadRequest], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnLoadRequest, [onLoadRequest]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnNavigationRequest( - _i3.NavigationRequestCallback? onNavigationRequest) => + _i3.NavigationRequestCallback? onNavigationRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnNavigationRequest, - [onNavigationRequest], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnNavigationRequest, [onNavigationRequest]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnPageStarted(_i3.PageEventCallback? onPageStarted) => (super.noSuchMethod( - Invocation.method( - #setOnPageStarted, - [onPageStarted], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnPageStarted, [onPageStarted]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnPageFinished(_i3.PageEventCallback? onPageFinished) => (super.noSuchMethod( - Invocation.method( - #setOnPageFinished, - [onPageFinished], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnPageFinished, [onPageFinished]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnHttpError(_i3.HttpResponseErrorCallback? onHttpError) => (super.noSuchMethod( - Invocation.method( - #setOnHttpError, - [onHttpError], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnHttpError, [onHttpError]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnProgress(_i3.ProgressCallback? onProgress) => (super.noSuchMethod( - Invocation.method( - #setOnProgress, - [onProgress], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnProgress, [onProgress]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnWebResourceError( - _i3.WebResourceErrorCallback? onWebResourceError) => + _i3.WebResourceErrorCallback? onWebResourceError, + ) => (super.noSuchMethod( - Invocation.method( - #setOnWebResourceError, - [onWebResourceError], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnWebResourceError, [onWebResourceError]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnUrlChange(_i3.UrlChangeCallback? onUrlChange) => (super.noSuchMethod( - Invocation.method( - #setOnUrlChange, - [onUrlChange], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnUrlChange, [onUrlChange]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnHttpAuthRequest( - _i3.HttpAuthRequestCallback? onHttpAuthRequest) => + _i3.HttpAuthRequestCallback? onHttpAuthRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnHttpAuthRequest, - [onHttpAuthRequest], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnHttpAuthRequest, [onHttpAuthRequest]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnSSlAuthError( - _i3.SslAuthErrorCallback? onSslAuthError) => - (super.noSuchMethod( - Invocation.method( - #setOnSSlAuthError, - [onSslAuthError], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i3.SslAuthErrorCallback? onSslAuthError, + ) => + (super.noSuchMethod( + Invocation.method(#setOnSSlAuthError, [onSslAuthError]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); } /// A class which mocks [AndroidWebViewController]. @@ -448,425 +339,366 @@ class MockAndroidNavigationDelegate extends _i1.Mock class MockAndroidWebViewController extends _i1.Mock implements _i7.AndroidWebViewController { @override - int get webViewIdentifier => (super.noSuchMethod( - Invocation.getter(#webViewIdentifier), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); - - @override - _i3.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod( - Invocation.getter(#params), - returnValue: _FakePlatformWebViewControllerCreationParams_4( - this, - Invocation.getter(#params), - ), - returnValueForMissingStub: - _FakePlatformWebViewControllerCreationParams_4( - this, - Invocation.getter(#params), - ), - ) as _i3.PlatformWebViewControllerCreationParams); - - @override - _i8.Future setAllowFileAccess(bool? allow) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [allow], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future loadFile(String? absoluteFilePath) => (super.noSuchMethod( - Invocation.method( - #loadFile, - [absoluteFilePath], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future loadFlutterAsset(String? key) => (super.noSuchMethod( - Invocation.method( - #loadFlutterAsset, - [key], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future loadHtmlString( - String? html, { - String? baseUrl, - }) => + int get webViewIdentifier => + (super.noSuchMethod( + Invocation.getter(#webViewIdentifier), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); + + @override + _i3.PlatformWebViewControllerCreationParams get params => + (super.noSuchMethod( + Invocation.getter(#params), + returnValue: _FakePlatformWebViewControllerCreationParams_4( + this, + Invocation.getter(#params), + ), + returnValueForMissingStub: + _FakePlatformWebViewControllerCreationParams_4( + this, + Invocation.getter(#params), + ), + ) + as _i3.PlatformWebViewControllerCreationParams); + + @override + _i8.Future setAllowFileAccess(bool? allow) => + (super.noSuchMethod( + Invocation.method(#setAllowFileAccess, [allow]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future loadFile(String? absoluteFilePath) => (super.noSuchMethod( - Invocation.method( - #loadHtmlString, - [html], - {#baseUrl: baseUrl}, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#loadFile, [absoluteFilePath]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future loadFlutterAsset(String? key) => + (super.noSuchMethod( + Invocation.method(#loadFlutterAsset, [key]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future loadHtmlString(String? html, {String? baseUrl}) => + (super.noSuchMethod( + Invocation.method(#loadHtmlString, [html], {#baseUrl: baseUrl}), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future loadRequest(_i3.LoadRequestParams? params) => (super.noSuchMethod( - Invocation.method( - #loadRequest, - [params], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future currentUrl() => (super.noSuchMethod( - Invocation.method( - #currentUrl, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), - returnValue: _i8.Future.value(false), - returnValueForMissingStub: _i8.Future.value(false), - ) as _i8.Future); - - @override - _i8.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), - returnValue: _i8.Future.value(false), - returnValueForMissingStub: _i8.Future.value(false), - ) as _i8.Future); - - @override - _i8.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future clearCache() => (super.noSuchMethod( - Invocation.method( - #clearCache, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future clearLocalStorage() => (super.noSuchMethod( - Invocation.method( - #clearLocalStorage, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#loadRequest, [params]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future currentUrl() => + (super.noSuchMethod( + Invocation.method(#currentUrl, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future canGoBack() => + (super.noSuchMethod( + Invocation.method(#canGoBack, []), + returnValue: _i8.Future.value(false), + returnValueForMissingStub: _i8.Future.value(false), + ) + as _i8.Future); + + @override + _i8.Future canGoForward() => + (super.noSuchMethod( + Invocation.method(#canGoForward, []), + returnValue: _i8.Future.value(false), + returnValueForMissingStub: _i8.Future.value(false), + ) + as _i8.Future); + + @override + _i8.Future goBack() => + (super.noSuchMethod( + Invocation.method(#goBack, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future goForward() => + (super.noSuchMethod( + Invocation.method(#goForward, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future reload() => + (super.noSuchMethod( + Invocation.method(#reload, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future clearCache() => + (super.noSuchMethod( + Invocation.method(#clearCache, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future clearLocalStorage() => + (super.noSuchMethod( + Invocation.method(#clearLocalStorage, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setPlatformNavigationDelegate( - _i3.PlatformNavigationDelegate? handler) => + _i3.PlatformNavigationDelegate? handler, + ) => (super.noSuchMethod( - Invocation.method( - #setPlatformNavigationDelegate, - [handler], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setPlatformNavigationDelegate, [handler]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future runJavaScript(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScript, - [javaScript], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future runJavaScript(String? javaScript) => + (super.noSuchMethod( + Invocation.method(#runJavaScript, [javaScript]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future runJavaScriptReturningResult(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - returnValue: _i8.Future.value(_FakeObject_5( - this, - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - )), - returnValueForMissingStub: _i8.Future.value(_FakeObject_5( - this, - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - )), - ) as _i8.Future); + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + returnValue: _i8.Future.value( + _FakeObject_5( + this, + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + ), + ), + returnValueForMissingStub: _i8.Future.value( + _FakeObject_5( + this, + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + ), + ), + ) + as _i8.Future); @override _i8.Future addJavaScriptChannel( - _i3.JavaScriptChannelParams? javaScriptChannelParams) => + _i3.JavaScriptChannelParams? javaScriptChannelParams, + ) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [javaScriptChannelParams], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#addJavaScriptChannel, [javaScriptChannelParams]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future removeJavaScriptChannel(String? javaScriptChannelName) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [javaScriptChannelName], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#removeJavaScriptChannel, [ + javaScriptChannelName, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future getTitle() => + (super.noSuchMethod( + Invocation.method(#getTitle, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future scrollTo( - int? x, - int? y, - ) => + _i8.Future scrollTo(int? x, int? y) => (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future scrollBy( - int? x, - int? y, - ) => + Invocation.method(#scrollTo, [x, y]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future scrollBy(int? x, int? y) => (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], - ), - returnValue: _i8.Future<_i4.Offset>.value(_FakeOffset_6( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - returnValueForMissingStub: _i8.Future<_i4.Offset>.value(_FakeOffset_6( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - ) as _i8.Future<_i4.Offset>); - - @override - _i8.Future enableZoom(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #enableZoom, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setBackgroundColor(_i4.Color? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#scrollBy, [x, y]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future<_i4.Offset> getScrollPosition() => + (super.noSuchMethod( + Invocation.method(#getScrollPosition, []), + returnValue: _i8.Future<_i4.Offset>.value( + _FakeOffset_6(this, Invocation.method(#getScrollPosition, [])), + ), + returnValueForMissingStub: _i8.Future<_i4.Offset>.value( + _FakeOffset_6(this, Invocation.method(#getScrollPosition, [])), + ), + ) + as _i8.Future<_i4.Offset>); + + @override + _i8.Future enableZoom(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#enableZoom, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setBackgroundColor(_i4.Color? color) => + (super.noSuchMethod( + Invocation.method(#setBackgroundColor, [color]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setJavaScriptMode(_i3.JavaScriptMode? javaScriptMode) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptMode, - [javaScriptMode], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setJavaScriptMode, [javaScriptMode]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future setUserAgent(String? userAgent) => (super.noSuchMethod( - Invocation.method( - #setUserAgent, - [userAgent], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future setUserAgent(String? userAgent) => + (super.noSuchMethod( + Invocation.method(#setUserAgent, [userAgent]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnScrollPositionChange( - void Function(_i3.ScrollPositionChange)? onScrollPositionChange) => + void Function(_i3.ScrollPositionChange)? onScrollPositionChange, + ) => (super.noSuchMethod( - Invocation.method( - #setOnScrollPositionChange, - [onScrollPositionChange], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnScrollPositionChange, [ + onScrollPositionChange, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setUseWideViewPort(bool? use) => (super.noSuchMethod( - Invocation.method( - #setUseWideViewPort, - [use], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setTextZoom(int? textZoom) => + (super.noSuchMethod( + Invocation.method(#setTextZoom, [textZoom]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setUseWideViewPort(bool? use) => + (super.noSuchMethod( + Invocation.method(#setUseWideViewPort, [use]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setAllowContentAccess(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setAllowContentAccess, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setGeolocationEnabled(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setGeolocationEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnShowFileSelector( - _i8.Future> Function(_i7.FileSelectorParams)? - onShowFileSelector) => + _i8.Future> Function(_i7.FileSelectorParams)? + onShowFileSelector, + ) => (super.noSuchMethod( - Invocation.method( - #setOnShowFileSelector, - [onShowFileSelector], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnShowFileSelector, [onShowFileSelector]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnPlatformPermissionRequest( - void Function(_i3.PlatformWebViewPermissionRequest)? - onPermissionRequest) => + void Function(_i3.PlatformWebViewPermissionRequest)? onPermissionRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnPlatformPermissionRequest, - [onPermissionRequest], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnPlatformPermissionRequest, [ + onPermissionRequest, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setGeolocationPermissionsPromptCallbacks({ @@ -874,17 +706,14 @@ class MockAndroidWebViewController extends _i1.Mock _i7.OnGeolocationPermissionsHidePrompt? onHidePrompt, }) => (super.noSuchMethod( - Invocation.method( - #setGeolocationPermissionsPromptCallbacks, - [], - { - #onShowPrompt: onShowPrompt, - #onHidePrompt: onHidePrompt, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setGeolocationPermissionsPromptCallbacks, [], { + #onShowPrompt: onShowPrompt, + #onHidePrompt: onHidePrompt, + }), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setCustomWidgetCallbacks({ @@ -892,155 +721,141 @@ class MockAndroidWebViewController extends _i1.Mock required _i7.OnHideCustomWidgetCallback? onHideCustomWidget, }) => (super.noSuchMethod( - Invocation.method( - #setCustomWidgetCallbacks, - [], - { - #onShowCustomWidget: onShowCustomWidget, - #onHideCustomWidget: onHideCustomWidget, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setCustomWidgetCallbacks, [], { + #onShowCustomWidget: onShowCustomWidget, + #onHideCustomWidget: onHideCustomWidget, + }), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnConsoleMessage( - void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage) => + void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage, + ) => (super.noSuchMethod( - Invocation.method( - #setOnConsoleMessage, - [onConsoleMessage], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnConsoleMessage, [onConsoleMessage]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future getUserAgent() => (super.noSuchMethod( - Invocation.method( - #getUserAgent, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future getUserAgent() => + (super.noSuchMethod( + Invocation.method(#getUserAgent, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnJavaScriptAlertDialog( - _i8.Future Function(_i3.JavaScriptAlertDialogRequest)? - onJavaScriptAlertDialog) => + _i8.Future Function(_i3.JavaScriptAlertDialogRequest)? + onJavaScriptAlertDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptAlertDialog, - [onJavaScriptAlertDialog], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnJavaScriptAlertDialog, [ + onJavaScriptAlertDialog, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnJavaScriptConfirmDialog( - _i8.Future Function(_i3.JavaScriptConfirmDialogRequest)? - onJavaScriptConfirmDialog) => + _i8.Future Function(_i3.JavaScriptConfirmDialogRequest)? + onJavaScriptConfirmDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptConfirmDialog, - [onJavaScriptConfirmDialog], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnJavaScriptConfirmDialog, [ + onJavaScriptConfirmDialog, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOnJavaScriptTextInputDialog( - _i8.Future Function(_i3.JavaScriptTextInputDialogRequest)? - onJavaScriptTextInputDialog) => + _i8.Future Function(_i3.JavaScriptTextInputDialogRequest)? + onJavaScriptTextInputDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptTextInputDialog, - [onJavaScriptTextInputDialog], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOnJavaScriptTextInputDialog, [ + onJavaScriptTextInputDialog, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setVerticalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setVerticalScrollBarEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setVerticalScrollBarEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setHorizontalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setHorizontalScrollBarEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setHorizontalScrollBarEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - bool supportsSetScrollBarsEnabled() => (super.noSuchMethod( - Invocation.method( - #supportsSetScrollBarsEnabled, - [], - ), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool supportsSetScrollBarsEnabled() => + (super.noSuchMethod( + Invocation.method(#supportsSetScrollBarsEnabled, []), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override _i8.Future setOverScrollMode(_i3.WebViewOverScrollMode? mode) => (super.noSuchMethod( - Invocation.method( - #setOverScrollMode, - [mode], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOverScrollMode, [mode]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setMixedContentMode(_i7.MixedContentMode? mode) => (super.noSuchMethod( - Invocation.method( - #setMixedContentMode, - [mode], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setMixedContentMode, [mode]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future isWebViewFeatureSupported( - _i7.WebViewFeatureType? featureType) => + _i7.WebViewFeatureType? featureType, + ) => (super.noSuchMethod( - Invocation.method( - #isWebViewFeatureSupported, - [featureType], - ), - returnValue: _i8.Future.value(false), - returnValueForMissingStub: _i8.Future.value(false), - ) as _i8.Future); + Invocation.method(#isWebViewFeatureSupported, [featureType]), + returnValue: _i8.Future.value(false), + returnValueForMissingStub: _i8.Future.value(false), + ) + as _i8.Future); @override _i8.Future setPaymentRequestEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setPaymentRequestEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setPaymentRequestEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); } /// A class which mocks [AndroidWebViewProxy]. @@ -1049,544 +864,446 @@ class MockAndroidWebViewController extends _i1.Mock class MockAndroidWebViewProxy extends _i1.Mock implements _i9.AndroidWebViewProxy { @override - _i2.WebView Function( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged}) get newWebView => (super.noSuchMethod( - Invocation.getter(#newWebView), - returnValue: ( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged}) => - _FakeWebView_7( - this, - Invocation.getter(#newWebView), - ), - returnValueForMissingStub: ( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged}) => - _FakeWebView_7( - this, - Invocation.getter(#newWebView), - ), - ) as _i2.WebView Function( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged})); + _i2.WebView Function({ + void Function(_i2.WebView, int, int, int, int)? onScrollChanged, + }) + get newWebView => + (super.noSuchMethod( + Invocation.getter(#newWebView), + returnValue: + ({ + void Function(_i2.WebView, int, int, int, int)? + onScrollChanged, + }) => _FakeWebView_7(this, Invocation.getter(#newWebView)), + returnValueForMissingStub: + ({ + void Function(_i2.WebView, int, int, int, int)? + onScrollChanged, + }) => _FakeWebView_7(this, Invocation.getter(#newWebView)), + ) + as _i2.WebView Function({ + void Function(_i2.WebView, int, int, int, int)? onScrollChanged, + })); @override _i2.JavaScriptChannel Function({ required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, - }) get newJavaScriptChannel => (super.noSuchMethod( - Invocation.getter(#newJavaScriptChannel), - returnValue: ({ - required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, - }) => - _FakeJavaScriptChannel_8( - this, - Invocation.getter(#newJavaScriptChannel), - ), - returnValueForMissingStub: ({ - required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, - }) => - _FakeJavaScriptChannel_8( - this, - Invocation.getter(#newJavaScriptChannel), - ), - ) as _i2.JavaScriptChannel Function({ - required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, - })); + required void Function(_i2.JavaScriptChannel, String) postMessage, + }) + get newJavaScriptChannel => + (super.noSuchMethod( + Invocation.getter(#newJavaScriptChannel), + returnValue: + ({ + required String channelName, + required void Function(_i2.JavaScriptChannel, String) + postMessage, + }) => _FakeJavaScriptChannel_8( + this, + Invocation.getter(#newJavaScriptChannel), + ), + returnValueForMissingStub: + ({ + required String channelName, + required void Function(_i2.JavaScriptChannel, String) + postMessage, + }) => _FakeJavaScriptChannel_8( + this, + Invocation.getter(#newJavaScriptChannel), + ), + ) + as _i2.JavaScriptChannel Function({ + required String channelName, + required void Function(_i2.JavaScriptChannel, String) postMessage, + })); @override _i2.WebViewClient Function({ - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, void Function( _i2.WebViewClient, _i2.WebView, _i2.AndroidMessage, _i2.AndroidMessage, - )? onFormResubmission, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onLoadResource, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageCommitVisible, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.ClientCertRequest, - )? onReceivedClientCertRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, + )? + onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, + void Function(_i2.WebViewClient, _i2.WebView, _i2.ClientCertRequest)? + onReceivedClientCertRequest, + void Function(_i2.WebViewClient, _i2.WebView, int, String, String)? + onReceivedError, void Function( _i2.WebViewClient, _i2.WebView, _i2.HttpAuthHandler, String, String, - )? onReceivedHttpAuthRequest, + )? + onReceivedHttpAuthRequest, void Function( _i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest, _i2.WebResourceResponse, - )? onReceivedHttpError, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - String?, - String, - )? onReceivedLoginRequest, + )? + onReceivedHttpError, + void Function(_i2.WebViewClient, _i2.WebView, String, String?, String)? + onReceivedLoginRequest, void Function( _i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest, _i2.WebResourceError, - )? onReceivedRequestError, + )? + onReceivedRequestError, void Function( _i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest, _i2.WebResourceErrorCompat, - )? onReceivedRequestErrorCompat, + )? + onReceivedRequestErrorCompat, void Function( _i2.WebViewClient, _i2.WebView, _i2.SslErrorHandler, _i2.SslError, - )? onReceivedSslError, - void Function( - _i2.WebViewClient, - _i2.WebView, - double, - double, - )? onScaleChanged, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, - void Function( - _i2.WebViewClient, - _i2.WebView, + )? + onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, + void Function(_i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest)? + requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, + }) + get newWebViewClient => + (super.noSuchMethod( + Invocation.getter(#newWebViewClient), + returnValue: + ({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? + onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageStarted, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.ClientCertRequest, + )? + onReceivedClientCertRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + int, + String, + String, + )? + onReceivedError, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.HttpAuthHandler, + String, + String, + )? + onReceivedHttpAuthRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceResponse, + )? + onReceivedHttpError, + void Function( + _i2.WebViewClient, + _i2.WebView, + String, + String?, + String, + )? + onReceivedLoginRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceError, + )? + onReceivedRequestError, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceErrorCompat, + )? + onReceivedRequestErrorCompat, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.SslErrorHandler, + _i2.SslError, + )? + onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + )? + requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? + urlLoading, + }) => _FakeWebViewClient_1( + this, + Invocation.getter(#newWebViewClient), + ), + returnValueForMissingStub: + ({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? + onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageStarted, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.ClientCertRequest, + )? + onReceivedClientCertRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + int, + String, + String, + )? + onReceivedError, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.HttpAuthHandler, + String, + String, + )? + onReceivedHttpAuthRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceResponse, + )? + onReceivedHttpError, + void Function( + _i2.WebViewClient, + _i2.WebView, + String, + String?, + String, + )? + onReceivedLoginRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceError, + )? + onReceivedRequestError, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceErrorCompat, + )? + onReceivedRequestErrorCompat, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.SslErrorHandler, + _i2.SslError, + )? + onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + )? + requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? + urlLoading, + }) => _FakeWebViewClient_1( + this, + Invocation.getter(#newWebViewClient), + ), + ) + as _i2.WebViewClient Function({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? + onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageStarted, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.ClientCertRequest, + )? + onReceivedClientCertRequest, + void Function(_i2.WebViewClient, _i2.WebView, int, String, String)? + onReceivedError, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.HttpAuthHandler, + String, + String, + )? + onReceivedHttpAuthRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceResponse, + )? + onReceivedHttpError, + void Function( + _i2.WebViewClient, + _i2.WebView, + String, + String?, + String, + )? + onReceivedLoginRequest, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceError, + )? + onReceivedRequestError, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + _i2.WebResourceErrorCompat, + )? + onReceivedRequestErrorCompat, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.SslErrorHandler, + _i2.SslError, + )? + onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, + void Function( + _i2.WebViewClient, + _i2.WebView, + _i2.WebResourceRequest, + )? + requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, + })); + + @override + _i2.DownloadListener Function({ + required void Function( + _i2.DownloadListener, String, - )? urlLoading, - }) get newWebViewClient => (super.noSuchMethod( - Invocation.getter(#newWebViewClient), - returnValue: ({ - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.AndroidMessage, - _i2.AndroidMessage, - )? onFormResubmission, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onLoadResource, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageCommitVisible, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.ClientCertRequest, - )? onReceivedClientCertRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.HttpAuthHandler, - String, - String, - )? onReceivedHttpAuthRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceResponse, - )? onReceivedHttpError, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - String?, - String, - )? onReceivedLoginRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceError, - )? onReceivedRequestError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceErrorCompat, - )? onReceivedRequestErrorCompat, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.SslErrorHandler, - _i2.SslError, - )? onReceivedSslError, - void Function( - _i2.WebViewClient, - _i2.WebView, - double, - double, - )? onScaleChanged, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? urlLoading, - }) => - _FakeWebViewClient_1( - this, - Invocation.getter(#newWebViewClient), - ), - returnValueForMissingStub: ({ - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.AndroidMessage, - _i2.AndroidMessage, - )? onFormResubmission, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onLoadResource, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageCommitVisible, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.ClientCertRequest, - )? onReceivedClientCertRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.HttpAuthHandler, - String, - String, - )? onReceivedHttpAuthRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceResponse, - )? onReceivedHttpError, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - String?, - String, - )? onReceivedLoginRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceError, - )? onReceivedRequestError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceErrorCompat, - )? onReceivedRequestErrorCompat, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.SslErrorHandler, - _i2.SslError, - )? onReceivedSslError, - void Function( - _i2.WebViewClient, - _i2.WebView, - double, - double, - )? onScaleChanged, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? urlLoading, - }) => - _FakeWebViewClient_1( - this, - Invocation.getter(#newWebViewClient), - ), - ) as _i2.WebViewClient Function({ - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.AndroidMessage, - _i2.AndroidMessage, - )? onFormResubmission, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onLoadResource, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageCommitVisible, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.ClientCertRequest, - )? onReceivedClientCertRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.HttpAuthHandler, - String, - String, - )? onReceivedHttpAuthRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceResponse, - )? onReceivedHttpError, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - String?, - String, - )? onReceivedLoginRequest, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceError, - )? onReceivedRequestError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - _i2.WebResourceErrorCompat, - )? onReceivedRequestErrorCompat, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.SslErrorHandler, - _i2.SslError, - )? onReceivedSslError, - void Function( - _i2.WebViewClient, - _i2.WebView, - double, - double, - )? onScaleChanged, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? urlLoading, - })); - - @override - _i2.DownloadListener Function( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart}) get newDownloadListener => (super.noSuchMethod( - Invocation.getter(#newDownloadListener), - returnValue: ( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart}) => - _FakeDownloadListener_2( - this, - Invocation.getter(#newDownloadListener), - ), - returnValueForMissingStub: ( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart}) => - _FakeDownloadListener_2( - this, - Invocation.getter(#newDownloadListener), - ), - ) as _i2.DownloadListener Function( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart})); + String, + String, + String, + int, + ) + onDownloadStart, + }) + get newDownloadListener => + (super.noSuchMethod( + Invocation.getter(#newDownloadListener), + returnValue: + ({ + required void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + ) + onDownloadStart, + }) => _FakeDownloadListener_2( + this, + Invocation.getter(#newDownloadListener), + ), + returnValueForMissingStub: + ({ + required void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + ) + onDownloadStart, + }) => _FakeDownloadListener_2( + this, + Invocation.getter(#newDownloadListener), + ), + ) + as _i2.DownloadListener Function({ + required void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + ) + onDownloadStart, + })); @override _i2.WebChromeClient Function({ @@ -1595,293 +1312,286 @@ class MockAndroidWebViewProxy extends _i1.Mock _i2.WebView, String, String, - ) onJsConfirm, + ) + onJsConfirm, required _i8.Future> Function( _i2.WebChromeClient, _i2.WebView, _i2.FileChooserParams, - ) onShowFileChooser, - void Function( - _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, + ) + onShowFileChooser, + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? onConsoleMessage, void Function(_i2.WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function( _i2.WebChromeClient, String, _i2.GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, + )? + onGeolocationPermissionsShowPrompt, void Function(_i2.WebChromeClient)? onHideCustomView, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsAlert, + _i8.Future Function(_i2.WebChromeClient, _i2.WebView, String, String)? + onJsAlert, _i8.Future Function( _i2.WebChromeClient, _i2.WebView, String, String, String, - )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, - void Function( - _i2.WebChromeClient, - _i2.View, - _i2.CustomViewCallback, - )? onShowCustomView, - }) get newWebChromeClient => (super.noSuchMethod( - Invocation.getter(#newWebChromeClient), - returnValue: ({ - void Function( - _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, - void Function(_i2.WebChromeClient)? - onGeolocationPermissionsHidePrompt, - void Function( - _i2.WebChromeClient, - String, - _i2.GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, - void Function(_i2.WebChromeClient)? onHideCustomView, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsAlert, - required _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - ) onJsConfirm, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - String, - )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, - void Function( - _i2.WebChromeClient, - _i2.View, - _i2.CustomViewCallback, - )? onShowCustomView, - required _i8.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - ) onShowFileChooser, - }) => - _FakeWebChromeClient_0( - this, - Invocation.getter(#newWebChromeClient), - ), - returnValueForMissingStub: ({ - void Function( - _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, - void Function(_i2.WebChromeClient)? - onGeolocationPermissionsHidePrompt, - void Function( - _i2.WebChromeClient, - String, - _i2.GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, - void Function(_i2.WebChromeClient)? onHideCustomView, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsAlert, - required _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - ) onJsConfirm, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - String, - )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, - void Function( - _i2.WebChromeClient, - _i2.View, - _i2.CustomViewCallback, - )? onShowCustomView, - required _i8.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - ) onShowFileChooser, - }) => - _FakeWebChromeClient_0( - this, - Invocation.getter(#newWebChromeClient), - ), - ) as _i2.WebChromeClient Function({ - required _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - ) onJsConfirm, - required _i8.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - ) onShowFileChooser, - void Function( - _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, - void Function(_i2.WebChromeClient)? onGeolocationPermissionsHidePrompt, - void Function( - _i2.WebChromeClient, - String, - _i2.GeolocationPermissionsCallback, - )? onGeolocationPermissionsShowPrompt, - void Function(_i2.WebChromeClient)? onHideCustomView, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsAlert, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - String, - )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, - void Function( - _i2.WebChromeClient, - _i2.View, - _i2.CustomViewCallback, - )? onShowCustomView, - })); + )? + onJsPrompt, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? onProgressChanged, + void Function(_i2.WebChromeClient, _i2.View, _i2.CustomViewCallback)? + onShowCustomView, + }) + get newWebChromeClient => + (super.noSuchMethod( + Invocation.getter(#newWebChromeClient), + returnValue: + ({ + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? + onConsoleMessage, + void Function(_i2.WebChromeClient)? + onGeolocationPermissionsHidePrompt, + void Function( + _i2.WebChromeClient, + String, + _i2.GeolocationPermissionsCallback, + )? + onGeolocationPermissionsShowPrompt, + void Function(_i2.WebChromeClient)? onHideCustomView, + _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )? + onJsAlert, + required _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + ) + onJsConfirm, + _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + String, + )? + onJsPrompt, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? + onProgressChanged, + void Function( + _i2.WebChromeClient, + _i2.View, + _i2.CustomViewCallback, + )? + onShowCustomView, + required _i8.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + ) + onShowFileChooser, + }) => _FakeWebChromeClient_0( + this, + Invocation.getter(#newWebChromeClient), + ), + returnValueForMissingStub: + ({ + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? + onConsoleMessage, + void Function(_i2.WebChromeClient)? + onGeolocationPermissionsHidePrompt, + void Function( + _i2.WebChromeClient, + String, + _i2.GeolocationPermissionsCallback, + )? + onGeolocationPermissionsShowPrompt, + void Function(_i2.WebChromeClient)? onHideCustomView, + _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )? + onJsAlert, + required _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + ) + onJsConfirm, + _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + String, + )? + onJsPrompt, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? + onProgressChanged, + void Function( + _i2.WebChromeClient, + _i2.View, + _i2.CustomViewCallback, + )? + onShowCustomView, + required _i8.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + ) + onShowFileChooser, + }) => _FakeWebChromeClient_0( + this, + Invocation.getter(#newWebChromeClient), + ), + ) + as _i2.WebChromeClient Function({ + required _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + ) + onJsConfirm, + required _i8.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + ) + onShowFileChooser, + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? + onConsoleMessage, + void Function(_i2.WebChromeClient)? + onGeolocationPermissionsHidePrompt, + void Function( + _i2.WebChromeClient, + String, + _i2.GeolocationPermissionsCallback, + )? + onGeolocationPermissionsShowPrompt, + void Function(_i2.WebChromeClient)? onHideCustomView, + _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )? + onJsAlert, + _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + String, + )? + onJsPrompt, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? + onProgressChanged, + void Function( + _i2.WebChromeClient, + _i2.View, + _i2.CustomViewCallback, + )? + onShowCustomView, + })); @override _i8.Future Function(bool) get setWebContentsDebuggingEnabledWebView => (super.noSuchMethod( - Invocation.getter(#setWebContentsDebuggingEnabledWebView), - returnValue: (bool __p0) => _i8.Future.value(), - returnValueForMissingStub: (bool __p0) => _i8.Future.value(), - ) as _i8.Future Function(bool)); + Invocation.getter(#setWebContentsDebuggingEnabledWebView), + returnValue: (bool __p0) => _i8.Future.value(), + returnValueForMissingStub: (bool __p0) => _i8.Future.value(), + ) + as _i8.Future Function(bool)); @override - _i2.CookieManager Function() get instanceCookieManager => (super.noSuchMethod( - Invocation.getter(#instanceCookieManager), - returnValue: () => _FakeCookieManager_9( - this, - Invocation.getter(#instanceCookieManager), - ), - returnValueForMissingStub: () => _FakeCookieManager_9( - this, - Invocation.getter(#instanceCookieManager), - ), - ) as _i2.CookieManager Function()); + _i2.CookieManager Function() get instanceCookieManager => + (super.noSuchMethod( + Invocation.getter(#instanceCookieManager), + returnValue: + () => _FakeCookieManager_9( + this, + Invocation.getter(#instanceCookieManager), + ), + returnValueForMissingStub: + () => _FakeCookieManager_9( + this, + Invocation.getter(#instanceCookieManager), + ), + ) + as _i2.CookieManager Function()); @override _i2.FlutterAssetManager Function() get instanceFlutterAssetManager => (super.noSuchMethod( - Invocation.getter(#instanceFlutterAssetManager), - returnValue: () => _FakeFlutterAssetManager_10( - this, - Invocation.getter(#instanceFlutterAssetManager), - ), - returnValueForMissingStub: () => _FakeFlutterAssetManager_10( - this, - Invocation.getter(#instanceFlutterAssetManager), - ), - ) as _i2.FlutterAssetManager Function()); - - @override - _i2.WebStorage Function() get instanceWebStorage => (super.noSuchMethod( - Invocation.getter(#instanceWebStorage), - returnValue: () => _FakeWebStorage_11( - this, - Invocation.getter(#instanceWebStorage), - ), - returnValueForMissingStub: () => _FakeWebStorage_11( - this, - Invocation.getter(#instanceWebStorage), - ), - ) as _i2.WebStorage Function()); + Invocation.getter(#instanceFlutterAssetManager), + returnValue: + () => _FakeFlutterAssetManager_10( + this, + Invocation.getter(#instanceFlutterAssetManager), + ), + returnValueForMissingStub: + () => _FakeFlutterAssetManager_10( + this, + Invocation.getter(#instanceFlutterAssetManager), + ), + ) + as _i2.FlutterAssetManager Function()); + + @override + _i2.WebStorage Function() get instanceWebStorage => + (super.noSuchMethod( + Invocation.getter(#instanceWebStorage), + returnValue: + () => _FakeWebStorage_11( + this, + Invocation.getter(#instanceWebStorage), + ), + returnValueForMissingStub: + () => _FakeWebStorage_11( + this, + Invocation.getter(#instanceWebStorage), + ), + ) + as _i2.WebStorage Function()); @override _i8.Future Function(String) get isWebViewFeatureSupported => (super.noSuchMethod( - Invocation.getter(#isWebViewFeatureSupported), - returnValue: (String __p0) => _i8.Future.value(false), - returnValueForMissingStub: (String __p0) => - _i8.Future.value(false), - ) as _i8.Future Function(String)); - - @override - _i8.Future Function( - _i2.WebSettings, - bool, - ) get setPaymentRequestEnabled => (super.noSuchMethod( - Invocation.getter(#setPaymentRequestEnabled), - returnValue: ( - _i2.WebSettings __p0, - bool __p1, - ) => - _i8.Future.value(), - returnValueForMissingStub: ( - _i2.WebSettings __p0, - bool __p1, - ) => - _i8.Future.value(), - ) as _i8.Future Function( - _i2.WebSettings, - bool, - )); + Invocation.getter(#isWebViewFeatureSupported), + returnValue: (String __p0) => _i8.Future.value(false), + returnValueForMissingStub: + (String __p0) => _i8.Future.value(false), + ) + as _i8.Future Function(String)); + + @override + _i8.Future Function(_i2.WebSettings, bool) + get setPaymentRequestEnabled => + (super.noSuchMethod( + Invocation.getter(#setPaymentRequestEnabled), + returnValue: + (_i2.WebSettings __p0, bool __p1) => _i8.Future.value(), + returnValueForMissingStub: + (_i2.WebSettings __p0, bool __p1) => _i8.Future.value(), + ) + as _i8.Future Function(_i2.WebSettings, bool)); } /// A class which mocks [AndroidWebViewWidgetCreationParams]. @@ -1891,67 +1601,77 @@ class MockAndroidWebViewProxy extends _i1.Mock class MockAndroidWebViewWidgetCreationParams extends _i1.Mock implements _i7.AndroidWebViewWidgetCreationParams { @override - _i2.PigeonInstanceManager get instanceManager => (super.noSuchMethod( - Invocation.getter(#instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get instanceManager => + (super.noSuchMethod( + Invocation.getter(#instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i5.PlatformViewsServiceProxy get platformViewsServiceProxy => (super.noSuchMethod( - Invocation.getter(#platformViewsServiceProxy), - returnValue: _FakePlatformViewsServiceProxy_13( - this, - Invocation.getter(#platformViewsServiceProxy), - ), - returnValueForMissingStub: _FakePlatformViewsServiceProxy_13( - this, - Invocation.getter(#platformViewsServiceProxy), - ), - ) as _i5.PlatformViewsServiceProxy); - - @override - bool get displayWithHybridComposition => (super.noSuchMethod( - Invocation.getter(#displayWithHybridComposition), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); - - @override - _i3.PlatformWebViewController get controller => (super.noSuchMethod( - Invocation.getter(#controller), - returnValue: _FakePlatformWebViewController_14( - this, - Invocation.getter(#controller), - ), - returnValueForMissingStub: _FakePlatformWebViewController_14( - this, - Invocation.getter(#controller), - ), - ) as _i3.PlatformWebViewController); - - @override - _i4.TextDirection get layoutDirection => (super.noSuchMethod( - Invocation.getter(#layoutDirection), - returnValue: _i4.TextDirection.rtl, - returnValueForMissingStub: _i4.TextDirection.rtl, - ) as _i4.TextDirection); + Invocation.getter(#platformViewsServiceProxy), + returnValue: _FakePlatformViewsServiceProxy_13( + this, + Invocation.getter(#platformViewsServiceProxy), + ), + returnValueForMissingStub: _FakePlatformViewsServiceProxy_13( + this, + Invocation.getter(#platformViewsServiceProxy), + ), + ) + as _i5.PlatformViewsServiceProxy); + + @override + bool get displayWithHybridComposition => + (super.noSuchMethod( + Invocation.getter(#displayWithHybridComposition), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); + + @override + _i3.PlatformWebViewController get controller => + (super.noSuchMethod( + Invocation.getter(#controller), + returnValue: _FakePlatformWebViewController_14( + this, + Invocation.getter(#controller), + ), + returnValueForMissingStub: _FakePlatformWebViewController_14( + this, + Invocation.getter(#controller), + ), + ) + as _i3.PlatformWebViewController); + + @override + _i4.TextDirection get layoutDirection => + (super.noSuchMethod( + Invocation.getter(#layoutDirection), + returnValue: _i4.TextDirection.rtl, + returnValueForMissingStub: _i4.TextDirection.rtl, + ) + as _i4.TextDirection); @override Set<_i10.Factory<_i11.OneSequenceGestureRecognizer>> get gestureRecognizers => (super.noSuchMethod( - Invocation.getter(#gestureRecognizers), - returnValue: <_i10.Factory<_i11.OneSequenceGestureRecognizer>>{}, - returnValueForMissingStub: <_i10 - .Factory<_i11.OneSequenceGestureRecognizer>>{}, - ) as Set<_i10.Factory<_i11.OneSequenceGestureRecognizer>>); + Invocation.getter(#gestureRecognizers), + returnValue: <_i10.Factory<_i11.OneSequenceGestureRecognizer>>{}, + returnValueForMissingStub: + <_i10.Factory<_i11.OneSequenceGestureRecognizer>>{}, + ) + as Set<_i10.Factory<_i11.OneSequenceGestureRecognizer>>); } /// A class which mocks [ExpensiveAndroidViewController]. @@ -1960,187 +1680,160 @@ class MockAndroidWebViewWidgetCreationParams extends _i1.Mock class MockExpensiveAndroidViewController extends _i1.Mock implements _i6.ExpensiveAndroidViewController { @override - bool get requiresViewComposition => (super.noSuchMethod( - Invocation.getter(#requiresViewComposition), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool get requiresViewComposition => + (super.noSuchMethod( + Invocation.getter(#requiresViewComposition), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - int get viewId => (super.noSuchMethod( - Invocation.getter(#viewId), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + int get viewId => + (super.noSuchMethod( + Invocation.getter(#viewId), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override - bool get awaitingCreation => (super.noSuchMethod( - Invocation.getter(#awaitingCreation), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool get awaitingCreation => + (super.noSuchMethod( + Invocation.getter(#awaitingCreation), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - _i6.PointTransformer get pointTransformer => (super.noSuchMethod( - Invocation.getter(#pointTransformer), - returnValue: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), - returnValueForMissingStub: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), - ) as _i6.PointTransformer); + _i6.PointTransformer get pointTransformer => + (super.noSuchMethod( + Invocation.getter(#pointTransformer), + returnValue: + (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: + (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), + ) + as _i6.PointTransformer); @override - bool get isCreated => (super.noSuchMethod( - Invocation.getter(#isCreated), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool get isCreated => + (super.noSuchMethod( + Invocation.getter(#isCreated), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override List<_i6.PlatformViewCreatedCallback> get createdCallbacks => (super.noSuchMethod( - Invocation.getter(#createdCallbacks), - returnValue: <_i6.PlatformViewCreatedCallback>[], - returnValueForMissingStub: <_i6.PlatformViewCreatedCallback>[], - ) as List<_i6.PlatformViewCreatedCallback>); + Invocation.getter(#createdCallbacks), + returnValue: <_i6.PlatformViewCreatedCallback>[], + returnValueForMissingStub: <_i6.PlatformViewCreatedCallback>[], + ) + as List<_i6.PlatformViewCreatedCallback>); @override set pointTransformer(_i6.PointTransformer? transformer) => super.noSuchMethod( - Invocation.setter( - #pointTransformer, - transformer, - ), - returnValueForMissingStub: null, - ); - - @override - _i8.Future setOffset(_i4.Offset? off) => (super.noSuchMethod( - Invocation.method( - #setOffset, - [off], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future create({ - _i4.Size? size, - _i4.Offset? position, - }) => + Invocation.setter(#pointTransformer, transformer), + returnValueForMissingStub: null, + ); + + @override + _i8.Future setOffset(_i4.Offset? off) => (super.noSuchMethod( - Invocation.method( - #create, - [], - { - #size: size, - #position: position, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod( - Invocation.method( - #setSize, - [size], - ), - returnValue: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), - returnValueForMissingStub: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), - ) as _i8.Future<_i4.Size>); + Invocation.method(#setOffset, [off]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future create({_i4.Size? size, _i4.Offset? position}) => + (super.noSuchMethod( + Invocation.method(#create, [], {#size: size, #position: position}), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future<_i4.Size> setSize(_i4.Size? size) => + (super.noSuchMethod( + Invocation.method(#setSize, [size]), + returnValue: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), + ), + ) + as _i8.Future<_i4.Size>); @override _i8.Future sendMotionEvent(_i6.AndroidMotionEvent? event) => (super.noSuchMethod( - Invocation.method( - #sendMotionEvent, - [event], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#sendMotionEvent, [event]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override void addOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #addOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override void removeOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #removeOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override _i8.Future setLayoutDirection(_i4.TextDirection? layoutDirection) => (super.noSuchMethod( - Invocation.method( - #setLayoutDirection, - [layoutDirection], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setLayoutDirection, [layoutDirection]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future dispatchPointerEvent(_i11.PointerEvent? event) => (super.noSuchMethod( - Invocation.method( - #dispatchPointerEvent, - [event], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future clearFocus() => (super.noSuchMethod( - Invocation.method( - #clearFocus, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#dispatchPointerEvent, [event]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future clearFocus() => + (super.noSuchMethod( + Invocation.method(#clearFocus, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future dispose() => + (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); } /// A class which mocks [FlutterAssetManager]. @@ -2149,73 +1842,64 @@ class MockExpensiveAndroidViewController extends _i1.Mock class MockFlutterAssetManager extends _i1.Mock implements _i2.FlutterAssetManager { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i8.Future> list(String? path) => (super.noSuchMethod( - Invocation.method( - #list, - [path], - ), - returnValue: _i8.Future>.value([]), - returnValueForMissingStub: _i8.Future>.value([]), - ) as _i8.Future>); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i8.Future> list(String? path) => + (super.noSuchMethod( + Invocation.method(#list, [path]), + returnValue: _i8.Future>.value([]), + returnValueForMissingStub: _i8.Future>.value( + [], + ), + ) + as _i8.Future>); @override _i8.Future getAssetFilePathByName(String? name) => (super.noSuchMethod( - Invocation.method( - #getAssetFilePathByName, - [name], - ), - returnValue: _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getAssetFilePathByName, - [name], - ), - )), - returnValueForMissingStub: - _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getAssetFilePathByName, - [name], - ), - )), - ) as _i8.Future); - - @override - _i2.FlutterAssetManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeFlutterAssetManager_10( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeFlutterAssetManager_10( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.FlutterAssetManager); + Invocation.method(#getAssetFilePathByName, [name]), + returnValue: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getAssetFilePathByName, [name]), + ), + ), + returnValueForMissingStub: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getAssetFilePathByName, [name]), + ), + ), + ) + as _i8.Future); + + @override + _i2.FlutterAssetManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFlutterAssetManager_10( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeFlutterAssetManager_10( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.FlutterAssetManager); } /// A class which mocks [GeolocationPermissionsCallback]. @@ -2224,58 +1908,43 @@ class MockFlutterAssetManager extends _i1.Mock class MockGeolocationPermissionsCallback extends _i1.Mock implements _i2.GeolocationPermissionsCallback { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i8.Future invoke( - String? origin, - bool? allow, - bool? retain, - ) => - (super.noSuchMethod( - Invocation.method( - #invoke, - [ - origin, - allow, - retain, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.GeolocationPermissionsCallback pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeGeolocationPermissionsCallback_16( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeGeolocationPermissionsCallback_16( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.GeolocationPermissionsCallback); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i8.Future invoke(String? origin, bool? allow, bool? retain) => + (super.noSuchMethod( + Invocation.method(#invoke, [origin, allow, retain]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.GeolocationPermissionsCallback pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeGeolocationPermissionsCallback_16( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeGeolocationPermissionsCallback_16( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.GeolocationPermissionsCallback); } /// A class which mocks [JavaScriptChannel]. @@ -2283,71 +1952,60 @@ class MockGeolocationPermissionsCallback extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockJavaScriptChannel extends _i1.Mock implements _i2.JavaScriptChannel { @override - String get channelName => (super.noSuchMethod( - Invocation.getter(#channelName), - returnValue: _i12.dummyValue( - this, - Invocation.getter(#channelName), - ), - returnValueForMissingStub: _i12.dummyValue( - this, - Invocation.getter(#channelName), - ), - ) as String); - - @override - void Function( - _i2.JavaScriptChannel, - String, - ) get postMessage => (super.noSuchMethod( - Invocation.getter(#postMessage), - returnValue: ( - _i2.JavaScriptChannel pigeon_instance, - String message, - ) {}, - returnValueForMissingStub: ( - _i2.JavaScriptChannel pigeon_instance, - String message, - ) {}, - ) as void Function( - _i2.JavaScriptChannel, - String, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.JavaScriptChannel pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeJavaScriptChannel_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeJavaScriptChannel_8( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.JavaScriptChannel); + String get channelName => + (super.noSuchMethod( + Invocation.getter(#channelName), + returnValue: _i12.dummyValue( + this, + Invocation.getter(#channelName), + ), + returnValueForMissingStub: _i12.dummyValue( + this, + Invocation.getter(#channelName), + ), + ) + as String); + + @override + void Function(_i2.JavaScriptChannel, String) get postMessage => + (super.noSuchMethod( + Invocation.getter(#postMessage), + returnValue: + (_i2.JavaScriptChannel pigeon_instance, String message) {}, + returnValueForMissingStub: + (_i2.JavaScriptChannel pigeon_instance, String message) {}, + ) + as void Function(_i2.JavaScriptChannel, String)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.JavaScriptChannel pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeJavaScriptChannel_8( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeJavaScriptChannel_8( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.JavaScriptChannel); } /// A class which mocks [PermissionRequest]. @@ -2355,66 +2013,61 @@ class MockJavaScriptChannel extends _i1.Mock implements _i2.JavaScriptChannel { /// See the documentation for Mockito's code generation for more information. class MockPermissionRequest extends _i1.Mock implements _i2.PermissionRequest { @override - List get resources => (super.noSuchMethod( - Invocation.getter(#resources), - returnValue: [], - returnValueForMissingStub: [], - ) as List); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i8.Future grant(List? resources) => (super.noSuchMethod( - Invocation.method( - #grant, - [resources], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future deny() => (super.noSuchMethod( - Invocation.method( - #deny, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.PermissionRequest pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakePermissionRequest_17( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakePermissionRequest_17( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.PermissionRequest); + List get resources => + (super.noSuchMethod( + Invocation.getter(#resources), + returnValue: [], + returnValueForMissingStub: [], + ) + as List); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i8.Future grant(List? resources) => + (super.noSuchMethod( + Invocation.method(#grant, [resources]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future deny() => + (super.noSuchMethod( + Invocation.method(#deny, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.PermissionRequest pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePermissionRequest_17( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakePermissionRequest_17( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.PermissionRequest); } /// A class which mocks [PlatformViewsServiceProxy]. @@ -2433,49 +2086,38 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i4.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - returnValue: _FakeExpensiveAndroidViewController_18( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - ), - returnValueForMissingStub: _FakeExpensiveAndroidViewController_18( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { + Invocation.method(#initExpensiveAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - ), - ) as _i6.ExpensiveAndroidViewController); + }), + returnValue: _FakeExpensiveAndroidViewController_18( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeExpensiveAndroidViewController_18( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) + as _i6.ExpensiveAndroidViewController); @override _i6.SurfaceAndroidViewController initSurfaceAndroidView({ @@ -2487,49 +2129,38 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i4.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - returnValue: _FakeSurfaceAndroidViewController_19( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { + Invocation.method(#initSurfaceAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - ), - returnValueForMissingStub: _FakeSurfaceAndroidViewController_19( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), - ), - ) as _i6.SurfaceAndroidViewController); + }), + returnValue: _FakeSurfaceAndroidViewController_19( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeSurfaceAndroidViewController_19( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) + as _i6.SurfaceAndroidViewController); } /// A class which mocks [SurfaceAndroidViewController]. @@ -2538,187 +2169,160 @@ class MockPlatformViewsServiceProxy extends _i1.Mock class MockSurfaceAndroidViewController extends _i1.Mock implements _i6.SurfaceAndroidViewController { @override - bool get requiresViewComposition => (super.noSuchMethod( - Invocation.getter(#requiresViewComposition), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool get requiresViewComposition => + (super.noSuchMethod( + Invocation.getter(#requiresViewComposition), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - int get viewId => (super.noSuchMethod( - Invocation.getter(#viewId), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + int get viewId => + (super.noSuchMethod( + Invocation.getter(#viewId), + returnValue: 0, + returnValueForMissingStub: 0, + ) + as int); @override - bool get awaitingCreation => (super.noSuchMethod( - Invocation.getter(#awaitingCreation), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool get awaitingCreation => + (super.noSuchMethod( + Invocation.getter(#awaitingCreation), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override - _i6.PointTransformer get pointTransformer => (super.noSuchMethod( - Invocation.getter(#pointTransformer), - returnValue: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), - returnValueForMissingStub: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), - ) as _i6.PointTransformer); + _i6.PointTransformer get pointTransformer => + (super.noSuchMethod( + Invocation.getter(#pointTransformer), + returnValue: + (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: + (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), + ) + as _i6.PointTransformer); @override - bool get isCreated => (super.noSuchMethod( - Invocation.getter(#isCreated), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); + bool get isCreated => + (super.noSuchMethod( + Invocation.getter(#isCreated), + returnValue: false, + returnValueForMissingStub: false, + ) + as bool); @override List<_i6.PlatformViewCreatedCallback> get createdCallbacks => (super.noSuchMethod( - Invocation.getter(#createdCallbacks), - returnValue: <_i6.PlatformViewCreatedCallback>[], - returnValueForMissingStub: <_i6.PlatformViewCreatedCallback>[], - ) as List<_i6.PlatformViewCreatedCallback>); + Invocation.getter(#createdCallbacks), + returnValue: <_i6.PlatformViewCreatedCallback>[], + returnValueForMissingStub: <_i6.PlatformViewCreatedCallback>[], + ) + as List<_i6.PlatformViewCreatedCallback>); @override set pointTransformer(_i6.PointTransformer? transformer) => super.noSuchMethod( - Invocation.setter( - #pointTransformer, - transformer, - ), - returnValueForMissingStub: null, - ); - - @override - _i8.Future setOffset(_i4.Offset? off) => (super.noSuchMethod( - Invocation.method( - #setOffset, - [off], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future create({ - _i4.Size? size, - _i4.Offset? position, - }) => + Invocation.setter(#pointTransformer, transformer), + returnValueForMissingStub: null, + ); + + @override + _i8.Future setOffset(_i4.Offset? off) => + (super.noSuchMethod( + Invocation.method(#setOffset, [off]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future create({_i4.Size? size, _i4.Offset? position}) => + (super.noSuchMethod( + Invocation.method(#create, [], {#size: size, #position: position}), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod( - Invocation.method( - #create, - [], - { - #size: size, - #position: position, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod( - Invocation.method( - #setSize, - [size], - ), - returnValue: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), - returnValueForMissingStub: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), - ) as _i8.Future<_i4.Size>); + Invocation.method(#setSize, [size]), + returnValue: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), + ), + ) + as _i8.Future<_i4.Size>); @override _i8.Future sendMotionEvent(_i6.AndroidMotionEvent? event) => (super.noSuchMethod( - Invocation.method( - #sendMotionEvent, - [event], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#sendMotionEvent, [event]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override void addOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #addOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override void removeOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => - super.noSuchMethod( - Invocation.method( - #removeOnPlatformViewCreatedListener, - [listener], - ), - returnValueForMissingStub: null, - ); + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override _i8.Future setLayoutDirection(_i4.TextDirection? layoutDirection) => (super.noSuchMethod( - Invocation.method( - #setLayoutDirection, - [layoutDirection], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setLayoutDirection, [layoutDirection]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future dispatchPointerEvent(_i11.PointerEvent? event) => (super.noSuchMethod( - Invocation.method( - #dispatchPointerEvent, - [event], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future clearFocus() => (super.noSuchMethod( - Invocation.method( - #clearFocus, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#dispatchPointerEvent, [event]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future clearFocus() => + (super.noSuchMethod( + Invocation.method(#clearFocus, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future dispose() => + (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); } /// A class which mocks [WebChromeClient]. @@ -2730,144 +2334,136 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { _i2.WebChromeClient, _i2.WebView, _i2.FileChooserParams, - ) get onShowFileChooser => (super.noSuchMethod( - Invocation.getter(#onShowFileChooser), - returnValue: ( - _i2.WebChromeClient pigeon_instance, - _i2.WebView webView, - _i2.FileChooserParams params, - ) => - _i8.Future>.value([]), - returnValueForMissingStub: ( - _i2.WebChromeClient pigeon_instance, - _i2.WebView webView, - _i2.FileChooserParams params, - ) => - _i8.Future>.value([]), - ) as _i8.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - )); - - @override - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - ) get onJsConfirm => (super.noSuchMethod( - Invocation.getter(#onJsConfirm), - returnValue: ( - _i2.WebChromeClient pigeon_instance, - _i2.WebView webView, - String url, - String message, - ) => - _i8.Future.value(false), - returnValueForMissingStub: ( - _i2.WebChromeClient pigeon_instance, - _i2.WebView webView, - String url, - String message, - ) => - _i8.Future.value(false), - ) as _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + ) + get onShowFileChooser => + (super.noSuchMethod( + Invocation.getter(#onShowFileChooser), + returnValue: + ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + _i2.FileChooserParams params, + ) => _i8.Future>.value([]), + returnValueForMissingStub: + ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + _i2.FileChooserParams params, + ) => _i8.Future>.value([]), + ) + as _i8.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + )); + + @override + _i8.Future Function(_i2.WebChromeClient, _i2.WebView, String, String) + get onJsConfirm => + (super.noSuchMethod( + Invocation.getter(#onJsConfirm), + returnValue: + ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + String url, + String message, + ) => _i8.Future.value(false), + returnValueForMissingStub: + ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + String url, + String message, + ) => _i8.Future.value(false), + ) + as _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i8.Future setSynchronousReturnValueForOnShowFileChooser(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnShowFileChooser, - [value], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setSynchronousReturnValueForOnShowFileChooser, [ + value, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setSynchronousReturnValueForOnConsoleMessage(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnConsoleMessage, - [value], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setSynchronousReturnValueForOnConsoleMessage, [ + value, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setSynchronousReturnValueForOnJsAlert(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsAlert, - [value], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setSynchronousReturnValueForOnJsAlert, [value]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setSynchronousReturnValueForOnJsConfirm(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsConfirm, - [value], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setSynchronousReturnValueForOnJsConfirm, [ + value, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setSynchronousReturnValueForOnJsPrompt(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsPrompt, - [value], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.WebChromeClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebChromeClient_0( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeWebChromeClient_0( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebChromeClient); + Invocation.method(#setSynchronousReturnValueForOnJsPrompt, [value]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.WebChromeClient pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebChromeClient_0( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeWebChromeClient_0( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebChromeClient); } /// A class which mocks [WebSettings]. @@ -2875,228 +2471,199 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { /// See the documentation for Mockito's code generation for more information. class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i8.Future setDomStorageEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setDomStorageEnabled, - [flag], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i8.Future setDomStorageEnabled(bool? flag) => + (super.noSuchMethod( + Invocation.method(#setDomStorageEnabled, [flag]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setJavaScriptCanOpenWindowsAutomatically(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptCanOpenWindowsAutomatically, - [flag], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setJavaScriptCanOpenWindowsAutomatically, [ + flag, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setSupportMultipleWindows(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportMultipleWindows, - [support], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setSupportMultipleWindows, [support]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future setJavaScriptEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptEnabled, - [flag], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future setJavaScriptEnabled(bool? flag) => + (super.noSuchMethod( + Invocation.method(#setJavaScriptEnabled, [flag]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setUserAgentString(String? userAgentString) => (super.noSuchMethod( - Invocation.method( - #setUserAgentString, - [userAgentString], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setUserAgentString, [userAgentString]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future setSupportZoom(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportZoom, - [support], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future setSupportZoom(bool? support) => + (super.noSuchMethod( + Invocation.method(#setSupportZoom, [support]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setLoadWithOverviewMode(bool? overview) => (super.noSuchMethod( - Invocation.method( - #setLoadWithOverviewMode, - [overview], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setUseWideViewPort(bool? use) => (super.noSuchMethod( - Invocation.method( - #setUseWideViewPort, - [use], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setDisplayZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setDisplayZoomControls, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setBuiltInZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setBuiltInZoomControls, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setAllowFileAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future getUserAgentString() => (super.noSuchMethod( - Invocation.method( - #getUserAgentString, - [], - ), - returnValue: _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getUserAgentString, - [], - ), - )), - returnValueForMissingStub: - _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getUserAgentString, - [], - ), - )), - ) as _i8.Future); + Invocation.method(#setLoadWithOverviewMode, [overview]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setUseWideViewPort(bool? use) => + (super.noSuchMethod( + Invocation.method(#setUseWideViewPort, [use]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setDisplayZoomControls(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setDisplayZoomControls, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setBuiltInZoomControls(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setBuiltInZoomControls, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setAllowFileAccess(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setAllowFileAccess, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setAllowContentAccess(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setAllowContentAccess, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setGeolocationEnabled(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setGeolocationEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setTextZoom(int? textZoom) => + (super.noSuchMethod( + Invocation.method(#setTextZoom, [textZoom]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future getUserAgentString() => + (super.noSuchMethod( + Invocation.method(#getUserAgentString, []), + returnValue: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getUserAgentString, []), + ), + ), + returnValueForMissingStub: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getUserAgentString, []), + ), + ), + ) + as _i8.Future); @override _i8.Future setMixedContentMode(_i2.MixedContentMode? mode) => (super.noSuchMethod( - Invocation.method( - #setMixedContentMode, - [mode], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.WebSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebSettings_20( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeWebSettings_20( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebSettings); + Invocation.method(#setMixedContentMode, [mode]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.WebSettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebSettings_20( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeWebSettings_20( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebSettings); } /// A class which mocks [WebView]. @@ -3104,71 +2671,58 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { /// See the documentation for Mockito's code generation for more information. class MockWebView extends _i1.Mock implements _i2.WebView { @override - _i2.WebSettings get settings => (super.noSuchMethod( - Invocation.getter(#settings), - returnValue: _FakeWebSettings_20( - this, - Invocation.getter(#settings), - ), - returnValueForMissingStub: _FakeWebSettings_20( - this, - Invocation.getter(#settings), - ), - ) as _i2.WebSettings); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.WebSettings pigeonVar_settings() => (super.noSuchMethod( - Invocation.method( - #pigeonVar_settings, - [], - ), - returnValue: _FakeWebSettings_20( - this, - Invocation.method( - #pigeonVar_settings, - [], - ), - ), - returnValueForMissingStub: _FakeWebSettings_20( - this, - Invocation.method( - #pigeonVar_settings, - [], - ), - ), - ) as _i2.WebSettings); - - @override - _i8.Future loadData( - String? data, - String? mimeType, - String? encoding, - ) => + _i2.WebSettings get settings => + (super.noSuchMethod( + Invocation.getter(#settings), + returnValue: _FakeWebSettings_20( + this, + Invocation.getter(#settings), + ), + returnValueForMissingStub: _FakeWebSettings_20( + this, + Invocation.getter(#settings), + ), + ) + as _i2.WebSettings); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.method( - #loadData, - [ - data, - mimeType, - encoding, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.WebSettings pigeonVar_settings() => + (super.noSuchMethod( + Invocation.method(#pigeonVar_settings, []), + returnValue: _FakeWebSettings_20( + this, + Invocation.method(#pigeonVar_settings, []), + ), + returnValueForMissingStub: _FakeWebSettings_20( + this, + Invocation.method(#pigeonVar_settings, []), + ), + ) + as _i2.WebSettings); + + @override + _i8.Future loadData(String? data, String? mimeType, String? encoding) => + (super.noSuchMethod( + Invocation.method(#loadData, [data, mimeType, encoding]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future loadDataWithBaseUrl( @@ -3179,330 +2733,258 @@ class MockWebView extends _i1.Mock implements _i2.WebView { String? historyUrl, ) => (super.noSuchMethod( - Invocation.method( - #loadDataWithBaseUrl, - [ - baseUrl, - data, - mimeType, - encoding, - historyUrl, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future loadUrl( - String? url, - Map? headers, - ) => + Invocation.method(#loadDataWithBaseUrl, [ + baseUrl, + data, + mimeType, + encoding, + historyUrl, + ]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future loadUrl(String? url, Map? headers) => (super.noSuchMethod( - Invocation.method( - #loadUrl, - [ - url, - headers, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future postUrl( - String? url, - _i13.Uint8List? data, - ) => + Invocation.method(#loadUrl, [url, headers]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future postUrl(String? url, _i13.Uint8List? data) => + (super.noSuchMethod( + Invocation.method(#postUrl, [url, data]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future getUrl() => + (super.noSuchMethod( + Invocation.method(#getUrl, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future canGoBack() => + (super.noSuchMethod( + Invocation.method(#canGoBack, []), + returnValue: _i8.Future.value(false), + returnValueForMissingStub: _i8.Future.value(false), + ) + as _i8.Future); + + @override + _i8.Future canGoForward() => + (super.noSuchMethod( + Invocation.method(#canGoForward, []), + returnValue: _i8.Future.value(false), + returnValueForMissingStub: _i8.Future.value(false), + ) + as _i8.Future); + + @override + _i8.Future goBack() => + (super.noSuchMethod( + Invocation.method(#goBack, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future goForward() => + (super.noSuchMethod( + Invocation.method(#goForward, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future reload() => (super.noSuchMethod( - Invocation.method( - #postUrl, - [ - url, - data, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future getUrl() => (super.noSuchMethod( - Invocation.method( - #getUrl, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), - returnValue: _i8.Future.value(false), - returnValueForMissingStub: _i8.Future.value(false), - ) as _i8.Future); - - @override - _i8.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), - returnValue: _i8.Future.value(false), - returnValueForMissingStub: _i8.Future.value(false), - ) as _i8.Future); - - @override - _i8.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future clearCache(bool? includeDiskFiles) => (super.noSuchMethod( - Invocation.method( - #clearCache, - [includeDiskFiles], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#reload, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future clearCache(bool? includeDiskFiles) => + (super.noSuchMethod( + Invocation.method(#clearCache, [includeDiskFiles]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future evaluateJavascript(String? javascriptString) => (super.noSuchMethod( - Invocation.method( - #evaluateJavascript, - [javascriptString], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#evaluateJavascript, [javascriptString]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future getTitle() => + (super.noSuchMethod( + Invocation.method(#getTitle, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setWebViewClient(_i2.WebViewClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebViewClient, - [client], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setWebViewClient, [client]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future addJavaScriptChannel(_i2.JavaScriptChannel? channel) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [channel], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#addJavaScriptChannel, [channel]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override - _i8.Future removeJavaScriptChannel(String? name) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [name], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + _i8.Future removeJavaScriptChannel(String? name) => + (super.noSuchMethod( + Invocation.method(#removeJavaScriptChannel, [name]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setDownloadListener(_i2.DownloadListener? listener) => (super.noSuchMethod( - Invocation.method( - #setDownloadListener, - [listener], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setDownloadListener, [listener]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setWebChromeClient(_i2.WebChromeClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebChromeClient, - [client], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future setBackgroundColor(int? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.WebView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebView_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeWebView_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebView); - - @override - _i8.Future scrollTo( - int? x, - int? y, - ) => + Invocation.method(#setWebChromeClient, [client]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future setBackgroundColor(int? color) => (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future scrollBy( - int? x, - int? y, - ) => + Invocation.method(#setBackgroundColor, [color]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future destroy() => (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i8.Future<_i2.WebViewPoint> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], - ), - returnValue: _i8.Future<_i2.WebViewPoint>.value(_FakeWebViewPoint_21( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - returnValueForMissingStub: - _i8.Future<_i2.WebViewPoint>.value(_FakeWebViewPoint_21( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - ) as _i8.Future<_i2.WebViewPoint>); + Invocation.method(#destroy, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.WebView pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebView_7( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeWebView_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebView); + + @override + _i8.Future scrollTo(int? x, int? y) => + (super.noSuchMethod( + Invocation.method(#scrollTo, [x, y]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future scrollBy(int? x, int? y) => + (super.noSuchMethod( + Invocation.method(#scrollBy, [x, y]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i8.Future<_i2.WebViewPoint> getScrollPosition() => + (super.noSuchMethod( + Invocation.method(#getScrollPosition, []), + returnValue: _i8.Future<_i2.WebViewPoint>.value( + _FakeWebViewPoint_21( + this, + Invocation.method(#getScrollPosition, []), + ), + ), + returnValueForMissingStub: _i8.Future<_i2.WebViewPoint>.value( + _FakeWebViewPoint_21( + this, + Invocation.method(#getScrollPosition, []), + ), + ), + ) + as _i8.Future<_i2.WebViewPoint>); @override _i8.Future setVerticalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setVerticalScrollBarEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setVerticalScrollBarEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setHorizontalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setHorizontalScrollBarEnabled, - [enabled], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setHorizontalScrollBarEnabled, [enabled]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); @override _i8.Future setOverScrollMode(_i2.OverScrollMode? mode) => (super.noSuchMethod( - Invocation.method( - #setOverScrollMode, - [mode], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); + Invocation.method(#setOverScrollMode, [mode]), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); } /// A class which mocks [WebViewClient]. @@ -3510,51 +2992,48 @@ class MockWebView extends _i1.Mock implements _i2.WebView { /// See the documentation for Mockito's code generation for more information. class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i8.Future setSynchronousReturnValueForShouldOverrideUrlLoading( - bool? value) => - (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForShouldOverrideUrlLoading, - [value], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.WebViewClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebViewClient_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeWebViewClient_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebViewClient); + bool? value, + ) => + (super.noSuchMethod( + Invocation.method( + #setSynchronousReturnValueForShouldOverrideUrlLoading, + [value], + ), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.WebViewClient pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebViewClient_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeWebViewClient_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebViewClient); } /// A class which mocks [WebStorage]. @@ -3562,47 +3041,41 @@ class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { /// See the documentation for Mockito's code generation for more information. class MockWebStorage extends _i1.Mock implements _i2.WebStorage { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_12( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i8.Future deleteAllData() => (super.noSuchMethod( - Invocation.method( - #deleteAllData, - [], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - - @override - _i2.WebStorage pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebStorage_11( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - returnValueForMissingStub: _FakeWebStorage_11( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebStorage); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_12( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i8.Future deleteAllData() => + (super.noSuchMethod( + Invocation.method(#deleteAllData, []), + returnValue: _i8.Future.value(), + returnValueForMissingStub: _i8.Future.value(), + ) + as _i8.Future); + + @override + _i2.WebStorage pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebStorage_11( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeWebStorage_11( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebStorage); } diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart index 04c108a46b1..c8d85365c20 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart @@ -12,27 +12,27 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte import 'android_webview_cookie_manager_test.mocks.dart'; -@GenerateMocks([ - android_webview.CookieManager, - AndroidWebViewController, -]) +@GenerateMocks([android_webview.CookieManager, AndroidWebViewController]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('clearCookies should call android_webview.clearCookies', () async { final android_webview.CookieManager mockCookieManager = MockCookieManager(); - when(mockCookieManager.removeAllCookies()) - .thenAnswer((_) => Future.value(true)); + when( + mockCookieManager.removeAllCookies(), + ).thenAnswer((_) => Future.value(true)); final AndroidWebViewCookieManagerCreationParams params = - AndroidWebViewCookieManagerCreationParams - .fromPlatformWebViewCookieManagerCreationParams( - const PlatformWebViewCookieManagerCreationParams()); + AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( + const PlatformWebViewCookieManagerCreationParams(), + ); - final bool hasClearedCookies = await AndroidWebViewCookieManager(params, - cookieManager: mockCookieManager) - .clearCookies(); + final bool hasClearedCookies = + await AndroidWebViewCookieManager( + params, + cookieManager: mockCookieManager, + ).clearCookies(); expect(hasClearedCookies, true); verify(mockCookieManager.removeAllCookies()); @@ -40,45 +40,48 @@ void main() { test('setCookie should throw ArgumentError for cookie with invalid path', () { final AndroidWebViewCookieManagerCreationParams params = - AndroidWebViewCookieManagerCreationParams - .fromPlatformWebViewCookieManagerCreationParams( - const PlatformWebViewCookieManagerCreationParams()); + AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( + const PlatformWebViewCookieManagerCreationParams(), + ); final AndroidWebViewCookieManager androidCookieManager = AndroidWebViewCookieManager(params, cookieManager: MockCookieManager()); expect( - () => androidCookieManager.setCookie(const WebViewCookie( - name: 'foo', - value: 'bar', - domain: 'flutter.dev', - path: 'invalid;path', - )), + () => androidCookieManager.setCookie( + const WebViewCookie( + name: 'foo', + value: 'bar', + domain: 'flutter.dev', + path: 'invalid;path', + ), + ), throwsA(const TypeMatcher()), ); }); test( - 'setCookie should call android_webview.setCookie with properly formatted cookie value', - () { - final android_webview.CookieManager mockCookieManager = MockCookieManager(); - final AndroidWebViewCookieManagerCreationParams params = - AndroidWebViewCookieManagerCreationParams - .fromPlatformWebViewCookieManagerCreationParams( - const PlatformWebViewCookieManagerCreationParams()); - - AndroidWebViewCookieManager(params, cookieManager: mockCookieManager) - .setCookie(const WebViewCookie( - name: 'foo&', - value: 'bar@', - domain: 'flutter.dev', - )); - - verify(mockCookieManager.setCookie( - 'flutter.dev', - 'foo%26=bar%40; path=/', - )); - }); + 'setCookie should call android_webview.setCookie with properly formatted cookie value', + () { + final android_webview.CookieManager mockCookieManager = + MockCookieManager(); + final AndroidWebViewCookieManagerCreationParams params = + AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( + const PlatformWebViewCookieManagerCreationParams(), + ); + + AndroidWebViewCookieManager( + params, + cookieManager: mockCookieManager, + ).setCookie( + const WebViewCookie(name: 'foo&', value: 'bar@', domain: 'flutter.dev'), + ); + + verify( + mockCookieManager.setCookie('flutter.dev', 'foo%26=bar%40; path=/'), + ); + }, + ); test('setAcceptThirdPartyCookies', () async { final MockAndroidWebViewController mockController = @@ -86,20 +89,19 @@ void main() { final android_webview.PigeonInstanceManager instanceManager = android_webview.PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); - final android_webview.WebView webView = - android_webview.WebView.pigeon_detached( - pigeon_instanceManager: instanceManager, - ); + final android_webview.WebView webView = android_webview + .WebView.pigeon_detached(pigeon_instanceManager: instanceManager); - final int webViewIdentifier = - instanceManager.addDartCreatedInstance(webView); + final int webViewIdentifier = instanceManager.addDartCreatedInstance( + webView, + ); when(mockController.webViewIdentifier).thenReturn(webViewIdentifier); final AndroidWebViewCookieManagerCreationParams params = - AndroidWebViewCookieManagerCreationParams - .fromPlatformWebViewCookieManagerCreationParams( - const PlatformWebViewCookieManagerCreationParams()); + AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( + const PlatformWebViewCookieManagerCreationParams(), + ); final MockCookieManager mockCookieManager = MockCookieManager(); // ignore: invalid_use_of_protected_member diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart index c305241cbf6..67506bd8218 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart @@ -29,23 +29,13 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCookieManager_1 extends _i1.SmartFake implements _i2.CookieManager { - _FakeCookieManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCookieManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformWebViewControllerCreationParams_2 extends _i1.SmartFake @@ -53,30 +43,17 @@ class _FakePlatformWebViewControllerCreationParams_2 extends _i1.SmartFake _FakePlatformWebViewControllerCreationParams_2( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeObject_3 extends _i1.SmartFake implements Object { - _FakeObject_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOffset_4 extends _i1.SmartFake implements _i4.Offset { - _FakeOffset_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOffset_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [CookieManager]. @@ -88,39 +65,32 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i5.Future setCookie( - String? url, - String? value, - ) => + _i5.Future setCookie(String? url, String? value) => (super.noSuchMethod( - Invocation.method( - #setCookie, - [ - url, - value, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setCookie, [url, value]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future removeAllCookies() => (super.noSuchMethod( - Invocation.method( - #removeAllCookies, - [], - ), - returnValue: _i5.Future.value(false), - ) as _i5.Future); + _i5.Future removeAllCookies() => + (super.noSuchMethod( + Invocation.method(#removeAllCookies, []), + returnValue: _i5.Future.value(false), + ) + as _i5.Future); @override _i5.Future setAcceptThirdPartyCookies( @@ -128,31 +98,22 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { bool? accept, ) => (super.noSuchMethod( - Invocation.method( - #setAcceptThirdPartyCookies, - [ - webView, - accept, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i2.CookieManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeCookieManager_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.CookieManager); + Invocation.method(#setAcceptThirdPartyCookies, [webView, accept]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i2.CookieManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCookieManager_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.CookieManager); } /// A class which mocks [AndroidWebViewController]. @@ -165,401 +126,344 @@ class MockAndroidWebViewController extends _i1.Mock } @override - int get webViewIdentifier => (super.noSuchMethod( - Invocation.getter(#webViewIdentifier), - returnValue: 0, - ) as int); + int get webViewIdentifier => + (super.noSuchMethod(Invocation.getter(#webViewIdentifier), returnValue: 0) + as int); @override - _i3.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod( - Invocation.getter(#params), - returnValue: _FakePlatformWebViewControllerCreationParams_2( - this, - Invocation.getter(#params), - ), - ) as _i3.PlatformWebViewControllerCreationParams); + _i3.PlatformWebViewControllerCreationParams get params => + (super.noSuchMethod( + Invocation.getter(#params), + returnValue: _FakePlatformWebViewControllerCreationParams_2( + this, + Invocation.getter(#params), + ), + ) + as _i3.PlatformWebViewControllerCreationParams); @override - _i5.Future setAllowFileAccess(bool? allow) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [allow], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future setAllowFileAccess(bool? allow) => + (super.noSuchMethod( + Invocation.method(#setAllowFileAccess, [allow]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future loadFile(String? absoluteFilePath) => (super.noSuchMethod( - Invocation.method( - #loadFile, - [absoluteFilePath], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future loadFile(String? absoluteFilePath) => + (super.noSuchMethod( + Invocation.method(#loadFile, [absoluteFilePath]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future loadFlutterAsset(String? key) => (super.noSuchMethod( - Invocation.method( - #loadFlutterAsset, - [key], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future loadFlutterAsset(String? key) => + (super.noSuchMethod( + Invocation.method(#loadFlutterAsset, [key]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future loadHtmlString( - String? html, { - String? baseUrl, - }) => + _i5.Future loadHtmlString(String? html, {String? baseUrl}) => (super.noSuchMethod( - Invocation.method( - #loadHtmlString, - [html], - {#baseUrl: baseUrl}, - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#loadHtmlString, [html], {#baseUrl: baseUrl}), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future loadRequest(_i3.LoadRequestParams? params) => (super.noSuchMethod( - Invocation.method( - #loadRequest, - [params], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future currentUrl() => (super.noSuchMethod( - Invocation.method( - #currentUrl, - [], - ), - returnValue: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), - returnValue: _i5.Future.value(false), - ) as _i5.Future); - - @override - _i5.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), - returnValue: _i5.Future.value(false), - ) as _i5.Future); - - @override - _i5.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future clearCache() => (super.noSuchMethod( - Invocation.method( - #clearCache, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future clearLocalStorage() => (super.noSuchMethod( - Invocation.method( - #clearLocalStorage, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#loadRequest, [params]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future currentUrl() => + (super.noSuchMethod( + Invocation.method(#currentUrl, []), + returnValue: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future canGoBack() => + (super.noSuchMethod( + Invocation.method(#canGoBack, []), + returnValue: _i5.Future.value(false), + ) + as _i5.Future); + + @override + _i5.Future canGoForward() => + (super.noSuchMethod( + Invocation.method(#canGoForward, []), + returnValue: _i5.Future.value(false), + ) + as _i5.Future); + + @override + _i5.Future goBack() => + (super.noSuchMethod( + Invocation.method(#goBack, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future goForward() => + (super.noSuchMethod( + Invocation.method(#goForward, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future reload() => + (super.noSuchMethod( + Invocation.method(#reload, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future clearCache() => + (super.noSuchMethod( + Invocation.method(#clearCache, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future clearLocalStorage() => + (super.noSuchMethod( + Invocation.method(#clearLocalStorage, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setPlatformNavigationDelegate( - _i3.PlatformNavigationDelegate? handler) => + _i3.PlatformNavigationDelegate? handler, + ) => (super.noSuchMethod( - Invocation.method( - #setPlatformNavigationDelegate, - [handler], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setPlatformNavigationDelegate, [handler]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future runJavaScript(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScript, - [javaScript], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future runJavaScript(String? javaScript) => + (super.noSuchMethod( + Invocation.method(#runJavaScript, [javaScript]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future runJavaScriptReturningResult(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - returnValue: _i5.Future.value(_FakeObject_3( - this, - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - )), - ) as _i5.Future); + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + returnValue: _i5.Future.value( + _FakeObject_3( + this, + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + ), + ), + ) + as _i5.Future); @override _i5.Future addJavaScriptChannel( - _i3.JavaScriptChannelParams? javaScriptChannelParams) => + _i3.JavaScriptChannelParams? javaScriptChannelParams, + ) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [javaScriptChannelParams], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#addJavaScriptChannel, [javaScriptChannelParams]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future removeJavaScriptChannel(String? javaScriptChannelName) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [javaScriptChannelName], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#removeJavaScriptChannel, [ + javaScriptChannelName, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), - returnValue: _i5.Future.value(), - ) as _i5.Future); + _i5.Future getTitle() => + (super.noSuchMethod( + Invocation.method(#getTitle, []), + returnValue: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future scrollTo( - int? x, - int? y, - ) => + _i5.Future scrollTo(int? x, int? y) => (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future scrollBy( - int? x, - int? y, - ) => + Invocation.method(#scrollTo, [x, y]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future scrollBy(int? x, int? y) => (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], - ), - returnValue: _i5.Future<_i4.Offset>.value(_FakeOffset_4( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - ) as _i5.Future<_i4.Offset>); - - @override - _i5.Future enableZoom(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #enableZoom, - [enabled], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setBackgroundColor(_i4.Color? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#scrollBy, [x, y]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i4.Offset> getScrollPosition() => + (super.noSuchMethod( + Invocation.method(#getScrollPosition, []), + returnValue: _i5.Future<_i4.Offset>.value( + _FakeOffset_4(this, Invocation.method(#getScrollPosition, [])), + ), + ) + as _i5.Future<_i4.Offset>); + + @override + _i5.Future enableZoom(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#enableZoom, [enabled]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setBackgroundColor(_i4.Color? color) => + (super.noSuchMethod( + Invocation.method(#setBackgroundColor, [color]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setJavaScriptMode(_i3.JavaScriptMode? javaScriptMode) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptMode, - [javaScriptMode], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setJavaScriptMode, [javaScriptMode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future setUserAgent(String? userAgent) => (super.noSuchMethod( - Invocation.method( - #setUserAgent, - [userAgent], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + _i5.Future setUserAgent(String? userAgent) => + (super.noSuchMethod( + Invocation.method(#setUserAgent, [userAgent]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnScrollPositionChange( - void Function(_i3.ScrollPositionChange)? onScrollPositionChange) => + void Function(_i3.ScrollPositionChange)? onScrollPositionChange, + ) => (super.noSuchMethod( - Invocation.method( - #setOnScrollPositionChange, - [onScrollPositionChange], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnScrollPositionChange, [ + onScrollPositionChange, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setUseWideViewPort(bool? use) => (super.noSuchMethod( - Invocation.method( - #setUseWideViewPort, - [use], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setTextZoom(int? textZoom) => + (super.noSuchMethod( + Invocation.method(#setTextZoom, [textZoom]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setUseWideViewPort(bool? use) => + (super.noSuchMethod( + Invocation.method(#setUseWideViewPort, [use]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setAllowContentAccess(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setAllowContentAccess, [enabled]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setGeolocationEnabled(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setGeolocationEnabled, [enabled]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnShowFileSelector( - _i5.Future> Function(_i6.FileSelectorParams)? - onShowFileSelector) => + _i5.Future> Function(_i6.FileSelectorParams)? + onShowFileSelector, + ) => (super.noSuchMethod( - Invocation.method( - #setOnShowFileSelector, - [onShowFileSelector], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnShowFileSelector, [onShowFileSelector]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnPlatformPermissionRequest( - void Function(_i3.PlatformWebViewPermissionRequest)? - onPermissionRequest) => + void Function(_i3.PlatformWebViewPermissionRequest)? onPermissionRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnPlatformPermissionRequest, - [onPermissionRequest], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnPlatformPermissionRequest, [ + onPermissionRequest, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setGeolocationPermissionsPromptCallbacks({ @@ -567,17 +471,14 @@ class MockAndroidWebViewController extends _i1.Mock _i6.OnGeolocationPermissionsHidePrompt? onHidePrompt, }) => (super.noSuchMethod( - Invocation.method( - #setGeolocationPermissionsPromptCallbacks, - [], - { - #onShowPrompt: onShowPrompt, - #onHidePrompt: onHidePrompt, - }, - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setGeolocationPermissionsPromptCallbacks, [], { + #onShowPrompt: onShowPrompt, + #onHidePrompt: onHidePrompt, + }), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setCustomWidgetCallbacks({ @@ -585,150 +486,136 @@ class MockAndroidWebViewController extends _i1.Mock required _i6.OnHideCustomWidgetCallback? onHideCustomWidget, }) => (super.noSuchMethod( - Invocation.method( - #setCustomWidgetCallbacks, - [], - { - #onShowCustomWidget: onShowCustomWidget, - #onHideCustomWidget: onHideCustomWidget, - }, - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setCustomWidgetCallbacks, [], { + #onShowCustomWidget: onShowCustomWidget, + #onHideCustomWidget: onHideCustomWidget, + }), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnConsoleMessage( - void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage) => + void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage, + ) => (super.noSuchMethod( - Invocation.method( - #setOnConsoleMessage, - [onConsoleMessage], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnConsoleMessage, [onConsoleMessage]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - _i5.Future getUserAgent() => (super.noSuchMethod( - Invocation.method( - #getUserAgent, - [], - ), - returnValue: _i5.Future.value(), - ) as _i5.Future); + _i5.Future getUserAgent() => + (super.noSuchMethod( + Invocation.method(#getUserAgent, []), + returnValue: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnJavaScriptAlertDialog( - _i5.Future Function(_i3.JavaScriptAlertDialogRequest)? - onJavaScriptAlertDialog) => + _i5.Future Function(_i3.JavaScriptAlertDialogRequest)? + onJavaScriptAlertDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptAlertDialog, - [onJavaScriptAlertDialog], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnJavaScriptAlertDialog, [ + onJavaScriptAlertDialog, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnJavaScriptConfirmDialog( - _i5.Future Function(_i3.JavaScriptConfirmDialogRequest)? - onJavaScriptConfirmDialog) => + _i5.Future Function(_i3.JavaScriptConfirmDialogRequest)? + onJavaScriptConfirmDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptConfirmDialog, - [onJavaScriptConfirmDialog], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnJavaScriptConfirmDialog, [ + onJavaScriptConfirmDialog, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setOnJavaScriptTextInputDialog( - _i5.Future Function(_i3.JavaScriptTextInputDialogRequest)? - onJavaScriptTextInputDialog) => + _i5.Future Function(_i3.JavaScriptTextInputDialogRequest)? + onJavaScriptTextInputDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptTextInputDialog, - [onJavaScriptTextInputDialog], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOnJavaScriptTextInputDialog, [ + onJavaScriptTextInputDialog, + ]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setVerticalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setVerticalScrollBarEnabled, - [enabled], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setVerticalScrollBarEnabled, [enabled]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setHorizontalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setHorizontalScrollBarEnabled, - [enabled], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setHorizontalScrollBarEnabled, [enabled]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override - bool supportsSetScrollBarsEnabled() => (super.noSuchMethod( - Invocation.method( - #supportsSetScrollBarsEnabled, - [], - ), - returnValue: false, - ) as bool); + bool supportsSetScrollBarsEnabled() => + (super.noSuchMethod( + Invocation.method(#supportsSetScrollBarsEnabled, []), + returnValue: false, + ) + as bool); @override _i5.Future setOverScrollMode(_i3.WebViewOverScrollMode? mode) => (super.noSuchMethod( - Invocation.method( - #setOverScrollMode, - [mode], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setOverScrollMode, [mode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future setMixedContentMode(_i6.MixedContentMode? mode) => (super.noSuchMethod( - Invocation.method( - #setMixedContentMode, - [mode], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setMixedContentMode, [mode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); @override _i5.Future isWebViewFeatureSupported( - _i6.WebViewFeatureType? featureType) => + _i6.WebViewFeatureType? featureType, + ) => (super.noSuchMethod( - Invocation.method( - #isWebViewFeatureSupported, - [featureType], - ), - returnValue: _i5.Future.value(false), - ) as _i5.Future); + Invocation.method(#isWebViewFeatureSupported, [featureType]), + returnValue: _i5.Future.value(false), + ) + as _i5.Future); @override _i5.Future setPaymentRequestEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setPaymentRequestEnabled, - [enabled], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); + Invocation.method(#setPaymentRequestEnabled, [enabled]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); } diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/surface_android_test.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/surface_android_test.dart index 9d41208b5f6..3141c97009c 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/surface_android_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/surface_android_test.dart @@ -18,22 +18,21 @@ void main() { setUpAll(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - SystemChannels.platform_views, - (MethodCall call) async { - log.add(call); - if (call.method == 'resize') { - final Map arguments = - (call.arguments as Map) - .cast(); - return { - 'width': arguments['width'], - 'height': arguments['height'], - }; - } - return null; - }, - ); + .setMockMethodCallHandler(SystemChannels.platform_views, ( + MethodCall call, + ) async { + log.add(call); + if (call.method == 'resize') { + final Map arguments = + (call.arguments as Map) + .cast(); + return { + 'width': arguments['width'], + 'height': arguments['height'], + }; + } + return null; + }); }); tearDownAll(() { @@ -46,43 +45,54 @@ void main() { }); testWidgets( - 'uses hybrid composition when background color is not 100% opaque', - (WidgetTester tester) async { - await tester.pumpWidget(Builder(builder: (BuildContext context) { - return SurfaceAndroidWebView().build( - context: context, - creationParams: CreationParams( - backgroundColor: Colors.transparent, - webSettings: WebSettings( - userAgent: const WebSetting.absent(), - hasNavigationDelegate: false, - )), - javascriptChannelRegistry: JavascriptChannelRegistry(null), - webViewPlatformCallbacksHandler: - TestWebViewPlatformCallbacksHandler(), + 'uses hybrid composition when background color is not 100% opaque', + (WidgetTester tester) async { + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return SurfaceAndroidWebView().build( + context: context, + creationParams: CreationParams( + backgroundColor: Colors.transparent, + webSettings: WebSettings( + userAgent: const WebSetting.absent(), + hasNavigationDelegate: false, + ), + ), + javascriptChannelRegistry: JavascriptChannelRegistry(null), + webViewPlatformCallbacksHandler: + TestWebViewPlatformCallbacksHandler(), + ); + }, + ), ); - })); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - final MethodCall createMethodCall = log[0]; - expect(createMethodCall.method, 'create'); - expect(createMethodCall.arguments, containsPair('hybrid', true)); - }); + final MethodCall createMethodCall = log[0]; + expect(createMethodCall.method, 'create'); + expect(createMethodCall.arguments, containsPair('hybrid', true)); + }, + ); testWidgets('default text direction is ltr', (WidgetTester tester) async { - await tester.pumpWidget(Builder(builder: (BuildContext context) { - return SurfaceAndroidWebView().build( - context: context, - creationParams: CreationParams( - webSettings: WebSettings( - userAgent: const WebSetting.absent(), - hasNavigationDelegate: false, - )), - javascriptChannelRegistry: JavascriptChannelRegistry(null), - webViewPlatformCallbacksHandler: - TestWebViewPlatformCallbacksHandler(), - ); - })); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return SurfaceAndroidWebView().build( + context: context, + creationParams: CreationParams( + webSettings: WebSettings( + userAgent: const WebSetting.absent(), + hasNavigationDelegate: false, + ), + ), + javascriptChannelRegistry: JavascriptChannelRegistry(null), + webViewPlatformCallbacksHandler: + TestWebViewPlatformCallbacksHandler(), + ); + }, + ), + ); await tester.pumpAndSettle(); final MethodCall createMethodCall = log[0]; diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart index 3738cc8959c..9112838d8c4 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart @@ -18,8 +18,9 @@ void main() { test('clearCookies should call android_webview.clearCookies', () { final MockCookieManager mockCookieManager = MockCookieManager(); - when(mockCookieManager.removeAllCookies()) - .thenAnswer((_) => Future.value(true)); + when( + mockCookieManager.removeAllCookies(), + ).thenAnswer((_) => Future.value(true)); WebViewAndroidCookieManager( cookieManager: mockCookieManager, ).clearCookies(); @@ -28,27 +29,30 @@ void main() { test('setCookie should throw ArgumentError for cookie with invalid path', () { expect( - () => WebViewAndroidCookieManager(cookieManager: MockCookieManager()) - .setCookie(const WebViewCookie( - name: 'foo', - value: 'bar', - domain: 'flutter.dev', - path: 'invalid;path', - )), + () => WebViewAndroidCookieManager( + cookieManager: MockCookieManager(), + ).setCookie( + const WebViewCookie( + name: 'foo', + value: 'bar', + domain: 'flutter.dev', + path: 'invalid;path', + ), + ), throwsA(const TypeMatcher()), ); }); test( - 'setCookie should call android_webview.csetCookie with properly formatted cookie value', - () { - final MockCookieManager mockCookieManager = MockCookieManager(); - WebViewAndroidCookieManager(cookieManager: mockCookieManager) - .setCookie(const WebViewCookie( - name: 'foo&', - value: 'bar@', - domain: 'flutter.dev', - )); - verify(mockCookieManager.setCookie('flutter.dev', 'foo%26=bar%40; path=/')); - }); + 'setCookie should call android_webview.csetCookie with properly formatted cookie value', + () { + final MockCookieManager mockCookieManager = MockCookieManager(); + WebViewAndroidCookieManager(cookieManager: mockCookieManager).setCookie( + const WebViewCookie(name: 'foo&', value: 'bar@', domain: 'flutter.dev'), + ); + verify( + mockCookieManager.setCookie('flutter.dev', 'foo%26=bar%40; path=/'), + ); + }, + ); } diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart index 3e523c6bf42..7b26a909591 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart @@ -24,23 +24,13 @@ import 'package:webview_flutter_android/src/android_webkit.g.dart' as _i2; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCookieManager_1 extends _i1.SmartFake implements _i2.CookieManager { - _FakeCookieManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCookieManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [CookieManager]. @@ -52,39 +42,32 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i3.Future setCookie( - String? url, - String? value, - ) => + _i3.Future setCookie(String? url, String? value) => (super.noSuchMethod( - Invocation.method( - #setCookie, - [ - url, - value, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setCookie, [url, value]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i3.Future removeAllCookies() => (super.noSuchMethod( - Invocation.method( - #removeAllCookies, - [], - ), - returnValue: _i3.Future.value(false), - ) as _i3.Future); + _i3.Future removeAllCookies() => + (super.noSuchMethod( + Invocation.method(#removeAllCookies, []), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); @override _i3.Future setAcceptThirdPartyCookies( @@ -92,29 +75,20 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { bool? accept, ) => (super.noSuchMethod( - Invocation.method( - #setAcceptThirdPartyCookies, - [ - webView, - accept, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); + Invocation.method(#setAcceptThirdPartyCookies, [webView, accept]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); @override - _i2.CookieManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeCookieManager_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.CookieManager); + _i2.CookieManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCookieManager_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.CookieManager); } diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart index 0729179af85..8d29ef90ce5 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart @@ -59,17 +59,19 @@ void main() { mockWebViewProxy = MockWebViewProxy(); when(mockWebViewProxy.createWebView()).thenReturn(mockWebView); - when(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).thenReturn(mockWebViewClient); + when( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: anyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), + ), + ).thenReturn(mockWebViewClient); mockCallbacksHandler = MockWebViewPlatformCallbacksHandler(); mockJavascriptChannelRegistry = MockJavascriptChannelRegistry(); @@ -83,24 +85,28 @@ void main() { bool hasProgressTracking = false, bool useHybridComposition = false, }) async { - await tester.pumpWidget(WebViewAndroidWidget( - creationParams: creationParams ?? - CreationParams( + await tester.pumpWidget( + WebViewAndroidWidget( + creationParams: + creationParams ?? + CreationParams( webSettings: WebSettings( - userAgent: const WebSetting.absent(), - hasNavigationDelegate: hasNavigationDelegate, - hasProgressTracking: hasProgressTracking, - )), - callbacksHandler: mockCallbacksHandler, - javascriptChannelRegistry: mockJavascriptChannelRegistry, - webViewProxy: mockWebViewProxy, - flutterAssetManager: mockFlutterAssetManager, - webStorage: mockWebStorage, - onBuildWidget: (WebViewAndroidPlatformController controller) { - testController = controller; - return Container(); - }, - )); + userAgent: const WebSetting.absent(), + hasNavigationDelegate: hasNavigationDelegate, + hasProgressTracking: hasProgressTracking, + ), + ), + callbacksHandler: mockCallbacksHandler, + javascriptChannelRegistry: mockJavascriptChannelRegistry, + webViewProxy: mockWebViewProxy, + flutterAssetManager: mockFlutterAssetManager, + webStorage: mockWebStorage, + onBuildWidget: (WebViewAndroidPlatformController controller) { + testController = controller; + return Container(); + }, + ), + ); mockWebViewClient = testController.webViewClient as MockWebViewClient; downloadListener = testController.downloadListener; @@ -125,13 +131,12 @@ void main() { ]); }); - testWidgets( - 'Create Widget with Hybrid Composition', - (WidgetTester tester) async { - await buildWidget(tester, useHybridComposition: true); - verify(mockWebViewProxy.createWebView()); - }, - ); + testWidgets('Create Widget with Hybrid Composition', ( + WidgetTester tester, + ) async { + await buildWidget(tester, useHybridComposition: true); + verify(mockWebViewProxy.createWebView()); + }); group('CreationParams', () { testWidgets('initialUrl', (WidgetTester tester) async { @@ -145,10 +150,9 @@ void main() { ), ), ); - verify(mockWebView.loadUrl( - 'https://www.google.com', - {}, - )); + verify( + mockWebView.loadUrl('https://www.google.com', {}), + ); }); testWidgets('userAgent', (WidgetTester tester) async { @@ -208,9 +212,9 @@ void main() { ); final List javaScriptChannels = - verify(mockWebView.addJavaScriptChannel(captureAny)) - .captured - .cast(); + verify( + mockWebView.addJavaScriptChannel(captureAny), + ).captured.cast(); expect(javaScriptChannels[0].channelName, 'a'); expect(javaScriptChannels[1].channelName, 'b'); }); @@ -233,18 +237,21 @@ void main() { testWidgets('hasNavigationDelegate', (WidgetTester tester) async { final MockWebViewClient mockWebViewClient = MockWebViewClient(); - when(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: - anyNamed('onReceivedClientCertRequest'), - )).thenReturn(mockWebViewClient); + when( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: anyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).thenReturn(mockWebViewClient); await buildWidget( tester, @@ -324,33 +331,32 @@ void main() { }); group('WebViewPlatformController', () { - testWidgets('loadFile without "file://" prefix', - (WidgetTester tester) async { + testWidgets('loadFile without "file://" prefix', ( + WidgetTester tester, + ) async { await buildWidget(tester); const String filePath = '/path/to/file.html'; await testController.loadFile(filePath); - verify(mockWebView.loadUrl( - 'file://$filePath', - {}, - )); + verify(mockWebView.loadUrl('file://$filePath', {})); }); - testWidgets('loadFile with "file://" prefix', - (WidgetTester tester) async { + testWidgets('loadFile with "file://" prefix', ( + WidgetTester tester, + ) async { await buildWidget(tester); await testController.loadFile('file:///path/to/file.html'); - verify(mockWebView.loadUrl( - 'file:///path/to/file.html', - {}, - )); + verify( + mockWebView.loadUrl('file:///path/to/file.html', {}), + ); }); - testWidgets('loadFile should setAllowFileAccess to true', - (WidgetTester tester) async { + testWidgets('loadFile should setAllowFileAccess to true', ( + WidgetTester tester, + ) async { await buildWidget(tester); await testController.loadFile('file:///path/to/file.html'); @@ -362,78 +368,92 @@ void main() { await buildWidget(tester); const String assetKey = 'test_assets/index.html'; - when(mockFlutterAssetManager.getAssetFilePathByName(assetKey)) - .thenAnswer( - (_) => Future.value('flutter_assets/$assetKey')); - when(mockFlutterAssetManager.list('flutter_assets/test_assets')) - .thenAnswer( - (_) => Future>.value(['index.html'])); + when( + mockFlutterAssetManager.getAssetFilePathByName(assetKey), + ).thenAnswer((_) => Future.value('flutter_assets/$assetKey')); + when( + mockFlutterAssetManager.list('flutter_assets/test_assets'), + ).thenAnswer((_) => Future>.value(['index.html'])); await testController.loadFlutterAsset(assetKey); - verify(mockWebView.loadUrl( - 'file:///android_asset/flutter_assets/$assetKey', - {}, - )); + verify( + mockWebView.loadUrl( + 'file:///android_asset/flutter_assets/$assetKey', + {}, + ), + ); }); - testWidgets('loadFlutterAsset with file in root', - (WidgetTester tester) async { + testWidgets('loadFlutterAsset with file in root', ( + WidgetTester tester, + ) async { await buildWidget(tester); const String assetKey = 'index.html'; - when(mockFlutterAssetManager.getAssetFilePathByName(assetKey)) - .thenAnswer( - (_) => Future.value('flutter_assets/$assetKey')); - when(mockFlutterAssetManager.list('flutter_assets')).thenAnswer( - (_) => Future>.value(['index.html'])); + when( + mockFlutterAssetManager.getAssetFilePathByName(assetKey), + ).thenAnswer((_) => Future.value('flutter_assets/$assetKey')); + when( + mockFlutterAssetManager.list('flutter_assets'), + ).thenAnswer((_) => Future>.value(['index.html'])); await testController.loadFlutterAsset(assetKey); - verify(mockWebView.loadUrl( - 'file:///android_asset/flutter_assets/$assetKey', - {}, - )); + verify( + mockWebView.loadUrl( + 'file:///android_asset/flutter_assets/$assetKey', + {}, + ), + ); }); testWidgets( - 'loadFlutterAsset throws ArgumentError when asset does not exist', - (WidgetTester tester) async { - await buildWidget(tester); - const String assetKey = 'test_assets/index.html'; + 'loadFlutterAsset throws ArgumentError when asset does not exist', + (WidgetTester tester) async { + await buildWidget(tester); + const String assetKey = 'test_assets/index.html'; - when(mockFlutterAssetManager.getAssetFilePathByName(assetKey)) - .thenAnswer( - (_) => Future.value('flutter_assets/$assetKey')); - when(mockFlutterAssetManager.list('flutter_assets/test_assets')) - .thenAnswer((_) => Future>.value([''])); + when( + mockFlutterAssetManager.getAssetFilePathByName(assetKey), + ).thenAnswer((_) => Future.value('flutter_assets/$assetKey')); + when( + mockFlutterAssetManager.list('flutter_assets/test_assets'), + ).thenAnswer((_) => Future>.value([''])); - expect( - () => testController.loadFlutterAsset(assetKey), - throwsA( - isA() - .having((ArgumentError error) => error.name, 'name', 'key') - .having((ArgumentError error) => error.message, 'message', - 'Asset for key "$assetKey" not found.'), - ), - ); - }); + expect( + () => testController.loadFlutterAsset(assetKey), + throwsA( + isA() + .having((ArgumentError error) => error.name, 'name', 'key') + .having( + (ArgumentError error) => error.message, + 'message', + 'Asset for key "$assetKey" not found.', + ), + ), + ); + }, + ); - testWidgets('loadHtmlString without base URL', - (WidgetTester tester) async { + testWidgets('loadHtmlString without base URL', ( + WidgetTester tester, + ) async { await buildWidget(tester); const String htmlString = 'Test data.'; await testController.loadHtmlString(htmlString); - verify(mockWebView.loadDataWithBaseUrl( - null, - htmlString, - 'text/html', - null, - null, - )); + verify( + mockWebView.loadDataWithBaseUrl( + null, + htmlString, + 'text/html', + null, + null, + ), + ); }); testWidgets('loadHtmlString with base URL', (WidgetTester tester) async { @@ -446,85 +466,92 @@ void main() { baseUrl: 'https://flutter.dev', ); - verify(mockWebView.loadDataWithBaseUrl( - 'https://flutter.dev', - htmlString, - 'text/html', - null, - null, - )); + verify( + mockWebView.loadDataWithBaseUrl( + 'https://flutter.dev', + htmlString, + 'text/html', + null, + null, + ), + ); }); testWidgets('loadUrl', (WidgetTester tester) async { await buildWidget(tester); - await testController.loadUrl( - 'https://www.google.com', - {'a': 'header'}, - ); + await testController.loadUrl('https://www.google.com', { + 'a': 'header', + }); - verify(mockWebView.loadUrl( - 'https://www.google.com', - {'a': 'header'}, - )); + verify( + mockWebView.loadUrl('https://www.google.com', { + 'a': 'header', + }), + ); }); group('loadRequest', () { - testWidgets('Throws ArgumentError for empty scheme', - (WidgetTester tester) async { + testWidgets('Throws ArgumentError for empty scheme', ( + WidgetTester tester, + ) async { await buildWidget(tester); expect( - () async => testController.loadRequest( - WebViewRequest( - uri: Uri.parse('www.google.com'), - method: WebViewRequestMethod.get, - ), - ), - throwsA(const TypeMatcher())); + () async => testController.loadRequest( + WebViewRequest( + uri: Uri.parse('www.google.com'), + method: WebViewRequestMethod.get, + ), + ), + throwsA(const TypeMatcher()), + ); }); testWidgets('GET without headers', (WidgetTester tester) async { await buildWidget(tester); - await testController.loadRequest(WebViewRequest( - uri: Uri.parse('https://www.google.com'), - method: WebViewRequestMethod.get, - )); + await testController.loadRequest( + WebViewRequest( + uri: Uri.parse('https://www.google.com'), + method: WebViewRequestMethod.get, + ), + ); - verify(mockWebView.loadUrl( - 'https://www.google.com', - {}, - )); + verify( + mockWebView.loadUrl('https://www.google.com', {}), + ); }); testWidgets('GET with headers', (WidgetTester tester) async { await buildWidget(tester); - await testController.loadRequest(WebViewRequest( - uri: Uri.parse('https://www.google.com'), - method: WebViewRequestMethod.get, - headers: {'a': 'header'}, - )); + await testController.loadRequest( + WebViewRequest( + uri: Uri.parse('https://www.google.com'), + method: WebViewRequestMethod.get, + headers: {'a': 'header'}, + ), + ); - verify(mockWebView.loadUrl( - 'https://www.google.com', - {'a': 'header'}, - )); + verify( + mockWebView.loadUrl('https://www.google.com', { + 'a': 'header', + }), + ); }); testWidgets('POST without body', (WidgetTester tester) async { await buildWidget(tester); - await testController.loadRequest(WebViewRequest( - uri: Uri.parse('https://www.google.com'), - method: WebViewRequestMethod.post, - )); + await testController.loadRequest( + WebViewRequest( + uri: Uri.parse('https://www.google.com'), + method: WebViewRequestMethod.post, + ), + ); - verify(mockWebView.postUrl( - 'https://www.google.com', - Uint8List(0), - )); + verify(mockWebView.postUrl('https://www.google.com', Uint8List(0))); }); testWidgets('POST with body', (WidgetTester tester) async { @@ -532,40 +559,42 @@ void main() { final Uint8List body = Uint8List.fromList('Test Body'.codeUnits); - await testController.loadRequest(WebViewRequest( + await testController.loadRequest( + WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.post, - body: body)); + body: body, + ), + ); - verify(mockWebView.postUrl( - 'https://www.google.com', - body, - )); + verify(mockWebView.postUrl('https://www.google.com', body)); }); }); - testWidgets('no update to userAgentString when there is no change', - (WidgetTester tester) async { + testWidgets('no update to userAgentString when there is no change', ( + WidgetTester tester, + ) async { await buildWidget(tester); reset(mockWebSettings); - await testController.updateSettings(WebSettings( - userAgent: const WebSetting.absent(), - )); + await testController.updateSettings( + WebSettings(userAgent: const WebSetting.absent()), + ); verifyNever(mockWebSettings.setUserAgentString(any)); }); - testWidgets('update null userAgentString with empty string', - (WidgetTester tester) async { + testWidgets('update null userAgentString with empty string', ( + WidgetTester tester, + ) async { await buildWidget(tester); reset(mockWebSettings); - await testController.updateSettings(WebSettings( - userAgent: const WebSetting.of(null), - )); + await testController.updateSettings( + WebSettings(userAgent: const WebSetting.of(null)), + ); verify(mockWebSettings.setUserAgentString('')); }); @@ -573,27 +602,30 @@ void main() { testWidgets('currentUrl', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.getUrl()) - .thenAnswer((_) => Future.value('https://www.google.com')); + when( + mockWebView.getUrl(), + ).thenAnswer((_) => Future.value('https://www.google.com')); expect( - testController.currentUrl(), completion('https://www.google.com')); + testController.currentUrl(), + completion('https://www.google.com'), + ); }); testWidgets('canGoBack', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.canGoBack()).thenAnswer( - (_) => Future.value(false), - ); + when( + mockWebView.canGoBack(), + ).thenAnswer((_) => Future.value(false)); expect(testController.canGoBack(), completion(false)); }); testWidgets('canGoForward', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.canGoForward()).thenAnswer( - (_) => Future.value(true), - ); + when( + mockWebView.canGoForward(), + ).thenAnswer((_) => Future.value(true)); expect(testController.canGoForward(), completion(true)); }); @@ -629,9 +661,9 @@ void main() { testWidgets('evaluateJavascript', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.evaluateJavascript('runJavaScript')).thenAnswer( - (_) => Future.value('returnString'), - ); + when( + mockWebView.evaluateJavascript('runJavaScript'), + ).thenAnswer((_) => Future.value('returnString')); expect( testController.evaluateJavascript('runJavaScript'), completion('returnString'), @@ -641,9 +673,9 @@ void main() { testWidgets('runJavascriptReturningResult', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.evaluateJavascript('runJavaScript')).thenAnswer( - (_) => Future.value('returnString'), - ); + when( + mockWebView.evaluateJavascript('runJavaScript'), + ).thenAnswer((_) => Future.value('returnString')); expect( testController.runJavascriptReturningResult('runJavaScript'), completion('returnString'), @@ -653,13 +685,10 @@ void main() { testWidgets('runJavascript', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.evaluateJavascript('runJavaScript')).thenAnswer( - (_) => Future.value('returnString'), - ); - expect( - testController.runJavascript('runJavaScript'), - completes, - ); + when( + mockWebView.evaluateJavascript('runJavaScript'), + ).thenAnswer((_) => Future.value('returnString')); + expect(testController.runJavascript('runJavaScript'), completes); }); testWidgets('addJavascriptChannels', (WidgetTester tester) async { @@ -667,9 +696,9 @@ void main() { await testController.addJavascriptChannels({'c', 'd'}); final List javaScriptChannels = - verify(mockWebView.addJavaScriptChannel(captureAny)) - .captured - .cast(); + verify( + mockWebView.addJavaScriptChannel(captureAny), + ).captured.cast(); expect(javaScriptChannels[0].channelName, 'c'); expect(javaScriptChannels[1].channelName, 'd'); }); @@ -686,8 +715,9 @@ void main() { testWidgets('getTitle', (WidgetTester tester) async { await buildWidget(tester); - when(mockWebView.getTitle()) - .thenAnswer((_) => Future.value('Web Title')); + when( + mockWebView.getTitle(), + ).thenAnswer((_) => Future.value('Web Title')); expect(testController.getTitle(), completion('Web Title')); }); @@ -732,19 +762,31 @@ void main() { testWidgets('onPageStarted', (WidgetTester tester) async { await buildWidget(tester); final void Function( - android_webview.WebViewClient, android_webview.WebView, String) - onPageStarted = verify(mockWebViewProxy.createWebViewClient( - onPageStarted: captureAnyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).captured.single as void Function( - android_webview.WebViewClient, android_webview.WebView, String); + android_webview.WebViewClient, + android_webview.WebView, + String, + ) + onPageStarted = + verify( + mockWebViewProxy.createWebViewClient( + onPageStarted: captureAnyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: anyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).captured.single + as void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + ); onPageStarted(MockWebViewClient(), mockWebView, 'https://google.com'); verify(mockCallbacksHandler.onPageStarted('https://google.com')); @@ -754,42 +796,71 @@ void main() { await buildWidget(tester); final void Function( - android_webview.WebViewClient, android_webview.WebView, String) - onPageFinished = verify(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: captureAnyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).captured.single as void Function( - android_webview.WebViewClient, android_webview.WebView, String); + android_webview.WebViewClient, + android_webview.WebView, + String, + ) + onPageFinished = + verify( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: captureAnyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: anyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).captured.single + as void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + ); onPageFinished(MockWebViewClient(), mockWebView, 'https://google.com'); verify(mockCallbacksHandler.onPageFinished('https://google.com')); }); - testWidgets('onWebResourceError from onReceivedError', - (WidgetTester tester) async { + testWidgets('onWebResourceError from onReceivedError', ( + WidgetTester tester, + ) async { await buildWidget(tester); - final void Function(android_webview.WebViewClient, - android_webview.WebView, int, String, String) onReceivedError = - verify(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: captureAnyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).captured.single as void Function(android_webview.WebViewClient, - android_webview.WebView, int, String, String); + final void Function( + android_webview.WebViewClient, + android_webview.WebView, + int, + String, + String, + ) + onReceivedError = + verify( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: captureAnyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: anyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).captured.single + as void Function( + android_webview.WebViewClient, + android_webview.WebView, + int, + String, + String, + ); onReceivedError( MockWebViewClient(), @@ -800,9 +871,10 @@ void main() { ); final WebResourceError error = - verify(mockCallbacksHandler.onWebResourceError(captureAny)) - .captured - .single as WebResourceError; + verify( + mockCallbacksHandler.onWebResourceError(captureAny), + ).captured.single + as WebResourceError; expect(error.description, 'description'); expect(error.errorCode, -4); expect(error.failingUrl, 'https://google.com'); @@ -810,8 +882,9 @@ void main() { expect(error.errorType, WebResourceErrorType.authentication); }); - testWidgets('onWebResourceError from onReceivedRequestError', - (WidgetTester tester) async { + testWidgets('onWebResourceError from onReceivedRequestError', ( + WidgetTester tester, + ) async { await buildWidget(tester); final void Function( @@ -819,22 +892,31 @@ void main() { android_webview.WebView, android_webview.WebResourceRequest, android_webview.WebResourceError, - ) onReceivedRequestError = verify(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: captureAnyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).captured.single as void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.WebResourceRequest, - android_webview.WebResourceError, - ); + ) + onReceivedRequestError = + verify( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: captureAnyNamed( + 'onReceivedRequestError', + ), + requestLoading: anyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).captured.single + as void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.WebResourceRequest, + android_webview.WebResourceError, + ); onReceivedRequestError( MockWebViewClient(), @@ -854,9 +936,10 @@ void main() { ); final WebResourceError error = - verify(mockCallbacksHandler.onWebResourceError(captureAny)) - .captured - .single as WebResourceError; + verify( + mockCallbacksHandler.onWebResourceError(captureAny), + ).captured.single + as WebResourceError; expect(error.description, 'description'); expect(error.errorCode, -16); expect(error.failingUrl, 'https://google.com'); @@ -864,64 +947,91 @@ void main() { expect(error.errorType, WebResourceErrorType.unsafeResource); }); - testWidgets('onNavigationRequest from urlLoading', - (WidgetTester tester) async { + testWidgets('onNavigationRequest from urlLoading', ( + WidgetTester tester, + ) async { await buildWidget(tester, hasNavigationDelegate: true); - when(mockCallbacksHandler.onNavigationRequest( - isForMainFrame: argThat(isTrue, named: 'isForMainFrame'), - url: 'https://google.com', - )).thenReturn(true); + when( + mockCallbacksHandler.onNavigationRequest( + isForMainFrame: argThat(isTrue, named: 'isForMainFrame'), + url: 'https://google.com', + ), + ).thenReturn(true); final void Function( - android_webview.WebViewClient, android_webview.WebView, String) - urlLoading = verify(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: anyNamed('requestLoading'), - urlLoading: captureAnyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).captured.single as void Function( - android_webview.WebViewClient, android_webview.WebView, String); + android_webview.WebViewClient, + android_webview.WebView, + String, + ) + urlLoading = + verify( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: anyNamed('requestLoading'), + urlLoading: captureAnyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).captured.single + as void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + ); urlLoading(MockWebViewClient(), mockWebView, 'https://google.com'); - verify(mockCallbacksHandler.onNavigationRequest( - url: 'https://google.com', - isForMainFrame: true, - )); + verify( + mockCallbacksHandler.onNavigationRequest( + url: 'https://google.com', + isForMainFrame: true, + ), + ); verify(mockWebView.loadUrl('https://google.com', {})); }); - testWidgets('onNavigationRequest from requestLoading', - (WidgetTester tester) async { + testWidgets('onNavigationRequest from requestLoading', ( + WidgetTester tester, + ) async { await buildWidget(tester, hasNavigationDelegate: true); - when(mockCallbacksHandler.onNavigationRequest( - isForMainFrame: argThat(isTrue, named: 'isForMainFrame'), - url: 'https://google.com', - )).thenReturn(true); + when( + mockCallbacksHandler.onNavigationRequest( + isForMainFrame: argThat(isTrue, named: 'isForMainFrame'), + url: 'https://google.com', + ), + ).thenReturn(true); final void Function( android_webview.WebViewClient, android_webview.WebView, android_webview.WebResourceRequest, - ) requestLoading = verify(mockWebViewProxy.createWebViewClient( - onPageStarted: anyNamed('onPageStarted'), - onPageFinished: anyNamed('onPageFinished'), - onReceivedError: anyNamed('onReceivedError'), - onReceivedRequestError: anyNamed('onReceivedRequestError'), - requestLoading: captureAnyNamed('requestLoading'), - urlLoading: anyNamed('urlLoading'), - onReceivedSslError: anyNamed('onReceivedSslError'), - onFormResubmission: anyNamed('onFormResubmission'), - onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), - )).captured.single as void Function( - android_webview.WebViewClient, - android_webview.WebView, - android_webview.WebResourceRequest, - ); + ) + requestLoading = + verify( + mockWebViewProxy.createWebViewClient( + onPageStarted: anyNamed('onPageStarted'), + onPageFinished: anyNamed('onPageFinished'), + onReceivedError: anyNamed('onReceivedError'), + onReceivedRequestError: anyNamed('onReceivedRequestError'), + requestLoading: captureAnyNamed('requestLoading'), + urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed( + 'onReceivedClientCertRequest', + ), + ), + ).captured.single + as void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.WebResourceRequest, + ); requestLoading( MockWebViewClient(), @@ -935,10 +1045,12 @@ void main() { requestHeaders: const {}, ), ); - verify(mockCallbacksHandler.onNavigationRequest( - url: 'https://google.com', - isForMainFrame: true, - )); + verify( + mockCallbacksHandler.onNavigationRequest( + url: 'https://google.com', + isForMainFrame: true, + ), + ); verify(mockWebView.loadUrl('https://google.com', {})); }); @@ -949,14 +1061,17 @@ void main() { await testController.addJavascriptChannels({'hello'}); final WebViewAndroidJavaScriptChannel javaScriptChannel = - verify(mockWebView.addJavaScriptChannel(captureAny)) - .captured - .single as WebViewAndroidJavaScriptChannel; + verify( + mockWebView.addJavaScriptChannel(captureAny), + ).captured.single + as WebViewAndroidJavaScriptChannel; javaScriptChannel.postMessage(javaScriptChannel, 'goodbye'); - verify(mockJavascriptChannelRegistry.onJavascriptChannelMessage( - 'hello', - 'goodbye', - )); + verify( + mockJavascriptChannelRegistry.onJavascriptChannelMessage( + 'hello', + 'goodbye', + ), + ); }); }); }); diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart index d4253056809..ea2911f6f0f 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart @@ -30,129 +30,69 @@ import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_ class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFlutterAssetManager_1 extends _i1.SmartFake implements _i2.FlutterAssetManager { - _FakeFlutterAssetManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFlutterAssetManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebSettings_2 extends _i1.SmartFake implements _i2.WebSettings { - _FakeWebSettings_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebSettings_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebStorage_3 extends _i1.SmartFake implements _i2.WebStorage { - _FakeWebStorage_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebStorage_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebView_4 extends _i1.SmartFake implements _i2.WebView { - _FakeWebView_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebView_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewPoint_5 extends _i1.SmartFake implements _i2.WebViewPoint { - _FakeWebViewPoint_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewPoint_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebResourceRequest_6 extends _i1.SmartFake implements _i2.WebResourceRequest { - _FakeWebResourceRequest_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebResourceRequest_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDownloadListener_7 extends _i1.SmartFake implements _i2.DownloadListener { - _FakeDownloadListener_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDownloadListener_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeJavascriptChannelRegistry_8 extends _i1.SmartFake implements _i3.JavascriptChannelRegistry { - _FakeJavascriptChannelRegistry_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeJavascriptChannelRegistry_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeJavaScriptChannel_9 extends _i1.SmartFake implements _i2.JavaScriptChannel { - _FakeJavaScriptChannel_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeJavaScriptChannel_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebChromeClient_10 extends _i1.SmartFake implements _i2.WebChromeClient { - _FakeWebChromeClient_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebChromeClient_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewClient_11 extends _i1.SmartFake implements _i2.WebViewClient { - _FakeWebViewClient_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewClient_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [FlutterAssetManager]. @@ -165,53 +105,47 @@ class MockFlutterAssetManager extends _i1.Mock } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i4.Future> list(String? path) => (super.noSuchMethod( - Invocation.method( - #list, - [path], - ), - returnValue: _i4.Future>.value([]), - ) as _i4.Future>); + _i4.Future> list(String? path) => + (super.noSuchMethod( + Invocation.method(#list, [path]), + returnValue: _i4.Future>.value([]), + ) + as _i4.Future>); @override _i4.Future getAssetFilePathByName(String? name) => (super.noSuchMethod( - Invocation.method( - #getAssetFilePathByName, - [name], - ), - returnValue: _i4.Future.value(_i5.dummyValue( - this, - Invocation.method( - #getAssetFilePathByName, - [name], - ), - )), - ) as _i4.Future); - - @override - _i2.FlutterAssetManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeFlutterAssetManager_1( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.FlutterAssetManager); + Invocation.method(#getAssetFilePathByName, [name]), + returnValue: _i4.Future.value( + _i5.dummyValue( + this, + Invocation.method(#getAssetFilePathByName, [name]), + ), + ), + ) + as _i4.Future); + + @override + _i2.FlutterAssetManager pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFlutterAssetManager_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.FlutterAssetManager); } /// A class which mocks [WebSettings]. @@ -223,209 +157,185 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override - _i4.Future setDomStorageEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setDomStorageEnabled, - [flag], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setDomStorageEnabled(bool? flag) => + (super.noSuchMethod( + Invocation.method(#setDomStorageEnabled, [flag]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setJavaScriptCanOpenWindowsAutomatically(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptCanOpenWindowsAutomatically, - [flag], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setJavaScriptCanOpenWindowsAutomatically, [ + flag, + ]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setSupportMultipleWindows(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportMultipleWindows, - [support], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setSupportMultipleWindows, [support]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future setJavaScriptEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptEnabled, - [flag], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setJavaScriptEnabled(bool? flag) => + (super.noSuchMethod( + Invocation.method(#setJavaScriptEnabled, [flag]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setUserAgentString(String? userAgentString) => (super.noSuchMethod( - Invocation.method( - #setUserAgentString, - [userAgentString], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setUserAgentString, [userAgentString]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future setSupportZoom(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportZoom, - [support], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future setSupportZoom(bool? support) => + (super.noSuchMethod( + Invocation.method(#setSupportZoom, [support]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setLoadWithOverviewMode(bool? overview) => (super.noSuchMethod( - Invocation.method( - #setLoadWithOverviewMode, - [overview], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setUseWideViewPort(bool? use) => (super.noSuchMethod( - Invocation.method( - #setUseWideViewPort, - [use], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setDisplayZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setDisplayZoomControls, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setBuiltInZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setBuiltInZoomControls, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setAllowFileAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future getUserAgentString() => (super.noSuchMethod( - Invocation.method( - #getUserAgentString, - [], - ), - returnValue: _i4.Future.value(_i5.dummyValue( - this, - Invocation.method( - #getUserAgentString, - [], - ), - )), - ) as _i4.Future); + Invocation.method(#setLoadWithOverviewMode, [overview]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setUseWideViewPort(bool? use) => + (super.noSuchMethod( + Invocation.method(#setUseWideViewPort, [use]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setDisplayZoomControls(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setDisplayZoomControls, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setBuiltInZoomControls(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setBuiltInZoomControls, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setAllowFileAccess(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setAllowFileAccess, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setAllowContentAccess(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setAllowContentAccess, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setGeolocationEnabled(bool? enabled) => + (super.noSuchMethod( + Invocation.method(#setGeolocationEnabled, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setTextZoom(int? textZoom) => + (super.noSuchMethod( + Invocation.method(#setTextZoom, [textZoom]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future getUserAgentString() => + (super.noSuchMethod( + Invocation.method(#getUserAgentString, []), + returnValue: _i4.Future.value( + _i5.dummyValue( + this, + Invocation.method(#getUserAgentString, []), + ), + ), + ) + as _i4.Future); @override _i4.Future setMixedContentMode(_i2.MixedContentMode? mode) => (super.noSuchMethod( - Invocation.method( - #setMixedContentMode, - [mode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.WebSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebSettings_2( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebSettings); + Invocation.method(#setMixedContentMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.WebSettings pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebSettings_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebSettings); } /// A class which mocks [WebStorage]. @@ -437,38 +347,35 @@ class MockWebStorage extends _i1.Mock implements _i2.WebStorage { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i4.Future deleteAllData() => (super.noSuchMethod( - Invocation.method( - #deleteAllData, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.WebStorage pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebStorage_3( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebStorage); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i4.Future deleteAllData() => + (super.noSuchMethod( + Invocation.method(#deleteAllData, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.WebStorage pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebStorage_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebStorage); } /// A class which mocks [WebView]. @@ -480,56 +387,43 @@ class MockWebView extends _i1.Mock implements _i2.WebView { } @override - _i2.WebSettings get settings => (super.noSuchMethod( - Invocation.getter(#settings), - returnValue: _FakeWebSettings_2( - this, - Invocation.getter(#settings), - ), - ) as _i2.WebSettings); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.WebSettings pigeonVar_settings() => (super.noSuchMethod( - Invocation.method( - #pigeonVar_settings, - [], - ), - returnValue: _FakeWebSettings_2( - this, - Invocation.method( - #pigeonVar_settings, - [], - ), - ), - ) as _i2.WebSettings); - - @override - _i4.Future loadData( - String? data, - String? mimeType, - String? encoding, - ) => + _i2.WebSettings get settings => + (super.noSuchMethod( + Invocation.getter(#settings), + returnValue: _FakeWebSettings_2(this, Invocation.getter(#settings)), + ) + as _i2.WebSettings); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.method( - #loadData, - [ - data, - mimeType, - encoding, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.WebSettings pigeonVar_settings() => + (super.noSuchMethod( + Invocation.method(#pigeonVar_settings, []), + returnValue: _FakeWebSettings_2( + this, + Invocation.method(#pigeonVar_settings, []), + ), + ) + as _i2.WebSettings); + + @override + _i4.Future loadData(String? data, String? mimeType, String? encoding) => + (super.noSuchMethod( + Invocation.method(#loadData, [data, mimeType, encoding]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future loadDataWithBaseUrl( @@ -540,310 +434,243 @@ class MockWebView extends _i1.Mock implements _i2.WebView { String? historyUrl, ) => (super.noSuchMethod( - Invocation.method( - #loadDataWithBaseUrl, - [ - baseUrl, - data, - mimeType, - encoding, - historyUrl, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future loadUrl( - String? url, - Map? headers, - ) => + Invocation.method(#loadDataWithBaseUrl, [ + baseUrl, + data, + mimeType, + encoding, + historyUrl, + ]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future loadUrl(String? url, Map? headers) => (super.noSuchMethod( - Invocation.method( - #loadUrl, - [ - url, - headers, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future postUrl( - String? url, - _i6.Uint8List? data, - ) => + Invocation.method(#loadUrl, [url, headers]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future postUrl(String? url, _i6.Uint8List? data) => + (super.noSuchMethod( + Invocation.method(#postUrl, [url, data]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future getUrl() => + (super.noSuchMethod( + Invocation.method(#getUrl, []), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future canGoBack() => + (super.noSuchMethod( + Invocation.method(#canGoBack, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future canGoForward() => + (super.noSuchMethod( + Invocation.method(#canGoForward, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future goBack() => + (super.noSuchMethod( + Invocation.method(#goBack, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future goForward() => + (super.noSuchMethod( + Invocation.method(#goForward, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future reload() => + (super.noSuchMethod( + Invocation.method(#reload, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future clearCache(bool? includeDiskFiles) => (super.noSuchMethod( - Invocation.method( - #postUrl, - [ - url, - data, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future getUrl() => (super.noSuchMethod( - Invocation.method( - #getUrl, - [], - ), - returnValue: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); - - @override - _i4.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), - returnValue: _i4.Future.value(false), - ) as _i4.Future); - - @override - _i4.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future clearCache(bool? includeDiskFiles) => (super.noSuchMethod( - Invocation.method( - #clearCache, - [includeDiskFiles], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#clearCache, [includeDiskFiles]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future evaluateJavascript(String? javascriptString) => (super.noSuchMethod( - Invocation.method( - #evaluateJavascript, - [javascriptString], - ), - returnValue: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#evaluateJavascript, [javascriptString]), + returnValue: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), - returnValue: _i4.Future.value(), - ) as _i4.Future); + _i4.Future getTitle() => + (super.noSuchMethod( + Invocation.method(#getTitle, []), + returnValue: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setWebViewClient(_i2.WebViewClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebViewClient, - [client], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setWebViewClient, [client]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future addJavaScriptChannel(_i2.JavaScriptChannel? channel) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [channel], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#addJavaScriptChannel, [channel]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override - _i4.Future removeJavaScriptChannel(String? name) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [name], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + _i4.Future removeJavaScriptChannel(String? name) => + (super.noSuchMethod( + Invocation.method(#removeJavaScriptChannel, [name]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setDownloadListener(_i2.DownloadListener? listener) => (super.noSuchMethod( - Invocation.method( - #setDownloadListener, - [listener], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setDownloadListener, [listener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setWebChromeClient(_i2.WebChromeClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebChromeClient, - [client], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future setBackgroundColor(int? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.WebView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebView_4( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebView); - - @override - _i4.Future scrollTo( - int? x, - int? y, - ) => + Invocation.method(#setWebChromeClient, [client]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future setBackgroundColor(int? color) => (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future scrollBy( - int? x, - int? y, - ) => + Invocation.method(#setBackgroundColor, [color]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future destroy() => (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future<_i2.WebViewPoint> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], - ), - returnValue: _i4.Future<_i2.WebViewPoint>.value(_FakeWebViewPoint_5( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - ) as _i4.Future<_i2.WebViewPoint>); + Invocation.method(#destroy, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.WebView pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebView_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebView); + + @override + _i4.Future scrollTo(int? x, int? y) => + (super.noSuchMethod( + Invocation.method(#scrollTo, [x, y]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future scrollBy(int? x, int? y) => + (super.noSuchMethod( + Invocation.method(#scrollBy, [x, y]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future<_i2.WebViewPoint> getScrollPosition() => + (super.noSuchMethod( + Invocation.method(#getScrollPosition, []), + returnValue: _i4.Future<_i2.WebViewPoint>.value( + _FakeWebViewPoint_5( + this, + Invocation.method(#getScrollPosition, []), + ), + ), + ) + as _i4.Future<_i2.WebViewPoint>); @override _i4.Future setVerticalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setVerticalScrollBarEnabled, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setVerticalScrollBarEnabled, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setHorizontalScrollBarEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setHorizontalScrollBarEnabled, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setHorizontalScrollBarEnabled, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOverScrollMode(_i2.OverScrollMode? mode) => (super.noSuchMethod( - Invocation.method( - #setOverScrollMode, - [mode], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOverScrollMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } /// A class which mocks [WebResourceRequest]. @@ -856,58 +683,58 @@ class MockWebResourceRequest extends _i1.Mock } @override - String get url => (super.noSuchMethod( - Invocation.getter(#url), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#url), - ), - ) as String); - - @override - bool get isForMainFrame => (super.noSuchMethod( - Invocation.getter(#isForMainFrame), - returnValue: false, - ) as bool); - - @override - bool get hasGesture => (super.noSuchMethod( - Invocation.getter(#hasGesture), - returnValue: false, - ) as bool); - - @override - String get method => (super.noSuchMethod( - Invocation.getter(#method), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#method), - ), - ) as String); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.WebResourceRequest pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebResourceRequest_6( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebResourceRequest); + String get url => + (super.noSuchMethod( + Invocation.getter(#url), + returnValue: _i5.dummyValue(this, Invocation.getter(#url)), + ) + as String); + + @override + bool get isForMainFrame => + (super.noSuchMethod( + Invocation.getter(#isForMainFrame), + returnValue: false, + ) + as bool); + + @override + bool get hasGesture => + (super.noSuchMethod(Invocation.getter(#hasGesture), returnValue: false) + as bool); + + @override + String get method => + (super.noSuchMethod( + Invocation.getter(#method), + returnValue: _i5.dummyValue( + this, + Invocation.getter(#method), + ), + ) + as String); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.WebResourceRequest pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebResourceRequest_6( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebResourceRequest); } /// A class which mocks [DownloadListener]. @@ -919,55 +746,50 @@ class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener { } @override - void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) get onDownloadStart => (super.noSuchMethod( - Invocation.getter(#onDownloadStart), - returnValue: ( - _i2.DownloadListener pigeon_instance, - String url, - String userAgent, - String contentDisposition, - String mimetype, - int contentLength, - ) {}, - ) as void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.DownloadListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeDownloadListener_7( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.DownloadListener); + void Function(_i2.DownloadListener, String, String, String, String, int) + get onDownloadStart => + (super.noSuchMethod( + Invocation.getter(#onDownloadStart), + returnValue: + ( + _i2.DownloadListener pigeon_instance, + String url, + String userAgent, + String contentDisposition, + String mimetype, + int contentLength, + ) {}, + ) + as void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + )); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.DownloadListener pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeDownloadListener_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.DownloadListener); } /// A class which mocks [WebViewAndroidJavaScriptChannel]. @@ -982,60 +804,55 @@ class MockWebViewAndroidJavaScriptChannel extends _i1.Mock @override _i3.JavascriptChannelRegistry get javascriptChannelRegistry => (super.noSuchMethod( - Invocation.getter(#javascriptChannelRegistry), - returnValue: _FakeJavascriptChannelRegistry_8( - this, - Invocation.getter(#javascriptChannelRegistry), - ), - ) as _i3.JavascriptChannelRegistry); - - @override - String get channelName => (super.noSuchMethod( - Invocation.getter(#channelName), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#channelName), - ), - ) as String); - - @override - void Function( - _i2.JavaScriptChannel, - String, - ) get postMessage => (super.noSuchMethod( - Invocation.getter(#postMessage), - returnValue: ( - _i2.JavaScriptChannel pigeon_instance, - String message, - ) {}, - ) as void Function( - _i2.JavaScriptChannel, - String, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); - - @override - _i2.JavaScriptChannel pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeJavaScriptChannel_9( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.JavaScriptChannel); + Invocation.getter(#javascriptChannelRegistry), + returnValue: _FakeJavascriptChannelRegistry_8( + this, + Invocation.getter(#javascriptChannelRegistry), + ), + ) + as _i3.JavascriptChannelRegistry); + + @override + String get channelName => + (super.noSuchMethod( + Invocation.getter(#channelName), + returnValue: _i5.dummyValue( + this, + Invocation.getter(#channelName), + ), + ) + as String); + + @override + void Function(_i2.JavaScriptChannel, String) get postMessage => + (super.noSuchMethod( + Invocation.getter(#postMessage), + returnValue: + (_i2.JavaScriptChannel pigeon_instance, String message) {}, + ) + as void Function(_i2.JavaScriptChannel, String)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); + + @override + _i2.JavaScriptChannel pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeJavaScriptChannel_9( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.JavaScriptChannel); } /// A class which mocks [WebChromeClient]. @@ -1051,120 +868,115 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { _i2.WebChromeClient, _i2.WebView, _i2.FileChooserParams, - ) get onShowFileChooser => (super.noSuchMethod( - Invocation.getter(#onShowFileChooser), - returnValue: ( - _i2.WebChromeClient pigeon_instance, - _i2.WebView webView, - _i2.FileChooserParams params, - ) => - _i4.Future>.value([]), - ) as _i4.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - )); - - @override - _i4.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - ) get onJsConfirm => (super.noSuchMethod( - Invocation.getter(#onJsConfirm), - returnValue: ( - _i2.WebChromeClient pigeon_instance, - _i2.WebView webView, - String url, - String message, - ) => - _i4.Future.value(false), - ) as _i4.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + ) + get onShowFileChooser => + (super.noSuchMethod( + Invocation.getter(#onShowFileChooser), + returnValue: + ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + _i2.FileChooserParams params, + ) => _i4.Future>.value([]), + ) + as _i4.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + )); + + @override + _i4.Future Function(_i2.WebChromeClient, _i2.WebView, String, String) + get onJsConfirm => + (super.noSuchMethod( + Invocation.getter(#onJsConfirm), + returnValue: + ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + String url, + String message, + ) => _i4.Future.value(false), + ) + as _i4.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i4.Future setSynchronousReturnValueForOnShowFileChooser(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnShowFileChooser, - [value], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setSynchronousReturnValueForOnShowFileChooser, [ + value, + ]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setSynchronousReturnValueForOnConsoleMessage(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnConsoleMessage, - [value], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setSynchronousReturnValueForOnConsoleMessage, [ + value, + ]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setSynchronousReturnValueForOnJsAlert(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsAlert, - [value], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setSynchronousReturnValueForOnJsAlert, [value]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setSynchronousReturnValueForOnJsConfirm(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsConfirm, - [value], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setSynchronousReturnValueForOnJsConfirm, [ + value, + ]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setSynchronousReturnValueForOnJsPrompt(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsPrompt, - [value], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.WebChromeClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebChromeClient_10( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebChromeClient); + Invocation.method(#setSynchronousReturnValueForOnJsPrompt, [value]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.WebChromeClient pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebChromeClient_10( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebChromeClient); } /// A class which mocks [WebViewClient]. @@ -1176,40 +988,40 @@ class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { } @override - _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => + (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) + as _i2.PigeonInstanceManager); @override _i4.Future setSynchronousReturnValueForShouldOverrideUrlLoading( - bool? value) => - (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForShouldOverrideUrlLoading, - [value], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i2.WebViewClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), - returnValue: _FakeWebViewClient_11( - this, - Invocation.method( - #pigeon_copy, - [], - ), - ), - ) as _i2.WebViewClient); + bool? value, + ) => + (super.noSuchMethod( + Invocation.method( + #setSynchronousReturnValueForShouldOverrideUrlLoading, + [value], + ), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i2.WebViewClient pigeon_copy() => + (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeWebViewClient_11( + this, + Invocation.method(#pigeon_copy, []), + ), + ) + as _i2.WebViewClient); } /// A class which mocks [JavascriptChannelRegistry]. @@ -1222,34 +1034,24 @@ class MockJavascriptChannelRegistry extends _i1.Mock } @override - Map get channels => (super.noSuchMethod( - Invocation.getter(#channels), - returnValue: {}, - ) as Map); + Map get channels => + (super.noSuchMethod( + Invocation.getter(#channels), + returnValue: {}, + ) + as Map); @override - void onJavascriptChannelMessage( - String? channel, - String? message, - ) => + void onJavascriptChannelMessage(String? channel, String? message) => super.noSuchMethod( - Invocation.method( - #onJavascriptChannelMessage, - [ - channel, - message, - ], - ), + Invocation.method(#onJavascriptChannelMessage, [channel, message]), returnValueForMissingStub: null, ); @override void updateJavascriptChannelsFromSet(Set<_i3.JavascriptChannel>? channels) => super.noSuchMethod( - Invocation.method( - #updateJavascriptChannelsFromSet, - [channels], - ), + Invocation.method(#updateJavascriptChannelsFromSet, [channels]), returnValueForMissingStub: null, ); } @@ -1269,52 +1071,37 @@ class MockWebViewPlatformCallbacksHandler extends _i1.Mock required bool? isForMainFrame, }) => (super.noSuchMethod( - Invocation.method( - #onNavigationRequest, - [], - { - #url: url, - #isForMainFrame: isForMainFrame, - }, - ), - returnValue: _i4.Future.value(false), - ) as _i4.FutureOr); + Invocation.method(#onNavigationRequest, [], { + #url: url, + #isForMainFrame: isForMainFrame, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.FutureOr); @override void onPageStarted(String? url) => super.noSuchMethod( - Invocation.method( - #onPageStarted, - [url], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onPageStarted, [url]), + returnValueForMissingStub: null, + ); @override void onPageFinished(String? url) => super.noSuchMethod( - Invocation.method( - #onPageFinished, - [url], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onPageFinished, [url]), + returnValueForMissingStub: null, + ); @override void onProgress(int? progress) => super.noSuchMethod( - Invocation.method( - #onProgress, - [progress], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onProgress, [progress]), + returnValueForMissingStub: null, + ); @override void onWebResourceError(_i3.WebResourceError? error) => super.noSuchMethod( - Invocation.method( - #onWebResourceError, - [error], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onWebResourceError, [error]), + returnValueForMissingStub: null, + ); } /// A class which mocks [WebViewProxy]. @@ -1326,95 +1113,51 @@ class MockWebViewProxy extends _i1.Mock implements _i7.WebViewProxy { } @override - _i2.WebView createWebView() => (super.noSuchMethod( - Invocation.method( - #createWebView, - [], - ), - returnValue: _FakeWebView_4( - this, - Invocation.method( - #createWebView, - [], - ), - ), - ) as _i2.WebView); + _i2.WebView createWebView() => + (super.noSuchMethod( + Invocation.method(#createWebView, []), + returnValue: _FakeWebView_4( + this, + Invocation.method(#createWebView, []), + ), + ) + as _i2.WebView); @override _i2.WebViewClient createWebViewClient({ - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, void Function( _i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest, _i2.WebResourceError, - )? onReceivedRequestError, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, + )? + onReceivedRequestError, + void Function(_i2.WebViewClient, _i2.WebView, int, String, String)? + onReceivedError, + void Function(_i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest)? + requestLoading, void Function( _i2.WebViewClient, _i2.WebView, _i2.AndroidMessage, _i2.AndroidMessage, - )? onFormResubmission, - void Function( - _i2.WebViewClient, - _i2.WebView, - _i2.ClientCertRequest, - )? onReceivedClientCertRequest, + )? + onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, _i2.ClientCertRequest)? + onReceivedClientCertRequest, void Function( _i2.WebViewClient, _i2.WebView, _i2.SslErrorHandler, _i2.SslError, - )? onReceivedSslError, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? urlLoading, + )? + onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, }) => (super.noSuchMethod( - Invocation.method( - #createWebViewClient, - [], - { - #onPageStarted: onPageStarted, - #onPageFinished: onPageFinished, - #onReceivedRequestError: onReceivedRequestError, - #onReceivedError: onReceivedError, - #requestLoading: requestLoading, - #onFormResubmission: onFormResubmission, - #onReceivedClientCertRequest: onReceivedClientCertRequest, - #onReceivedSslError: onReceivedSslError, - #urlLoading: urlLoading, - }, - ), - returnValue: _FakeWebViewClient_11( - this, - Invocation.method( - #createWebViewClient, - [], - { + Invocation.method(#createWebViewClient, [], { #onPageStarted: onPageStarted, #onPageFinished: onPageFinished, #onReceivedRequestError: onReceivedRequestError, @@ -1424,19 +1167,30 @@ class MockWebViewProxy extends _i1.Mock implements _i7.WebViewProxy { #onReceivedClientCertRequest: onReceivedClientCertRequest, #onReceivedSslError: onReceivedSslError, #urlLoading: urlLoading, - }, - ), - ), - ) as _i2.WebViewClient); + }), + returnValue: _FakeWebViewClient_11( + this, + Invocation.method(#createWebViewClient, [], { + #onPageStarted: onPageStarted, + #onPageFinished: onPageFinished, + #onReceivedRequestError: onReceivedRequestError, + #onReceivedError: onReceivedError, + #requestLoading: requestLoading, + #onFormResubmission: onFormResubmission, + #onReceivedClientCertRequest: onReceivedClientCertRequest, + #onReceivedSslError: onReceivedSslError, + #urlLoading: urlLoading, + }), + ), + ) + as _i2.WebViewClient); @override _i4.Future setWebContentsDebuggingEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setWebContentsDebuggingEnabled, - [enabled], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setWebContentsDebuggingEnabled, [enabled]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md b/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md index 4e0ea24d731..6e20e84d2ed 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 2.14.0 * Adds `PlatformWebViewController.loadFileWithParams(LoadFileParams)` to support loading local HTML files with platform-specific parameters. diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_cookie_manager.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_cookie_manager.dart index 90dfc2a548b..cd021c52679 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_cookie_manager.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_cookie_manager.dart @@ -29,7 +29,8 @@ abstract class WebViewCookieManagerPlatform extends PlatformInterface { static set instance(WebViewCookieManagerPlatform? instance) { if (instance == null) { throw AssertionError( - 'Platform interfaces can only be set to a non-null instance'); + 'Platform interfaces can only be set to a non-null instance', + ); } PlatformInterface.verify(instance, _token); _instance = instance; @@ -40,12 +41,14 @@ abstract class WebViewCookieManagerPlatform extends PlatformInterface { /// Returns true if cookies were present before clearing, else false. Future clearCookies() { throw UnimplementedError( - 'clearCookies is not implemented on the current platform'); + 'clearCookies is not implemented on the current platform', + ); } /// Sets a cookie for all [WebView] instances. Future setCookie(WebViewCookie cookie) { throw UnimplementedError( - 'setCookie is not implemented on the current platform'); + 'setCookie is not implemented on the current platform', + ); } } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform.dart index 31cdec56e90..4a425ad2615 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform.dart @@ -14,8 +14,8 @@ import 'webview_platform_controller.dart'; /// Signature for callbacks reporting that a [WebViewPlatformController] was created. /// /// See also the `onWebViewPlatformCreated` argument for [WebViewPlatform.build]. -typedef WebViewPlatformCreatedCallback = void Function( - WebViewPlatformController? webViewPlatformController); +typedef WebViewPlatformCreatedCallback = + void Function(WebViewPlatformController? webViewPlatformController); /// Interface for a platform implementation of a WebView. /// @@ -62,6 +62,7 @@ abstract class WebViewPlatform { /// Soon to be deprecated. 'Use `WebViewCookieManagerPlatform.clearCookies` instead. Future clearCookies() { throw UnimplementedError( - 'WebView clearCookies is not implemented on the current platform'); + 'WebView clearCookies is not implemented on the current platform', + ); } } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_callbacks_handler.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_callbacks_handler.dart index 44dae2ece43..99dbda14b6e 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_callbacks_handler.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_callbacks_handler.dart @@ -14,8 +14,10 @@ abstract class WebViewPlatformCallbacksHandler { /// Invoked by [WebViewPlatformController] when a navigation request is pending. /// /// If true is returned the navigation is allowed, otherwise it is blocked. - FutureOr onNavigationRequest( - {required String url, required bool isForMainFrame}); + FutureOr onNavigationRequest({ + required String url, + required bool isForMainFrame, + }); /// Invoked by [WebViewPlatformController] when a page has started loading. void onPageStarted(String url); diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_controller.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_controller.dart index 3437fe1f2c0..b4c8a0d4770 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_controller.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_controller.dart @@ -33,34 +33,30 @@ abstract class WebViewPlatformController { /// `/Users/username/Documents/www/index.html`. /// /// Throws an ArgumentError if the [absoluteFilePath] does not exist. - Future loadFile( - String absoluteFilePath, - ) { + Future loadFile(String absoluteFilePath) { throw UnimplementedError( - 'WebView loadFile is not implemented on the current platform'); + 'WebView loadFile is not implemented on the current platform', + ); } /// Loads the Flutter asset specified in the pubspec.yaml file. /// /// Throws an ArgumentError if [key] is not part of the specified assets /// in the pubspec.yaml file. - Future loadFlutterAsset( - String key, - ) { + Future loadFlutterAsset(String key) { throw UnimplementedError( - 'WebView loadFlutterAsset is not implemented on the current platform'); + 'WebView loadFlutterAsset is not implemented on the current platform', + ); } /// Loads the supplied HTML string. /// /// The [baseUrl] parameter is used when resolving relative URLs within the /// HTML string. - Future loadHtmlString( - String html, { - String? baseUrl, - }) { + Future loadHtmlString(String html, {String? baseUrl}) { throw UnimplementedError( - 'WebView loadHtmlString is not implemented on the current platform'); + 'WebView loadHtmlString is not implemented on the current platform', + ); } /// Loads the specified URL. @@ -71,12 +67,10 @@ abstract class WebViewPlatformController { /// `url` must not be null. /// /// Throws an ArgumentError if `url` is not a valid URL string. - Future loadUrl( - String url, - Map? headers, - ) { + Future loadUrl(String url, Map? headers) { throw UnimplementedError( - 'WebView loadUrl is not implemented on the current platform'); + 'WebView loadUrl is not implemented on the current platform', + ); } /// Makes a specific HTTP request ands loads the response in the webview. @@ -91,11 +85,10 @@ abstract class WebViewPlatformController { /// for the request. /// /// Throws an ArgumentError if [WebViewRequest.uri] has empty scheme. - Future loadRequest( - WebViewRequest request, - ) { + Future loadRequest(WebViewRequest request) { throw UnimplementedError( - 'WebView loadRequest is not implemented on the current platform'); + 'WebView loadRequest is not implemented on the current platform', + ); } /// Updates the webview settings. @@ -104,7 +97,8 @@ abstract class WebViewPlatformController { /// All null fields in `settings` are ignored. Future updateSettings(WebSettings setting) { throw UnimplementedError( - 'WebView updateSettings is not implemented on the current platform'); + 'WebView updateSettings is not implemented on the current platform', + ); } /// Accessor to the current URL that the WebView is displaying. @@ -112,19 +106,22 @@ abstract class WebViewPlatformController { /// If no URL was ever loaded, returns `null`. Future currentUrl() { throw UnimplementedError( - 'WebView currentUrl is not implemented on the current platform'); + 'WebView currentUrl is not implemented on the current platform', + ); } /// Checks whether there's a back history item. Future canGoBack() { throw UnimplementedError( - 'WebView canGoBack is not implemented on the current platform'); + 'WebView canGoBack is not implemented on the current platform', + ); } /// Checks whether there's a forward history item. Future canGoForward() { throw UnimplementedError( - 'WebView canGoForward is not implemented on the current platform'); + 'WebView canGoForward is not implemented on the current platform', + ); } /// Goes back in the history of this WebView. @@ -132,7 +129,8 @@ abstract class WebViewPlatformController { /// If there is no back history item this is a no-op. Future goBack() { throw UnimplementedError( - 'WebView goBack is not implemented on the current platform'); + 'WebView goBack is not implemented on the current platform', + ); } /// Goes forward in the history of this WebView. @@ -140,13 +138,15 @@ abstract class WebViewPlatformController { /// If there is no forward history item this is a no-op. Future goForward() { throw UnimplementedError( - 'WebView goForward is not implemented on the current platform'); + 'WebView goForward is not implemented on the current platform', + ); } /// Reloads the current URL. Future reload() { throw UnimplementedError( - 'WebView reload is not implemented on the current platform'); + 'WebView reload is not implemented on the current platform', + ); } /// Clears all caches used by the [WebView]. @@ -159,7 +159,8 @@ abstract class WebViewPlatformController { /// 4. Local Storage. Future clearCache() { throw UnimplementedError( - 'WebView clearCache is not implemented on the current platform'); + 'WebView clearCache is not implemented on the current platform', + ); } /// Evaluates a JavaScript expression in the context of the current page. @@ -168,7 +169,8 @@ abstract class WebViewPlatformController { /// evaluated expression is not supported (e.g on iOS not all non-primitive types can be evaluated). Future evaluateJavascript(String javascript) { throw UnimplementedError( - 'WebView evaluateJavascript is not implemented on the current platform'); + 'WebView evaluateJavascript is not implemented on the current platform', + ); } /// Runs the given JavaScript in the context of the current page. @@ -176,7 +178,8 @@ abstract class WebViewPlatformController { /// The Future completes with an error if a JavaScript error occurred. Future runJavascript(String javascript) { throw UnimplementedError( - 'WebView runJavascript is not implemented on the current platform'); + 'WebView runJavascript is not implemented on the current platform', + ); } /// Runs the given JavaScript in the context of the current page, and returns the result. @@ -186,7 +189,8 @@ abstract class WebViewPlatformController { /// certain non-primitive types on iOS, as well as `undefined` or `null` on iOS 14+. Future runJavascriptReturningResult(String javascript) { throw UnimplementedError( - 'WebView runJavascriptReturningResult is not implemented on the current platform'); + 'WebView runJavascriptReturningResult is not implemented on the current platform', + ); } /// Adds new JavaScript channels to the set of enabled channels. @@ -202,7 +206,8 @@ abstract class WebViewPlatformController { /// See also: [CreationParams.javascriptChannelNames]. Future addJavascriptChannels(Set javascriptChannelNames) { throw UnimplementedError( - 'WebView addJavascriptChannels is not implemented on the current platform'); + 'WebView addJavascriptChannels is not implemented on the current platform', + ); } /// Removes JavaScript channel names from the set of enabled channels. @@ -211,13 +216,15 @@ abstract class WebViewPlatformController { /// [CreationParams.javascriptChannelNames]. Future removeJavascriptChannels(Set javascriptChannelNames) { throw UnimplementedError( - 'WebView removeJavascriptChannels is not implemented on the current platform'); + 'WebView removeJavascriptChannels is not implemented on the current platform', + ); } /// Returns the title of the currently loaded page. Future getTitle() { throw UnimplementedError( - 'WebView getTitle is not implemented on the current platform'); + 'WebView getTitle is not implemented on the current platform', + ); } /// Set the scrolled position of this view. @@ -225,7 +232,8 @@ abstract class WebViewPlatformController { /// The parameters `x` and `y` specify the position to scroll to in WebView pixels. Future scrollTo(int x, int y) { throw UnimplementedError( - 'WebView scrollTo is not implemented on the current platform'); + 'WebView scrollTo is not implemented on the current platform', + ); } /// Move the scrolled position of this view. @@ -233,7 +241,8 @@ abstract class WebViewPlatformController { /// The parameters `x` and `y` specify the amount of WebView pixels to scroll by. Future scrollBy(int x, int y) { throw UnimplementedError( - 'WebView scrollBy is not implemented on the current platform'); + 'WebView scrollBy is not implemented on the current platform', + ); } /// Return the horizontal scroll position of this view. @@ -241,7 +250,8 @@ abstract class WebViewPlatformController { /// Scroll position is measured from left. Future getScrollX() { throw UnimplementedError( - 'WebView getScrollX is not implemented on the current platform'); + 'WebView getScrollX is not implemented on the current platform', + ); } /// Return the vertical scroll position of this view. @@ -249,6 +259,7 @@ abstract class WebViewPlatformController { /// Scroll position is measured from top. Future getScrollY() { throw UnimplementedError( - 'WebView getScrollY is not implemented on the current platform'); + 'WebView getScrollY is not implemented on the current platform', + ); } } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_channel.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_channel.dart index e340625f91a..2d8e262c0bd 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_channel.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_channel.dart @@ -14,10 +14,8 @@ class JavascriptChannel { /// Constructs a JavaScript channel. /// /// The parameters `name` and `onMessageReceived` must not be null. - JavascriptChannel({ - required this.name, - required this.onMessageReceived, - }) : assert(_validChannelNames.hasMatch(name)); + JavascriptChannel({required this.name, required this.onMessageReceived}) + : assert(_validChannelNames.hasMatch(name)); /// The channel's name. /// diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_settings.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_settings.dart index 91f0768e38c..c9b65f4c586 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_settings.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_settings.dart @@ -14,16 +14,12 @@ class WebSetting { /// The [isPresent] field for the instance will be false. /// /// Accessing [value] for an absent instance will throw. - const WebSetting.absent() - : _value = null, - isPresent = false; + const WebSetting.absent() : _value = null, isPresent = false; /// Constructs a setting of the given `value`. /// /// The [isPresent] field for the instance will be true. - const WebSetting.of(T value) - : _value = value, - isPresent = true; + const WebSetting.of(T value) : _value = value, isPresent = true; final T? _value; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_cookie.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_cookie.dart index 406c510afd4..2c0da71b855 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_cookie.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_cookie.dart @@ -6,11 +6,12 @@ /// using [WebViewCookieManagerPlatform]. class WebViewCookie { /// Constructs a new [WebViewCookie]. - const WebViewCookie( - {required this.name, - required this.value, - required this.domain, - this.path = '/'}); + const WebViewCookie({ + required this.name, + required this.value, + required this.domain, + this.path = '/', + }); /// The cookie-name of the cookie. /// @@ -43,7 +44,7 @@ class WebViewCookie { 'name': name, 'value': value, 'domain': domain, - 'path': path + 'path': path, }; } } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_request.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_request.dart index 940e3a25f4b..894324ec724 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_request.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_request.dart @@ -50,9 +50,9 @@ class WebViewRequest { /// Serializes the [WebViewRequest] to JSON. Map toJson() => { - 'uri': uri.toString(), - 'method': method.serialize(), - 'headers': headers, - 'body': body, - }; + 'uri': uri.toString(), + 'method': method.serialize(), + 'headers': headers, + 'body': body, + }; } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_navigation_delegate.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_navigation_delegate.dart index 040ab246613..7712e2f17fb 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_navigation_delegate.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_navigation_delegate.dart @@ -12,8 +12,8 @@ import 'types/types.dart'; import 'webview_platform.dart' show WebViewPlatform; /// Signature for callbacks that report a pending navigation request. -typedef NavigationRequestCallback = FutureOr Function( - NavigationRequest navigationRequest); +typedef NavigationRequestCallback = + FutureOr Function(NavigationRequest navigationRequest); /// Signature for callbacks that report page events triggered by the native web view. typedef PageEventCallback = void Function(String url); @@ -50,7 +50,8 @@ typedef SslAuthErrorCallback = void Function(PlatformSslAuthError error); abstract class PlatformNavigationDelegate extends PlatformInterface { /// Creates a new [PlatformNavigationDelegate] factory PlatformNavigationDelegate( - PlatformNavigationDelegateCreationParams params) { + PlatformNavigationDelegateCreationParams params, + ) { assert( WebViewPlatform.instance != null, 'A platform implementation for `webview_flutter` has not been set. Please ' @@ -58,8 +59,9 @@ abstract class PlatformNavigationDelegate extends PlatformInterface { '`WebViewPlatform.instance` before use. For unit testing, ' '`WebViewPlatform.instance` can be set with your own test implementation.', ); - final PlatformNavigationDelegate callbackDelegate = - WebViewPlatform.instance!.createPlatformNavigationDelegate(params); + final PlatformNavigationDelegate callbackDelegate = WebViewPlatform + .instance! + .createPlatformNavigationDelegate(params); PlatformInterface.verify(callbackDelegate, _token); return callbackDelegate; } @@ -83,47 +85,44 @@ abstract class PlatformNavigationDelegate extends PlatformInterface { NavigationRequestCallback onNavigationRequest, ) { throw UnimplementedError( - 'setOnNavigationRequest is not implemented on the current platform.'); + 'setOnNavigationRequest is not implemented on the current platform.', + ); } /// Invoked when a page has started loading. /// /// See [PlatformWebViewController.setPlatformNavigationDelegate]. - Future setOnPageStarted( - PageEventCallback onPageStarted, - ) { + Future setOnPageStarted(PageEventCallback onPageStarted) { throw UnimplementedError( - 'setOnPageStarted is not implemented on the current platform.'); + 'setOnPageStarted is not implemented on the current platform.', + ); } /// Invoked when a page has finished loading. /// /// See [PlatformWebViewController.setPlatformNavigationDelegate]. - Future setOnPageFinished( - PageEventCallback onPageFinished, - ) { + Future setOnPageFinished(PageEventCallback onPageFinished) { throw UnimplementedError( - 'setOnPageFinished is not implemented on the current platform.'); + 'setOnPageFinished is not implemented on the current platform.', + ); } /// Invoked when an HTTP error has occurred during loading. /// /// See [PlatformWebViewController.setPlatformNavigationDelegate]. - Future setOnHttpError( - HttpResponseErrorCallback onHttpError, - ) { + Future setOnHttpError(HttpResponseErrorCallback onHttpError) { throw UnimplementedError( - 'setOnHttpError is not implemented on the current platform.'); + 'setOnHttpError is not implemented on the current platform.', + ); } /// Invoked when a page is loading to report the progress. /// /// See [PlatformWebViewController.setPlatformNavigationDelegate]. - Future setOnProgress( - ProgressCallback onProgress, - ) { + Future setOnProgress(ProgressCallback onProgress) { throw UnimplementedError( - 'setOnProgress is not implemented on the current platform.'); + 'setOnProgress is not implemented on the current platform.', + ); } /// Invoked when a resource loading error occurred. @@ -133,7 +132,8 @@ abstract class PlatformNavigationDelegate extends PlatformInterface { WebResourceErrorCallback onWebResourceError, ) { throw UnimplementedError( - 'setOnWebResourceError is not implemented on the current platform.'); + 'setOnWebResourceError is not implemented on the current platform.', + ); } /// Invoked when the underlying web view changes to a new url. diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_controller.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_controller.dart index 7a2e5f51364..6fba2f22853 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_controller.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_controller.dart @@ -21,7 +21,8 @@ import 'webview_platform.dart' show WebViewPlatform; abstract class PlatformWebViewController extends PlatformInterface { /// Creates a new [PlatformWebViewController] factory PlatformWebViewController( - PlatformWebViewControllerCreationParams params) { + PlatformWebViewControllerCreationParams params, + ) { assert( WebViewPlatform.instance != null, 'A platform implementation for `webview_flutter` has not been set. Please ' @@ -29,8 +30,9 @@ abstract class PlatformWebViewController extends PlatformInterface { '`WebViewPlatform.instance` before use. For unit testing, ' '`WebViewPlatform.instance` can be set with your own test implementation.', ); - final PlatformWebViewController webViewControllerDelegate = - WebViewPlatform.instance!.createPlatformWebViewController(params); + final PlatformWebViewController webViewControllerDelegate = WebViewPlatform + .instance! + .createPlatformWebViewController(params); PlatformInterface.verify(webViewControllerDelegate, _token); return webViewControllerDelegate; } @@ -54,11 +56,10 @@ abstract class PlatformWebViewController extends PlatformInterface { /// `/Users/username/Documents/www/index.html`. /// /// Throws an ArgumentError if the [absoluteFilePath] does not exist. - Future loadFile( - String absoluteFilePath, - ) { + Future loadFile(String absoluteFilePath) { throw UnimplementedError( - 'loadFile is not implemented on the current platform'); + 'loadFile is not implemented on the current platform', + ); } /// Loads a local HTML file using the provided [params]. @@ -69,9 +70,7 @@ abstract class PlatformWebViewController extends PlatformInterface { /// /// Platform-specific implementations may extend [LoadFileParams] to support /// additional parameters, such as iOS/macOS-specific read access options. - Future loadFileWithParams( - LoadFileParams params, - ) { + Future loadFileWithParams(LoadFileParams params) { return loadFile(params.absoluteFilePath); } @@ -79,23 +78,20 @@ abstract class PlatformWebViewController extends PlatformInterface { /// /// Throws an ArgumentError if [key] is not part of the specified assets /// in the pubspec.yaml file. - Future loadFlutterAsset( - String key, - ) { + Future loadFlutterAsset(String key) { throw UnimplementedError( - 'loadFlutterAsset is not implemented on the current platform'); + 'loadFlutterAsset is not implemented on the current platform', + ); } /// Loads the supplied HTML string. /// /// The [baseUrl] parameter is used when resolving relative URLs within the /// HTML string. - Future loadHtmlString( - String html, { - String? baseUrl, - }) { + Future loadHtmlString(String html, {String? baseUrl}) { throw UnimplementedError( - 'loadHtmlString is not implemented on the current platform'); + 'loadHtmlString is not implemented on the current platform', + ); } /// Makes a specific HTTP request ands loads the response in the webview. @@ -110,11 +106,10 @@ abstract class PlatformWebViewController extends PlatformInterface { /// for the request. /// /// Throws an ArgumentError if [WebViewRequest.uri] has empty scheme. - Future loadRequest( - LoadRequestParams params, - ) { + Future loadRequest(LoadRequestParams params) { throw UnimplementedError( - 'loadRequest is not implemented on the current platform'); + 'loadRequest is not implemented on the current platform', + ); } /// Accessor to the current URL that the WebView is displaying. @@ -122,19 +117,22 @@ abstract class PlatformWebViewController extends PlatformInterface { /// If no URL was ever loaded, returns `null`. Future currentUrl() { throw UnimplementedError( - 'currentUrl is not implemented on the current platform'); + 'currentUrl is not implemented on the current platform', + ); } /// Checks whether there's a back history item. Future canGoBack() { throw UnimplementedError( - 'canGoBack is not implemented on the current platform'); + 'canGoBack is not implemented on the current platform', + ); } /// Checks whether there's a forward history item. Future canGoForward() { throw UnimplementedError( - 'canGoForward is not implemented on the current platform'); + 'canGoForward is not implemented on the current platform', + ); } /// Goes back in the history of this WebView. @@ -142,7 +140,8 @@ abstract class PlatformWebViewController extends PlatformInterface { /// If there is no back history item this is a no-op. Future goBack() { throw UnimplementedError( - 'goBack is not implemented on the current platform'); + 'goBack is not implemented on the current platform', + ); } /// Goes forward in the history of this WebView. @@ -150,13 +149,15 @@ abstract class PlatformWebViewController extends PlatformInterface { /// If there is no forward history item this is a no-op. Future goForward() { throw UnimplementedError( - 'goForward is not implemented on the current platform'); + 'goForward is not implemented on the current platform', + ); } /// Reloads the current URL. Future reload() { throw UnimplementedError( - 'reload is not implemented on the current platform'); + 'reload is not implemented on the current platform', + ); } /// Clears all caches used by the [WebView]. @@ -168,21 +169,25 @@ abstract class PlatformWebViewController extends PlatformInterface { /// 3. Application cache. Future clearCache() { throw UnimplementedError( - 'clearCache is not implemented on the current platform'); + 'clearCache is not implemented on the current platform', + ); } /// Clears the local storage used by the [WebView]. Future clearLocalStorage() { throw UnimplementedError( - 'clearLocalStorage is not implemented on the current platform'); + 'clearLocalStorage is not implemented on the current platform', + ); } /// Sets the [PlatformNavigationDelegate] containing the callback methods that /// are called during navigation events. Future setPlatformNavigationDelegate( - PlatformNavigationDelegate handler) { + PlatformNavigationDelegate handler, + ) { throw UnimplementedError( - 'setPlatformNavigationDelegate is not implemented on the current platform'); + 'setPlatformNavigationDelegate is not implemented on the current platform', + ); } /// Runs the given JavaScript in the context of the current page. @@ -190,7 +195,8 @@ abstract class PlatformWebViewController extends PlatformInterface { /// The Future completes with an error if a JavaScript error occurred. Future runJavaScript(String javaScript) { throw UnimplementedError( - 'runJavaScript is not implemented on the current platform'); + 'runJavaScript is not implemented on the current platform', + ); } /// Runs the given JavaScript in the context of the current page, and returns the result. @@ -200,7 +206,8 @@ abstract class PlatformWebViewController extends PlatformInterface { /// certain non-primitive types on iOS, as well as `undefined` or `null` on iOS 14+. Future runJavaScriptReturningResult(String javaScript) { throw UnimplementedError( - 'runJavaScriptReturningResult is not implemented on the current platform'); + 'runJavaScriptReturningResult is not implemented on the current platform', + ); } /// Adds a new JavaScript channel to the set of enabled channels. @@ -208,7 +215,8 @@ abstract class PlatformWebViewController extends PlatformInterface { JavaScriptChannelParams javaScriptChannelParams, ) { throw UnimplementedError( - 'addJavaScriptChannel is not implemented on the current platform'); + 'addJavaScriptChannel is not implemented on the current platform', + ); } /// Removes the JavaScript channel with the matching name from the set of @@ -218,13 +226,15 @@ abstract class PlatformWebViewController extends PlatformInterface { /// enabled through the [addJavaScriptChannel]. Future removeJavaScriptChannel(String javaScriptChannelName) { throw UnimplementedError( - 'removeJavaScriptChannel is not implemented on the current platform'); + 'removeJavaScriptChannel is not implemented on the current platform', + ); } /// Returns the title of the currently loaded page. Future getTitle() { throw UnimplementedError( - 'getTitle is not implemented on the current platform'); + 'getTitle is not implemented on the current platform', + ); } /// Set the scrolled position of this view. @@ -232,7 +242,8 @@ abstract class PlatformWebViewController extends PlatformInterface { /// The parameters `x` and `y` specify the position to scroll to in WebView pixels. Future scrollTo(int x, int y) { throw UnimplementedError( - 'scrollTo is not implemented on the current platform'); + 'scrollTo is not implemented on the current platform', + ); } /// Move the scrolled position of this view. @@ -240,19 +251,22 @@ abstract class PlatformWebViewController extends PlatformInterface { /// The parameters `x` and `y` specify the amount of WebView pixels to scroll by. Future scrollBy(int x, int y) { throw UnimplementedError( - 'scrollBy is not implemented on the current platform'); + 'scrollBy is not implemented on the current platform', + ); } /// Whether the vertical scrollbar should be drawn or not. Future setVerticalScrollBarEnabled(bool enabled) { throw UnimplementedError( - 'setVerticalScrollBarEnabled is not implemented on the current platform'); + 'setVerticalScrollBarEnabled is not implemented on the current platform', + ); } /// Whether the horizontal scrollbar should be drawn or not. Future setHorizontalScrollBarEnabled(bool enabled) { throw UnimplementedError( - 'setHorizontalScrollBarEnabled is not implemented on the current platform'); + 'setHorizontalScrollBarEnabled is not implemented on the current platform', + ); } /// Returns true if the current platform supports setting whether scrollbars @@ -268,31 +282,36 @@ abstract class PlatformWebViewController extends PlatformInterface { /// Scroll position is measured from the top left. Future getScrollPosition() { throw UnimplementedError( - 'getScrollPosition is not implemented on the current platform'); + 'getScrollPosition is not implemented on the current platform', + ); } /// Whether to support zooming using its on-screen zoom controls and gestures. Future enableZoom(bool enabled) { throw UnimplementedError( - 'enableZoom is not implemented on the current platform'); + 'enableZoom is not implemented on the current platform', + ); } /// Set the current background color of this view. Future setBackgroundColor(Color color) { throw UnimplementedError( - 'setBackgroundColor is not implemented on the current platform'); + 'setBackgroundColor is not implemented on the current platform', + ); } /// Sets the JavaScript execution mode to be used by the webview. Future setJavaScriptMode(JavaScriptMode javaScriptMode) { throw UnimplementedError( - 'setJavaScriptMode is not implemented on the current platform'); + 'setJavaScriptMode is not implemented on the current platform', + ); } /// Sets the value used for the HTTP `User-Agent:` request header. Future setUserAgent(String? userAgent) { throw UnimplementedError( - 'setUserAgent is not implemented on the current platform'); + 'setUserAgent is not implemented on the current platform', + ); } /// Sets a callback that notifies the host application that web content is @@ -315,7 +334,8 @@ abstract class PlatformWebViewController extends PlatformInterface { /// Sets a callback that notifies the host application of any console messages /// written to the JavaScript console. Future setOnConsoleMessage( - void Function(JavaScriptConsoleMessage consoleMessage) onConsoleMessage) { + void Function(JavaScriptConsoleMessage consoleMessage) onConsoleMessage, + ) { throw UnimplementedError( 'setOnConsoleMessage is not implemented on the current platform', ); @@ -323,17 +343,20 @@ abstract class PlatformWebViewController extends PlatformInterface { /// Sets the listener for content offset changes. Future setOnScrollPositionChange( - void Function(ScrollPositionChange scrollPositionChange)? - onScrollPositionChange) { + void Function(ScrollPositionChange scrollPositionChange)? + onScrollPositionChange, + ) { throw UnimplementedError( - 'setOnScrollPositionChange is not implemented on the current platform'); + 'setOnScrollPositionChange is not implemented on the current platform', + ); } /// Sets a callback that notifies the host application that the web page /// wants to display a JavaScript alert() dialog. Future setOnJavaScriptAlertDialog( - Future Function(JavaScriptAlertDialogRequest request) - onJavaScriptAlertDialog) async { + Future Function(JavaScriptAlertDialogRequest request) + onJavaScriptAlertDialog, + ) async { throw UnimplementedError( 'setOnJavaScriptAlertDialog is not implemented on the current platform', ); @@ -342,8 +365,9 @@ abstract class PlatformWebViewController extends PlatformInterface { /// Sets a callback that notifies the host application that the web page /// wants to display a JavaScript confirm() dialog. Future setOnJavaScriptConfirmDialog( - Future Function(JavaScriptConfirmDialogRequest request) - onJavaScriptConfirmDialog) async { + Future Function(JavaScriptConfirmDialogRequest request) + onJavaScriptConfirmDialog, + ) async { throw UnimplementedError( 'setOnJavaScriptConfirmDialog is not implemented on the current platform', ); @@ -352,8 +376,9 @@ abstract class PlatformWebViewController extends PlatformInterface { /// Sets a callback that notifies the host application that the web page /// wants to display a JavaScript prompt() dialog. Future setOnJavaScriptTextInputDialog( - Future Function(JavaScriptTextInputDialogRequest request) - onJavaScriptTextInputDialog) async { + Future Function(JavaScriptTextInputDialogRequest request) + onJavaScriptTextInputDialog, + ) async { throw UnimplementedError( 'setOnJavaScriptTextInputDialog is not implemented on the current platform', ); diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_cookie_manager.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_cookie_manager.dart index f87a386cf0e..25f925b1f10 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_cookie_manager.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_cookie_manager.dart @@ -19,7 +19,8 @@ import 'webview_platform.dart' show WebViewPlatform; abstract class PlatformWebViewCookieManager extends PlatformInterface { /// Creates a new [PlatformWebViewCookieManager] factory PlatformWebViewCookieManager( - PlatformWebViewCookieManagerCreationParams params) { + PlatformWebViewCookieManagerCreationParams params, + ) { assert( WebViewPlatform.instance != null, 'A platform implementation for `webview_flutter` has not been set. Please ' @@ -27,8 +28,9 @@ abstract class PlatformWebViewCookieManager extends PlatformInterface { '`WebViewPlatform.instance` before use. For unit testing, ' '`WebViewPlatform.instance` can be set with your own test implementation.', ); - final PlatformWebViewCookieManager cookieManagerDelegate = - WebViewPlatform.instance!.createPlatformCookieManager(params); + final PlatformWebViewCookieManager cookieManagerDelegate = WebViewPlatform + .instance! + .createPlatformCookieManager(params); PlatformInterface.verify(cookieManagerDelegate, _token); return cookieManagerDelegate; } @@ -40,7 +42,7 @@ abstract class PlatformWebViewCookieManager extends PlatformInterface { /// a class that only contains a factory constructor. @protected PlatformWebViewCookieManager.implementation(this.params) - : super(token: _token); + : super(token: _token); static final Object _token = Object(); @@ -52,12 +54,14 @@ abstract class PlatformWebViewCookieManager extends PlatformInterface { /// Returns true if cookies were present before clearing, else false. Future clearCookies() { throw UnimplementedError( - 'clearCookies is not implemented on the current platform'); + 'clearCookies is not implemented on the current platform', + ); } /// Sets a cookie for all [WebView] instances. Future setCookie(WebViewCookie cookie) { throw UnimplementedError( - 'setCookie is not implemented on the current platform'); + 'setCookie is not implemented on the current platform', + ); } } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_widget.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_widget.dart index 124ba5747b1..7f4fa92b630 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_widget.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_widget.dart @@ -19,8 +19,9 @@ abstract class PlatformWebViewWidget extends PlatformInterface { '`WebViewPlatform.instance` before use. For unit testing, ' '`WebViewPlatform.instance` can be set with your own test implementation.', ); - final PlatformWebViewWidget webViewWidgetDelegate = - WebViewPlatform.instance!.createPlatformWebViewWidget(params); + final PlatformWebViewWidget webViewWidgetDelegate = WebViewPlatform + .instance! + .createPlatformWebViewWidget(params); PlatformInterface.verify(webViewWidgetDelegate, _token); return webViewWidgetDelegate; } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart index beca1f680df..e51667f11b4 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart @@ -39,10 +39,7 @@ import 'web_resource_response.dart'; @immutable class HttpResponseError { /// Used by the platform implementation to create a new [HttpResponseError]. - const HttpResponseError({ - this.request, - this.response, - }); + const HttpResponseError({this.request, this.response}); /// The associated request. final WebResourceRequest? request; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_console_message.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_console_message.dart index 3509e685f4f..ec1321f89a0 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_console_message.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_console_message.dart @@ -10,10 +10,7 @@ import 'javascript_log_level.dart'; @immutable class JavaScriptConsoleMessage { /// Creates a [JavaScriptConsoleMessage]. - const JavaScriptConsoleMessage({ - required this.level, - required this.message, - }); + const JavaScriptConsoleMessage({required this.level, required this.message}); /// The severity of a JavaScript log message. final JavaScriptLogLevel level; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_message.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_message.dart index b5a18fba9c5..ca8f2fb0198 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_message.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_message.dart @@ -40,9 +40,7 @@ import 'package:flutter/foundation.dart'; @immutable class JavaScriptMessage { /// Creates a new JavaScript message object. - const JavaScriptMessage({ - required this.message, - }); + const JavaScriptMessage({required this.message}); /// The contents of the message that was sent by the JavaScript code. final String message; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_file_params.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_file_params.dart index 70141c1cbf1..1cdd1576519 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_file_params.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_file_params.dart @@ -29,9 +29,7 @@ import 'package:flutter/material.dart'; @immutable base class LoadFileParams { /// Creates a new [LoadFileParams] object. - const LoadFileParams({ - required this.absoluteFilePath, - }); + const LoadFileParams({required this.absoluteFilePath}); /// The path to the local HTML file to be loaded. final String absoluteFilePath; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/navigation_request.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/navigation_request.dart index ee3f1f910f9..3fba043eaf6 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/navigation_request.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/navigation_request.dart @@ -5,10 +5,7 @@ /// Defines the parameters of the pending navigation callback. class NavigationRequest { /// Creates a [NavigationRequest]. - const NavigationRequest({ - required this.url, - required this.isMainFrame, - }); + const NavigationRequest({required this.url, required this.isMainFrame}); /// The URL of the pending navigation request. final String url; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_credential.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_credential.dart index 8c109e94847..aea16da6175 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_credential.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_credential.dart @@ -11,10 +11,7 @@ import '../types/http_auth_request.dart'; @immutable class WebViewCredential { /// Creates a [WebViewCredential]. - const WebViewCredential({ - required this.user, - required this.password, - }); + const WebViewCredential({required this.user, required this.password}); /// The user name. final String user; diff --git a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/webview_platform.dart b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/webview_platform.dart index e593627511f..c7dbb9a06d2 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/lib/src/webview_platform.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/lib/src/webview_platform.dart @@ -31,7 +31,8 @@ abstract class WebViewPlatform extends PlatformInterface { static set instance(WebViewPlatform? instance) { if (instance == null) { throw AssertionError( - 'Platform interfaces can only be set to a non-null instance'); + 'Platform interfaces can only be set to a non-null instance', + ); } PlatformInterface.verify(instance, _token); @@ -46,7 +47,8 @@ abstract class WebViewPlatform extends PlatformInterface { PlatformWebViewCookieManagerCreationParams params, ) { throw UnimplementedError( - 'createPlatformCookieManager is not implemented on the current platform.'); + 'createPlatformCookieManager is not implemented on the current platform.', + ); } /// Creates a new [PlatformNavigationDelegate]. @@ -57,7 +59,8 @@ abstract class WebViewPlatform extends PlatformInterface { PlatformNavigationDelegateCreationParams params, ) { throw UnimplementedError( - 'createPlatformNavigationDelegate is not implemented on the current platform.'); + 'createPlatformNavigationDelegate is not implemented on the current platform.', + ); } /// Create a new [PlatformWebViewController]. @@ -68,7 +71,8 @@ abstract class WebViewPlatform extends PlatformInterface { PlatformWebViewControllerCreationParams params, ) { throw UnimplementedError( - 'createPlatformWebViewController is not implemented on the current platform.'); + 'createPlatformWebViewController is not implemented on the current platform.', + ); } /// Create a new [PlatformWebViewWidget]. @@ -79,6 +83,7 @@ abstract class WebViewPlatform extends PlatformInterface { PlatformWebViewWidgetCreationParams params, ) { throw UnimplementedError( - 'createPlatformWebViewWidget is not implemented on the current platform.'); + 'createPlatformWebViewWidget is not implemented on the current platform.', + ); } } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml b/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml index ef60f1c986a..9a1dc625b26 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml +++ b/packages/webview_flutter/webview_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.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/javascript_channel_registry_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/javascript_channel_registry_test.dart index c9d27c60198..74b91e1c947 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/javascript_channel_registry_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/javascript_channel_registry_test.dart @@ -10,18 +10,18 @@ void main() { final Set channels = { JavascriptChannel( name: 'js_channel_1', - onMessageReceived: (JavascriptMessage message) => - log['js_channel_1'] = message.message, + onMessageReceived: + (JavascriptMessage message) => log['js_channel_1'] = message.message, ), JavascriptChannel( name: 'js_channel_2', - onMessageReceived: (JavascriptMessage message) => - log['js_channel_2'] = message.message, + onMessageReceived: + (JavascriptMessage message) => log['js_channel_2'] = message.message, ), JavascriptChannel( name: 'js_channel_3', - onMessageReceived: (JavascriptMessage message) => - log['js_channel_3'] = message.message, + onMessageReceived: + (JavascriptMessage message) => log['js_channel_3'] = message.message, ), }; @@ -30,8 +30,9 @@ void main() { }); test('ctor should initialize with channels.', () { - final JavascriptChannelRegistry registry = - JavascriptChannelRegistry(channels); + final JavascriptChannelRegistry registry = JavascriptChannelRegistry( + channels, + ); expect(registry.channels.length, 3); for (final JavascriptChannel channel in channels) { @@ -39,79 +40,90 @@ void main() { } }); - test('onJavascriptChannelMessage should forward message on correct channel.', - () { - final JavascriptChannelRegistry registry = - JavascriptChannelRegistry(channels); + test( + 'onJavascriptChannelMessage should forward message on correct channel.', + () { + final JavascriptChannelRegistry registry = JavascriptChannelRegistry( + channels, + ); - registry.onJavascriptChannelMessage( - 'js_channel_2', - 'test message on channel 2', - ); + registry.onJavascriptChannelMessage( + 'js_channel_2', + 'test message on channel 2', + ); - expect( - log, - containsPair( - 'js_channel_2', - 'test message on channel 2', - )); - }); + expect(log, containsPair('js_channel_2', 'test message on channel 2')); + }, + ); test( - 'onJavascriptChannelMessage should throw ArgumentError when message arrives on non-existing channel.', - () { - final JavascriptChannelRegistry registry = - JavascriptChannelRegistry(channels); + 'onJavascriptChannelMessage should throw ArgumentError when message arrives on non-existing channel.', + () { + final JavascriptChannelRegistry registry = JavascriptChannelRegistry( + channels, + ); - expect( + expect( () => registry.onJavascriptChannelMessage( - 'js_channel_4', - 'test message on channel 2', - ), + 'js_channel_4', + 'test message on channel 2', + ), throwsA( - isA().having((ArgumentError error) => error.message, - 'message', 'No channel registered with name js_channel_4.'), - )); - }); + isA().having( + (ArgumentError error) => error.message, + 'message', + 'No channel registered with name js_channel_4.', + ), + ), + ); + }, + ); test( - 'updateJavascriptChannelsFromSet should clear all channels when null is supplied.', - () { - final JavascriptChannelRegistry registry = - JavascriptChannelRegistry(channels); - - expect(registry.channels.length, 3); - - registry.updateJavascriptChannelsFromSet(null); + 'updateJavascriptChannelsFromSet should clear all channels when null is supplied.', + () { + final JavascriptChannelRegistry registry = JavascriptChannelRegistry( + channels, + ); - expect(registry.channels, isEmpty); - }); + expect(registry.channels.length, 3); - test('updateJavascriptChannelsFromSet should update registry with new set.', - () { - final JavascriptChannelRegistry registry = - JavascriptChannelRegistry(channels); + registry.updateJavascriptChannelsFromSet(null); - expect(registry.channels.length, 3); + expect(registry.channels, isEmpty); + }, + ); - final Set newChannels = { - JavascriptChannel( - name: 'new_js_channel_1', - onMessageReceived: (JavascriptMessage message) => - log['new_js_channel_1'] = message.message, - ), - JavascriptChannel( - name: 'new_js_channel_2', - onMessageReceived: (JavascriptMessage message) => - log['new_js_channel_2'] = message.message, - ), - }; - - registry.updateJavascriptChannelsFromSet(newChannels); - - expect(registry.channels.length, 2); - for (final JavascriptChannel channel in newChannels) { - expect(registry.channels[channel.name], channel); - } - }); + test( + 'updateJavascriptChannelsFromSet should update registry with new set.', + () { + final JavascriptChannelRegistry registry = JavascriptChannelRegistry( + channels, + ); + + expect(registry.channels.length, 3); + + final Set newChannels = { + JavascriptChannel( + name: 'new_js_channel_1', + onMessageReceived: + (JavascriptMessage message) => + log['new_js_channel_1'] = message.message, + ), + JavascriptChannel( + name: 'new_js_channel_2', + onMessageReceived: + (JavascriptMessage message) => + log['new_js_channel_2'] = message.message, + ), + }; + + registry.updateJavascriptChannelsFromSet(newChannels); + + expect(registry.channels.length, 2); + for (final JavascriptChannel channel in newChannels) { + expect(registry.channels[channel.name], channel); + } + }, + ); } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/webview_cookie_manager_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/webview_cookie_manager_test.dart index a9faea52e40..45527d53207 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/webview_cookie_manager_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/webview_cookie_manager_test.dart @@ -17,8 +17,11 @@ void main() { }); test('setCookie should throw UnimplementedError', () { - const WebViewCookie cookie = - WebViewCookie(domain: 'flutter.dev', name: 'foo', value: 'bar'); + const WebViewCookie cookie = WebViewCookie( + domain: 'flutter.dev', + name: 'foo', + value: 'bar', + ); expect(() => cookieManager!.setCookie(cookie), throwsUnimplementedError); }); } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/javascript_channel_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/javascript_channel_test.dart index ecb9c3fbed1..4c66fd85bb0 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/javascript_channel_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/javascript_channel_test.dart @@ -8,22 +8,26 @@ import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_ void main() { final List validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_'.split(''); - final List commonInvalidChars = - r'`~!@#$%^&*()-=+[]{}\|"' ':;/?<>,. '.split(''); + final List commonInvalidChars = r'`~!@#$%^&*()-=+[]{}\|"' + ':;/?<>,. ' + .split(''); final List digits = List.generate(10, (int index) => index++); test( - 'ctor should create JavascriptChannel when name starts with a valid character followed by a number.', - () { - for (final String char in validChars) { - for (final int digit in digits) { - final JavascriptChannel channel = - JavascriptChannel(name: '$char$digit', onMessageReceived: (_) {}); + 'ctor should create JavascriptChannel when name starts with a valid character followed by a number.', + () { + for (final String char in validChars) { + for (final int digit in digits) { + final JavascriptChannel channel = JavascriptChannel( + name: '$char$digit', + onMessageReceived: (_) {}, + ); - expect(channel.name, '$char$digit'); + expect(channel.name, '$char$digit'); + } } - } - }); + }, + ); test('ctor should assert when channel name starts with a number.', () { for (final int i in digits) { @@ -39,7 +43,9 @@ void main() { for (final String invalidChar in commonInvalidChars) { expect( () => JavascriptChannel( - name: validChar + invalidChar, onMessageReceived: (_) {}), + name: validChar + invalidChar, + onMessageReceived: (_) {}, + ), throwsAssertionError, ); } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_cookie_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_cookie_test.dart index f1702f4ad1c..c87488e9009 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_cookie_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_cookie_test.dart @@ -11,7 +11,11 @@ void main() { Map serializedCookie; // Test serialization cookie = const WebViewCookie( - name: 'foo', value: 'bar', domain: 'example.com', path: '/test'); + name: 'foo', + value: 'bar', + domain: 'example.com', + path: '/test', + ); serializedCookie = cookie.toJson(); expect(serializedCookie['name'], 'foo'); expect(serializedCookie['value'], 'bar'); diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart index 73ee279a4a9..63a1c33d333 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart @@ -17,8 +17,9 @@ void main() { test('Cannot be implemented with `implements`', () { const PlatformNavigationDelegateCreationParams params = PlatformNavigationDelegateCreationParams(); - when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params)) - .thenReturn(ImplementsPlatformNavigationDelegate()); + when( + WebViewPlatform.instance!.createPlatformNavigationDelegate(params), + ).thenReturn(ImplementsPlatformNavigationDelegate()); expect(() { PlatformNavigationDelegate(params); @@ -35,8 +36,9 @@ void main() { test('Can be extended', () { const PlatformNavigationDelegateCreationParams params = PlatformNavigationDelegateCreationParams(); - when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params)) - .thenReturn(ExtendsPlatformNavigationDelegate(params)); + when( + WebViewPlatform.instance!.createPlatformNavigationDelegate(params), + ).thenReturn(ExtendsPlatformNavigationDelegate(params)); expect(PlatformNavigationDelegate(params), isNotNull); }); @@ -44,130 +46,153 @@ void main() { test('Can be mocked with `implements`', () { const PlatformNavigationDelegateCreationParams params = PlatformNavigationDelegateCreationParams(); - when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params)) - .thenReturn(MockNavigationDelegate()); + when( + WebViewPlatform.instance!.createPlatformNavigationDelegate(params), + ).thenReturn(MockNavigationDelegate()); expect(PlatformNavigationDelegate(params), isNotNull); }); test( - 'Default implementation of setOnNavigationRequest should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnNavigationRequest( - (NavigationRequest navigationRequest) => NavigationDecision.navigate), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnNavigationRequest should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => callbackDelegate.setOnNavigationRequest( + (NavigationRequest navigationRequest) => NavigationDecision.navigate, + ), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnPageStarted should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnPageStarted((String url) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnPageStarted should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => callbackDelegate.setOnPageStarted((String url) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnPageFinished should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnPageFinished((String url) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnPageFinished should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => callbackDelegate.setOnPageFinished((String url) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnHttpError should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnHttpError((HttpResponseError error) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnHttpError should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => callbackDelegate.setOnHttpError((HttpResponseError error) {}), + throwsUnimplementedError, + ); + }, + ); test( - // ignore: lines_longer_than_80_chars - 'Default implementation of setOnProgress should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnProgress((int progress) {}), - throwsUnimplementedError, - ); - }); + // ignore: lines_longer_than_80_chars + 'Default implementation of setOnProgress should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => callbackDelegate.setOnProgress((int progress) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnWebResourceError should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnWebResourceError((WebResourceError error) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnWebResourceError should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => + callbackDelegate.setOnWebResourceError((WebResourceError error) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnUrlChange should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnUrlChange((UrlChange change) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnUrlChange should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => callbackDelegate.setOnUrlChange((UrlChange change) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnHttpAuthRequest should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnHttpAuthRequest((HttpAuthRequest request) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnHttpAuthRequest should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => + callbackDelegate.setOnHttpAuthRequest((HttpAuthRequest request) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnSSlAuthError should throw unimplemented error', - () { - final PlatformNavigationDelegate callbackDelegate = - ExtendsPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()); - - expect( - () => callbackDelegate.setOnSSlAuthError((PlatformSslAuthError eror) {}), - throwsUnimplementedError, - ); - }); + 'Default implementation of setOnSSlAuthError should throw unimplemented error', + () { + final PlatformNavigationDelegate callbackDelegate = + ExtendsPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + + expect( + () => + callbackDelegate.setOnSSlAuthError((PlatformSslAuthError eror) {}), + throwsUnimplementedError, + ); + }, + ); } class MockWebViewPlatformWithMixin extends MockWebViewPlatform @@ -185,8 +210,7 @@ class MockNavigationDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin - implements - PlatformNavigationDelegate {} + implements PlatformNavigationDelegate {} class ExtendsPlatformNavigationDelegate extends PlatformNavigationDelegate { ExtendsPlatformNavigationDelegate(super.params) : super.implementation(); diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.dart index 64c7e001ae4..399f36ea65d 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.dart @@ -19,13 +19,15 @@ void main() { }); test('Cannot be implemented with `implements`', () { - when((WebViewPlatform.instance! as MockWebViewPlatform) - .createPlatformWebViewController(any)) - .thenReturn(ImplementsPlatformWebViewController()); + when( + (WebViewPlatform.instance! as MockWebViewPlatform) + .createPlatformWebViewController(any), + ).thenReturn(ImplementsPlatformWebViewController()); expect(() { PlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + const PlatformWebViewControllerCreationParams(), + ); // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes throw @@ -39,46 +41,48 @@ void main() { test('Can be extended', () { const PlatformWebViewControllerCreationParams params = PlatformWebViewControllerCreationParams(); - when((WebViewPlatform.instance! as MockWebViewPlatform) - .createPlatformWebViewController(any)) - .thenReturn(ExtendsPlatformWebViewController(params)); + when( + (WebViewPlatform.instance! as MockWebViewPlatform) + .createPlatformWebViewController(any), + ).thenReturn(ExtendsPlatformWebViewController(params)); expect(PlatformWebViewController(params), isNotNull); }); test('Can be mocked with `implements`', () { - when((WebViewPlatform.instance! as MockWebViewPlatform) - .createPlatformWebViewController(any)) - .thenReturn(MockWebViewControllerDelegate()); + when( + (WebViewPlatform.instance! as MockWebViewPlatform) + .createPlatformWebViewController(any), + ).thenReturn(MockWebViewControllerDelegate()); expect( - PlatformWebViewController( - const PlatformWebViewControllerCreationParams()), - isNotNull); + PlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ), + isNotNull, + ); }); - test('Default implementation of loadFile should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of loadFile should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.loadFile(''), - throwsUnimplementedError, - ); - }); + expect(() => controller.loadFile(''), throwsUnimplementedError); + }, + ); test('loadFileWithParams redirects to loadFile with correct path', () async { final LoadFileSpyPlatformWebViewController controller = LoadFileSpyPlatformWebViewController( - const PlatformWebViewControllerCreationParams(), - ); + const PlatformWebViewControllerCreationParams(), + ); const String testPath = 'file:///test/index.html'; - const LoadFileParams params = LoadFileParams( - absoluteFilePath: testPath, - ); + const LoadFileParams params = LoadFileParams(absoluteFilePath: testPath); await controller.loadFileWithParams(params); @@ -86,145 +90,141 @@ void main() { }); test( - 'Default implementation of loadFlutterAsset should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of loadFlutterAsset should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.loadFlutterAsset(''), - throwsUnimplementedError, - ); - }); + expect(() => controller.loadFlutterAsset(''), throwsUnimplementedError); + }, + ); test( - 'Default implementation of loadHtmlString should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of loadHtmlString should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.loadHtmlString(''), - throwsUnimplementedError, - ); - }); + expect(() => controller.loadHtmlString(''), throwsUnimplementedError); + }, + ); - test('Default implementation of loadRequest should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of loadRequest should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.loadRequest(MockLoadRequestParamsDelegate()), - throwsUnimplementedError, - ); - }); + expect( + () => controller.loadRequest(MockLoadRequestParamsDelegate()), + throwsUnimplementedError, + ); + }, + ); - test('Default implementation of currentUrl should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of currentUrl should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.currentUrl(), - throwsUnimplementedError, - ); - }); + expect(() => controller.currentUrl(), throwsUnimplementedError); + }, + ); - test('Default implementation of canGoBack should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of canGoBack should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.canGoBack(), - throwsUnimplementedError, - ); - }); + expect(() => controller.canGoBack(), throwsUnimplementedError); + }, + ); test( - 'Default implementation of canGoForward should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of canGoForward should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.canGoForward(), - throwsUnimplementedError, - ); - }); + expect(() => controller.canGoForward(), throwsUnimplementedError); + }, + ); test('Default implementation of goBack should throw unimplemented error', () { final PlatformWebViewController controller = ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.goBack(), - throwsUnimplementedError, - ); + expect(() => controller.goBack(), throwsUnimplementedError); }); - test('Default implementation of goForward should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of goForward should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.goForward(), - throwsUnimplementedError, - ); - }); + expect(() => controller.goForward(), throwsUnimplementedError); + }, + ); test('Default implementation of reload should throw unimplemented error', () { final PlatformWebViewController controller = ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.reload(), - throwsUnimplementedError, - ); + expect(() => controller.reload(), throwsUnimplementedError); }); - test('Default implementation of clearCache should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of clearCache should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.clearCache(), - throwsUnimplementedError, - ); - }); + expect(() => controller.clearCache(), throwsUnimplementedError); + }, + ); test( - 'Default implementation of clearLocalStorage should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of clearLocalStorage should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.clearLocalStorage(), - throwsUnimplementedError, - ); - }); + expect(() => controller.clearLocalStorage(), throwsUnimplementedError); + }, + ); test( 'Default implementation of the setNavigationCallback should throw unimplemented error', () { final PlatformWebViewController controller = ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + const PlatformWebViewControllerCreationParams(), + ); expect( () => @@ -235,292 +235,318 @@ void main() { ); test( - 'Default implementation of runJavaScript should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of runJavaScript should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.runJavaScript('javaScript'), - throwsUnimplementedError, - ); - }); + expect( + () => controller.runJavaScript('javaScript'), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of runJavaScriptReturningResult should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of runJavaScriptReturningResult should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.runJavaScriptReturningResult('javaScript'), - throwsUnimplementedError, - ); - }); + expect( + () => controller.runJavaScriptReturningResult('javaScript'), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of addJavaScriptChannel should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of addJavaScriptChannel should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.addJavaScriptChannel( - JavaScriptChannelParams( - name: 'test', - onMessageReceived: (_) {}, + expect( + () => controller.addJavaScriptChannel( + JavaScriptChannelParams(name: 'test', onMessageReceived: (_) {}), ), - ), - throwsUnimplementedError, - ); - }); + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of removeJavaScriptChannel should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of removeJavaScriptChannel should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.removeJavaScriptChannel('test'), - throwsUnimplementedError, - ); - }); + expect( + () => controller.removeJavaScriptChannel('test'), + throwsUnimplementedError, + ); + }, + ); - test('Default implementation of getTitle should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of getTitle should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.getTitle(), - throwsUnimplementedError, - ); - }); + expect(() => controller.getTitle(), throwsUnimplementedError); + }, + ); - test('Default implementation of scrollTo should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of scrollTo should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.scrollTo(0, 0), - throwsUnimplementedError, - ); - }); + expect(() => controller.scrollTo(0, 0), throwsUnimplementedError); + }, + ); - test('Default implementation of scrollBy should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of scrollBy should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.scrollBy(0, 0), - throwsUnimplementedError, - ); - }); + expect(() => controller.scrollBy(0, 0), throwsUnimplementedError); + }, + ); test( - 'Default implementation of setVerticalScrollBarEnabled should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setVerticalScrollBarEnabled should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setVerticalScrollBarEnabled(false), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setVerticalScrollBarEnabled(false), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setHorizontalScrollBarEnabled should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setHorizontalScrollBarEnabled should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setHorizontalScrollBarEnabled(false), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setHorizontalScrollBarEnabled(false), + throwsUnimplementedError, + ); + }, + ); - test('Default implementation of supportsSetScrollBarsEnabled returns false', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of supportsSetScrollBarsEnabled returns false', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect(controller.supportsSetScrollBarsEnabled(), isFalse); - }); + expect(controller.supportsSetScrollBarsEnabled(), isFalse); + }, + ); test( - 'Default implementation of getScrollPosition should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of getScrollPosition should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.getScrollPosition(), - throwsUnimplementedError, - ); - }); + expect(() => controller.getScrollPosition(), throwsUnimplementedError); + }, + ); - test('Default implementation of enableZoom should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + test( + 'Default implementation of enableZoom should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.enableZoom(true), - throwsUnimplementedError, - ); - }); + expect(() => controller.enableZoom(true), throwsUnimplementedError); + }, + ); test( - 'Default implementation of setBackgroundColor should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setBackgroundColor should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setBackgroundColor(Colors.blue), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setBackgroundColor(Colors.blue), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setJavaScriptMode should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setJavaScriptMode should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setJavaScriptMode(JavaScriptMode.disabled), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setJavaScriptMode(JavaScriptMode.disabled), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setUserAgent should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setUserAgent should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setUserAgent(null), - throwsUnimplementedError, - ); - }); + expect(() => controller.setUserAgent(null), throwsUnimplementedError); + }, + ); test( - 'Default implementation of setOnPermissionRequest should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setOnPermissionRequest should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setOnPlatformPermissionRequest((_) {}), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setOnPlatformPermissionRequest((_) {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of getUserAgent should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of getUserAgent should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.getUserAgent(), - throwsUnimplementedError, - ); - }); + expect(() => controller.getUserAgent(), throwsUnimplementedError); + }, + ); test( - 'Default implementation of setOnConsoleMessage should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setOnConsoleMessage should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => - controller.setOnConsoleMessage((JavaScriptConsoleMessage message) {}), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setOnConsoleMessage( + (JavaScriptConsoleMessage message) {}, + ), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnJavaScriptAlertDialog should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setOnJavaScriptAlertDialog should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setOnJavaScriptAlertDialog((_) async {}), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setOnJavaScriptAlertDialog((_) async {}), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnJavaScriptConfirmDialog should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setOnJavaScriptConfirmDialog should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setOnJavaScriptConfirmDialog((_) async { - return false; - }), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setOnJavaScriptConfirmDialog((_) async { + return false; + }), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOnJavaScriptTextInputDialog should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setOnJavaScriptTextInputDialog should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setOnJavaScriptTextInputDialog((_) async { - return ''; - }), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setOnJavaScriptTextInputDialog((_) async { + return ''; + }), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of setOverScrollMode should throw unimplemented error', - () { - final PlatformWebViewController controller = - ExtendsPlatformWebViewController( - const PlatformWebViewControllerCreationParams()); + 'Default implementation of setOverScrollMode should throw unimplemented error', + () { + final PlatformWebViewController controller = + ExtendsPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - expect( - () => controller.setOverScrollMode(WebViewOverScrollMode.always), - throwsUnimplementedError, - ); - }); + expect( + () => controller.setOverScrollMode(WebViewOverScrollMode.always), + throwsUnimplementedError, + ); + }, + ); } class MockWebViewPlatformWithMixin extends MockWebViewPlatform @@ -537,8 +563,7 @@ class MockWebViewControllerDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin - implements - PlatformWebViewController {} + implements PlatformWebViewController {} class ExtendsPlatformWebViewController extends PlatformWebViewController { ExtendsPlatformWebViewController(super.params) : super.implementation(); @@ -560,5 +585,4 @@ class MockLoadRequestParamsDelegate extends Mock with //ignore: prefer_mixin MockPlatformInterfaceMixin - implements - LoadRequestParams {} + implements LoadRequestParams {} diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.mocks.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.mocks.dart index e6839d00a31..acb3653dd2a 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.mocks.dart @@ -28,10 +28,7 @@ class _FakePlatformNavigationDelegateCreationParams_0 extends _i1.SmartFake _FakePlatformNavigationDelegateCreationParams_0( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } /// A class which mocks [PlatformNavigationDelegate]. @@ -46,101 +43,89 @@ class MockPlatformNavigationDelegate extends _i1.Mock @override _i2.PlatformNavigationDelegateCreationParams get params => (super.noSuchMethod( - Invocation.getter(#params), - returnValue: _FakePlatformNavigationDelegateCreationParams_0( - this, - Invocation.getter(#params), - ), - ) as _i2.PlatformNavigationDelegateCreationParams); + Invocation.getter(#params), + returnValue: _FakePlatformNavigationDelegateCreationParams_0( + this, + Invocation.getter(#params), + ), + ) + as _i2.PlatformNavigationDelegateCreationParams); @override _i4.Future setOnNavigationRequest( - _i3.NavigationRequestCallback? onNavigationRequest) => + _i3.NavigationRequestCallback? onNavigationRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnNavigationRequest, - [onNavigationRequest], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnNavigationRequest, [onNavigationRequest]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnPageStarted(_i3.PageEventCallback? onPageStarted) => (super.noSuchMethod( - Invocation.method( - #setOnPageStarted, - [onPageStarted], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnPageStarted, [onPageStarted]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnPageFinished(_i3.PageEventCallback? onPageFinished) => (super.noSuchMethod( - Invocation.method( - #setOnPageFinished, - [onPageFinished], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnPageFinished, [onPageFinished]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnHttpError(_i3.HttpResponseErrorCallback? onHttpError) => (super.noSuchMethod( - Invocation.method( - #setOnHttpError, - [onHttpError], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnHttpError, [onHttpError]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnProgress(_i3.ProgressCallback? onProgress) => (super.noSuchMethod( - Invocation.method( - #setOnProgress, - [onProgress], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnProgress, [onProgress]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnWebResourceError( - _i3.WebResourceErrorCallback? onWebResourceError) => + _i3.WebResourceErrorCallback? onWebResourceError, + ) => (super.noSuchMethod( - Invocation.method( - #setOnWebResourceError, - [onWebResourceError], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnWebResourceError, [onWebResourceError]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnUrlChange(_i3.UrlChangeCallback? onUrlChange) => (super.noSuchMethod( - Invocation.method( - #setOnUrlChange, - [onUrlChange], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnUrlChange, [onUrlChange]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); @override _i4.Future setOnHttpAuthRequest( - _i3.HttpAuthRequestCallback? onHttpAuthRequest) => + _i3.HttpAuthRequestCallback? onHttpAuthRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnHttpAuthRequest, - [onHttpAuthRequest], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); + Invocation.method(#setOnHttpAuthRequest, [onHttpAuthRequest]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); } diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_widget_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_widget_test.dart index ce0a02617ee..cba3ca8ff7c 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_widget_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_widget_test.dart @@ -20,8 +20,9 @@ void main() { MockWebViewControllerDelegate(); final PlatformWebViewWidgetCreationParams params = PlatformWebViewWidgetCreationParams(controller: controller); - when(WebViewPlatform.instance!.createPlatformWebViewWidget(params)) - .thenReturn(ImplementsWebViewWidgetDelegate()); + when( + WebViewPlatform.instance!.createPlatformWebViewWidget(params), + ).thenReturn(ImplementsWebViewWidgetDelegate()); expect(() { PlatformWebViewWidget(params); @@ -40,8 +41,9 @@ void main() { MockWebViewControllerDelegate(); final PlatformWebViewWidgetCreationParams params = PlatformWebViewWidgetCreationParams(controller: controller); - when(WebViewPlatform.instance!.createPlatformWebViewWidget(params)) - .thenReturn(ExtendsWebViewWidgetDelegate(params)); + when( + WebViewPlatform.instance!.createPlatformWebViewWidget(params), + ).thenReturn(ExtendsWebViewWidgetDelegate(params)); expect(PlatformWebViewWidget(params), isNotNull); }); @@ -51,8 +53,9 @@ void main() { MockWebViewControllerDelegate(); final PlatformWebViewWidgetCreationParams params = PlatformWebViewWidgetCreationParams(controller: controller); - when(WebViewPlatform.instance!.createPlatformWebViewWidget(params)) - .thenReturn(MockWebViewWidgetDelegate()); + when( + WebViewPlatform.instance!.createPlatformWebViewWidget(params), + ).thenReturn(MockWebViewWidgetDelegate()); expect(PlatformWebViewWidget(params), isNotNull); }); @@ -72,8 +75,7 @@ class MockWebViewWidgetDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin - implements - PlatformWebViewWidget {} + implements PlatformWebViewWidget {} class ExtendsWebViewWidgetDelegate extends PlatformWebViewWidget { ExtendsWebViewWidgetDelegate(super.params) : super.implementation(); @@ -81,7 +83,8 @@ class ExtendsWebViewWidgetDelegate extends PlatformWebViewWidget { @override Widget build(BuildContext context) { throw UnimplementedError( - 'build is not implemented for ExtendedWebViewWidgetDelegate.'); + 'build is not implemented for ExtendedWebViewWidgetDelegate.', + ); } } @@ -89,5 +92,4 @@ class MockWebViewControllerDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin - implements - PlatformWebViewController {} + implements PlatformWebViewController {} diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.dart index f1e4dbb7442..68e73bf5d42 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.dart @@ -20,66 +20,75 @@ void main() { // This test can only run while `WebViewPlatform.instance` is still null. test( - 'Interface classes throw assertion error when `WebViewPlatform.instance` is null', - () { - expect( - () => PlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams(), - ), - throwsA(isA().having( - (AssertionError error) => error.message, - 'message', - 'A platform implementation for `webview_flutter` has not been set. Please ' - 'ensure that an implementation of `WebViewPlatform` has been set to ' - '`WebViewPlatform.instance` before use. For unit testing, ' - '`WebViewPlatform.instance` can be set with your own test implementation.', - )), - ); - - expect( - () => PlatformWebViewController( - const PlatformWebViewControllerCreationParams(), - ), - throwsA(isA().having( - (AssertionError error) => error.message, - 'message', - 'A platform implementation for `webview_flutter` has not been set. Please ' - 'ensure that an implementation of `WebViewPlatform` has been set to ' - '`WebViewPlatform.instance` before use. For unit testing, ' - '`WebViewPlatform.instance` can be set with your own test implementation.', - )), - ); - - expect( - () => PlatformWebViewCookieManager( - const PlatformWebViewCookieManagerCreationParams(), - ), - throwsA(isA().having( - (AssertionError error) => error.message, - 'message', - 'A platform implementation for `webview_flutter` has not been set. Please ' - 'ensure that an implementation of `WebViewPlatform` has been set to ' - '`WebViewPlatform.instance` before use. For unit testing, ' - '`WebViewPlatform.instance` can be set with your own test implementation.', - )), - ); - - expect( - () => PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams( - controller: MockWebViewControllerDelegate(), + 'Interface classes throw assertion error when `WebViewPlatform.instance` is null', + () { + expect( + () => PlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), ), - ), - throwsA(isA().having( - (AssertionError error) => error.message, - 'message', - 'A platform implementation for `webview_flutter` has not been set. Please ' - 'ensure that an implementation of `WebViewPlatform` has been set to ' - '`WebViewPlatform.instance` before use. For unit testing, ' - '`WebViewPlatform.instance` can be set with your own test implementation.', - )), - ); - }); + throwsA( + isA().having( + (AssertionError error) => error.message, + 'message', + 'A platform implementation for `webview_flutter` has not been set. Please ' + 'ensure that an implementation of `WebViewPlatform` has been set to ' + '`WebViewPlatform.instance` before use. For unit testing, ' + '`WebViewPlatform.instance` can be set with your own test implementation.', + ), + ), + ); + + expect( + () => PlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ), + throwsA( + isA().having( + (AssertionError error) => error.message, + 'message', + 'A platform implementation for `webview_flutter` has not been set. Please ' + 'ensure that an implementation of `WebViewPlatform` has been set to ' + '`WebViewPlatform.instance` before use. For unit testing, ' + '`WebViewPlatform.instance` can be set with your own test implementation.', + ), + ), + ); + + expect( + () => PlatformWebViewCookieManager( + const PlatformWebViewCookieManagerCreationParams(), + ), + throwsA( + isA().having( + (AssertionError error) => error.message, + 'message', + 'A platform implementation for `webview_flutter` has not been set. Please ' + 'ensure that an implementation of `WebViewPlatform` has been set to ' + '`WebViewPlatform.instance` before use. For unit testing, ' + '`WebViewPlatform.instance` can be set with your own test implementation.', + ), + ), + ); + + expect( + () => PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams( + controller: MockWebViewControllerDelegate(), + ), + ), + throwsA( + isA().having( + (AssertionError error) => error.message, + 'message', + 'A platform implementation for `webview_flutter` has not been set. Please ' + 'ensure that an implementation of `WebViewPlatform` has been set to ' + '`WebViewPlatform.instance` before use. For unit testing, ' + '`WebViewPlatform.instance` can be set with your own test implementation.', + ), + ), + ); + }, + ); test('Cannot be implemented with `implements`', () { expect(() { @@ -104,54 +113,62 @@ void main() { }); test( - 'Default implementation of createCookieManagerDelegate should throw unimplemented error', - () { - final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); - - expect( - () => webViewPlatform.createPlatformCookieManager( - const PlatformWebViewCookieManagerCreationParams()), - throwsUnimplementedError, - ); - }); + 'Default implementation of createCookieManagerDelegate should throw unimplemented error', + () { + final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); + + expect( + () => webViewPlatform.createPlatformCookieManager( + const PlatformWebViewCookieManagerCreationParams(), + ), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of createNavigationCallbackHandlerDelegate should throw unimplemented error', - () { - final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); - - expect( - () => webViewPlatform.createPlatformNavigationDelegate( - const PlatformNavigationDelegateCreationParams()), - throwsUnimplementedError, - ); - }); + 'Default implementation of createNavigationCallbackHandlerDelegate should throw unimplemented error', + () { + final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); + + expect( + () => webViewPlatform.createPlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of createWebViewControllerDelegate should throw unimplemented error', - () { - final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); - - expect( - () => webViewPlatform.createPlatformWebViewController( - const PlatformWebViewControllerCreationParams()), - throwsUnimplementedError, - ); - }); + 'Default implementation of createWebViewControllerDelegate should throw unimplemented error', + () { + final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); + + expect( + () => webViewPlatform.createPlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ), + throwsUnimplementedError, + ); + }, + ); test( - 'Default implementation of createWebViewWidgetDelegate should throw unimplemented error', - () { - final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); - final MockWebViewControllerDelegate controller = - MockWebViewControllerDelegate(); - - expect( - () => webViewPlatform.createPlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller)), - throwsUnimplementedError, - ); - }); + 'Default implementation of createWebViewWidgetDelegate should throw unimplemented error', + () { + final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform(); + final MockWebViewControllerDelegate controller = + MockWebViewControllerDelegate(); + + expect( + () => webViewPlatform.createPlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ), + throwsUnimplementedError, + ); + }, + ); } class ImplementsWebViewPlatform implements WebViewPlatform { @@ -170,5 +187,4 @@ class MockWebViewControllerDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin - implements - PlatformWebViewController {} + implements PlatformWebViewController {} diff --git a/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart b/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart index 9ae24623c0c..2fbc62b7006 100644 --- a/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart @@ -34,43 +34,25 @@ class _FakePlatformWebViewCookieManager_0 extends _i1.SmartFake _FakePlatformWebViewCookieManager_0( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakePlatformNavigationDelegate_1 extends _i1.SmartFake implements _i3.PlatformNavigationDelegate { - _FakePlatformNavigationDelegate_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformNavigationDelegate_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformWebViewController_2 extends _i1.SmartFake implements _i4.PlatformWebViewController { - _FakePlatformWebViewController_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformWebViewController_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformWebViewWidget_3 extends _i1.SmartFake implements _i5.PlatformWebViewWidget { - _FakePlatformWebViewWidget_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformWebViewWidget_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WebViewPlatform]. @@ -83,69 +65,53 @@ class MockWebViewPlatform extends _i1.Mock implements _i6.WebViewPlatform { @override _i2.PlatformWebViewCookieManager createPlatformCookieManager( - _i7.PlatformWebViewCookieManagerCreationParams? params) => + _i7.PlatformWebViewCookieManagerCreationParams? params, + ) => (super.noSuchMethod( - Invocation.method( - #createPlatformCookieManager, - [params], - ), - returnValue: _FakePlatformWebViewCookieManager_0( - this, - Invocation.method( - #createPlatformCookieManager, - [params], - ), - ), - ) as _i2.PlatformWebViewCookieManager); + Invocation.method(#createPlatformCookieManager, [params]), + returnValue: _FakePlatformWebViewCookieManager_0( + this, + Invocation.method(#createPlatformCookieManager, [params]), + ), + ) + as _i2.PlatformWebViewCookieManager); @override _i3.PlatformNavigationDelegate createPlatformNavigationDelegate( - _i7.PlatformNavigationDelegateCreationParams? params) => + _i7.PlatformNavigationDelegateCreationParams? params, + ) => (super.noSuchMethod( - Invocation.method( - #createPlatformNavigationDelegate, - [params], - ), - returnValue: _FakePlatformNavigationDelegate_1( - this, - Invocation.method( - #createPlatformNavigationDelegate, - [params], - ), - ), - ) as _i3.PlatformNavigationDelegate); + Invocation.method(#createPlatformNavigationDelegate, [params]), + returnValue: _FakePlatformNavigationDelegate_1( + this, + Invocation.method(#createPlatformNavigationDelegate, [params]), + ), + ) + as _i3.PlatformNavigationDelegate); @override _i4.PlatformWebViewController createPlatformWebViewController( - _i7.PlatformWebViewControllerCreationParams? params) => + _i7.PlatformWebViewControllerCreationParams? params, + ) => (super.noSuchMethod( - Invocation.method( - #createPlatformWebViewController, - [params], - ), - returnValue: _FakePlatformWebViewController_2( - this, - Invocation.method( - #createPlatformWebViewController, - [params], - ), - ), - ) as _i4.PlatformWebViewController); + Invocation.method(#createPlatformWebViewController, [params]), + returnValue: _FakePlatformWebViewController_2( + this, + Invocation.method(#createPlatformWebViewController, [params]), + ), + ) + as _i4.PlatformWebViewController); @override _i5.PlatformWebViewWidget createPlatformWebViewWidget( - _i7.PlatformWebViewWidgetCreationParams? params) => + _i7.PlatformWebViewWidgetCreationParams? params, + ) => (super.noSuchMethod( - Invocation.method( - #createPlatformWebViewWidget, - [params], - ), - returnValue: _FakePlatformWebViewWidget_3( - this, - Invocation.method( - #createPlatformWebViewWidget, - [params], - ), - ), - ) as _i5.PlatformWebViewWidget); + Invocation.method(#createPlatformWebViewWidget, [params]), + returnValue: _FakePlatformWebViewWidget_3( + this, + Invocation.method(#createPlatformWebViewWidget, [params]), + ), + ) + as _i5.PlatformWebViewWidget); } diff --git a/packages/webview_flutter/webview_flutter_web/CHANGELOG.md b/packages/webview_flutter/webview_flutter_web/CHANGELOG.md index 17e1ba40c27..7296d418b68 100644 --- a/packages/webview_flutter/webview_flutter_web/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.27/Dart 3.6. +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. ## 0.2.3+4 diff --git a/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart b/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart index 56fd4eee622..4a37c699577 100644 --- a/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart +++ b/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart @@ -19,13 +19,9 @@ Future main() async { final WebWebViewController controller = WebWebViewController( const PlatformWebViewControllerCreationParams(), ); - await controller.loadRequest( - LoadRequestParams(uri: Uri.parse(fakeUrl)), - ); + await controller.loadRequest(LoadRequestParams(uri: Uri.parse(fakeUrl))); - await tester.pumpWidget( - wrappedWebView(controller), - ); + await tester.pumpWidget(wrappedWebView(controller)); // Pump 2 frames so the framework injects the platform view into the DOM. // The duration of the second pump is set so the browser has some idle time // to actually show the contents of the iFrame. @@ -47,9 +43,7 @@ Future main() async { 'data:text/html;charset=utf-8,${Uri.encodeFull('test html')}', ); - await tester.pumpWidget( - wrappedWebView(controller), - ); + await tester.pumpWidget(wrappedWebView(controller)); // Pump 2 frames so the framework injects the platform view into the DOM. // The duration of the second pump is set so the browser has some idle time // to actually show the contents of the iFrame. diff --git a/packages/webview_flutter/webview_flutter_web/example/integration_test/wrapped_webview.dart b/packages/webview_flutter/webview_flutter_web/example/integration_test/wrapped_webview.dart index 0dc10cbf5c2..8dc1e01b585 100644 --- a/packages/webview_flutter/webview_flutter_web/example/integration_test/wrapped_webview.dart +++ b/packages/webview_flutter/webview_flutter_web/example/integration_test/wrapped_webview.dart @@ -12,9 +12,10 @@ import 'package:webview_flutter_web_example/legacy/web_view.dart'; Widget wrappedWebView(WebWebViewController controller) { return _wrapped( Builder( - builder: (BuildContext ctx) => PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(ctx), + builder: + (BuildContext ctx) => PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(ctx), ), ); } @@ -22,12 +23,7 @@ Widget wrappedWebView(WebWebViewController controller) { /// Returns a (legacy) webview widget for an [url], that calls [onCreated] when /// done, wrapped so it works in our integration tests. Widget wrappedLegacyWebView(String url, WebViewCreatedCallback onCreated) { - return _wrapped( - WebView( - initialUrl: url, - onWebViewCreated: onCreated, - ), - ); + return _wrapped(WebView(initialUrl: url, onWebViewCreated: onCreated)); } // Wraps a [child] widget in the scaffolding this test needs. @@ -36,11 +32,7 @@ Widget _wrapped(Widget child) { home: Scaffold( body: Center( child: Container( - decoration: BoxDecoration( - border: Border.all( - color: Colors.red, - ), - ), + decoration: BoxDecoration(border: Border.all(color: Colors.red)), width: 320, height: 200, child: child, diff --git a/packages/webview_flutter/webview_flutter_web/example/lib/legacy/web_view.dart b/packages/webview_flutter/webview_flutter_web/example/lib/legacy/web_view.dart index 8b390c7565c..eecefa62b26 100644 --- a/packages/webview_flutter/webview_flutter_web/example/lib/legacy/web_view.dart +++ b/packages/webview_flutter/webview_flutter_web/example/lib/legacy/web_view.dart @@ -28,11 +28,7 @@ class WebView extends StatefulWidget { /// /// The web view can be controlled using a `WebViewController` that is passed to the /// `onWebViewCreated` callback once the web view is created. - const WebView({ - super.key, - this.onWebViewCreated, - this.initialUrl, - }); + const WebView({super.key, this.onWebViewCreated, this.initialUrl}); /// The WebView platform that's used by this WebView. /// @@ -74,8 +70,9 @@ class _WebViewState extends State { Widget build(BuildContext context) { return WebView.platform.build( context: context, - onWebViewPlatformCreated: - (WebViewPlatformController? webViewPlatformController) { + onWebViewPlatformCreated: ( + WebViewPlatformController? webViewPlatformController, + ) { final WebViewController controller = WebViewController( widget, webViewPlatformController!, @@ -91,8 +88,9 @@ class _WebViewState extends State { initialUrl: widget.initialUrl, webSettings: _webSettingsFromWidget(widget), ), - javascriptChannelRegistry: - JavascriptChannelRegistry({}), + javascriptChannelRegistry: JavascriptChannelRegistry( + {}, + ), ); } } @@ -101,8 +99,10 @@ class _PlatformCallbacksHandler implements WebViewPlatformCallbacksHandler { _PlatformCallbacksHandler(); @override - FutureOr onNavigationRequest( - {required String url, required bool isForMainFrame}) { + FutureOr onNavigationRequest({ + required String url, + required bool isForMainFrame, + }) { throw UnimplementedError(); } @@ -126,10 +126,7 @@ class _PlatformCallbacksHandler implements WebViewPlatformCallbacksHandler { class WebViewController { /// Creates a [WebViewController] which can be used to control the provided /// [WebView] widget. - WebViewController( - this._widget, - this._webViewPlatformController, - ) { + WebViewController(this._widget, this._webViewPlatformController) { _settings = _webSettingsFromWidget(_widget); } @@ -147,10 +144,7 @@ class WebViewController { /// `url` must not be null. /// /// Throws an ArgumentError if `url` is not a valid URL string. - Future loadUrl( - String url, { - Map? headers, - }) async { + Future loadUrl(String url, {Map? headers}) async { _validateUrlString(url); return _webViewPlatformController.loadUrl(url, headers); } @@ -228,8 +222,10 @@ class WebViewController { } Future _updateSettings(WebSettings newSettings) { - final WebSettings update = - _clearUnchangedWebSettings(_settings, newSettings); + final WebSettings update = _clearUnchangedWebSettings( + _settings, + newSettings, + ); _settings = newSettings; return _webViewPlatformController.updateSettings(update); } @@ -238,8 +234,11 @@ class WebViewController { // ignore: public_member_api_docs Future evaluateJavascript(String javascriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { - return Future.error(FlutterError( - 'JavaScript mode must be enabled/unrestricted when calling evaluateJavascript.')); + return Future.error( + FlutterError( + 'JavaScript mode must be enabled/unrestricted when calling evaluateJavascript.', + ), + ); } return _webViewPlatformController.evaluateJavascript(javascriptString); } @@ -253,8 +252,11 @@ class WebViewController { // embedded in the main frame HTML has been loaded. Future runJavascript(String javaScriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { - return Future.error(FlutterError( - 'Javascript mode must be enabled/unrestricted when calling runJavascript.')); + return Future.error( + FlutterError( + 'Javascript mode must be enabled/unrestricted when calling runJavascript.', + ), + ); } return _webViewPlatformController.runJavascript(javaScriptString); } @@ -269,11 +271,15 @@ class WebViewController { /// embedded in the main frame HTML has been loaded. Future runJavascriptReturningResult(String javaScriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { - return Future.error(FlutterError( - 'Javascript mode must be enabled/unrestricted when calling runJavascriptReturningResult.')); + return Future.error( + FlutterError( + 'Javascript mode must be enabled/unrestricted when calling runJavascriptReturningResult.', + ), + ); } - return _webViewPlatformController - .runJavascriptReturningResult(javaScriptString); + return _webViewPlatformController.runJavascriptReturningResult( + javaScriptString, + ); } /// Returns the title of the currently loaded page. @@ -311,7 +317,9 @@ class WebViewController { // This method assumes that no fields in `currentValue` are null. WebSettings _clearUnchangedWebSettings( - WebSettings currentValue, WebSettings newValue) { + WebSettings currentValue, + WebSettings newValue, + ) { assert(currentValue.javascriptMode != null); assert(currentValue.hasNavigationDelegate != null); assert(currentValue.hasProgressTracking != null); diff --git a/packages/webview_flutter/webview_flutter_web/example/lib/main.dart b/packages/webview_flutter/webview_flutter_web/example/lib/main.dart index 9ce00603127..173cb0d67fb 100644 --- a/packages/webview_flutter/webview_flutter_web/example/lib/main.dart +++ b/packages/webview_flutter/webview_flutter_web/example/lib/main.dart @@ -25,20 +25,14 @@ class _WebViewExample extends StatefulWidget { class _WebViewExampleState extends State<_WebViewExample> { final PlatformWebViewController _controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), - )..loadRequest( - LoadRequestParams( - uri: Uri.parse('https://flutter.dev'), - ), - ); + )..loadRequest(LoadRequestParams(uri: Uri.parse('https://flutter.dev'))); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter WebView example'), - actions: [ - _SampleMenu(_controller), - ], + actions: [_SampleMenu(_controller)], ), body: PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: _controller), @@ -47,9 +41,7 @@ class _WebViewExampleState extends State<_WebViewExample> { } } -enum _MenuOptions { - doPostRequest, -} +enum _MenuOptions { doPostRequest } class _SampleMenu extends StatelessWidget { const _SampleMenu(this.controller); @@ -65,12 +57,13 @@ class _SampleMenu extends StatelessWidget { _onDoPostRequest(controller); } }, - itemBuilder: (BuildContext context) => >[ - const PopupMenuItem<_MenuOptions>( - value: _MenuOptions.doPostRequest, - child: Text('Post Request'), - ), - ], + itemBuilder: + (BuildContext context) => >[ + const PopupMenuItem<_MenuOptions>( + value: _MenuOptions.doPostRequest, + child: Text('Post Request'), + ), + ], ); } @@ -80,7 +73,7 @@ class _SampleMenu extends StatelessWidget { method: LoadRequestMethod.post, headers: const { 'foo': 'bar', - 'Content-Type': 'text/plain' + 'Content-Type': 'text/plain', }, body: Uint8List.fromList('Test Body'.codeUnits), ); diff --git a/packages/webview_flutter/webview_flutter_web/example/pubspec.yaml b/packages/webview_flutter/webview_flutter_web/example/pubspec.yaml index ee79cbd4e50..f55482a90c9 100644 --- a/packages/webview_flutter/webview_flutter_web/example/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_web/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the webview_flutter_web plugin. publish_to: none environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: diff --git a/packages/webview_flutter/webview_flutter_web/lib/src/content_type.dart b/packages/webview_flutter/webview_flutter_web/lib/src/content_type.dart index e0456a92ff7..05cd5d684c7 100644 --- a/packages/webview_flutter/webview_flutter_web/lib/src/content_type.dart +++ b/packages/webview_flutter/webview_flutter_web/lib/src/content_type.dart @@ -9,8 +9,9 @@ class ContentType { /// See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type /// See: https://httpwg.org/specs/rfc9110.html#media.type ContentType.parse(String header) { - final Iterable chunks = - header.split(';').map((String e) => e.trim().toLowerCase()); + final Iterable chunks = header + .split(';') + .map((String e) => e.trim().toLowerCase()); for (final String chunk in chunks) { if (!chunk.contains('=')) { diff --git a/packages/webview_flutter/webview_flutter_web/lib/src/http_request_factory.dart b/packages/webview_flutter/webview_flutter_web/lib/src/http_request_factory.dart index 1500921201b..cbd3a39d0c8 100644 --- a/packages/webview_flutter/webview_flutter_web/lib/src/http_request_factory.dart +++ b/packages/webview_flutter/webview_flutter_web/lib/src/http_request_factory.dart @@ -79,13 +79,14 @@ class HttpRequestFactory { }; return web.window .fetch( - url.toJS, - web.RequestInit( - method: method, - body: sendData?.toJS, - credentials: withCredentials ? 'include' : 'same-origin', - headers: headers.jsify()! as web.HeadersInit, - )) + url.toJS, + web.RequestInit( + method: method, + body: sendData?.toJS, + credentials: withCredentials ? 'include' : 'same-origin', + headers: headers.jsify()! as web.HeadersInit, + ), + ) .toDart; } } diff --git a/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_controller.dart b/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_controller.dart index d18987223a1..5a99282e34f 100644 --- a/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_controller.dart +++ b/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_controller.dart @@ -39,39 +39,45 @@ class WebWebViewControllerCreationParams /// The underlying element used as the WebView. @visibleForTesting - final web.HTMLIFrameElement iFrame = web.HTMLIFrameElement() - ..id = 'webView${_nextIFrameId++}' - ..style.width = '100%' - ..style.height = '100%' - ..style.border = 'none'; + final web.HTMLIFrameElement iFrame = + web.HTMLIFrameElement() + ..id = 'webView${_nextIFrameId++}' + ..style.width = '100%' + ..style.height = '100%' + ..style.border = 'none'; } /// An implementation of [PlatformWebViewController] using Flutter for Web API. class WebWebViewController extends PlatformWebViewController { /// Constructs a [WebWebViewController]. WebWebViewController(PlatformWebViewControllerCreationParams params) - : super.implementation(params is WebWebViewControllerCreationParams + : super.implementation( + params is WebWebViewControllerCreationParams ? params - : WebWebViewControllerCreationParams - .fromPlatformWebViewControllerCreationParams(params)); + : WebWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams( + params, + ), + ); WebWebViewControllerCreationParams get _webWebViewParams => params as WebWebViewControllerCreationParams; @override Future loadHtmlString(String html, {String? baseUrl}) async { - _webWebViewParams.iFrame.src = Uri.dataFromString( - html, - mimeType: 'text/html', - encoding: utf8, - ).toString(); + _webWebViewParams.iFrame.src = + Uri.dataFromString( + html, + mimeType: 'text/html', + encoding: utf8, + ).toString(); } @override Future loadRequest(LoadRequestParams params) async { if (!params.uri.hasScheme) { throw ArgumentError( - 'LoadRequestParams#uri is required to have a scheme.'); + 'LoadRequestParams#uri is required to have a scheme.', + ); } if (params.headers.isEmpty && @@ -87,21 +93,23 @@ class WebWebViewController extends PlatformWebViewController { Future _updateIFrameFromXhr(LoadRequestParams params) async { final web.Response response = await _webWebViewParams.httpRequestFactory.request( - params.uri.toString(), - method: params.method.serialize(), - requestHeaders: params.headers, - sendData: params.body, - ) as web.Response; + params.uri.toString(), + method: params.method.serialize(), + requestHeaders: params.headers, + sendData: params.body, + ) + as web.Response; final String header = response.headers.get('content-type') ?? 'text/html'; final ContentType contentType = ContentType.parse(header); final Encoding encoding = Encoding.getByName(contentType.charset) ?? utf8; - _webWebViewParams.iFrame.src = Uri.dataFromString( - (await response.text().toDart).toDart, - mimeType: contentType.mimeType, - encoding: encoding, - ).toString(); + _webWebViewParams.iFrame.src = + Uri.dataFromString( + (await response.text().toDart).toDart, + mimeType: contentType.mimeType, + encoding: encoding, + ).toString(); } } @@ -109,7 +117,7 @@ class WebWebViewController extends PlatformWebViewController { class WebWebViewWidget extends PlatformWebViewWidget { /// Constructs a [WebWebViewWidget]. WebWebViewWidget(PlatformWebViewWidgetCreationParams params) - : super.implementation(params) { + : super.implementation(params) { final WebWebViewController controller = params.controller as WebWebViewController; ui_web.platformViewRegistry.registerViewFactory( @@ -122,10 +130,11 @@ class WebWebViewWidget extends PlatformWebViewWidget { Widget build(BuildContext context) { return HtmlElementView( key: params.key, - viewType: (params.controller as WebWebViewController) - ._webWebViewParams - .iFrame - .id, + viewType: + (params.controller as WebWebViewController) + ._webWebViewParams + .iFrame + .id, ); } } diff --git a/packages/webview_flutter/webview_flutter_web/lib/src/webview_flutter_web_legacy.dart b/packages/webview_flutter/webview_flutter_web/lib/src/webview_flutter_web_legacy.dart index 4471ce6fed6..2897e9f167b 100644 --- a/packages/webview_flutter/webview_flutter_web/lib/src/webview_flutter_web_legacy.dart +++ b/packages/webview_flutter/webview_flutter_web/lib/src/webview_flutter_web_legacy.dart @@ -39,9 +39,7 @@ class WebWebViewPlatform implements WebViewPlatform { iFrame.src = initialUrl; } if (onWebViewPlatformCreated != null) { - onWebViewPlatformCreated( - WebWebViewPlatformController(iFrame), - ); + onWebViewPlatformCreated(WebWebViewPlatformController(iFrame)); } }, ); @@ -170,15 +168,13 @@ class WebWebViewPlatformController implements WebViewPlatformController { } @override - Future loadHtmlString( - String html, { - String? baseUrl, - }) async { - _element.src = Uri.dataFromString( - html, - mimeType: 'text/html', - encoding: utf8, - ).toString(); + Future loadHtmlString(String html, {String? baseUrl}) async { + _element.src = + Uri.dataFromString( + html, + mimeType: 'text/html', + encoding: utf8, + ).toString(); } @override @@ -186,20 +182,24 @@ class WebWebViewPlatformController implements WebViewPlatformController { if (!request.uri.hasScheme) { throw ArgumentError('WebViewRequest#uri is required to have a scheme.'); } - final web.Response response = await _httpRequestFactory.request( - request.uri.toString(), - method: request.method.serialize(), - requestHeaders: request.headers, - sendData: request.body) as web.Response; + final web.Response response = + await _httpRequestFactory.request( + request.uri.toString(), + method: request.method.serialize(), + requestHeaders: request.headers, + sendData: request.body, + ) + as web.Response; final String contentType = response.headers.get('content-type') ?? 'text/html'; - _element.src = Uri.dataFromString( - (await response.text().toDart).toDart, - mimeType: contentType, - encoding: utf8, - ).toString(); + _element.src = + Uri.dataFromString( + (await response.text().toDart).toDart, + mimeType: contentType, + encoding: utf8, + ).toString(); } @override diff --git a/packages/webview_flutter/webview_flutter_web/pubspec.yaml b/packages/webview_flutter/webview_flutter_web/pubspec.yaml index b3959e87e1a..c77b853f16f 100644 --- a/packages/webview_flutter/webview_flutter_web/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.2.3+4 environment: - sdk: ^3.6.0 - flutter: ">=3.27.0" + sdk: ^3.7.0 + flutter: ">=3.29.0" flutter: plugin: diff --git a/packages/webview_flutter/webview_flutter_web/test/content_type_test.dart b/packages/webview_flutter/webview_flutter_web/test/content_type_test.dart index 936eeae4f57..3877a77a217 100644 --- a/packages/webview_flutter/webview_flutter_web/test/content_type_test.dart +++ b/packages/webview_flutter/webview_flutter_web/test/content_type_test.dart @@ -16,8 +16,9 @@ void main() { }); test('with charset', () { - final ContentType contentType = - ContentType.parse('text/pLaIn; charset=utf-8'); + final ContentType contentType = ContentType.parse( + 'text/pLaIn; charset=utf-8', + ); expect(contentType.mimeType, 'text/plain'); expect(contentType.boundary, isNull); @@ -25,8 +26,9 @@ void main() { }); test('with boundary', () { - final ContentType contentType = - ContentType.parse('text/pLaIn; boundary=---xyz'); + final ContentType contentType = ContentType.parse( + 'text/pLaIn; boundary=---xyz', + ); expect(contentType.mimeType, 'text/plain'); expect(contentType.boundary, '---xyz'); @@ -34,8 +36,9 @@ void main() { }); test('with charset and boundary', () { - final ContentType contentType = - ContentType.parse('text/pLaIn; charset=utf-8; boundary=---xyz'); + final ContentType contentType = ContentType.parse( + 'text/pLaIn; charset=utf-8; boundary=---xyz', + ); expect(contentType.mimeType, 'text/plain'); expect(contentType.boundary, '---xyz'); @@ -43,8 +46,9 @@ void main() { }); test('with boundary and charset', () { - final ContentType contentType = - ContentType.parse('text/pLaIn; boundary=---xyz; charset=utf-8'); + final ContentType contentType = ContentType.parse( + 'text/pLaIn; boundary=---xyz; charset=utf-8', + ); expect(contentType.mimeType, 'text/plain'); expect(contentType.boundary, '---xyz'); @@ -53,7 +57,8 @@ void main() { test('with a bunch of whitespace, boundary and charset', () { final ContentType contentType = ContentType.parse( - ' text/pLaIn ; boundary=---xyz; charset=utf-8 '); + ' text/pLaIn ; boundary=---xyz; charset=utf-8 ', + ); expect(contentType.mimeType, 'text/plain'); expect(contentType.boundary, '---xyz'); diff --git a/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.dart b/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.dart index 22e2a06e66e..edadbe1e536 100644 --- a/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.dart +++ b/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.dart @@ -62,8 +62,10 @@ void main() { // Run controller.loadHtmlString('test html'); // Verify - expect(fakeIFrame.src, - 'data:text/html;charset=utf-8,${Uri.encodeFull('test html')}'); + expect( + fakeIFrame.src, + 'data:text/html;charset=utf-8,${Uri.encodeFull('test html')}', + ); }); test('loadHtmlString escapes "#" correctly', () { @@ -87,60 +89,70 @@ void main() { // Run & Verify expect( - () async => controller.loadRequest( - WebViewRequest( - uri: Uri.parse('flutter.dev'), - method: WebViewRequestMethod.get, - ), - ), - throwsA(const TypeMatcher())); + () async => controller.loadRequest( + WebViewRequest( + uri: Uri.parse('flutter.dev'), + method: WebViewRequestMethod.get, + ), + ), + throwsA(const TypeMatcher()), + ); }); - test('loadRequest makes request and loads response into iframe', - () async { - // Setup - final web.HTMLIFrameElement fakeIFrame = web.HTMLIFrameElement(); - final WebWebViewPlatformController controller = - WebWebViewPlatformController(fakeIFrame); + test( + 'loadRequest makes request and loads response into iframe', + () async { + // Setup + final web.HTMLIFrameElement fakeIFrame = web.HTMLIFrameElement(); + final WebWebViewPlatformController controller = + WebWebViewPlatformController(fakeIFrame); - final web.Response fakeResponse = web.Response( + final web.Response fakeResponse = web.Response( 'test data'.toJS, { - 'headers': { - 'content-type': 'text/plain', - }, - }.jsify()! as web.ResponseInit); - - final MockHttpRequestFactory mockHttpRequestFactory = - MockHttpRequestFactory(); - when(mockHttpRequestFactory.request( - any, - method: anyNamed('method'), - requestHeaders: anyNamed('requestHeaders'), - sendData: anyNamed('sendData'), - )).thenAnswer((_) => Future.value(fakeResponse)); - - controller.httpRequestFactory = mockHttpRequestFactory; - - // Run - await controller.loadRequest( - WebViewRequest( + 'headers': {'content-type': 'text/plain'}, + }.jsify()! + as web.ResponseInit, + ); + + final MockHttpRequestFactory mockHttpRequestFactory = + MockHttpRequestFactory(); + when( + mockHttpRequestFactory.request( + any, + method: anyNamed('method'), + requestHeaders: anyNamed('requestHeaders'), + sendData: anyNamed('sendData'), + ), + ).thenAnswer((_) => Future.value(fakeResponse)); + + controller.httpRequestFactory = mockHttpRequestFactory; + + // Run + await controller.loadRequest( + WebViewRequest( uri: Uri.parse('https://flutter.dev'), method: WebViewRequestMethod.post, body: Uint8List.fromList('test body'.codeUnits), - headers: {'Foo': 'Bar'}), - ); - // Verify - verify(mockHttpRequestFactory.request( - 'https://flutter.dev', - method: 'post', - requestHeaders: {'Foo': 'Bar'}, - sendData: Uint8List.fromList('test body'.codeUnits), - )); - - expect(fakeIFrame.src, - 'data:;charset=utf-8,${Uri.encodeFull('test data')}'); - }); + headers: {'Foo': 'Bar'}, + ), + ); + // Verify + verify( + mockHttpRequestFactory.request( + 'https://flutter.dev', + method: 'post', + requestHeaders: {'Foo': 'Bar'}, + sendData: Uint8List.fromList('test body'.codeUnits), + ), + ); + + expect( + fakeIFrame.src, + 'data:;charset=utf-8,${Uri.encodeFull('test data')}', + ); + }, + ); test('loadRequest escapes "#" correctly', () async { // Setup @@ -149,31 +161,34 @@ void main() { WebWebViewPlatformController(fakeIFrame); final web.Response fakeResponse = web.Response( - '#'.toJS, - { - 'headers': { - 'content-type': 'text/html', - }, - }.jsify()! as web.ResponseInit); + '#'.toJS, + { + 'headers': {'content-type': 'text/html'}, + }.jsify()! + as web.ResponseInit, + ); final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); - when(mockHttpRequestFactory.request( - any, - method: anyNamed('method'), - requestHeaders: anyNamed('requestHeaders'), - sendData: anyNamed('sendData'), - )).thenAnswer((_) => Future.value(fakeResponse)); + when( + mockHttpRequestFactory.request( + any, + method: anyNamed('method'), + requestHeaders: anyNamed('requestHeaders'), + sendData: anyNamed('sendData'), + ), + ).thenAnswer((_) => Future.value(fakeResponse)); controller.httpRequestFactory = mockHttpRequestFactory; // Run await controller.loadRequest( WebViewRequest( - uri: Uri.parse('https://flutter.dev'), - method: WebViewRequestMethod.post, - body: Uint8List.fromList('test body'.codeUnits), - headers: {'Foo': 'Bar'}), + uri: Uri.parse('https://flutter.dev'), + method: WebViewRequestMethod.post, + body: Uint8List.fromList('test body'.codeUnits), + headers: {'Foo': 'Bar'}, + ), ); expect(fakeIFrame.src, contains('%23')); diff --git a/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.mocks.dart b/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.mocks.dart index 896f9e397f0..947aee3b7a8 100644 --- a/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.mocks.dart @@ -30,13 +30,8 @@ import 'package:webview_flutter_web/src/http_request_factory.dart' as _i8; // ignore_for_file: subtype_of_sealed_class class _FakeWidget_0 extends _i1.SmartFake implements _i2.Widget { - _FakeWidget_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWidget_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); @override String toString({_i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info}) => @@ -45,13 +40,8 @@ class _FakeWidget_0 extends _i1.SmartFake implements _i2.Widget { class _FakeInheritedWidget_1 extends _i1.SmartFake implements _i2.InheritedWidget { - _FakeInheritedWidget_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeInheritedWidget_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); @override String toString({_i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info}) => @@ -60,30 +50,19 @@ class _FakeInheritedWidget_1 extends _i1.SmartFake class _FakeDiagnosticsNode_2 extends _i1.SmartFake implements _i3.DiagnosticsNode { - _FakeDiagnosticsNode_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDiagnosticsNode_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); @override String toString({ _i3.TextTreeConfiguration? parentConfiguration, _i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info, - }) => - super.toString(); + }) => super.toString(); } class _FakeObject_3 extends _i1.SmartFake implements Object { - _FakeObject_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [BuildContext]. @@ -95,25 +74,25 @@ class MockBuildContext extends _i1.Mock implements _i2.BuildContext { } @override - _i2.Widget get widget => (super.noSuchMethod( - Invocation.getter(#widget), - returnValue: _FakeWidget_0( - this, - Invocation.getter(#widget), - ), - ) as _i2.Widget); + _i2.Widget get widget => + (super.noSuchMethod( + Invocation.getter(#widget), + returnValue: _FakeWidget_0(this, Invocation.getter(#widget)), + ) + as _i2.Widget); @override - bool get mounted => (super.noSuchMethod( - Invocation.getter(#mounted), - returnValue: false, - ) as bool); + bool get mounted => + (super.noSuchMethod(Invocation.getter(#mounted), returnValue: false) + as bool); @override - bool get debugDoingBuild => (super.noSuchMethod( - Invocation.getter(#debugDoingBuild), - returnValue: false, - ) as bool); + bool get debugDoingBuild => + (super.noSuchMethod( + Invocation.getter(#debugDoingBuild), + returnValue: false, + ) + as bool); @override _i2.InheritedWidget dependOnInheritedElement( @@ -121,47 +100,39 @@ class MockBuildContext extends _i1.Mock implements _i2.BuildContext { Object? aspect, }) => (super.noSuchMethod( - Invocation.method( - #dependOnInheritedElement, - [ancestor], - {#aspect: aspect}, - ), - returnValue: _FakeInheritedWidget_1( - this, - Invocation.method( - #dependOnInheritedElement, - [ancestor], - {#aspect: aspect}, - ), - ), - ) as _i2.InheritedWidget); + Invocation.method( + #dependOnInheritedElement, + [ancestor], + {#aspect: aspect}, + ), + returnValue: _FakeInheritedWidget_1( + this, + Invocation.method( + #dependOnInheritedElement, + [ancestor], + {#aspect: aspect}, + ), + ), + ) + as _i2.InheritedWidget); @override void visitAncestorElements(_i2.ConditionalElementVisitor? visitor) => super.noSuchMethod( - Invocation.method( - #visitAncestorElements, - [visitor], - ), + Invocation.method(#visitAncestorElements, [visitor]), returnValueForMissingStub: null, ); @override void visitChildElements(_i2.ElementVisitor? visitor) => super.noSuchMethod( - Invocation.method( - #visitChildElements, - [visitor], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#visitChildElements, [visitor]), + returnValueForMissingStub: null, + ); @override void dispatchNotification(_i4.Notification? notification) => super.noSuchMethod( - Invocation.method( - #dispatchNotification, - [notification], - ), + Invocation.method(#dispatchNotification, [notification]), returnValueForMissingStub: null, ); @@ -171,20 +142,13 @@ class MockBuildContext extends _i1.Mock implements _i2.BuildContext { _i3.DiagnosticsTreeStyle? style = _i3.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( - Invocation.method( - #describeElement, - [name], - {#style: style}, - ), - returnValue: _FakeDiagnosticsNode_2( - this, - Invocation.method( - #describeElement, - [name], - {#style: style}, - ), - ), - ) as _i3.DiagnosticsNode); + Invocation.method(#describeElement, [name], {#style: style}), + returnValue: _FakeDiagnosticsNode_2( + this, + Invocation.method(#describeElement, [name], {#style: style}), + ), + ) + as _i3.DiagnosticsNode); @override _i3.DiagnosticsNode describeWidget( @@ -192,48 +156,36 @@ class MockBuildContext extends _i1.Mock implements _i2.BuildContext { _i3.DiagnosticsTreeStyle? style = _i3.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( - Invocation.method( - #describeWidget, - [name], - {#style: style}, - ), - returnValue: _FakeDiagnosticsNode_2( - this, - Invocation.method( - #describeWidget, - [name], - {#style: style}, - ), - ), - ) as _i3.DiagnosticsNode); + Invocation.method(#describeWidget, [name], {#style: style}), + returnValue: _FakeDiagnosticsNode_2( + this, + Invocation.method(#describeWidget, [name], {#style: style}), + ), + ) + as _i3.DiagnosticsNode); @override - List<_i3.DiagnosticsNode> describeMissingAncestor( - {required Type? expectedAncestorType}) => + List<_i3.DiagnosticsNode> describeMissingAncestor({ + required Type? expectedAncestorType, + }) => (super.noSuchMethod( - Invocation.method( - #describeMissingAncestor, - [], - {#expectedAncestorType: expectedAncestorType}, - ), - returnValue: <_i3.DiagnosticsNode>[], - ) as List<_i3.DiagnosticsNode>); + Invocation.method(#describeMissingAncestor, [], { + #expectedAncestorType: expectedAncestorType, + }), + returnValue: <_i3.DiagnosticsNode>[], + ) + as List<_i3.DiagnosticsNode>); @override _i3.DiagnosticsNode describeOwnershipChain(String? name) => (super.noSuchMethod( - Invocation.method( - #describeOwnershipChain, - [name], - ), - returnValue: _FakeDiagnosticsNode_2( - this, - Invocation.method( - #describeOwnershipChain, - [name], - ), - ), - ) as _i3.DiagnosticsNode); + Invocation.method(#describeOwnershipChain, [name]), + returnValue: _FakeDiagnosticsNode_2( + this, + Invocation.method(#describeOwnershipChain, [name]), + ), + ) + as _i3.DiagnosticsNode); } /// A class which mocks [CreationParams]. @@ -245,24 +197,31 @@ class MockCreationParams extends _i1.Mock implements _i5.CreationParams { } @override - Set get javascriptChannelNames => (super.noSuchMethod( - Invocation.getter(#javascriptChannelNames), - returnValue: {}, - ) as Set); + Set get javascriptChannelNames => + (super.noSuchMethod( + Invocation.getter(#javascriptChannelNames), + returnValue: {}, + ) + as Set); @override _i5.AutoMediaPlaybackPolicy get autoMediaPlaybackPolicy => (super.noSuchMethod( - Invocation.getter(#autoMediaPlaybackPolicy), - returnValue: - _i5.AutoMediaPlaybackPolicy.require_user_action_for_all_media_types, - ) as _i5.AutoMediaPlaybackPolicy); + Invocation.getter(#autoMediaPlaybackPolicy), + returnValue: + _i5 + .AutoMediaPlaybackPolicy + .require_user_action_for_all_media_types, + ) + as _i5.AutoMediaPlaybackPolicy); @override - List<_i5.WebViewCookie> get cookies => (super.noSuchMethod( - Invocation.getter(#cookies), - returnValue: <_i5.WebViewCookie>[], - ) as List<_i5.WebViewCookie>); + List<_i5.WebViewCookie> get cookies => + (super.noSuchMethod( + Invocation.getter(#cookies), + returnValue: <_i5.WebViewCookie>[], + ) + as List<_i5.WebViewCookie>); } /// A class which mocks [WebViewPlatformCallbacksHandler]. @@ -280,52 +239,37 @@ class MockWebViewPlatformCallbacksHandler extends _i1.Mock required bool? isForMainFrame, }) => (super.noSuchMethod( - Invocation.method( - #onNavigationRequest, - [], - { - #url: url, - #isForMainFrame: isForMainFrame, - }, - ), - returnValue: _i7.Future.value(false), - ) as _i7.FutureOr); + Invocation.method(#onNavigationRequest, [], { + #url: url, + #isForMainFrame: isForMainFrame, + }), + returnValue: _i7.Future.value(false), + ) + as _i7.FutureOr); @override void onPageStarted(String? url) => super.noSuchMethod( - Invocation.method( - #onPageStarted, - [url], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onPageStarted, [url]), + returnValueForMissingStub: null, + ); @override void onPageFinished(String? url) => super.noSuchMethod( - Invocation.method( - #onPageFinished, - [url], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onPageFinished, [url]), + returnValueForMissingStub: null, + ); @override void onProgress(int? progress) => super.noSuchMethod( - Invocation.method( - #onProgress, - [progress], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onProgress, [progress]), + returnValueForMissingStub: null, + ); @override void onWebResourceError(_i5.WebResourceError? error) => super.noSuchMethod( - Invocation.method( - #onWebResourceError, - [error], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#onWebResourceError, [error]), + returnValueForMissingStub: null, + ); } /// A class which mocks [HttpRequestFactory]. @@ -347,30 +291,33 @@ class MockHttpRequestFactory extends _i1.Mock _i9.Uint8List? sendData, }) => (super.noSuchMethod( - Invocation.method( - #request, - [url], - { - #method: method, - #withCredentials: withCredentials, - #mimeType: mimeType, - #requestHeaders: requestHeaders, - #sendData: sendData, - }, - ), - returnValue: _i7.Future.value(_FakeObject_3( - this, - Invocation.method( - #request, - [url], - { - #method: method, - #withCredentials: withCredentials, - #mimeType: mimeType, - #requestHeaders: requestHeaders, - #sendData: sendData, - }, - ), - )), - ) as _i7.Future); + Invocation.method( + #request, + [url], + { + #method: method, + #withCredentials: withCredentials, + #mimeType: mimeType, + #requestHeaders: requestHeaders, + #sendData: sendData, + }, + ), + returnValue: _i7.Future.value( + _FakeObject_3( + this, + Invocation.method( + #request, + [url], + { + #method: method, + #withCredentials: withCredentials, + #mimeType: mimeType, + #requestHeaders: requestHeaders, + #sendData: sendData, + }, + ), + ), + ), + ) + as _i7.Future); } diff --git a/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.dart b/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.dart index c7a7245279e..8ef29d63dcc 100644 --- a/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.dart +++ b/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.dart @@ -16,9 +16,12 @@ import 'package:webview_flutter_web/webview_flutter_web.dart'; import 'web_webview_controller_test.mocks.dart'; -@GenerateMocks([], customMocks: >[ - MockSpec(onMissingStub: OnMissingStub.returnDefault), -]) +@GenerateMocks( + [], + customMocks: >[ + MockSpec(onMissingStub: OnMissingStub.returnDefault), + ], +) void main() { WidgetsFlutterBinding.ensureInitialized(); @@ -37,8 +40,9 @@ void main() { group('loadHtmlString', () { test('loadHtmlString loads html into iframe', () async { - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams()); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams(), + ); await controller.loadHtmlString('test html'); expect( @@ -48,8 +52,9 @@ void main() { }); test('loadHtmlString escapes "#" correctly', () async { - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams()); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams(), + ); await controller.loadHtmlString('#'); expect( @@ -61,35 +66,41 @@ void main() { group('loadRequest', () { test('throws ArgumentError on missing scheme', () async { - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams()); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams(), + ); await expectLater( - () async => controller.loadRequest( - LoadRequestParams(uri: Uri.parse('flutter.dev')), - ), - throwsA(const TypeMatcher())); + () async => controller.loadRequest( + LoadRequestParams(uri: Uri.parse('flutter.dev')), + ), + throwsA(const TypeMatcher()), + ); }); test('skips XHR for simple GETs (no headers, no data)', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams( - httpRequestFactory: mockHttpRequestFactory, - )); - - when(mockHttpRequestFactory.request( - any, - method: anyNamed('method'), - requestHeaders: anyNamed('requestHeaders'), - sendData: anyNamed('sendData'), - )).thenThrow( - StateError('The `request` method should not have been called.')); - - await controller.loadRequest(LoadRequestParams( - uri: Uri.parse('https://flutter.dev'), - )); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams( + httpRequestFactory: mockHttpRequestFactory, + ), + ); + + when( + mockHttpRequestFactory.request( + any, + method: anyNamed('method'), + requestHeaders: anyNamed('requestHeaders'), + sendData: anyNamed('sendData'), + ), + ).thenThrow( + StateError('The `request` method should not have been called.'), + ); + + await controller.loadRequest( + LoadRequestParams(uri: Uri.parse('https://flutter.dev')), + ); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, @@ -100,39 +111,46 @@ void main() { test('makes request and loads response into iframe', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams( - httpRequestFactory: mockHttpRequestFactory, - )); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams( + httpRequestFactory: mockHttpRequestFactory, + ), + ); final web.Response fakeResponse = web.Response( - 'test data'.toJS, - { - 'headers': { - 'content-type': 'text/plain', - }, - }.jsify()! as web.ResponseInit); - - when(mockHttpRequestFactory.request( - any, - method: anyNamed('method'), - requestHeaders: anyNamed('requestHeaders'), - sendData: anyNamed('sendData'), - )).thenAnswer((_) => Future.value(fakeResponse)); - - await controller.loadRequest(LoadRequestParams( - uri: Uri.parse('https://flutter.dev'), - method: LoadRequestMethod.post, - body: Uint8List.fromList('test body'.codeUnits), - headers: const {'Foo': 'Bar'}, - )); - - verify(mockHttpRequestFactory.request( - 'https://flutter.dev', - method: 'post', - requestHeaders: {'Foo': 'Bar'}, - sendData: Uint8List.fromList('test body'.codeUnits), - )); + 'test data'.toJS, + { + 'headers': {'content-type': 'text/plain'}, + }.jsify()! + as web.ResponseInit, + ); + + when( + mockHttpRequestFactory.request( + any, + method: anyNamed('method'), + requestHeaders: anyNamed('requestHeaders'), + sendData: anyNamed('sendData'), + ), + ).thenAnswer((_) => Future.value(fakeResponse)); + + await controller.loadRequest( + LoadRequestParams( + uri: Uri.parse('https://flutter.dev'), + method: LoadRequestMethod.post, + body: Uint8List.fromList('test body'.codeUnits), + headers: const {'Foo': 'Bar'}, + ), + ); + + verify( + mockHttpRequestFactory.request( + 'https://flutter.dev', + method: 'post', + requestHeaders: {'Foo': 'Bar'}, + sendData: Uint8List.fromList('test body'.codeUnits), + ), + ); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, @@ -143,32 +161,39 @@ void main() { test('parses content-type response header correctly', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams( - httpRequestFactory: mockHttpRequestFactory, - )); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams( + httpRequestFactory: mockHttpRequestFactory, + ), + ); final Encoding iso = Encoding.getByName('latin1')!; final web.Response fakeResponse = web.Response( - String.fromCharCodes(iso.encode('España')).toJS, - { - 'headers': { - 'content-type': 'Text/HTmL; charset=latin1', - }, - }.jsify()! as web.ResponseInit); - - when(mockHttpRequestFactory.request( - any, - method: anyNamed('method'), - requestHeaders: anyNamed('requestHeaders'), - sendData: anyNamed('sendData'), - )).thenAnswer((_) => Future.value(fakeResponse)); - - await controller.loadRequest(LoadRequestParams( - uri: Uri.parse('https://flutter.dev'), - method: LoadRequestMethod.post, - )); + String.fromCharCodes(iso.encode('España')).toJS, + { + 'headers': { + 'content-type': 'Text/HTmL; charset=latin1', + }, + }.jsify()! + as web.ResponseInit, + ); + + when( + mockHttpRequestFactory.request( + any, + method: anyNamed('method'), + requestHeaders: anyNamed('requestHeaders'), + sendData: anyNamed('sendData'), + ), + ).thenAnswer((_) => Future.value(fakeResponse)); + + await controller.loadRequest( + LoadRequestParams( + uri: Uri.parse('https://flutter.dev'), + method: LoadRequestMethod.post, + ), + ); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, @@ -179,32 +204,37 @@ void main() { test('escapes "#" correctly', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams( - httpRequestFactory: mockHttpRequestFactory, - )); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams( + httpRequestFactory: mockHttpRequestFactory, + ), + ); final web.Response fakeResponse = web.Response( - '#'.toJS, - { - 'headers': { - 'content-type': 'text/html', - }, - }.jsify()! as web.ResponseInit); - - when(mockHttpRequestFactory.request( - any, - method: anyNamed('method'), - requestHeaders: anyNamed('requestHeaders'), - sendData: anyNamed('sendData'), - )).thenAnswer((_) => Future.value(fakeResponse)); - - await controller.loadRequest(LoadRequestParams( - uri: Uri.parse('https://flutter.dev'), - method: LoadRequestMethod.post, - body: Uint8List.fromList('test body'.codeUnits), - headers: const {'Foo': 'Bar'}, - )); + '#'.toJS, + { + 'headers': {'content-type': 'text/html'}, + }.jsify()! + as web.ResponseInit, + ); + + when( + mockHttpRequestFactory.request( + any, + method: anyNamed('method'), + requestHeaders: anyNamed('requestHeaders'), + sendData: anyNamed('sendData'), + ), + ).thenAnswer((_) => Future.value(fakeResponse)); + + await controller.loadRequest( + LoadRequestParams( + uri: Uri.parse('https://flutter.dev'), + method: LoadRequestMethod.post, + body: Uint8List.fromList('test body'.codeUnits), + headers: const {'Foo': 'Bar'}, + ), + ); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, diff --git a/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart b/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart index 87fe1defb11..d308c5c6ee0 100644 --- a/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart @@ -23,13 +23,8 @@ import 'package:webview_flutter_web/src/http_request_factory.dart' as _i2; // ignore_for_file: subtype_of_sealed_class class _FakeObject_0 extends _i1.SmartFake implements Object { - _FakeObject_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [HttpRequestFactory]. @@ -47,44 +42,49 @@ class MockHttpRequestFactory extends _i1.Mock _i4.Uint8List? sendData, }) => (super.noSuchMethod( - Invocation.method( - #request, - [url], - { - #method: method, - #withCredentials: withCredentials, - #mimeType: mimeType, - #requestHeaders: requestHeaders, - #sendData: sendData, - }, - ), - returnValue: _i3.Future.value(_FakeObject_0( - this, - Invocation.method( - #request, - [url], - { - #method: method, - #withCredentials: withCredentials, - #mimeType: mimeType, - #requestHeaders: requestHeaders, - #sendData: sendData, - }, - ), - )), - returnValueForMissingStub: _i3.Future.value(_FakeObject_0( - this, - Invocation.method( - #request, - [url], - { - #method: method, - #withCredentials: withCredentials, - #mimeType: mimeType, - #requestHeaders: requestHeaders, - #sendData: sendData, - }, - ), - )), - ) as _i3.Future); + Invocation.method( + #request, + [url], + { + #method: method, + #withCredentials: withCredentials, + #mimeType: mimeType, + #requestHeaders: requestHeaders, + #sendData: sendData, + }, + ), + returnValue: _i3.Future.value( + _FakeObject_0( + this, + Invocation.method( + #request, + [url], + { + #method: method, + #withCredentials: withCredentials, + #mimeType: mimeType, + #requestHeaders: requestHeaders, + #sendData: sendData, + }, + ), + ), + ), + returnValueForMissingStub: _i3.Future.value( + _FakeObject_0( + this, + Invocation.method( + #request, + [url], + { + #method: method, + #withCredentials: withCredentials, + #mimeType: mimeType, + #requestHeaders: requestHeaders, + #sendData: sendData, + }, + ), + ), + ), + ) + as _i3.Future); } diff --git a/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart b/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart index 834d95f3ca2..5bacadde2cb 100644 --- a/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart +++ b/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart @@ -12,8 +12,9 @@ void main() { group('WebWebViewWidget', () { testWidgets('build returns a HtmlElementView', (WidgetTester tester) async { - final WebWebViewController controller = - WebWebViewController(WebWebViewControllerCreationParams()); + final WebWebViewController controller = WebWebViewController( + WebWebViewControllerCreationParams(), + ); final WebWebViewWidget widget = WebWebViewWidget( PlatformWebViewWidgetCreationParams( diff --git a/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md b/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md index 4b07bc9e2b9..3a499391328 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. + ## 3.23.0 * Adds support for `PlatformWebViewController.loadFileWithParams`. diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/legacy/webview_flutter_test.dart b/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/legacy/webview_flutter_test.dart index 5f481f1b28e..5b23a33b5b8 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/legacy/webview_flutter_test.dart +++ b/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/legacy/webview_flutter_test.dart @@ -30,22 +30,26 @@ const bool skipOnIosFor154676 = true; Future main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - final HttpServer server = - await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - unawaited(server.forEach((HttpRequest request) { - if (request.uri.path == '/hello.txt') { - request.response.writeln('Hello, world.'); - } else if (request.uri.path == '/secondary.txt') { - request.response.writeln('How are you today?'); - } else if (request.uri.path == '/headers') { - request.response.writeln('${request.headers}'); - } else if (request.uri.path == '/favicon.ico') { - request.response.statusCode = HttpStatus.notFound; - } else { - fail('unexpected request: ${request.method} ${request.uri}'); - } - request.response.close(); - })); + final HttpServer server = await HttpServer.bind( + InternetAddress.loopbackIPv4, + 0, + ); + unawaited( + server.forEach((HttpRequest request) { + if (request.uri.path == '/hello.txt') { + request.response.writeln('Hello, world.'); + } else if (request.uri.path == '/secondary.txt') { + request.response.writeln('How are you today?'); + } else if (request.uri.path == '/headers') { + request.response.writeln('${request.headers}'); + } else if (request.uri.path == '/favicon.ico') { + request.response.statusCode = HttpStatus.notFound; + } else { + fail('unexpected request: ${request.method} ${request.uri}'); + } + request.response.close(); + }), + ); final String prefixUrl = 'http://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; final String secondaryUrl = '$prefixUrl/secondary.txt'; @@ -77,23 +81,25 @@ Future main() async { }); testWidgets( - 'withWeakRefenceTo allows encapsulating class to be garbage collected', - (WidgetTester tester) async { - final Completer gcCompleter = Completer(); - final PigeonInstanceManager instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: gcCompleter.complete, - ); + 'withWeakRefenceTo allows encapsulating class to be garbage collected', + (WidgetTester tester) async { + final Completer gcCompleter = Completer(); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: gcCompleter.complete, + ); - ClassWithCallbackClass? instance = ClassWithCallbackClass(); - instanceManager.addDartCreatedInstance(instance.callbackClass); - instance = null; + ClassWithCallbackClass? instance = ClassWithCallbackClass(); + instanceManager.addDartCreatedInstance(instance.callbackClass); + instance = null; - // Force garbage collection. - await forceGC(); + // Force garbage collection. + await forceGC(); - final int gcIdentifier = await gcCompleter.future; - expect(gcIdentifier, 0); - }, timeout: const Timeout(Duration(seconds: 10))); + final int gcIdentifier = await gcCompleter.future; + expect(gcIdentifier, 0); + }, + timeout: const Timeout(Duration(seconds: 10)), + ); testWidgets('loadUrl', (WidgetTester tester) async { final Completer controllerCompleter = @@ -170,15 +176,16 @@ Future main() async { ); final WebViewController controller = await controllerCompleter.future; final Map headers = { - 'test_header': 'flutter_test_header' + 'test_header': 'flutter_test_header', }; await controller.loadUrl(headersUrl, headers: headers); await pageStarts.stream.firstWhere((String url) => url == headersUrl); await pageLoads.stream.firstWhere((String url) => url == headersUrl); - final String content = await controller - .runJavascriptReturningResult('document.documentElement.innerText'); + final String content = await controller.runJavascriptReturningResult( + 'document.documentElement.innerText', + ); expect(content.contains('flutter_test_header'), isTrue); }); @@ -232,14 +239,16 @@ Future main() async { final Completer onPageFinished = Completer(); bool resizeButtonTapped = false; - await tester.pumpWidget(ResizableWebView( - onResize: (_) { - if (resizeButtonTapped) { - buttonTapResizeCompleter.complete(); - } - }, - onPageFinished: () => onPageFinished.complete(), - )); + await tester.pumpWidget( + ResizableWebView( + onResize: (_) { + if (resizeButtonTapped) { + buttonTapResizeCompleter.complete(); + } + }, + onPageFinished: () => onPageFinished.complete(), + ), + ); await onPageFinished.future; resizeButtonTapped = true; @@ -286,8 +295,9 @@ Future main() async { expect(customUserAgent2, 'Custom_User_Agent2'); }); - testWidgets('use default platform userAgent after webView is rebuilt', - (WidgetTester tester) async { + testWidgets('use default platform userAgent after webView is rebuilt', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); final GlobalKey globalKey = GlobalKey(); @@ -337,13 +347,301 @@ Future main() async { expect(customUserAgent2, defaultPlatformUserAgent); }); - group('Video playback policy', () { - testWidgets( - 'Auto media playback', - (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); + group( + 'Video playback policy', + () { + testWidgets( + 'Auto media playback', + (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + Completer controllerCompleter = + Completer(); + Completer pageLoaded = Completer(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + initialUrl: + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + initialMediaPlaybackPolicy: + AutoMediaPlaybackPolicy.always_allow, + ), + ), + ); + WebViewController controller = await controllerCompleter.future; + await pageLoaded.future; + + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); + expect(isPaused, _webviewBool(false)); + + controllerCompleter = Completer(); + pageLoaded = Completer(); + + // We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + initialUrl: + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + ), + ), + ); + + controller = await controllerCompleter.future; + await pageLoaded.future; + + isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); + expect(isPaused, _webviewBool(true)); + }, + // Flakes on iOS: https://github.com/flutter/flutter/issues/164632 + skip: Platform.isIOS, + ); + + testWidgets( + 'Changes to initialMediaPlaybackPolicy are ignored', + (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + final Completer controllerCompleter = + Completer(); + Completer pageLoaded = Completer(); + + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: key, + initialUrl: + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + initialMediaPlaybackPolicy: + AutoMediaPlaybackPolicy.always_allow, + ), + ), + ); + final WebViewController controller = await controllerCompleter.future; + await pageLoaded.future; + + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); + expect(isPaused, _webviewBool(false)); + + pageLoaded = Completer(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: key, + initialUrl: + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + ), + ), + ); + + await controller.reload(); + + await pageLoaded.future; + + isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); + expect(isPaused, _webviewBool(false)); + }, + // Flakes on iOS: https://github.com/flutter/flutter/issues/164632 + skip: Platform.isIOS, + ); + + testWidgets( + 'Video plays inline when allowsInlineMediaPlayback is true', + (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + final Completer controllerCompleter = + Completer(); + final Completer pageLoaded = Completer(); + final Completer videoPlaying = Completer(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + initialUrl: + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + javascriptChannels: { + JavascriptChannel( + name: 'VideoTestTime', + onMessageReceived: (JavascriptMessage message) { + final double currentTime = double.parse(message.message); + // Let it play for at least 1 second to make sure the related video's properties are set. + if (currentTime > 1 && !videoPlaying.isCompleted) { + videoPlaying.complete(null); + } + }, + ), + }, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + initialMediaPlaybackPolicy: + AutoMediaPlaybackPolicy.always_allow, + allowsInlineMediaPlayback: true, + ), + ), + ); + final WebViewController controller = await controllerCompleter.future; + await pageLoaded.future; + + // Pump once to trigger the video play. + await tester.pump(); + + // Makes sure we get the correct event that indicates the video is actually playing. + await videoPlaying.future; + + final String fullScreen = await controller + .runJavascriptReturningResult('isFullScreen();'); + expect(fullScreen, _webviewBool(false)); + }, + skip: Platform.isMacOS || skipOnIosFor154676, + ); + + testWidgets( + 'Video plays full screen when allowsInlineMediaPlayback is false', + (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + final Completer controllerCompleter = + Completer(); + final Completer pageLoaded = Completer(); + final Completer videoPlaying = Completer(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + initialUrl: + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + javascriptChannels: { + JavascriptChannel( + name: 'VideoTestTime', + onMessageReceived: (JavascriptMessage message) { + final double currentTime = double.parse(message.message); + // Let it play for at least 1 second to make sure the related video's properties are set. + if (currentTime > 1 && !videoPlaying.isCompleted) { + videoPlaying.complete(null); + } + }, + ), + }, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + initialMediaPlaybackPolicy: + AutoMediaPlaybackPolicy.always_allow, + ), + ), + ); + final WebViewController controller = await controllerCompleter.future; + await pageLoaded.future; + + // Pump once to trigger the video play. + await tester.pump(); + + // Makes sure we get the correct event that indicates the video is actually playing. + await videoPlaying.future; + + final String fullScreen = await controller + .runJavascriptReturningResult('isFullScreen();'); + expect(fullScreen, _webviewBool(true)); + }, + skip: Platform.isMacOS || skipOnIosFor154676, + ); + }, + // allowsInlineMediaPlayback has no effect on macOS. + skip: Platform.isMacOS, + ); + + group( + 'Audio playback policy', + () { + late String audioTestBase64; + setUpAll(() async { + final ByteData audioData = await rootBundle.load( + 'assets/sample_audio.ogg', + ); + final String base64AudioData = base64Encode( + Uint8List.view(audioData.buffer), + ); + final String audioTest = ''' + + Audio auto play + + + + + + + '''; + audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest)); + }); + + testWidgets('Auto media playback', (WidgetTester tester) async { Completer controllerCompleter = Completer(); + Completer pageStarted = Completer(); Completer pageLoaded = Completer(); await tester.pumpWidget( @@ -352,11 +650,14 @@ Future main() async { child: WebView( key: GlobalKey(), initialUrl: - 'data:text/html;charset=utf-8;base64,$videoTestBase64', + 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, + onPageStarted: (String url) { + pageStarted.complete(null); + }, onPageFinished: (String url) { pageLoaded.complete(null); }, @@ -365,13 +666,16 @@ Future main() async { ), ); WebViewController controller = await controllerCompleter.future; + await pageStarted.future; await pageLoaded.future; - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); expect(isPaused, _webviewBool(false)); controllerCompleter = Completer(); + pageStarted = Completer(); pageLoaded = Completer(); // We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy @@ -381,11 +685,14 @@ Future main() async { child: WebView( key: GlobalKey(), initialUrl: - 'data:text/html;charset=utf-8;base64,$videoTestBase64', + 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, + onPageStarted: (String url) { + pageStarted.complete(null); + }, onPageFinished: (String url) { pageLoaded.complete(null); }, @@ -394,21 +701,19 @@ Future main() async { ); controller = await controllerCompleter.future; + await pageStarted.future; await pageLoaded.future; isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(true)); - }, - // Flakes on iOS: https://github.com/flutter/flutter/issues/164632 - skip: Platform.isIOS, - ); + }); - testWidgets( - 'Changes to initialMediaPlaybackPolicy are ignored', - (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); + testWidgets('Changes to initialMediaPlaybackPolicy are ignored', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); + Completer pageStarted = Completer(); Completer pageLoaded = Completer(); final GlobalKey key = GlobalKey(); @@ -418,11 +723,14 @@ Future main() async { child: WebView( key: key, initialUrl: - 'data:text/html;charset=utf-8;base64,$videoTestBase64', + 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, + onPageStarted: (String url) { + pageStarted.complete(null); + }, onPageFinished: (String url) { pageLoaded.complete(null); }, @@ -431,12 +739,15 @@ Future main() async { ), ); final WebViewController controller = await controllerCompleter.future; + await pageStarted.future; await pageLoaded.future; - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); + String isPaused = await controller.runJavascriptReturningResult( + 'isPaused();', + ); expect(isPaused, _webviewBool(false)); + pageStarted = Completer(); pageLoaded = Completer(); await tester.pumpWidget( @@ -445,11 +756,14 @@ Future main() async { child: WebView( key: key, initialUrl: - 'data:text/html;charset=utf-8;base64,$videoTestBase64', + 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, + onPageStarted: (String url) { + pageStarted.complete(null); + }, onPageFinished: (String url) { pageLoaded.complete(null); }, @@ -459,289 +773,17 @@ Future main() async { await controller.reload(); + await pageStarted.future; await pageLoaded.future; isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); - }, - // Flakes on iOS: https://github.com/flutter/flutter/issues/164632 - skip: Platform.isIOS, - ); - - testWidgets('Video plays inline when allowsInlineMediaPlayback is true', - (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); - final Completer controllerCompleter = - Completer(); - final Completer pageLoaded = Completer(); - final Completer videoPlaying = Completer(); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - javascriptChannels: { - JavascriptChannel( - name: 'VideoTestTime', - onMessageReceived: (JavascriptMessage message) { - final double currentTime = double.parse(message.message); - // Let it play for at least 1 second to make sure the related video's properties are set. - if (currentTime > 1 && !videoPlaying.isCompleted) { - videoPlaying.complete(null); - } - }, - ), - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, - initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, - allowsInlineMediaPlayback: true, - ), - ), - ); - final WebViewController controller = await controllerCompleter.future; - await pageLoaded.future; - - // Pump once to trigger the video play. - await tester.pump(); - - // Makes sure we get the correct event that indicates the video is actually playing. - await videoPlaying.future; - - final String fullScreen = - await controller.runJavascriptReturningResult('isFullScreen();'); - expect(fullScreen, _webviewBool(false)); - }, skip: Platform.isMacOS || skipOnIosFor154676); - - testWidgets( - 'Video plays full screen when allowsInlineMediaPlayback is false', - (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); - final Completer controllerCompleter = - Completer(); - final Completer pageLoaded = Completer(); - final Completer videoPlaying = Completer(); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - javascriptChannels: { - JavascriptChannel( - name: 'VideoTestTime', - onMessageReceived: (JavascriptMessage message) { - final double currentTime = double.parse(message.message); - // Let it play for at least 1 second to make sure the related video's properties are set. - if (currentTime > 1 && !videoPlaying.isCompleted) { - videoPlaying.complete(null); - } - }, - ), - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, - initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, - ), - ), - ); - final WebViewController controller = await controllerCompleter.future; - await pageLoaded.future; - - // Pump once to trigger the video play. - await tester.pump(); - - // Makes sure we get the correct event that indicates the video is actually playing. - await videoPlaying.future; - - final String fullScreen = - await controller.runJavascriptReturningResult('isFullScreen();'); - expect(fullScreen, _webviewBool(true)); - }, skip: Platform.isMacOS || skipOnIosFor154676); - }, - // allowsInlineMediaPlayback has no effect on macOS. - skip: Platform.isMacOS); - - group('Audio playback policy', () { - late String audioTestBase64; - setUpAll(() async { - final ByteData audioData = - await rootBundle.load('assets/sample_audio.ogg'); - final String base64AudioData = - base64Encode(Uint8List.view(audioData.buffer)); - final String audioTest = ''' - - Audio auto play - - - - - - - '''; - audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest)); - }); - - testWidgets('Auto media playback', (WidgetTester tester) async { - Completer controllerCompleter = - Completer(); - Completer pageStarted = Completer(); - Completer pageLoaded = Completer(); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - onPageStarted: (String url) { - pageStarted.complete(null); - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, - initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, - ), - ), - ); - WebViewController controller = await controllerCompleter.future; - await pageStarted.future; - await pageLoaded.future; - - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); - expect(isPaused, _webviewBool(false)); - - controllerCompleter = Completer(); - pageStarted = Completer(); - pageLoaded = Completer(); - - // We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - onPageStarted: (String url) { - pageStarted.complete(null); - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, - ), - ), - ); - - controller = await controllerCompleter.future; - await pageStarted.future; - await pageLoaded.future; - - isPaused = await controller.runJavascriptReturningResult('isPaused();'); - expect(isPaused, _webviewBool(true)); - }); - - testWidgets('Changes to initialMediaPlaybackPolicy are ignored', - (WidgetTester tester) async { - final Completer controllerCompleter = - Completer(); - Completer pageStarted = Completer(); - Completer pageLoaded = Completer(); - - final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: key, - initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - onPageStarted: (String url) { - pageStarted.complete(null); - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, - initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, - ), - ), - ); - final WebViewController controller = await controllerCompleter.future; - await pageStarted.future; - await pageLoaded.future; - - String isPaused = - await controller.runJavascriptReturningResult('isPaused();'); - expect(isPaused, _webviewBool(false)); - - pageStarted = Completer(); - pageLoaded = Completer(); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: key, - initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - onPageStarted: (String url) { - pageStarted.complete(null); - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, - ), - ), - ); - - await controller.reload(); - - await pageStarted.future; - await pageLoaded.future; - - isPaused = await controller.runJavascriptReturningResult('isPaused();'); - expect(isPaused, _webviewBool(false)); - }); - }, - // OGG playback is not supported on macOS, so the test data would need - // to be changed to support macOS. - skip: Platform.isMacOS); + }); + }, + // OGG playback is not supported on macOS, so the test data would need + // to be changed to support macOS. + skip: Platform.isMacOS, + ); testWidgets('getTitle', (WidgetTester tester) async { const String getTitleTest = ''' @@ -752,8 +794,9 @@ Future main() async { '''; - final String getTitleTestBase64 = - base64Encode(const Utf8Encoder().convert(getTitleTest)); + final String getTitleTestBase64 = base64Encode( + const Utf8Encoder().convert(getTitleTest), + ); final Completer pageStarted = Completer(); final Completer pageLoaded = Completer(); final Completer controllerCompleter = @@ -792,9 +835,11 @@ Future main() async { expect(title, 'Some title'); }); - group('Programmatic Scroll', () { - testWidgets('setAndGetScrollPosition', (WidgetTester tester) async { - const String scrollTestPage = ''' + group( + 'Programmatic Scroll', + () { + testWidgets('setAndGetScrollPosition', (WidgetTester tester) async { + const String scrollTestPage = ''' @@ -815,67 +860,70 @@ Future main() async { '''; - final String scrollTestPageBase64 = - base64Encode(const Utf8Encoder().convert(scrollTestPage)); + final String scrollTestPageBase64 = base64Encode( + const Utf8Encoder().convert(scrollTestPage), + ); - final Completer pageLoaded = Completer(); - final Completer controllerCompleter = - Completer(); + final Completer pageLoaded = Completer(); + final Completer controllerCompleter = + Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - initialUrl: - 'data:text/html;charset=utf-8;base64,$scrollTestPageBase64', - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - onPageFinished: (String url) { - pageLoaded.complete(null); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + initialUrl: + 'data:text/html;charset=utf-8;base64,$scrollTestPageBase64', + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + onPageFinished: (String url) { + pageLoaded.complete(null); + }, + ), ), - ), - ); + ); - final WebViewController controller = await controllerCompleter.future; - await pageLoaded.future; - - await tester.pumpAndSettle(const Duration(seconds: 3)); - - int scrollPosX = await controller.getScrollX(); - int scrollPosY = await controller.getScrollY(); - - // Check scrollTo() - const int X_SCROLL = 123; - const int Y_SCROLL = 321; - // Get the initial position; this ensures that scrollTo is actually - // changing something, but also gives the native view's scroll position - // time to settle. - expect(scrollPosX, isNot(X_SCROLL)); - expect(scrollPosX, isNot(Y_SCROLL)); - - await controller.scrollTo(X_SCROLL, Y_SCROLL); - scrollPosX = await controller.getScrollX(); - scrollPosY = await controller.getScrollY(); - expect(scrollPosX, X_SCROLL); - expect(scrollPosY, Y_SCROLL); - - // Check scrollBy() (on top of scrollTo()) - await controller.scrollBy(X_SCROLL, Y_SCROLL); - scrollPosX = await controller.getScrollX(); - scrollPosY = await controller.getScrollY(); - expect(scrollPosX, X_SCROLL * 2); - expect(scrollPosY, Y_SCROLL * 2); - }); - }, - // Scroll position is currently not implemented for macOS. - // Flakes on iOS: https://github.com/flutter/flutter/issues/154826 - skip: Platform.isMacOS || Platform.isIOS); + final WebViewController controller = await controllerCompleter.future; + await pageLoaded.future; + + await tester.pumpAndSettle(const Duration(seconds: 3)); + + int scrollPosX = await controller.getScrollX(); + int scrollPosY = await controller.getScrollY(); + + // Check scrollTo() + const int X_SCROLL = 123; + const int Y_SCROLL = 321; + // Get the initial position; this ensures that scrollTo is actually + // changing something, but also gives the native view's scroll position + // time to settle. + expect(scrollPosX, isNot(X_SCROLL)); + expect(scrollPosX, isNot(Y_SCROLL)); + + await controller.scrollTo(X_SCROLL, Y_SCROLL); + scrollPosX = await controller.getScrollX(); + scrollPosY = await controller.getScrollY(); + expect(scrollPosX, X_SCROLL); + expect(scrollPosY, Y_SCROLL); + + // Check scrollBy() (on top of scrollTo()) + await controller.scrollBy(X_SCROLL, Y_SCROLL); + scrollPosX = await controller.getScrollX(); + scrollPosY = await controller.getScrollY(); + expect(scrollPosX, X_SCROLL * 2); + expect(scrollPosY, Y_SCROLL * 2); + }); + }, + // Scroll position is currently not implemented for macOS. + // Flakes on iOS: https://github.com/flutter/flutter/issues/154826 + skip: Platform.isMacOS || Platform.isIOS, + ); group('NavigationDelegate', () { const String blankPage = ''; - final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,' + final String blankPageEncoded = + 'data:text/html;charset=utf-8;base64,' '${base64Encode(const Utf8Encoder().convert(blankPage))}'; testWidgets('can allow requests', (WidgetTester tester) async { @@ -937,13 +985,16 @@ Future main() async { expect(error.failingUrl, isNull); } else if (Platform.isAndroid) { expect(error.errorType, isNotNull); - expect(error.failingUrl?.startsWith('https://www.notawebsite..com'), - isTrue); + expect( + error.failingUrl?.startsWith('https://www.notawebsite..com'), + isTrue, + ); } }); - testWidgets('onWebResourceError is not called with valid url', - (WidgetTester tester) async { + testWidgets('onWebResourceError is not called with valid url', ( + WidgetTester tester, + ) async { final Completer errorCompleter = Completer(); final Completer pageFinishCompleter = Completer(); @@ -967,10 +1018,10 @@ Future main() async { await pageFinishCompleter.future; }); - testWidgets( - 'onWebResourceError only called for main frame', - (WidgetTester tester) async { - const String iframeTest = ''' + testWidgets('onWebResourceError only called for main frame', ( + WidgetTester tester, + ) async { + const String iframeTest = ''' @@ -981,32 +1032,31 @@ Future main() async { '''; - final String iframeTestBase64 = - base64Encode(const Utf8Encoder().convert(iframeTest)); + final String iframeTestBase64 = base64Encode( + const Utf8Encoder().convert(iframeTest), + ); - final Completer errorCompleter = - Completer(); - final Completer pageFinishCompleter = Completer(); + final Completer errorCompleter = + Completer(); + final Completer pageFinishCompleter = Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - initialUrl: - 'data:text/html;charset=utf-8;base64,$iframeTestBase64', - onWebResourceError: (WebResourceError error) { - errorCompleter.complete(error); - }, - onPageFinished: (_) => pageFinishCompleter.complete(), - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + initialUrl: 'data:text/html;charset=utf-8;base64,$iframeTestBase64', + onWebResourceError: (WebResourceError error) { + errorCompleter.complete(error); + }, + onPageFinished: (_) => pageFinishCompleter.complete(), ), - ); + ), + ); - expect(errorCompleter.future, doesNotComplete); - await pageFinishCompleter.future; - }, - ); + expect(errorCompleter.future, doesNotComplete); + await pageFinishCompleter.future; + }); testWidgets('can block requests', (WidgetTester tester) async { final Completer controllerCompleter = @@ -1035,14 +1085,17 @@ Future main() async { await pageLoads.stream.first; // Wait for initial page load. final WebViewController controller = await controllerCompleter.future; - await controller - .runJavascript('location.href = "https://www.youtube.com/"'); + await controller.runJavascript( + 'location.href = "https://www.youtube.com/"', + ); // There should never be any second page load, since our new URL is // blocked. Still wait for a potential page change for some time in order // to give the test a chance to fail. - await pageLoads.stream.first - .timeout(const Duration(milliseconds: 500), onTimeout: () => ''); + await pageLoads.stream.first.timeout( + const Duration(milliseconds: 500), + onTimeout: () => '', + ); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, isNot(contains('youtube.com'))); }); @@ -1065,8 +1118,9 @@ Future main() async { navigationDelegate: (NavigationRequest request) async { NavigationDecision decision = NavigationDecision.prevent; decision = await Future.delayed( - const Duration(milliseconds: 10), - () => NavigationDecision.navigate); + const Duration(milliseconds: 10), + () => NavigationDecision.navigate, + ); return decision; }, onPageFinished: (String url) => pageLoads.add(url), @@ -1084,8 +1138,9 @@ Future main() async { }); }); - testWidgets('launches with gestureNavigationEnabled on iOS', - (WidgetTester tester) async { + testWidgets('launches with gestureNavigationEnabled on iOS', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); await tester.pumpWidget( @@ -1110,8 +1165,9 @@ Future main() async { expect(currentUrl, primaryUrl); }); - testWidgets('target _blank opens in same window', - (WidgetTester tester) async { + testWidgets('target _blank opens in same window', ( + WidgetTester tester, + ) async { final Completer controllerCompleter = Completer(); final Completer pageLoaded = Completer(); @@ -1137,44 +1193,41 @@ Future main() async { expect(currentUrl, primaryUrl); }); - testWidgets( - 'can open new window and go back', - (WidgetTester tester) async { - final Completer controllerCompleter = - Completer(); - Completer pageLoaded = Completer(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WebView( - key: GlobalKey(), - onWebViewCreated: (WebViewController controller) { - controllerCompleter.complete(controller); - }, - javascriptMode: JavascriptMode.unrestricted, - onPageFinished: (String url) { - pageLoaded.complete(); - }, - initialUrl: primaryUrl, - ), + testWidgets('can open new window and go back', (WidgetTester tester) async { + final Completer controllerCompleter = + Completer(); + Completer pageLoaded = Completer(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WebView( + key: GlobalKey(), + onWebViewCreated: (WebViewController controller) { + controllerCompleter.complete(controller); + }, + javascriptMode: JavascriptMode.unrestricted, + onPageFinished: (String url) { + pageLoaded.complete(); + }, + initialUrl: primaryUrl, ), - ); - final WebViewController controller = await controllerCompleter.future; - expect(controller.currentUrl(), completion(primaryUrl)); - await pageLoaded.future; - pageLoaded = Completer(); - - await controller.runJavascript('window.open("$secondaryUrl")'); - await pageLoaded.future; - pageLoaded = Completer(); - expect(controller.currentUrl(), completion(secondaryUrl)); - - expect(controller.canGoBack(), completion(true)); - await controller.goBack(); - await pageLoaded.future; - await expectLater(controller.currentUrl(), completion(primaryUrl)); - }, - ); + ), + ); + final WebViewController controller = await controllerCompleter.future; + expect(controller.currentUrl(), completion(primaryUrl)); + await pageLoaded.future; + pageLoaded = Completer(); + + await controller.runJavascript('window.open("$secondaryUrl")'); + await pageLoaded.future; + pageLoaded = Completer(); + expect(controller.currentUrl(), completion(secondaryUrl)); + + expect(controller.canGoBack(), completion(true)); + await controller.goBack(); + await pageLoaded.future; + await expectLater(controller.currentUrl(), completion(primaryUrl)); + }); } // JavaScript booleans evaluate to different string values on different devices. @@ -1192,8 +1245,11 @@ Future _getUserAgent(WebViewController controller) async { } class ResizableWebView extends StatefulWidget { - const ResizableWebView( - {super.key, required this.onResize, required this.onPageFinished}); + const ResizableWebView({ + super.key, + required this.onResize, + required this.onPageFinished, + }); final JavascriptMessageHandler onResize; final VoidCallback onPageFinished; @@ -1225,8 +1281,9 @@ class ResizableWebViewState extends State { @override Widget build(BuildContext context) { - final String resizeTestBase64 = - base64Encode(const Utf8Encoder().convert(resizePage)); + final String resizeTestBase64 = base64Encode( + const Utf8Encoder().convert(resizePage), + ); return Directionality( textDirection: TextDirection.ltr, child: Column( @@ -1278,16 +1335,15 @@ class CopyableObjectWithCallback extends PigeonInternalProxyApiBaseClass { class ClassWithCallbackClass { ClassWithCallbackClass() { callbackClass = CopyableObjectWithCallback( - withWeakReferenceTo( - this, - (WeakReference weakReference) { - return () { - // Weak reference to `this` in callback. - // ignore: unnecessary_statements - weakReference; - }; - }, - ), + withWeakReferenceTo(this, ( + WeakReference weakReference, + ) { + return () { + // Weak reference to `this` in callback. + // ignore: unnecessary_statements + weakReference; + }; + }), ); } diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart b/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart index ef72e92c306..bae72a00e08 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart +++ b/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart @@ -26,31 +26,37 @@ import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; Future main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - final HttpServer server = - await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - unawaited(server.forEach((HttpRequest request) { - if (request.uri.path == '/hello.txt') { - request.response.writeln('Hello, world.'); - } else if (request.uri.path == '/secondary.txt') { - request.response.writeln('How are you today?'); - } else if (request.uri.path == '/headers') { - request.response.writeln('${request.headers}'); - } else if (request.uri.path == '/favicon.ico') { - request.response.statusCode = HttpStatus.notFound; - } else if (request.uri.path == '/http-basic-authentication') { - final bool isAuthenticating = request.headers['Authorization'] != null; - if (isAuthenticating) { - request.response.writeln('Authorized'); + final HttpServer server = await HttpServer.bind( + InternetAddress.loopbackIPv4, + 0, + ); + unawaited( + server.forEach((HttpRequest request) { + if (request.uri.path == '/hello.txt') { + request.response.writeln('Hello, world.'); + } else if (request.uri.path == '/secondary.txt') { + request.response.writeln('How are you today?'); + } else if (request.uri.path == '/headers') { + request.response.writeln('${request.headers}'); + } else if (request.uri.path == '/favicon.ico') { + request.response.statusCode = HttpStatus.notFound; + } else if (request.uri.path == '/http-basic-authentication') { + final bool isAuthenticating = request.headers['Authorization'] != null; + if (isAuthenticating) { + request.response.writeln('Authorized'); + } else { + request.response.headers.add( + 'WWW-Authenticate', + 'Basic realm="Test realm"', + ); + request.response.statusCode = HttpStatus.unauthorized; + } } else { - request.response.headers - .add('WWW-Authenticate', 'Basic realm="Test realm"'); - request.response.statusCode = HttpStatus.unauthorized; + fail('unexpected request: ${request.method} ${request.uri}'); } - } else { - fail('unexpected request: ${request.method} ${request.uri}'); - } - request.response.close(); - })); + request.response.close(); + }), + ); final String prefixUrl = 'http://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; final String secondaryUrl = '$prefixUrl/secondary.txt'; @@ -58,26 +64,27 @@ Future main() async { final String basicAuthUrl = '$prefixUrl/http-basic-authentication'; testWidgets( - 'withWeakReferenceTo allows encapsulating class to be garbage collected', - (WidgetTester tester) async { - final Completer gcCompleter = Completer(); - final PigeonInstanceManager instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: gcCompleter.complete, - ); + 'withWeakReferenceTo allows encapsulating class to be garbage collected', + (WidgetTester tester) async { + final Completer gcCompleter = Completer(); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: gcCompleter.complete, + ); - ClassWithCallbackClass? instance = ClassWithCallbackClass(); - instanceManager.addDartCreatedInstance(instance.callbackClass); - instance = null; + ClassWithCallbackClass? instance = ClassWithCallbackClass(); + instanceManager.addDartCreatedInstance(instance.callbackClass); + instance = null; - // Force garbage collection. - await forceGC(); + // Force garbage collection. + await forceGC(); - final int gcIdentifier = await gcCompleter.future; - expect(gcIdentifier, 0); - }, - // TODO(bparrishMines): See https://github.com/flutter/flutter/issues/148345 - skip: true, - timeout: const Timeout(Duration(seconds: 10))); + final int gcIdentifier = await gcCompleter.future; + expect(gcIdentifier, 0); + }, + // TODO(bparrishMines): See https://github.com/flutter/flutter/issues/148345 + skip: true, + timeout: const Timeout(Duration(seconds: 10)), + ); testWidgets( 'WKWebView is released by garbage collection', @@ -99,24 +106,27 @@ Future main() async { WebKitWebViewWidgetCreationParams( controller: PlatformWebViewController( WebKitWebViewControllerCreationParams( - webKitProxy: WebKitProxy(newPlatformWebView: ({ - required WKWebViewConfiguration initialConfiguration, - void Function( - NSObject, - String?, - NSObject?, - Map?, - )? observeValue, - }) { - final PlatformWebView platformWebView = PlatformWebView( - initialConfiguration: initialConfiguration, - ); - finalizer.attach( - platformWebView.nativeWebView, - webViewToken, - ); - return platformWebView; - }), + webKitProxy: WebKitProxy( + newPlatformWebView: ({ + required WKWebViewConfiguration initialConfiguration, + void Function( + NSObject, + String?, + NSObject?, + Map?, + )? + observeValue, + }) { + final PlatformWebView platformWebView = PlatformWebView( + initialConfiguration: initialConfiguration, + ); + finalizer.attach( + platformWebView.nativeWebView, + webViewToken, + ); + return platformWebView; + }, + ), ), ), ), @@ -128,10 +138,11 @@ Future main() async { await tester.pumpWidget(Container()); // Force garbage collection. - await IntegrationTestWidgetsFlutterBinding.instance - .watchPerformance(() async { - await tester.pumpAndSettle(); - }); + await IntegrationTestWidgetsFlutterBinding.instance.watchPerformance( + () async { + await tester.pumpAndSettle(); + }, + ); await expectLater(webViewGCCompleter.future, completes); }, @@ -149,17 +160,17 @@ Future main() async { ); unawaited(delegate.setOnPageFinished((_) => pageFinished.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); - await controller.loadRequest( - LoadRequestParams(uri: Uri.parse(primaryUrl)), - ); + await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageFinished.future; @@ -181,13 +192,15 @@ Future main() async { unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageFinished.future; @@ -199,7 +212,7 @@ Future main() async { testWidgets('loadRequest with headers', (WidgetTester tester) async { final Map headers = { - 'test_header': 'flutter_test_header' + 'test_header': 'flutter_test_header', }; final StreamController pageLoads = StreamController(); @@ -214,30 +227,32 @@ Future main() async { unawaited(delegate.setOnPageFinished((String url) => pageLoads.add(url))); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( - LoadRequestParams( - uri: Uri.parse(headersUrl), - headers: headers, - ), + LoadRequestParams(uri: Uri.parse(headersUrl), headers: headers), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageLoads.stream.firstWhere((String url) => url == headersUrl); - final String content = await controller.runJavaScriptReturningResult( - 'document.documentElement.innerText', - ) as String; + final String content = + await controller.runJavaScriptReturningResult( + 'document.documentElement.innerText', + ) + as String; expect(content.contains('flutter_test_header'), isTrue); }); - testWidgets('loadFlutterAsset successfully loads an HTML asset', - (WidgetTester tester) async { + testWidgets('loadFlutterAsset successfully loads an HTML asset', ( + WidgetTester tester, + ) async { final Completer pageFinished = Completer(); final PlatformWebViewController controller = PlatformWebViewController( @@ -254,13 +269,15 @@ Future main() async { completes, ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); // Verify page also loads. await pageFinished.future; @@ -292,13 +309,15 @@ Future main() async { 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageFinished.future; @@ -306,8 +325,9 @@ Future main() async { await expectLater(channelCompleter.future, completion('hello')); }); - testWidgets('JavaScriptChannel can receive undefined', - (WidgetTester tester) async { + testWidgets('JavaScriptChannel can receive undefined', ( + WidgetTester tester, + ) async { final Completer pageFinished = Completer(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), @@ -333,13 +353,15 @@ Future main() async { 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageFinished.future; @@ -352,14 +374,16 @@ Future main() async { final Completer onPageFinished = Completer(); bool resizeButtonTapped = false; - await tester.pumpWidget(ResizableWebView( - onResize: () { - if (resizeButtonTapped) { - buttonTapResizeCompleter.complete(); - } - }, - onPageFinished: () => onPageFinished.complete(), - )); + await tester.pumpWidget( + ResizableWebView( + onResize: () { + if (resizeButtonTapped) { + buttonTapResizeCompleter.complete(); + } + }, + onPageFinished: () => onPageFinished.complete(), + ), + ); await onPageFinished.future; @@ -378,37 +402,42 @@ Future main() async { unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited(controller.setUserAgent('Custom_User_Agent1')); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); final String? customUserAgent = await controller.getUserAgent(); expect(customUserAgent, 'Custom_User_Agent1'); }); testWidgets( - 'getUserAgent returns a default value when custom value is not set', - (WidgetTester tester) async { - final PlatformWebViewController controller = PlatformWebViewController( - const PlatformWebViewControllerCreationParams(), - ); + 'getUserAgent returns a default value when custom value is not set', + (WidgetTester tester) async { + final PlatformWebViewController controller = PlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); - final String? userAgent = await controller.getUserAgent(); - expect(userAgent, isNotNull); - expect(userAgent, isNotEmpty); - }); + final String? userAgent = await controller.getUserAgent(); + expect(userAgent, isNotNull); + expect(userAgent, isNotEmpty); + }, + ); group('Video playback policy', () { testWidgets('Auto media playback', (WidgetTester tester) async { @@ -435,13 +464,15 @@ Future main() async { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageLoaded.future; @@ -468,13 +499,15 @@ Future main() async { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await pageLoaded.future; @@ -483,8 +516,9 @@ Future main() async { expect(isPaused, true); }); - testWidgets('Video plays inline when allowsInlineMediaPlayback is true', - (WidgetTester tester) async { + testWidgets('Video plays inline when allowsInlineMediaPlayback is true', ( + WidgetTester tester, + ) async { final String videoTestBase64 = await getTestVideoBase64(); final Completer pageLoaded = Completer(); final Completer videoPlaying = Completer(); @@ -502,18 +536,20 @@ Future main() async { unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); - unawaited(controller.addJavaScriptChannel( - JavaScriptChannelParams( - name: 'VideoTestTime', - onMessageReceived: (JavaScriptMessage message) { - final double currentTime = double.parse(message.message); - // Let it play for at least 1 second to make sure the related video's properties are set. - if (currentTime > 1 && !videoPlaying.isCompleted) { - videoPlaying.complete(null); - } - }, + unawaited( + controller.addJavaScriptChannel( + JavaScriptChannelParams( + name: 'VideoTestTime', + onMessageReceived: (JavaScriptMessage message) { + final double currentTime = double.parse(message.message); + // Let it play for at least 1 second to make sure the related video's properties are set. + if (currentTime > 1 && !videoPlaying.isCompleted) { + videoPlaying.complete(null); + } + }, + ), ), - )); + ); await controller.loadRequest( LoadRequestParams( @@ -523,13 +559,15 @@ Future main() async { ), ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); await tester.pumpAndSettle(); await pageLoaded.future; @@ -537,81 +575,92 @@ Future main() async { // Makes sure we get the correct event that indicates the video is actually playing. await videoPlaying.future; - final bool fullScreen = await controller - .runJavaScriptReturningResult('isFullScreen();') as bool; + final bool fullScreen = + await controller.runJavaScriptReturningResult('isFullScreen();') + as bool; expect(fullScreen, false); }); testWidgets( - 'Video plays full screen when allowsInlineMediaPlayback is false', - (WidgetTester tester) async { - final String videoTestBase64 = await getTestVideoBase64(); - final Completer pageLoaded = Completer(); - final Completer videoPlaying = Completer(); + 'Video plays full screen when allowsInlineMediaPlayback is false', + (WidgetTester tester) async { + final String videoTestBase64 = await getTestVideoBase64(); + final Completer pageLoaded = Completer(); + final Completer videoPlaying = Completer(); - final PlatformWebViewController controller = PlatformWebViewController( - WebKitWebViewControllerCreationParams( - mediaTypesRequiringUserAction: const {}, - ), - ); - unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); - final WebKitNavigationDelegate delegate = WebKitNavigationDelegate( - const PlatformNavigationDelegateCreationParams(), - ); - unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); - unawaited(controller.setPlatformNavigationDelegate(delegate)); + final PlatformWebViewController controller = PlatformWebViewController( + WebKitWebViewControllerCreationParams( + mediaTypesRequiringUserAction: const {}, + ), + ); + unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); + final WebKitNavigationDelegate delegate = WebKitNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); + unawaited(controller.setPlatformNavigationDelegate(delegate)); - unawaited(controller.addJavaScriptChannel( - JavaScriptChannelParams( - name: 'VideoTestTime', - onMessageReceived: (JavaScriptMessage message) { - final double currentTime = double.parse(message.message); - // Let it play for at least 1 second to make sure the related video's properties are set. - if (currentTime > 1 && !videoPlaying.isCompleted) { - videoPlaying.complete(null); - } - }, - ), - )); + unawaited( + controller.addJavaScriptChannel( + JavaScriptChannelParams( + name: 'VideoTestTime', + onMessageReceived: (JavaScriptMessage message) { + final double currentTime = double.parse(message.message); + // Let it play for at least 1 second to make sure the related video's properties are set. + if (currentTime > 1 && !videoPlaying.isCompleted) { + videoPlaying.complete(null); + } + }, + ), + ), + ); - await controller.loadRequest( - LoadRequestParams( - uri: Uri.parse( - 'data:text/html;charset=utf-8;base64,$videoTestBase64', + await controller.loadRequest( + LoadRequestParams( + uri: Uri.parse( + 'data:text/html;charset=utf-8;base64,$videoTestBase64', + ), ), - ), - ); + ); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - return PlatformWebViewWidget( - PlatformWebViewWidgetCreationParams(controller: controller), - ).build(context); - }, - )); - await tester.pumpAndSettle(); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + ), + ); + await tester.pumpAndSettle(); - await pageLoaded.future; + await pageLoaded.future; - // Makes sure we get the correct event that indicates the video is actually playing. - await videoPlaying.future; + // Makes sure we get the correct event that indicates the video is actually playing. + await videoPlaying.future; - final bool fullScreen = await controller - .runJavaScriptReturningResult('isFullScreen();') as bool; - expect(fullScreen, true); - }, - // allowsInlineMediaPlayback has no effect on macOS. - skip: Platform.isMacOS); + final bool fullScreen = + await controller.runJavaScriptReturningResult('isFullScreen();') + as bool; + expect(fullScreen, true); + }, + // allowsInlineMediaPlayback has no effect on macOS. + skip: Platform.isMacOS, + ); }); - group('Audio playback policy', () { - late String audioTestBase64; - setUpAll(() async { - final ByteData audioData = - await rootBundle.load('assets/sample_audio.ogg'); - final String base64AudioData = - base64Encode(Uint8List.view(audioData.buffer)); - final String audioTest = ''' + group( + 'Audio playback policy', + () { + late String audioTestBase64; + setUpAll(() async { + final ByteData audioData = await rootBundle.load( + 'assets/sample_audio.ogg', + ); + final String base64AudioData = base64Encode( + Uint8List.view(audioData.buffer), + ); + final String audioTest = ''' Audio auto play