Updated analysis_options line width from flutter/flutter (#11692)
It seems like we're supposed to keep analysis_options.dart in sync with the one in flutter/flutter, but we haven't done it since 2023. This PR updates it. The most disruptive change appears to be the increased page width.
I'm inspired to update this after working on https://github.com/flutter/packages/pull/11669, which imports flutter/flutter code that is formatted according to the latest rules. Better to update the rules than to format the new code back to the old rules.
*Update*: This only updates the line width. Other changes will follow.
diff --git a/analysis_options.yaml b/analysis_options.yaml
index 5a160d9..f61260f 100644
--- a/analysis_options.yaml
+++ b/analysis_options.yaml
@@ -22,6 +22,9 @@
- '**/*.g.dart'
- '**/*.mocks.dart' # Mockito @GenerateMocks
+formatter:
+ page_width: 100
+
linter:
rules:
# This list is derived from the list of all available lints located at
diff --git a/packages/animations/example/lib/container_transition.dart b/packages/animations/example/lib/container_transition.dart
index a1fae14..3838544 100644
--- a/packages/animations/example/lib/container_transition.dart
+++ b/packages/animations/example/lib/container_transition.dart
@@ -49,15 +49,12 @@
}
}
-class _OpenContainerTransformDemoState
- extends State<OpenContainerTransformDemo> {
+class _OpenContainerTransformDemoState extends State<OpenContainerTransformDemo> {
ContainerTransitionType _transitionType = ContainerTransitionType.fade;
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!')));
}
}
@@ -73,10 +70,7 @@
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
- Text(
- 'Fade mode',
- style: Theme.of(context).textTheme.bodySmall,
- ),
+ Text('Fade mode', style: Theme.of(context).textTheme.bodySmall),
const SizedBox(height: 12),
ToggleButtons(
borderRadius: BorderRadius.circular(2.0),
@@ -152,10 +146,7 @@
child: _OpenContainerWrapper(
transitionType: _transitionType,
closedBuilder: (BuildContext _, VoidCallback openContainer) {
- return _SmallerCard(
- openContainer: openContainer,
- subtitle: 'Secondary text',
- );
+ return _SmallerCard(openContainer: openContainer, subtitle: 'Secondary text');
},
onClosed: _showMarkedAsDoneSnackbar,
),
@@ -165,10 +156,7 @@
child: _OpenContainerWrapper(
transitionType: _transitionType,
closedBuilder: (BuildContext _, VoidCallback openContainer) {
- return _SmallerCard(
- openContainer: openContainer,
- subtitle: 'Secondary text',
- );
+ return _SmallerCard(openContainer: openContainer, subtitle: 'Secondary text');
},
onClosed: _showMarkedAsDoneSnackbar,
),
@@ -182,10 +170,7 @@
child: _OpenContainerWrapper(
transitionType: _transitionType,
closedBuilder: (BuildContext _, VoidCallback openContainer) {
- return _SmallerCard(
- openContainer: openContainer,
- subtitle: 'Secondary',
- );
+ return _SmallerCard(openContainer: openContainer, subtitle: 'Secondary');
},
onClosed: _showMarkedAsDoneSnackbar,
),
@@ -195,10 +180,7 @@
child: _OpenContainerWrapper(
transitionType: _transitionType,
closedBuilder: (BuildContext _, VoidCallback openContainer) {
- return _SmallerCard(
- openContainer: openContainer,
- subtitle: 'Secondary',
- );
+ return _SmallerCard(openContainer: openContainer, subtitle: 'Secondary');
},
onClosed: _showMarkedAsDoneSnackbar,
),
@@ -208,10 +190,7 @@
child: _OpenContainerWrapper(
transitionType: _transitionType,
closedBuilder: (BuildContext _, VoidCallback openContainer) {
- return _SmallerCard(
- openContainer: openContainer,
- subtitle: 'Secondary',
- );
+ return _SmallerCard(openContainer: openContainer, subtitle: 'Secondary');
},
onClosed: _showMarkedAsDoneSnackbar,
),
@@ -255,12 +234,7 @@
return SizedBox(
height: _fabDimension,
width: _fabDimension,
- child: Center(
- child: Icon(
- Icons.add,
- color: Theme.of(context).colorScheme.onSecondary,
- ),
- ),
+ child: Center(child: Icon(Icons.add, color: Theme.of(context).colorScheme.onSecondary)),
);
},
),
@@ -309,27 +283,16 @@
Expanded(
child: ColoredBox(
color: Colors.black38,
- child: Center(
- child: Image.asset('assets/placeholder_image.png', width: 100),
- ),
+ child: Center(child: Image.asset('assets/placeholder_image.png', width: 100)),
),
),
- const ListTile(
- title: Text('Title'),
- subtitle: Text('Secondary text'),
- ),
+ const ListTile(title: Text('Title'), subtitle: Text('Secondary text')),
Padding(
- padding: const EdgeInsets.only(
- left: 16.0,
- right: 16.0,
- bottom: 16.0,
- ),
+ padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 16.0),
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),
),
),
],
@@ -355,9 +318,7 @@
Container(
color: Colors.black38,
height: 150,
- child: Center(
- child: Image.asset('assets/placeholder_image.png', width: 80),
- ),
+ child: Center(child: Image.asset('assets/placeholder_image.png', width: 80)),
),
Expanded(
child: Padding(
@@ -397,9 +358,7 @@
color: Colors.black38,
height: height,
width: height,
- child: Center(
- child: Image.asset('assets/placeholder_image.png', width: 60),
- ),
+ child: Center(child: Image.asset('assets/placeholder_image.png', width: 60)),
),
Expanded(
child: Padding(
@@ -425,12 +384,7 @@
}
class _InkWellOverlay extends StatelessWidget {
- const _InkWellOverlay({
- this.openContainer,
- this.height,
- this.constraints,
- this.child,
- });
+ const _InkWellOverlay({this.openContainer, this.height, this.constraints, this.child});
final VoidCallback? openContainer;
final double? height;
@@ -461,11 +415,7 @@
},
closedElevation: 0.0,
closedShadows: const <BoxShadow>[
- BoxShadow(
- color: Colors.blue,
- blurRadius: 15.0,
- offset: Offset(0.0, 5.0),
- ),
+ BoxShadow(color: Colors.blue, blurRadius: 15.0, offset: Offset(0.0, 5.0)),
],
openShadows: const <BoxShadow>[
BoxShadow(
@@ -528,10 +478,9 @@
children: <Widget>[
Text(
'Title',
- style: Theme.of(context).textTheme.headlineSmall!.copyWith(
- color: Colors.black54,
- fontSize: 30.0,
- ),
+ style: Theme.of(
+ context,
+ ).textTheme.headlineSmall!.copyWith(color: Colors.black54, fontSize: 30.0),
),
const SizedBox(height: 10),
Text(
diff --git a/packages/animations/example/lib/fade_scale_transition.dart b/packages/animations/example/lib/fade_scale_transition.dart
index 176363a..494bf2a 100644
--- a/packages/animations/example/lib/fade_scale_transition.dart
+++ b/packages/animations/example/lib/fade_scale_transition.dart
@@ -11,8 +11,7 @@
const FadeScaleTransitionDemo({super.key});
@override
- State<FadeScaleTransitionDemo> createState() =>
- _FadeScaleTransitionDemoState();
+ State<FadeScaleTransitionDemo> createState() => _FadeScaleTransitionDemoState();
}
class _FadeScaleTransitionDemoState extends State<FadeScaleTransitionDemo>
@@ -65,10 +64,7 @@
},
child: Visibility(
visible: _controller.status != AnimationStatus.dismissed,
- child: FloatingActionButton(
- child: const Icon(Icons.add),
- onPressed: () {},
- ),
+ child: FloatingActionButton(child: const Icon(Icons.add), onPressed: () {}),
),
),
bottomNavigationBar: Column(
diff --git a/packages/animations/example/lib/fade_through_transition.dart b/packages/animations/example/lib/fade_through_transition.dart
index 249c943..1cb03d6 100644
--- a/packages/animations/example/lib/fade_through_transition.dart
+++ b/packages/animations/example/lib/fade_through_transition.dart
@@ -11,8 +11,7 @@
const FadeThroughTransitionDemo({super.key});
@override
- State<FadeThroughTransitionDemo> createState() =>
- _FadeThroughTransitionDemoState();
+ State<FadeThroughTransitionDemo> createState() => _FadeThroughTransitionDemoState();
}
class _FadeThroughTransitionDemoState extends State<FadeThroughTransitionDemo> {
@@ -26,11 +25,7 @@
appBar: AppBar(title: const Text('Fade through')),
body: PageTransitionSwitcher(
transitionBuilder:
- (
- Widget child,
- Animation<double> animation,
- Animation<double> secondaryAnimation,
- ) {
+ (Widget child, Animation<double> animation, Animation<double> secondaryAnimation) {
return FadeThroughTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
@@ -47,10 +42,7 @@
});
},
items: const <BottomNavigationBarItem>[
- BottomNavigationBarItem(
- icon: Icon(Icons.photo_library),
- label: 'Albums',
- ),
+ BottomNavigationBarItem(icon: Icon(Icons.photo_library), label: 'Albums'),
BottomNavigationBarItem(icon: Icon(Icons.photo), label: 'Photos'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
],
@@ -74,9 +66,7 @@
color: Colors.black26,
child: Padding(
padding: const EdgeInsets.all(30.0),
- child: Ink.image(
- image: const AssetImage('assets/placeholder_image.png'),
- ),
+ child: Ink.image(image: const AssetImage('assets/placeholder_image.png')),
),
),
),
@@ -85,14 +75,8 @@
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
- Text(
- '123 photos',
- style: Theme.of(context).textTheme.bodyLarge,
- ),
- Text(
- '123 photos',
- style: Theme.of(context).textTheme.bodySmall,
- ),
+ Text('123 photos', style: Theme.of(context).textTheme.bodyLarge),
+ Text('123 photos', style: Theme.of(context).textTheme.bodySmall),
],
),
),
diff --git a/packages/animations/example/lib/main.dart b/packages/animations/example/lib/main.dart
index e06b7c9..66e8306 100644
--- a/packages/animations/example/lib/main.dart
+++ b/packages/animations/example/lib/main.dart
@@ -122,11 +122,7 @@
}
class _TransitionListTile extends StatelessWidget {
- const _TransitionListTile({
- this.onTap,
- required this.title,
- required this.subtitle,
- });
+ const _TransitionListTile({this.onTap, required this.title, required this.subtitle});
final GestureTapCallback? onTap;
final String title;
diff --git a/packages/animations/example/lib/shared_axis_transition.dart b/packages/animations/example/lib/shared_axis_transition.dart
index 4806644..c12548b 100644
--- a/packages/animations/example/lib/shared_axis_transition.dart
+++ b/packages/animations/example/lib/shared_axis_transition.dart
@@ -17,8 +17,7 @@
}
class _SharedAxisTransitionDemoState extends State<SharedAxisTransitionDemo> {
- SharedAxisTransitionType? _transitionType =
- SharedAxisTransitionType.horizontal;
+ SharedAxisTransitionType? _transitionType = SharedAxisTransitionType.horizontal;
bool _isLoggedIn = false;
void _updateTransitionType(SharedAxisTransitionType? newType) {
@@ -85,17 +84,11 @@
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- Radio<SharedAxisTransitionType>(
- value: SharedAxisTransitionType.horizontal,
- ),
+ Radio<SharedAxisTransitionType>(value: SharedAxisTransitionType.horizontal),
Text('X'),
- Radio<SharedAxisTransitionType>(
- value: SharedAxisTransitionType.vertical,
- ),
+ Radio<SharedAxisTransitionType>(value: SharedAxisTransitionType.vertical),
Text('Y'),
- Radio<SharedAxisTransitionType>(
- value: SharedAxisTransitionType.scaled,
- ),
+ Radio<SharedAxisTransitionType>(value: SharedAxisTransitionType.scaled),
Text('Z'),
],
),
@@ -177,10 +170,7 @@
Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 20)),
Image.asset('assets/avatar_logo.png', width: 80),
Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 50)),
- Text(
- 'Hi David Park',
- style: Theme.of(context).textTheme.headlineSmall,
- ),
+ Text('Hi David Park', style: Theme.of(context).textTheme.headlineSmall),
Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 50)),
const Text(
'Sign in with your account',
@@ -190,19 +180,10 @@
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Padding(
- padding: EdgeInsets.only(
- top: 40.0,
- left: 15.0,
- right: 15.0,
- bottom: 10.0,
- ),
+ padding: EdgeInsets.only(top: 40.0, left: 15.0, right: 15.0, bottom: 10.0),
child: TextField(
decoration: InputDecoration(
- suffixIcon: Icon(
- Icons.visibility,
- size: 20,
- color: Colors.black54,
- ),
+ suffixIcon: Icon(Icons.visibility, size: 20, color: Colors.black54),
isDense: true,
labelText: 'Email or phone number',
border: OutlineInputBorder(),
@@ -211,17 +192,11 @@
),
Padding(
padding: const EdgeInsets.only(left: 10.0),
- child: TextButton(
- onPressed: () {},
- child: const Text('FORGOT EMAIL?'),
- ),
+ child: TextButton(onPressed: () {}, child: const Text('FORGOT EMAIL?')),
),
Padding(
padding: const EdgeInsets.only(left: 10.0),
- child: TextButton(
- onPressed: () {},
- child: const Text('CREATE ACCOUNT'),
- ),
+ child: TextButton(onPressed: () {}, child: const Text('CREATE ACCOUNT')),
),
],
),
diff --git a/packages/animations/lib/src/fade_scale_transition.dart b/packages/animations/lib/src/fade_scale_transition.dart
index 9c525ea..4ccb66f 100644
--- a/packages/animations/lib/src/fade_scale_transition.dart
+++ b/packages/animations/lib/src/fade_scale_transition.dart
@@ -121,39 +121,26 @@
/// [secondaryAnimation].
final Widget? child;
- static final Animatable<double> _fadeInTransition = CurveTween(
- curve: const Interval(0.0, 0.3),
- );
+ static final Animatable<double> _fadeInTransition = CurveTween(curve: const Interval(0.0, 0.3));
static final Animatable<double> _scaleInTransition = Tween<double>(
begin: 0.80,
end: 1.00,
).chain(CurveTween(curve: Easing.legacyDecelerate));
- static final Animatable<double> _fadeOutTransition = Tween<double>(
- begin: 1.0,
- end: 0.0,
- );
+ static final Animatable<double> _fadeOutTransition = Tween<double>(begin: 1.0, end: 0.0);
@override
Widget build(BuildContext context) {
return DualTransitionBuilder(
animation: animation,
- forwardBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return FadeTransition(
- opacity: _fadeInTransition.animate(animation),
- child: ScaleTransition(
- scale: _scaleInTransition.animate(animation),
- child: child,
- ),
- );
- },
- reverseBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return FadeTransition(
- opacity: _fadeOutTransition.animate(animation),
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return FadeTransition(
+ opacity: _fadeInTransition.animate(animation),
+ child: ScaleTransition(scale: _scaleInTransition.animate(animation), child: child),
+ );
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return FadeTransition(opacity: _fadeOutTransition.animate(animation), child: child);
+ },
child: child,
);
}
diff --git a/packages/animations/lib/src/fade_through_transition.dart b/packages/animations/lib/src/fade_through_transition.dart
index 61a8cb5..e308bda 100644
--- a/packages/animations/lib/src/fade_through_transition.dart
+++ b/packages/animations/lib/src/fade_through_transition.dart
@@ -203,10 +203,7 @@
animation: animation,
child: ColoredBox(
color: fillColor ?? Theme.of(context).canvasColor,
- child: _ZoomedFadeInFadeOut(
- animation: ReverseAnimation(secondaryAnimation),
- child: child,
- ),
+ child: _ZoomedFadeInFadeOut(animation: ReverseAnimation(secondaryAnimation), child: child),
),
);
}
@@ -222,14 +219,12 @@
Widget build(BuildContext context) {
return DualTransitionBuilder(
animation: animation,
- forwardBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return _ZoomedFadeIn(animation: animation, child: child);
- },
- reverseBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return _FadeOut(animation: animation, child: child);
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return _ZoomedFadeIn(animation: animation, child: child);
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return _FadeOut(animation: animation, child: child);
+ },
child: child,
);
}
@@ -241,26 +236,17 @@
final Widget? child;
final Animation<double> animation;
- static final CurveTween _inCurve = CurveTween(
- curve: const Cubic(0.0, 0.0, 0.2, 1.0),
- );
- static final TweenSequence<double> _scaleIn =
- TweenSequence<double>(<TweenSequenceItem<double>>[
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(0.92),
- weight: 6 / 20,
- ),
- TweenSequenceItem<double>(
- tween: Tween<double>(begin: 0.92, end: 1.0).chain(_inCurve),
- weight: 14 / 20,
- ),
- ]);
+ static final CurveTween _inCurve = CurveTween(curve: const Cubic(0.0, 0.0, 0.2, 1.0));
+ static final TweenSequence<double> _scaleIn = TweenSequence<double>(<TweenSequenceItem<double>>[
+ TweenSequenceItem<double>(tween: ConstantTween<double>(0.92), weight: 6 / 20),
+ TweenSequenceItem<double>(
+ tween: Tween<double>(begin: 0.92, end: 1.0).chain(_inCurve),
+ weight: 14 / 20,
+ ),
+ ]);
static final TweenSequence<double> _fadeInOpacity =
TweenSequence<double>(<TweenSequenceItem<double>>[
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(0.0),
- weight: 6 / 20,
- ),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(0.0), weight: 6 / 20),
TweenSequenceItem<double>(
tween: Tween<double>(begin: 0.0, end: 1.0).chain(_inCurve),
weight: 14 / 20,
@@ -282,26 +268,18 @@
final Widget? child;
final Animation<double> animation;
- static final CurveTween _outCurve = CurveTween(
- curve: const Cubic(0.4, 0.0, 1.0, 1.0),
- );
+ static final CurveTween _outCurve = CurveTween(curve: const Cubic(0.4, 0.0, 1.0, 1.0));
static final TweenSequence<double> _fadeOutOpacity =
TweenSequence<double>(<TweenSequenceItem<double>>[
TweenSequenceItem<double>(
tween: Tween<double>(begin: 1.0, end: 0.0).chain(_outCurve),
weight: 6 / 20,
),
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(0.0),
- weight: 14 / 20,
- ),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(0.0), weight: 14 / 20),
]);
@override
Widget build(BuildContext context) {
- return FadeTransition(
- opacity: _fadeOutOpacity.animate(animation),
- child: child,
- );
+ return FadeTransition(opacity: _fadeOutOpacity.animate(animation), child: child);
}
}
diff --git a/packages/animations/lib/src/open_container.dart b/packages/animations/lib/src/open_container.dart
index a9d90f7..0eb6267 100644
--- a/packages/animations/lib/src/open_container.dart
+++ b/packages/animations/lib/src/open_container.dart
@@ -17,18 +17,14 @@
/// The `action` callback provided to [OpenContainer.openBuilder] can be used
/// to close the container.
typedef OpenContainerBuilder<S> =
- Widget Function(
- BuildContext context,
- CloseContainerActionCallback<S> action,
- );
+ Widget Function(BuildContext context, CloseContainerActionCallback<S> 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.
///
@@ -338,33 +334,28 @@
/// Open the container using the given middle color and specific route,
/// then call `onClosed` with the returned data after popped.
Future<void> openContainer() async {
- final Color middleColor =
- widget.middleColor ?? Theme.of(context).canvasColor;
- final T? data =
- await Navigator.of(
- context,
- rootNavigator: widget.useRootNavigator,
- ).push(
- _OpenContainerRoute<T>(
- 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,
- closedShadows: widget.closedShadows,
- openShadows: widget.openShadows,
- ),
- );
+ final Color middleColor = widget.middleColor ?? Theme.of(context).canvasColor;
+ final T? data = await Navigator.of(context, rootNavigator: widget.useRootNavigator).push(
+ _OpenContainerRoute<T>(
+ 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,
+ closedShadows: widget.closedShadows,
+ openShadows: widget.openShadows,
+ ),
+ );
if (widget.onClosed != null) {
widget.onClosed!(data);
}
@@ -515,18 +506,12 @@
switch (transitionType) {
case ContainerTransitionType.fade:
return _FlippableTweenSequence<Color?>(<TweenSequenceItem<Color?>>[
- TweenSequenceItem<Color>(
- tween: ConstantTween<Color>(closedColor),
- weight: 1 / 5,
- ),
+ TweenSequenceItem<Color>(tween: ConstantTween<Color>(closedColor), weight: 1 / 5),
TweenSequenceItem<Color?>(
tween: ColorTween(begin: closedColor, end: openColor),
weight: 1 / 5,
),
- TweenSequenceItem<Color>(
- tween: ConstantTween<Color>(openColor),
- weight: 3 / 5,
- ),
+ TweenSequenceItem<Color>(tween: ConstantTween<Color>(openColor), weight: 3 / 5),
]);
case ContainerTransitionType.fadeThrough:
return _FlippableTweenSequence<Color?>(<TweenSequenceItem<Color?>>[
@@ -548,21 +533,12 @@
switch (transitionType) {
case ContainerTransitionType.fade:
return _FlippableTweenSequence<double>(<TweenSequenceItem<double>>[
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(1.0),
- weight: 1,
- ),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(1.0), weight: 1),
]);
case ContainerTransitionType.fadeThrough:
return _FlippableTweenSequence<double>(<TweenSequenceItem<double>>[
- TweenSequenceItem<double>(
- tween: Tween<double>(begin: 1.0, end: 0.0),
- weight: 1 / 5,
- ),
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(0.0),
- weight: 4 / 5,
- ),
+ TweenSequenceItem<double>(tween: Tween<double>(begin: 1.0, end: 0.0), weight: 1 / 5),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(0.0), weight: 4 / 5),
]);
}
}
@@ -573,29 +549,14 @@
switch (transitionType) {
case ContainerTransitionType.fade:
return _FlippableTweenSequence<double>(<TweenSequenceItem<double>>[
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(0.0),
- weight: 1 / 5,
- ),
- TweenSequenceItem<double>(
- tween: Tween<double>(begin: 0.0, end: 1.0),
- weight: 1 / 5,
- ),
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(1.0),
- weight: 3 / 5,
- ),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(0.0), weight: 1 / 5),
+ TweenSequenceItem<double>(tween: Tween<double>(begin: 0.0, end: 1.0), weight: 1 / 5),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(1.0), weight: 3 / 5),
]);
case ContainerTransitionType.fadeThrough:
return _FlippableTweenSequence<double>(<TweenSequenceItem<double>>[
- TweenSequenceItem<double>(
- tween: ConstantTween<double>(0.0),
- weight: 1 / 5,
- ),
- TweenSequenceItem<double>(
- tween: Tween<double>(begin: 0.0, end: 1.0),
- weight: 4 / 5,
- ),
+ TweenSequenceItem<double>(tween: ConstantTween<double>(0.0), weight: 1 / 5),
+ TweenSequenceItem<double>(tween: Tween<double>(begin: 0.0, end: 1.0), weight: 4 / 5),
]);
}
}
@@ -635,10 +596,7 @@
tween: ColorTween(begin: Colors.transparent, end: Colors.black54),
weight: 1 / 5,
),
- TweenSequenceItem<Color>(
- tween: ConstantTween<Color>(Colors.black54),
- weight: 4 / 5,
- ),
+ TweenSequenceItem<Color>(tween: ConstantTween<Color>(Colors.black54), weight: 4 / 5),
]);
static final Tween<Color?> _scrimFadeOutTween = ColorTween(
begin: Colors.transparent,
@@ -691,10 +649,7 @@
@override
bool didPop(T? result) {
- _takeMeasurements(
- navigatorContext: subtreeContext!,
- delayForSourceRoute: true,
- );
+ _takeMeasurements(navigatorContext: subtreeContext!, delayForSourceRoute: true);
return super.didPop(result);
}
@@ -703,9 +658,7 @@
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();
}
@@ -723,10 +676,7 @@
bool delayForSourceRoute = false,
}) {
final navigator =
- Navigator.of(
- navigatorContext,
- rootNavigator: useRootNavigator,
- ).context.findRenderObject()!
+ Navigator.of(navigatorContext, rootNavigator: useRootNavigator).context.findRenderObject()!
as RenderBox;
final Size navSize = _getSize(navigator);
_rectTween.end = Offset.zero & navSize;
@@ -740,9 +690,7 @@
}
if (delayForSourceRoute) {
- SchedulerBinding.instance.addPostFrameCallback(
- takeMeasurementsInSourceRoute,
- );
+ SchedulerBinding.instance.addPostFrameCallback(takeMeasurementsInSourceRoute);
} else {
takeMeasurementsInSourceRoute();
}
@@ -760,10 +708,7 @@
assert(ancestor.hasSize);
final render = key.currentContext!.findRenderObject()! as RenderBox;
assert(render.hasSize);
- return MatrixUtils.transformRect(
- render.getTransformTo(ancestor),
- Offset.zero & render.size,
- );
+ return MatrixUtils.transformRect(render.getTransformTo(ancestor), Offset.zero & render.size);
}
bool get _transitionWasInterrupted {
@@ -825,10 +770,7 @@
child: openShadows == null
? material
: DecoratedBox(
- decoration: ShapeDecoration(
- shape: openShape,
- shadows: openShadows,
- ),
+ decoration: ShapeDecoration(shape: openShape, shadows: openShadows),
child: material,
),
);
@@ -837,9 +779,7 @@
final Animation<double> curvedAnimation = CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
- reverseCurve: _transitionWasInterrupted
- ? null
- : Curves.fastOutSlowIn.flipped,
+ reverseCurve: _transitionWasInterrupted ? null : Curves.fastOutSlowIn.flipped,
);
TweenSequence<Color?>? colorTween;
TweenSequence<double>? closedOpacityTween, openOpacityTween;
@@ -926,9 +866,7 @@
),
);
- final List<BoxShadow>? currentShadows = _shadowsTween.evaluate(
- curvedAnimation,
- );
+ final List<BoxShadow>? currentShadows = _shadowsTween.evaluate(curvedAnimation);
return SizedBox.expand(
child: Container(
diff --git a/packages/animations/lib/src/page_transition_switcher.dart b/packages/animations/lib/src/page_transition_switcher.dart
index 53d4f74..d56d3b3 100644
--- a/packages/animations/lib/src/page_transition_switcher.dart
+++ b/packages/animations/lib/src/page_transition_switcher.dart
@@ -56,8 +56,7 @@
/// 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<Widget> entries);
+typedef PageTransitionSwitcherLayoutBuilder = Widget Function(List<Widget> entries);
/// Signature for builders used to generate custom transitions for
/// [PageTransitionSwitcher].
@@ -296,8 +295,7 @@
final hasNewChild = widget.child != null;
final hasOldChild = _currentEntry != null;
if (hasNewChild != hasOldChild ||
- hasNewChild &&
- !Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)) {
+ hasNewChild && !Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)) {
// Child has changed, fade current entry out and add new entry.
_childNumber += 1;
_addEntryForNewChild(shouldAnimate: true);
@@ -327,14 +325,8 @@
if (widget.child == null) {
return;
}
- final primaryController = AnimationController(
- duration: widget.duration,
- vsync: this,
- );
- final secondaryController = AnimationController(
- duration: widget.duration,
- vsync: this,
- );
+ final primaryController = AnimationController(duration: widget.duration, vsync: this);
+ final secondaryController = AnimationController(duration: widget.duration, vsync: this);
if (shouldAnimate) {
if (widget.reverse) {
primaryController.value = 1.0;
@@ -368,11 +360,7 @@
required AnimationController primaryController,
required AnimationController secondaryController,
}) {
- final Widget transition = builder(
- child,
- primaryController,
- secondaryController,
- );
+ final Widget transition = builder(child, primaryController, secondaryController);
final entry = _ChildEntry(
widgetChild: child,
transition: KeyedSubtree.wrap(transition, _childNumber),
@@ -408,10 +396,7 @@
entry.primaryController,
entry.secondaryController,
);
- entry.transition = KeyedSubtree(
- key: entry.transition.key,
- child: transition,
- );
+ entry.transition = KeyedSubtree(key: entry.transition.key, child: transition);
}
@override
@@ -425,9 +410,7 @@
@override
Widget build(BuildContext context) {
return widget.layoutBuilder(
- _activeEntries
- .map<Widget>((_ChildEntry entry) => entry.transition)
- .toList(),
+ _activeEntries.map<Widget>((_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 f361f79..617a28d 100644
--- a/packages/animations/lib/src/shared_axis_transition.dart
+++ b/packages/animations/lib/src/shared_axis_transition.dart
@@ -73,10 +73,7 @@
/// ```
class SharedAxisPageTransitionsBuilder extends PageTransitionsBuilder {
/// Construct a [SharedAxisPageTransitionsBuilder].
- const SharedAxisPageTransitionsBuilder({
- required this.transitionType,
- this.fillColor,
- });
+ const SharedAxisPageTransitionsBuilder({required this.transitionType, this.fillColor});
/// Determines which [SharedAxisTransitionType] to build.
final SharedAxisTransitionType transitionType;
@@ -233,44 +230,36 @@
final Color color = fillColor ?? Theme.of(context).canvasColor;
return DualTransitionBuilder(
animation: animation,
- forwardBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return _EnterTransition(
- animation: animation,
- transitionType: transitionType,
- child: child,
- );
- },
- reverseBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return _ExitTransition(
- animation: animation,
- transitionType: transitionType,
- reverse: true,
- fillColor: color,
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return _EnterTransition(animation: animation, transitionType: transitionType, child: child);
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return _ExitTransition(
+ animation: animation,
+ transitionType: transitionType,
+ reverse: true,
+ fillColor: color,
+ child: child,
+ );
+ },
child: DualTransitionBuilder(
animation: ReverseAnimation(secondaryAnimation),
- forwardBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return _EnterTransition(
- animation: animation,
- transitionType: transitionType,
- reverse: true,
- child: child,
- );
- },
- reverseBuilder:
- (BuildContext context, Animation<double> animation, Widget? child) {
- return _ExitTransition(
- animation: animation,
- transitionType: transitionType,
- fillColor: color,
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return _EnterTransition(
+ animation: animation,
+ transitionType: transitionType,
+ reverse: true,
+ child: child,
+ );
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return _ExitTransition(
+ animation: animation,
+ transitionType: transitionType,
+ fillColor: color,
+ child: child,
+ );
+ },
child: child,
),
);
@@ -349,8 +338,7 @@
return FadeTransition(
opacity: _fadeInTransition.animate(animation),
child: ScaleTransition(
- scale: (!reverse ? _scaleUpTransition : _scaleDownTransition)
- .animate(animation),
+ scale: (!reverse ? _scaleUpTransition : _scaleDownTransition).animate(animation),
child: child,
),
);
@@ -440,8 +428,7 @@
child: ColoredBox(
color: fillColor,
child: ScaleTransition(
- scale: (!reverse ? _scaleUpTransition : _scaleDownTransition)
- .animate(animation),
+ scale: (!reverse ? _scaleUpTransition : _scaleDownTransition).animate(animation),
child: child,
),
),
diff --git a/packages/animations/test/dual_transition_builder_test.dart b/packages/animations/test/dual_transition_builder_test.dart
index 7c7e25f..a0fa77f 100644
--- a/packages/animations/test/dual_transition_builder_test.dart
+++ b/packages/animations/test/dual_transition_builder_test.dart
@@ -16,28 +16,15 @@
Center(
child: DualTransitionBuilder(
animation: controller,
- forwardBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return ScaleTransition(scale: animation, child: child);
- },
- reverseBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return FadeTransition(
- opacity: Tween<double>(
- begin: 1.0,
- end: 0.0,
- ).animate(animation),
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return ScaleTransition(scale: animation, child: child);
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return FadeTransition(
+ opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
+ child: child,
+ );
+ },
child: Container(color: Colors.green, height: 100, width: 100),
),
),
@@ -86,36 +73,21 @@
child: Center(
child: DualTransitionBuilder(
animation: controller,
- forwardBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return ScaleTransition(scale: animation, child: child);
- },
- reverseBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return FadeTransition(
- opacity: Tween<double>(
- begin: 1.0,
- end: 0.0,
- ).animate(animation),
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return ScaleTransition(scale: animation, child: child);
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return FadeTransition(
+ opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
+ child: child,
+ );
+ },
child: const _StatefulTestWidget(name: 'Foo'),
),
),
),
);
- final State<StatefulWidget> state = tester.state(
- find.byType(_StatefulTestWidget),
- );
+ final State<StatefulWidget> state = tester.state(find.byType(_StatefulTestWidget));
expect(state, isNotNull);
controller.forward();
@@ -143,9 +115,7 @@
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 controller = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
@@ -154,28 +124,15 @@
Center(
child: DualTransitionBuilder(
animation: controller,
- forwardBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return ScaleTransition(scale: animation, child: child);
- },
- reverseBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return FadeTransition(
- opacity: Tween<double>(
- begin: 1.0,
- end: 0.0,
- ).animate(animation),
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return ScaleTransition(scale: animation, child: child);
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return FadeTransition(
+ opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
+ child: child,
+ );
+ },
child: Container(color: Colors.green, height: 100, width: 100),
),
),
@@ -209,9 +166,7 @@
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 controller = AnimationController(
value: 1.0,
vsync: const TestVSync(),
@@ -221,28 +176,15 @@
Center(
child: DualTransitionBuilder(
animation: controller,
- forwardBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return ScaleTransition(scale: animation, child: child);
- },
- reverseBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Widget? child,
- ) {
- return FadeTransition(
- opacity: Tween<double>(
- begin: 1.0,
- end: 0.0,
- ).animate(animation),
- child: child,
- );
- },
+ forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return ScaleTransition(scale: animation, child: child);
+ },
+ reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) {
+ return FadeTransition(
+ opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
+ child: child,
+ );
+ },
child: Container(color: Colors.green, height: 100, width: 100),
),
),
diff --git a/packages/animations/test/fade_scale_transition_test.dart b/packages/animations/test/fade_scale_transition_test.dart
index f5631c7..83e6b5b 100644
--- a/packages/animations/test/fade_scale_transition_test.dart
+++ b/packages/animations/test/fade_scale_transition_test.dart
@@ -8,9 +8,7 @@
import 'package:flutter_test/flutter_test.dart';
void main() {
- testWidgets('FadeScaleTransitionConfiguration builds a new route', (
- WidgetTester tester,
- ) async {
+ testWidgets('FadeScaleTransitionConfiguration builds a new route', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
@@ -39,9 +37,7 @@
expect(find.byType(_FlutterLogoModal), findsOneWidget);
});
- testWidgets('FadeScaleTransitionConfiguration runs forward', (
- WidgetTester tester,
- ) async {
+ testWidgets('FadeScaleTransitionConfiguration runs forward', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
@@ -107,9 +103,7 @@
expect(find.byType(_FlutterLogoModal), findsOneWidget);
});
- testWidgets('FadeScaleTransitionConfiguration runs forward', (
- WidgetTester tester,
- ) async {
+ testWidgets('FadeScaleTransitionConfiguration runs forward', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
@@ -172,107 +166,104 @@
expect(find.byType(_FlutterLogoModal), findsNothing);
});
- testWidgets(
- 'FadeScaleTransitionConfiguration does not jump when interrupted',
- (WidgetTester tester) async {
- final GlobalKey key = GlobalKey();
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: Builder(
- builder: (BuildContext context) {
- return Center(
- child: ElevatedButton(
- onPressed: () {
- showModal<void>(
- context: context,
- builder: (BuildContext context) {
- return _FlutterLogoModal(key: key);
- },
- );
- },
- 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)
- // End of opacity animation
- await tester.pump(const Duration(milliseconds: 45));
- 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));
- topFadeTransitionOpacity = _getOpacity(key, tester);
- expect(topFadeTransitionOpacity, 1.0);
- topScale = _getScale(key, tester);
- expect(topScale, greaterThan(0.80));
- expect(topScale, lessThan(1.0));
-
- // Start the reverse transition by interrupting the forwards
- // transition.
- await tester.tapAt(Offset.zero);
- await tester.pump();
- // Opacity and scale values should remain the same after
- // the reverse animation starts.
- expect(_getOpacity(key, tester), topFadeTransitionOpacity);
- expect(_getScale(key, tester), topScale);
-
- // Should animate in reverse with 2/3 * 75ms = 50ms
- // using the enter transition's animation pattern
- // instead of the exit animation pattern.
-
- // Calculation for the time when the linear fade
- // transition should start if running backwards:
- // 3/10 * 75ms = 22.5ms
- // To get the 22.5ms timestamp, run backwards for:
- // 50ms - 22.5ms = ~27.5ms
- await tester.pump(const Duration(milliseconds: 27));
- topFadeTransitionOpacity = _getOpacity(key, tester);
- expect(topFadeTransitionOpacity, 1.0);
- topScale = _getScale(key, tester);
- expect(topScale, greaterThan(0.80));
- expect(topScale, lessThan(1.0));
-
- // Halfway through fade animation
- await tester.pump(const Duration(milliseconds: 12));
- 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));
-
- // Complete the rest of the animation
- await tester.pump(const Duration(milliseconds: 11));
- topFadeTransitionOpacity = _getOpacity(key, tester);
- expect(topFadeTransitionOpacity, 0.0);
- topScale = _getScale(key, tester);
- expect(topScale, 0.8);
-
- await tester.pump(const Duration(milliseconds: 1));
- expect(find.byType(_FlutterLogoModal), findsNothing);
- },
- );
-
- testWidgets('State is not lost when transitioning', (
+ testWidgets('FadeScaleTransitionConfiguration does not jump when interrupted', (
WidgetTester tester,
) async {
+ final GlobalKey key = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (BuildContext context) {
+ return Center(
+ child: ElevatedButton(
+ onPressed: () {
+ showModal<void>(
+ context: context,
+ builder: (BuildContext context) {
+ return _FlutterLogoModal(key: key);
+ },
+ );
+ },
+ 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)
+ // End of opacity animation
+ await tester.pump(const Duration(milliseconds: 45));
+ 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));
+ topFadeTransitionOpacity = _getOpacity(key, tester);
+ expect(topFadeTransitionOpacity, 1.0);
+ topScale = _getScale(key, tester);
+ expect(topScale, greaterThan(0.80));
+ expect(topScale, lessThan(1.0));
+
+ // Start the reverse transition by interrupting the forwards
+ // transition.
+ await tester.tapAt(Offset.zero);
+ await tester.pump();
+ // Opacity and scale values should remain the same after
+ // the reverse animation starts.
+ expect(_getOpacity(key, tester), topFadeTransitionOpacity);
+ expect(_getScale(key, tester), topScale);
+
+ // Should animate in reverse with 2/3 * 75ms = 50ms
+ // using the enter transition's animation pattern
+ // instead of the exit animation pattern.
+
+ // Calculation for the time when the linear fade
+ // transition should start if running backwards:
+ // 3/10 * 75ms = 22.5ms
+ // To get the 22.5ms timestamp, run backwards for:
+ // 50ms - 22.5ms = ~27.5ms
+ await tester.pump(const Duration(milliseconds: 27));
+ topFadeTransitionOpacity = _getOpacity(key, tester);
+ expect(topFadeTransitionOpacity, 1.0);
+ topScale = _getScale(key, tester);
+ expect(topScale, greaterThan(0.80));
+ expect(topScale, lessThan(1.0));
+
+ // Halfway through fade animation
+ await tester.pump(const Duration(milliseconds: 12));
+ 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));
+
+ // Complete the rest of the animation
+ await tester.pump(const Duration(milliseconds: 11));
+ topFadeTransitionOpacity = _getOpacity(key, tester);
+ expect(topFadeTransitionOpacity, 0.0);
+ topScale = _getScale(key, tester);
+ expect(topScale, 0.8);
+
+ 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();
@@ -289,10 +280,7 @@
showModal<void>(
context: context,
builder: (BuildContext context) {
- return _FlutterLogoModal(
- key: topKey,
- name: 'top route',
- );
+ return _FlutterLogoModal(key: topKey, name: 'top route');
},
);
},
@@ -309,9 +297,7 @@
);
// The bottom route's state should already exist.
- final _FlutterLogoModalState bottomState = tester.state(
- find.byKey(bottomKey),
- );
+ final _FlutterLogoModalState bottomState = tester.state(find.byKey(bottomKey));
expect(bottomState.widget.name, 'bottom route');
// Start the enter transition of the modal route.
@@ -334,10 +320,7 @@
// 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(bottomKey, skipOffstage: false)), bottomState);
expect(tester.state(find.byKey(topKey)), topState);
// Start the reverse animation. Both top and bottom
@@ -370,18 +353,13 @@
MaterialApp(
home: Scaffold(
body: Center(
- child: FadeScaleTransition(
- animation: controller,
- child: const _FlutterLogoModal(),
- ),
+ child: FadeScaleTransition(animation: controller, child: const _FlutterLogoModal()),
),
),
),
);
- final State<StatefulWidget> state = tester.state(
- find.byType(_FlutterLogoModal),
- );
+ final State<StatefulWidget> state = tester.state(find.byType(_FlutterLogoModal));
expect(state, isNotNull);
controller.forward();
@@ -411,10 +389,7 @@
}
double _getOpacity(GlobalKey key, WidgetTester tester) {
- final Finder finder = find.ancestor(
- of: find.byKey(key),
- matching: find.byType(FadeTransition),
- );
+ final Finder finder = find.ancestor(of: find.byKey(key), matching: find.byType(FadeTransition));
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final transition = widget as FadeTransition;
return a * transition.opacity.value;
@@ -422,10 +397,7 @@
}
double _getScale(GlobalKey key, WidgetTester tester) {
- final Finder finder = find.ancestor(
- of: find.byKey(key),
- matching: find.byType(ScaleTransition),
- );
+ final Finder finder = find.ancestor(of: find.byKey(key), matching: find.byType(ScaleTransition));
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final transition = widget as ScaleTransition;
return a * transition.scale.value;
diff --git a/packages/animations/test/fade_through_transition_test.dart b/packages/animations/test/fade_through_transition_test.dart
index 10973d0..32d8d59 100644
--- a/packages/animations/test/fade_through_transition_test.dart
+++ b/packages/animations/test/fade_through_transition_test.dart
@@ -7,29 +7,26 @@
import 'package:flutter_test/flutter_test.dart';
void main() {
- testWidgets(
- 'FadeThroughPageTransitionsBuilder builds a FadeThroughTransition',
- (WidgetTester tester) async {
- final animation = AnimationController(vsync: const TestVSync());
- final secondaryAnimation = AnimationController(vsync: const TestVSync());
-
- await tester.pumpWidget(
- const FadeThroughPageTransitionsBuilder().buildTransitions<void>(
- null,
- null,
- animation,
- secondaryAnimation,
- const Placeholder(),
- ),
- );
-
- expect(find.byType(FadeThroughTransition), findsOneWidget);
- },
- );
-
- testWidgets('FadeThroughTransition runs forward', (
+ testWidgets('FadeThroughPageTransitionsBuilder builds a FadeThroughTransition', (
WidgetTester tester,
) async {
+ final animation = AnimationController(vsync: const TestVSync());
+ final secondaryAnimation = AnimationController(vsync: const TestVSync());
+
+ await tester.pumpWidget(
+ const FadeThroughPageTransitionsBuilder().buildTransitions<void>(
+ null,
+ null,
+ animation,
+ secondaryAnimation,
+ const Placeholder(),
+ ),
+ );
+
+ expect(find.byType(FadeThroughTransition), findsOneWidget);
+ });
+
+ testWidgets('FadeThroughTransition runs forward', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -109,9 +106,7 @@
expect(find.text(topRoute), findsOneWidget);
});
- testWidgets('FadeThroughTransition runs backwards', (
- WidgetTester tester,
- ) async {
+ testWidgets('FadeThroughTransition runs backwards', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -159,14 +154,8 @@
expect(_getOpacity(topRoute, tester), 0.0);
// Top route is still invisible.
expect(find.text(bottomRoute), findsOneWidget);
- expect(
- _getScale(bottomRoute, tester),
- moreOrLessEquals(0.92, epsilon: 0.005),
- );
- expect(
- _getOpacity(bottomRoute, tester),
- moreOrLessEquals(0.0, epsilon: 0.005),
- );
+ expect(_getScale(bottomRoute, tester), moreOrLessEquals(0.92, epsilon: 0.005));
+ expect(_getOpacity(bottomRoute, tester), moreOrLessEquals(0.0, epsilon: 0.005));
// Let's jump to the middle of the fade-in.
await tester.pump(const Duration(milliseconds: 105));
@@ -199,9 +188,7 @@
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 navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -264,9 +251,7 @@
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 navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -275,10 +260,7 @@
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
- return _StatefulTestWidget(
- key: ValueKey<String?>(settings.name),
- name: settings.name,
- );
+ return _StatefulTestWidget(key: ValueKey<String?>(settings.name), name: settings.name);
},
),
);
@@ -292,64 +274,35 @@
await tester.pump();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
expect(
- tester.state(
- find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false),
- ),
+ tester.state(find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false)),
bottomState,
);
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
navigator.currentState!.pop();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
});
@@ -374,9 +327,7 @@
),
),
);
- final State<StatefulWidget> state = tester.state(
- find.byType(_StatefulTestWidget),
- );
+ final State<StatefulWidget> state = tester.state(find.byType(_StatefulTestWidget));
expect(state, isNotNull);
animation.forward();
@@ -467,10 +418,7 @@
builder: (BuildContext context) {
return contentBuilder != null
? contentBuilder!(settings)
- : Center(
- key: ValueKey<String?>(settings.name),
- child: Text(settings.name!),
- );
+ : Center(key: ValueKey<String?>(settings.name), child: Text(settings.name!));
},
);
},
diff --git a/packages/animations/test/modal_test.dart b/packages/animations/test/modal_test.dart
index eb29631..87089f7 100644
--- a/packages/animations/test/modal_test.dart
+++ b/packages/animations/test/modal_test.dart
@@ -9,48 +9,47 @@
import 'package:flutter_test/flutter_test.dart';
void main() {
- testWidgets(
- 'showModal builds a new route with specified barrier properties',
- (WidgetTester tester) async {
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: Builder(
- builder: (BuildContext context) {
- return Center(
- child: ElevatedButton(
- onPressed: () {
- showModal<void>(
- context: context,
- configuration: _TestModalConfiguration(),
- builder: (BuildContext context) {
- return const _FlutterLogoModal();
- },
- );
- },
- child: const Icon(Icons.add),
- ),
- );
- },
- ),
+ testWidgets('showModal builds a new route with specified barrier properties', (
+ WidgetTester tester,
+ ) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (BuildContext context) {
+ return Center(
+ child: ElevatedButton(
+ onPressed: () {
+ showModal<void>(
+ context: context,
+ configuration: _TestModalConfiguration(),
+ builder: (BuildContext context) {
+ return const _FlutterLogoModal();
+ },
+ );
+ },
+ 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<ModalBarrier>(
- find.byType(ModalBarrier).at(1),
- );
+ // New route containing _FlutterLogoModal is present.
+ expect(find.byType(_FlutterLogoModal), findsOneWidget);
+ final ModalBarrier topModalBarrier = tester.widget<ModalBarrier>(
+ find.byType(ModalBarrier).at(1),
+ );
- // Verify new route's modal barrier properties are correct.
- expect(topModalBarrier.color, Colors.green);
- expect(topModalBarrier.barrierSemanticsDismissible, true);
- expect(topModalBarrier.semanticsLabel, 'customLabel');
- },
- );
+ // Verify new route's modal barrier properties are correct.
+ expect(topModalBarrier.color, Colors.green);
+ expect(topModalBarrier.barrierSemanticsDismissible, true);
+ expect(topModalBarrier.semanticsLabel, 'customLabel');
+ });
testWidgets('showModal forwards animation', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
@@ -155,9 +154,7 @@
});
testWidgets('showModal builds a new route with specified barrier properties '
- 'with default configuration(FadeScaleTransitionConfiguration)', (
- WidgetTester tester,
- ) async {
+ 'with default configuration(FadeScaleTransitionConfiguration)', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
@@ -197,9 +194,7 @@
});
testWidgets('showModal forwards animation '
- 'with default configuration(FadeScaleTransitionConfiguration)', (
- WidgetTester tester,
- ) async {
+ 'with default configuration(FadeScaleTransitionConfiguration)', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
@@ -269,9 +264,7 @@
});
testWidgets('showModal reverse animation '
- 'with default configuration(FadeScaleTransitionConfiguration)', (
- WidgetTester tester,
- ) async {
+ 'with default configuration(FadeScaleTransitionConfiguration)', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
@@ -336,9 +329,7 @@
expect(find.byType(_FlutterLogoModal), findsNothing);
});
- testWidgets('State is not lost when transitioning', (
- WidgetTester tester,
- ) async {
+ testWidgets('State is not lost when transitioning', (WidgetTester tester) async {
final GlobalKey bottomKey = GlobalKey();
final GlobalKey topKey = GlobalKey();
@@ -356,10 +347,7 @@
context: context,
configuration: _TestModalConfiguration(),
builder: (BuildContext context) {
- return _FlutterLogoModal(
- key: topKey,
- name: 'top route',
- );
+ return _FlutterLogoModal(key: topKey, name: 'top route');
},
);
},
@@ -376,9 +364,7 @@
);
// The bottom route's state should already exist.
- final _FlutterLogoModalState bottomState = tester.state(
- find.byKey(bottomKey),
- );
+ final _FlutterLogoModalState bottomState = tester.state(find.byKey(bottomKey));
expect(bottomState.widget.name, 'bottom route');
// Start the enter transition of the modal route.
@@ -401,10 +387,7 @@
// 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(bottomKey, skipOffstage: false)), bottomState);
expect(tester.state(find.byKey(topKey)), topState);
// Start the reverse animation. Both top and bottom
@@ -430,10 +413,7 @@
testWidgets('showModal builds a new route with specified route settings', (
WidgetTester tester,
) async {
- const routeSettings = RouteSettings(
- name: 'route-name',
- arguments: 'arguments',
- );
+ const routeSettings = RouteSettings(name: 'route-name', arguments: 'arguments');
final Widget button = Builder(
builder: (BuildContext context) {
@@ -513,10 +493,7 @@
Widget _boilerplate(Widget child) => MaterialApp(home: Scaffold(body: child));
double _getOpacity(GlobalKey key, WidgetTester tester) {
- final Finder finder = find.ancestor(
- of: find.byKey(key),
- matching: find.byType(FadeTransition),
- );
+ final Finder finder = find.ancestor(of: find.byKey(key), matching: find.byType(FadeTransition));
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final transition = widget as FadeTransition;
return a * transition.opacity.value;
@@ -524,10 +501,7 @@
}
double _getScale(GlobalKey key, WidgetTester tester) {
- final Finder finder = find.ancestor(
- of: find.byKey(key),
- matching: find.byType(ScaleTransition),
- );
+ final Finder finder = find.ancestor(of: find.byKey(key), matching: find.byType(ScaleTransition));
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final transition = widget as ScaleTransition;
return a * transition.scale.value;
diff --git a/packages/animations/test/open_container_test.dart b/packages/animations/test/open_container_test.dart
index 5141388..7f5d64f 100644
--- a/packages/animations/test/open_container_test.dart
+++ b/packages/animations/test/open_container_test.dart
@@ -36,9 +36,7 @@
expect(find.text('Open'), findsOneWidget);
});
- testWidgets('Container opens - Fade (by default)', (
- WidgetTester tester,
- ) async {
+ testWidgets('Container opens - Fade (by default)', (WidgetTester tester) async {
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
);
@@ -112,9 +110,7 @@
await tester.pump(const Duration(milliseconds: 60)); // 300ms * 1/5 = 60ms
final dataPreFade = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataClosed,
@@ -128,9 +124,7 @@
await tester.pump(const Duration(milliseconds: 30)); // 300ms * 3/10 = 90ms
final dataMidFadeIn = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataPreFade,
@@ -147,9 +141,7 @@
final dataPostFadeIn = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidFadeIn,
@@ -163,9 +155,7 @@
await tester.pump(const Duration(milliseconds: 180));
final dataTransitionDone = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidFadeIn,
@@ -186,9 +176,7 @@
);
final dataOpen = _TrackedData(
finalMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == finalMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == finalMaterialElement)),
);
expect(dataOpen.material.color, dataTransitionDone.material.color);
expect(dataOpen.material.elevation, dataTransitionDone.material.elevation);
@@ -196,9 +184,7 @@
expect(dataOpen.rect, dataTransitionDone.rect);
});
- testWidgets('Container closes - Fade (by default)', (
- WidgetTester tester,
- ) async {
+ testWidgets('Container closes - Fade (by default)', (WidgetTester tester) async {
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
);
@@ -234,9 +220,7 @@
);
final dataOpen = _TrackedData(
initialMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == initialMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == initialMaterialElement)),
);
expect(dataOpen.material.color, Colors.blue);
expect(dataOpen.material.elevation, 8.0);
@@ -255,9 +239,7 @@
);
final dataTransitionStart = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
expect(dataTransitionStart.material.color, dataOpen.material.color);
expect(dataTransitionStart.material.elevation, dataOpen.material.elevation);
@@ -269,9 +251,7 @@
await tester.pump(const Duration(milliseconds: 60)); // 300 * 1/5 = 60
final dataPreFadeOut = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataPreFadeOut,
@@ -285,9 +265,7 @@
await tester.pump(const Duration(milliseconds: 30)); // 300 * 3/10 = 90
final dataMidpoint = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidpoint,
@@ -303,9 +281,7 @@
await tester.pump(const Duration(milliseconds: 30)); // 300 * 2/5 = 120
final dataPostFadeOut = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataPostFadeOut,
@@ -319,9 +295,7 @@
await tester.pump(const Duration(milliseconds: 180));
final dataTransitionDone = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataTransitionDone,
@@ -342,26 +316,17 @@
);
final dataClosed = _TrackedData(
finalMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == finalMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == finalMaterialElement)),
);
expect(dataClosed.material.color, dataTransitionDone.material.color);
- expect(
- dataClosed.material.elevation,
- dataTransitionDone.material.elevation,
- );
+ expect(dataClosed.material.elevation, dataTransitionDone.material.elevation);
expect(dataClosed.radius, dataTransitionDone.radius);
expect(dataClosed.rect, dataTransitionDone.rect);
});
testWidgets('Custom shadows work', (WidgetTester tester) async {
- const closedShadows = <BoxShadow>[
- BoxShadow(color: Colors.blue, blurRadius: 10.0),
- ];
- const openShadows = <BoxShadow>[
- BoxShadow(color: Colors.red, blurRadius: 20.0),
- ];
+ const closedShadows = <BoxShadow>[BoxShadow(color: Colors.blue, blurRadius: 10.0)];
+ const openShadows = <BoxShadow>[BoxShadow(color: Colors.red, blurRadius: 20.0)];
await tester.pumpWidget(
_boilerplate(
@@ -394,9 +359,7 @@
matching: find.byType(DecoratedBox),
),
);
- final decoration =
- (decoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ final decoration = (decoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
expect(decoration.shadows, closedShadows);
// Open the container.
@@ -407,21 +370,17 @@
final Element transitioningMaterialElement = tester.firstElement(
find.ancestor(of: find.text('Closed'), matching: find.byType(Material)),
);
- final transitioningMaterial =
- transitioningMaterialElement.widget as Material;
+ final transitioningMaterial = transitioningMaterialElement.widget as Material;
expect(transitioningMaterial.elevation, 0.0);
final Element transitioningDecoratedBoxElement = tester.firstElement(
find.ancestor(
- of: find.byElementPredicate(
- (Element e) => e == transitioningMaterialElement,
- ),
+ of: find.byElementPredicate((Element e) => e == transitioningMaterialElement),
matching: find.byType(DecoratedBox),
),
);
final transitioningDecoration =
- (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
// Verify shadows are lerping.
final double expectedT = Curves.fastOutSlowIn.transform(0.5);
@@ -429,10 +388,7 @@
transitioningDecoration.shadows![0].color,
Color.lerp(Colors.blue, Colors.red, expectedT),
);
- expect(
- transitioningDecoration.shadows![0].blurRadius,
- 10.0 + (20.0 - 10.0) * expectedT,
- );
+ expect(transitioningDecoration.shadows![0].blurRadius, 10.0 + (20.0 - 10.0) * expectedT);
await tester.pumpAndSettle();
@@ -450,17 +406,12 @@
),
);
final openDecoration =
- (openDecoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ (openDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
expect(openDecoration.shadows, openShadows);
});
- testWidgets('Closed elevation transitions into open custom shadows', (
- WidgetTester tester,
- ) async {
- const openShadows = <BoxShadow>[
- BoxShadow(color: Colors.red, blurRadius: 20.0),
- ];
+ testWidgets('Closed elevation transitions into open custom shadows', (WidgetTester tester) async {
+ const openShadows = <BoxShadow>[BoxShadow(color: Colors.red, blurRadius: 20.0)];
await tester.pumpWidget(
_boilerplate(
@@ -499,38 +450,24 @@
final Element transitioningMaterialElement = tester.firstElement(
find.ancestor(of: find.text('Closed'), matching: find.byType(Material)),
);
- final transitioningMaterial =
- transitioningMaterialElement.widget as Material;
+ final transitioningMaterial = transitioningMaterialElement.widget as Material;
expect(transitioningMaterial.elevation, lessThan(4.0));
expect(transitioningMaterial.elevation, greaterThan(0.0));
final Element transitioningDecoratedBoxElement = tester.firstElement(
find.ancestor(
- of: find.byElementPredicate(
- (Element e) => e == transitioningMaterialElement,
- ),
+ of: find.byElementPredicate((Element e) => e == transitioningMaterialElement),
matching: find.byType(DecoratedBox),
),
);
final transitioningDecoration =
- (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
final double expectedT = Curves.fastOutSlowIn.transform(0.5);
- final BoxShadow expectedShadow = BoxShadow.lerpList(
- null,
- openShadows,
- expectedT,
- )!.single;
+ final BoxShadow expectedShadow = BoxShadow.lerpList(null, openShadows, expectedT)!.single;
expect(transitioningDecoration.shadows, hasLength(1));
expect(transitioningDecoration.shadows![0].color, expectedShadow.color);
- expect(
- transitioningDecoration.shadows![0].blurRadius,
- expectedShadow.blurRadius,
- );
- expect(
- transitioningDecoration.shadows![0].spreadRadius,
- expectedShadow.spreadRadius,
- );
+ expect(transitioningDecoration.shadows![0].blurRadius, expectedShadow.blurRadius);
+ expect(transitioningDecoration.shadows![0].spreadRadius, expectedShadow.spreadRadius);
expect(transitioningDecoration.shadows![0].offset, expectedShadow.offset);
await tester.pumpAndSettle();
@@ -548,17 +485,12 @@
),
);
final openDecoration =
- (openDecoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ (openDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
expect(openDecoration.shadows, openShadows);
});
- testWidgets('Closed custom shadows transition into open elevation', (
- WidgetTester tester,
- ) async {
- const closedShadows = <BoxShadow>[
- BoxShadow(color: Colors.blue, blurRadius: 10.0),
- ];
+ testWidgets('Closed custom shadows transition into open elevation', (WidgetTester tester) async {
+ const closedShadows = <BoxShadow>[BoxShadow(color: Colors.blue, blurRadius: 10.0)];
await tester.pumpWidget(
_boilerplate(
@@ -590,8 +522,7 @@
),
);
final srcDecoration =
- (srcDecoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ (srcDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
expect(srcDecoration.shadows, closedShadows);
await tester.tap(find.text('Closed'));
@@ -601,38 +532,24 @@
final Element transitioningMaterialElement = tester.firstElement(
find.ancestor(of: find.text('Closed'), matching: find.byType(Material)),
);
- final transitioningMaterial =
- transitioningMaterialElement.widget as Material;
+ final transitioningMaterial = transitioningMaterialElement.widget as Material;
expect(transitioningMaterial.elevation, greaterThan(0.0));
expect(transitioningMaterial.elevation, lessThan(8.0));
final Element transitioningDecoratedBoxElement = tester.firstElement(
find.ancestor(
- of: find.byElementPredicate(
- (Element e) => e == transitioningMaterialElement,
- ),
+ of: find.byElementPredicate((Element e) => e == transitioningMaterialElement),
matching: find.byType(DecoratedBox),
),
);
final transitioningDecoration =
- (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration
- as ShapeDecoration;
+ (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration;
final double expectedT = Curves.fastOutSlowIn.transform(0.5);
- final BoxShadow expectedShadow = BoxShadow.lerpList(
- closedShadows,
- null,
- expectedT,
- )!.single;
+ final BoxShadow expectedShadow = BoxShadow.lerpList(closedShadows, null, expectedT)!.single;
expect(transitioningDecoration.shadows, hasLength(1));
expect(transitioningDecoration.shadows![0].color, expectedShadow.color);
- expect(
- transitioningDecoration.shadows![0].blurRadius,
- expectedShadow.blurRadius,
- );
- expect(
- transitioningDecoration.shadows![0].spreadRadius,
- expectedShadow.spreadRadius,
- );
+ expect(transitioningDecoration.shadows![0].blurRadius, expectedShadow.blurRadius);
+ expect(transitioningDecoration.shadows![0].spreadRadius, expectedShadow.spreadRadius);
expect(transitioningDecoration.shadows![0].offset, expectedShadow.offset);
await tester.pumpAndSettle();
@@ -727,9 +644,7 @@
await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/10 = 30ms
final dataMidFadeOut = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataClosed,
@@ -745,9 +660,7 @@
await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/5 = 60ms
final dataMidpoint = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidFadeOut,
@@ -762,9 +675,7 @@
await tester.pump(const Duration(milliseconds: 120)); // 300ms * 3/5 = 180ms
final dataMidFadeIn = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidpoint,
@@ -780,19 +691,14 @@
await tester.pump(const Duration(milliseconds: 120));
final dataTransitionDone = _TrackedData(
destMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == destMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == destMaterialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidFadeIn,
biggerMaterial: dataTransitionDone,
tester: tester,
);
- expect(
- dataTransitionDone.material.color,
- isNot(dataMidFadeIn.material.color),
- );
+ expect(dataTransitionDone.material.color, isNot(dataMidFadeIn.material.color));
expect(_getOpacity(tester, 'Open'), 1.0);
expect(_getOpacity(tester, 'Closed'), 0.0);
expect(dataTransitionDone.material.color, Colors.blue);
@@ -808,9 +714,7 @@
);
final dataOpen = _TrackedData(
finalMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == finalMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == finalMaterialElement)),
);
expect(dataOpen.material.color, dataTransitionDone.material.color);
expect(dataOpen.material.elevation, dataTransitionDone.material.elevation);
@@ -856,9 +760,7 @@
);
final dataOpen = _TrackedData(
initialMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == initialMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == initialMaterialElement)),
);
expect(dataOpen.material.color, Colors.blue);
expect(dataOpen.material.elevation, 8.0);
@@ -878,9 +780,7 @@
);
final dataTransitionStart = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
expect(dataTransitionStart.material.color, dataOpen.material.color);
expect(dataTransitionStart.material.elevation, dataOpen.material.elevation);
@@ -893,19 +793,14 @@
await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/10 = 30ms
final dataMidFadeOut = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidFadeOut,
biggerMaterial: dataTransitionStart,
tester: tester,
);
- expect(
- dataMidFadeOut.material.color,
- isNot(dataTransitionStart.material.color),
- );
+ expect(dataMidFadeOut.material.color, isNot(dataTransitionStart.material.color));
expect(_getOpacity(tester, 'Closed'), 0.0);
expect(_getOpacity(tester, 'Open'), lessThan(1.0));
expect(_getOpacity(tester, 'Open'), greaterThan(0.0));
@@ -914,9 +809,7 @@
await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/5 = 60ms
final dataMidpoint = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidpoint,
@@ -931,9 +824,7 @@
await tester.pump(const Duration(milliseconds: 120)); // 300ms * 3/5 = 180ms
final dataMidFadeIn = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataMidFadeIn,
@@ -949,19 +840,14 @@
await tester.pump(const Duration(milliseconds: 120));
final dataTransitionDone = _TrackedData(
materialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == materialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == materialElement)),
);
_expectMaterialPropertiesHaveAdvanced(
smallerMaterial: dataTransitionDone,
biggerMaterial: dataMidFadeIn,
tester: tester,
);
- expect(
- dataTransitionDone.material.color,
- isNot(dataMidFadeIn.material.color),
- );
+ expect(dataTransitionDone.material.color, isNot(dataMidFadeIn.material.color));
expect(_getOpacity(tester, 'Closed'), 1.0);
expect(_getOpacity(tester, 'Open'), 0.0);
expect(dataTransitionDone.material.color, Colors.green);
@@ -976,22 +862,15 @@
);
final dataClosed = _TrackedData(
finalMaterialElement.widget as Material,
- tester.getRect(
- find.byElementPredicate((Element e) => e == finalMaterialElement),
- ),
+ tester.getRect(find.byElementPredicate((Element e) => e == finalMaterialElement)),
);
expect(dataClosed.material.color, dataTransitionDone.material.color);
- expect(
- dataClosed.material.elevation,
- dataTransitionDone.material.elevation,
- );
+ expect(dataClosed.material.elevation, dataTransitionDone.material.elevation);
expect(dataClosed.radius, dataTransitionDone.radius);
expect(dataClosed.rect, dataTransitionDone.rect);
});
- testWidgets('Cannot tap container if tappable=false', (
- WidgetTester tester,
- ) async {
+ testWidgets('Cannot tap container if tappable=false', (WidgetTester tester) async {
await tester.pumpWidget(
_boilerplate(
child: Center(
@@ -1122,9 +1001,7 @@
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));
@@ -1136,9 +1013,7 @@
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));
});
@@ -1200,10 +1075,7 @@
child: Center(
child: OpenContainer(
closedBuilder: (BuildContext context, VoidCallback action) {
- return const _SizableContainer(
- initialSize: 100,
- child: Text('Closed'),
- );
+ return const _SizableContainer(initialSize: 100, child: Text('Closed'));
},
openBuilder: (BuildContext context, VoidCallback action) {
return GestureDetector(onTap: action, child: const Text('Open'));
@@ -1215,9 +1087,7 @@
await tester.pumpWidget(openContainer);
final Size orignalClosedRect = tester.getSize(
- find
- .ancestor(of: find.text('Closed'), matching: find.byType(Material))
- .first,
+ find.ancestor(of: find.text('Closed'), matching: find.byType(Material)).first,
);
expect(orignalClosedRect, const Size(100, 100));
@@ -1241,9 +1111,7 @@
expect(find.text('Closed'), findsOneWidget);
final Size transitionEndSize = tester.getSize(
- find
- .ancestor(of: find.text('Open'), matching: find.byType(Material))
- .first,
+ find.ancestor(of: find.text('Open'), matching: find.byType(Material)).first,
);
expect(transitionEndSize, const Size(200, 200));
@@ -1252,16 +1120,12 @@
expect(find.text('Closed'), findsOneWidget);
final Size finalSize = tester.getSize(
- find
- .ancestor(of: find.text('Closed'), matching: find.byType(Material))
- .first,
+ 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 {
+ testWidgets('transition is interrupted and should not jump', (WidgetTester tester) async {
await tester.pumpWidget(
_boilerplate(
child: Center(
@@ -1333,9 +1197,7 @@
expect(tester.getRect(find.byType(Navigator)), fullNavigator);
final Rect materialRectClosed = tester.getRect(
- find
- .ancestor(of: find.text('Closed'), matching: find.byType(Material))
- .first,
+ find.ancestor(of: find.text('Closed'), matching: find.byType(Material)).first,
);
await tester.tap(find.text('Closed'));
@@ -1363,9 +1225,7 @@
expect(materialRectOpen, fullNavigator);
});
- testWidgets('does not crash when disposed right after pop', (
- WidgetTester tester,
- ) async {
+ testWidgets('does not crash when disposed right after pop', (WidgetTester tester) async {
await tester.pumpWidget(
Center(
child: SizedBox(
@@ -1458,12 +1318,8 @@
child: _boilerplate(
child: Center(
child: OpenContainer(
- closedShape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(10),
- ),
- openShape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(40),
- ),
+ closedShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
+ openShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
closedBuilder: (BuildContext context, VoidCallback action) {
return const Text('Closed');
},
@@ -1480,9 +1336,7 @@
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)),
- ),
+ tester.firstWidget(find.ancestor(of: find.text('Closed'), matching: find.byType(Material))),
);
expect(closedRadius, 10.0);
@@ -1491,9 +1345,7 @@
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)),
- ),
+ tester.firstWidget(find.ancestor(of: find.text('Open'), matching: find.byType(Material))),
);
expect(openingRadius, 10.0);
@@ -1501,9 +1353,7 @@
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)),
- ),
+ tester.firstWidget(find.ancestor(of: find.text('Open'), matching: find.byType(Material))),
);
expect(halfwayRadius, greaterThan(10.0));
expect(halfwayRadius, lessThan(40.0));
@@ -1512,9 +1362,7 @@
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)),
- ),
+ tester.firstWidget(find.ancestor(of: find.text('Open'), matching: find.byType(Material))),
);
expect(openRadius, 40.0);
@@ -1522,9 +1370,7 @@
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)),
- ),
+ tester.firstWidget(find.ancestor(of: find.text('Open'), matching: find.byType(Material))),
);
expect(finalRadius, 40.0);
});
@@ -1592,193 +1438,170 @@
expect(_getScrimColor(tester), Colors.transparent);
});
- testWidgets(
- 'Container partly offscreen can be opened without crash - vertical',
- (WidgetTester tester) async {
- final 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');
- },
- );
- },
- ),
- ),
- ),
- ),
- );
-
- 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();
-
- // 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);
-
- 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 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');
- },
- );
- },
- ),
- ),
- ),
- ),
- );
-
- 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();
-
- // 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);
-
- 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()),
- );
-
- 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();
-
- 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();
-
- 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();
-
- 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', (
+ testWidgets('Container partly offscreen can be opened without crash - vertical', (
WidgetTester tester,
) async {
+ final 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');
+ },
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+
+ 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();
+
+ // 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);
+
+ 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 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');
+ },
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+
+ 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();
+
+ // 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);
+
+ 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()));
+
+ 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();
+
+ 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();
+
+ 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();
+
+ 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 {
var hasClosed = false;
final Widget openContainer = OpenContainer(
onClosed: (dynamic _) {
@@ -1812,68 +1635,57 @@
expect(hasClosed, isTrue);
});
- testWidgets(
- 'onClosed callback receives popped value when container has closed',
- (WidgetTester tester) async {
- bool? value = false;
- final Widget openContainer = OpenContainer<bool>(
- onClosed: (bool? poppedValue) {
- value = poppedValue;
- },
- closedBuilder: (BuildContext context, VoidCallback action) {
- return GestureDetector(onTap: action, child: const Text('Closed'));
- },
- openBuilder:
- (BuildContext context, CloseContainerActionCallback<bool> action) {
- return GestureDetector(
- onTap: () => action(returnValue: true),
- child: const Text('Open'),
- );
- },
- );
-
- await tester.pumpWidget(_boilerplate(child: openContainer));
-
- expect(find.text('Open'), findsNothing);
- expect(find.text('Closed'), findsOneWidget);
- expect(value, isFalse);
-
- await tester.tap(find.text('Closed'));
- await tester.pumpAndSettle();
-
- expect(find.text('Open'), findsOneWidget);
- expect(find.text('Closed'), findsNothing);
-
- await tester.tap(find.text('Open'));
- await tester.pumpAndSettle();
-
- expect(find.text('Open'), findsNothing);
- expect(find.text('Closed'), findsOneWidget);
- expect(value, isTrue);
- },
- );
-
- testWidgets('closedBuilder has anti-alias clip by default', (
+ testWidgets('onClosed callback receives popped value when container has closed', (
WidgetTester tester,
) async {
+ bool? value = false;
+ final Widget openContainer = OpenContainer<bool>(
+ onClosed: (bool? poppedValue) {
+ value = poppedValue;
+ },
+ closedBuilder: (BuildContext context, VoidCallback action) {
+ return GestureDetector(onTap: action, child: const Text('Closed'));
+ },
+ openBuilder: (BuildContext context, CloseContainerActionCallback<bool> action) {
+ return GestureDetector(onTap: () => action(returnValue: true), child: const Text('Open'));
+ },
+ );
+
+ await tester.pumpWidget(_boilerplate(child: openContainer));
+
+ expect(find.text('Open'), findsNothing);
+ expect(find.text('Closed'), findsOneWidget);
+ expect(value, isFalse);
+
+ await tester.tap(find.text('Closed'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Open'), findsOneWidget);
+ expect(find.text('Closed'), findsNothing);
+
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Open'), findsNothing);
+ expect(find.text('Closed'), findsOneWidget);
+ expect(value, isTrue);
+ });
+
+ 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<bool> action) {
- return const Text('Open');
- },
+ openBuilder: (BuildContext context, CloseContainerActionCallback<bool> action) {
+ return const Text('Open');
+ },
);
await tester.pumpWidget(_boilerplate(child: openContainer));
final Finder closedBuilderMaterial = find
- .ancestor(
- of: find.byKey(closedBuilderKey),
- matching: find.byType(Material),
- )
+ .ancestor(of: find.byKey(closedBuilderKey), matching: find.byType(Material))
.first;
final Material material = tester.widget<Material>(closedBuilderMaterial);
@@ -1886,20 +1698,16 @@
closedBuilder: (BuildContext context, VoidCallback action) {
return Text('Close', key: closedBuilderKey);
},
- openBuilder:
- (BuildContext context, CloseContainerActionCallback<bool> action) {
- return const Text('Open');
- },
+ openBuilder: (BuildContext context, CloseContainerActionCallback<bool> action) {
+ return const Text('Open');
+ },
clipBehavior: Clip.none,
);
await tester.pumpWidget(_boilerplate(child: openContainer));
final Finder closedBuilderMaterial = find
- .ancestor(
- of: find.byKey(closedBuilderKey),
- matching: find.byType(Material),
- )
+ .ancestor(of: find.byKey(closedBuilderKey), matching: find.byType(Material))
.first;
final Material material = tester.widget<Material>(closedBuilderMaterial);
@@ -1948,69 +1756,55 @@
);
}
- testWidgets(
- 'Verify that "useRootNavigator: false" uses the correct navigator',
- (WidgetTester tester) async {
- const appKey = Key('App');
- const nestedNavigatorKey = Key('Nested Navigator');
+ testWidgets('Verify that "useRootNavigator: false" uses the correct navigator', (
+ WidgetTester tester,
+ ) async {
+ const appKey = Key('App');
+ const nestedNavigatorKey = Key('Nested Navigator');
- await tester.pumpWidget(
- createRootNavigatorTest(
- appKey: appKey,
- nestedNavigatorKey: nestedNavigatorKey,
- useRootNavigator: false,
- ),
- );
+ 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(
- find.descendant(of: find.byKey(appKey), matching: find.text('Opened')),
- findsOneWidget,
- );
+ expect(find.descendant(of: find.byKey(appKey), matching: find.text('Opened')), findsOneWidget);
- expect(
- find.descendant(
- of: find.byKey(nestedNavigatorKey),
- matching: find.text('Opened'),
- ),
- findsOneWidget,
- );
- },
- );
+ 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 appKey = Key('App');
- const nestedNavigatorKey = Key('Nested Navigator');
+ testWidgets('Verify that "useRootNavigator: true" uses the correct navigator', (
+ WidgetTester tester,
+ ) async {
+ const appKey = Key('App');
+ const nestedNavigatorKey = Key('Nested Navigator');
- await tester.pumpWidget(
- createRootNavigatorTest(
- appKey: appKey,
- nestedNavigatorKey: nestedNavigatorKey,
- useRootNavigator: true,
- ),
- );
+ 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(
- find.descendant(of: find.byKey(appKey), matching: find.text('Opened')),
- findsOneWidget,
- );
+ expect(find.descendant(of: find.byKey(appKey), matching: find.text('Opened')), findsOneWidget);
- expect(
- find.descendant(
- of: find.byKey(nestedNavigatorKey),
- matching: find.text('Opened'),
- ),
- findsNothing,
- );
- },
- );
+ expect(
+ find.descendant(of: find.byKey(nestedNavigatorKey), matching: find.text('Opened')),
+ findsNothing,
+ );
+ });
testWidgets('Verify correct opened size when "useRootNavigator: false"', (
WidgetTester tester,
@@ -2052,19 +1846,11 @@
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(
- name: 'route-name',
- arguments: 'arguments',
- );
+ testWidgets('Verify routeSettings passed to Navigator', (WidgetTester tester) async {
+ const routeSettings = RouteSettings(name: 'route-name', arguments: 'arguments');
final Widget openContainer = OpenContainer(
routeSettings: routeSettings,
@@ -2084,9 +1870,7 @@
// Expect the last route pushed to the navigator to contain RouteSettings
// equal to the RouteSettings passed to the OpenContainer
- final ModalRoute<dynamic> modalRoute = ModalRoute.of(
- tester.element(find.text('Open')),
- )!;
+ final ModalRoute<dynamic> modalRoute = ModalRoute.of(tester.element(find.text('Open')))!;
expect(modalRoute.settings, routeSettings);
});
}
@@ -2094,10 +1878,7 @@
Color _getScrimColor(WidgetTester tester) {
return tester
.widget<ColoredBox>(
- find.descendant(
- of: find.byType(Container),
- matching: find.byType(ColoredBox),
- ),
+ find.descendant(of: find.byType(Container), matching: find.byType(ColoredBox)),
)
.color;
}
@@ -2107,10 +1888,7 @@
required _TrackedData smallerMaterial,
required WidgetTester tester,
}) {
- expect(
- biggerMaterial.material.elevation,
- greaterThan(smallerMaterial.material.elevation),
- );
+ expect(biggerMaterial.material.elevation, greaterThan(smallerMaterial.material.elevation));
expect(biggerMaterial.radius, lessThan(smallerMaterial.radius));
expect(biggerMaterial.rect.height, greaterThan(smallerMaterial.rect.height));
expect(biggerMaterial.rect.width, greaterThan(smallerMaterial.rect.width));
@@ -2186,12 +1964,10 @@
class _RemoveOpenContainerExample extends StatefulWidget {
@override
- __RemoveOpenContainerExampleState createState() =>
- __RemoveOpenContainerExampleState();
+ __RemoveOpenContainerExampleState createState() => __RemoveOpenContainerExampleState();
}
-class __RemoveOpenContainerExampleState
- extends State<_RemoveOpenContainerExample> {
+class __RemoveOpenContainerExampleState extends State<_RemoveOpenContainerExample> {
bool removeOpenContainerWidget = false;
@override
@@ -2199,23 +1975,16 @@
return removeOpenContainerWidget
? const Text('Container has been removed')
: OpenContainer(
- closedBuilder: (BuildContext context, VoidCallback action) =>
- Column(
- children: <Widget>[
- const Text('Closed'),
- ElevatedButton(
- onPressed: action,
- child: const Text('Open the container'),
- ),
- ],
- ),
+ closedBuilder: (BuildContext context, VoidCallback action) => Column(
+ children: <Widget>[
+ const Text('Closed'),
+ ElevatedButton(onPressed: action, child: const Text('Open the container')),
+ ],
+ ),
openBuilder: (BuildContext context, VoidCallback action) => Column(
children: <Widget>[
const Text('Open'),
- ElevatedButton(
- onPressed: action,
- child: const Text('Close the container'),
- ),
+ ElevatedButton(onPressed: action, child: const Text('Close the container')),
ElevatedButton(
onPressed: () {
setState(() {
diff --git a/packages/animations/test/page_transition_switcher_test.dart b/packages/animations/test/page_transition_switcher_test.dart
index 56f4c77..0030472 100644
--- a/packages/animations/test/page_transition_switcher_test.dart
+++ b/packages/animations/test/page_transition_switcher_test.dart
@@ -19,12 +19,8 @@
),
);
- Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- ], tester);
- Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- ], tester);
+ Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[containerOne], tester);
+ Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne], tester);
expect(primaryAnimation[containerOne], equals(1.0));
expect(secondaryAnimation[containerOne], equals(0.0));
@@ -37,14 +33,8 @@
);
await tester.pump(const Duration(milliseconds: 40));
- primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
- secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
+ primaryAnimation = _getPrimaryAnimation(<Key>[containerOne, containerTwo], tester);
+ secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne, containerTwo], tester);
// Secondary is running for outgoing widget.
expect(primaryAnimation[containerOne], equals(1.0));
expect(secondaryAnimation[containerOne], moreOrLessEquals(0.4));
@@ -84,9 +74,7 @@
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 containerOne = UniqueKey();
final containerTwo = UniqueKey();
final containerThree = UniqueKey();
@@ -99,12 +87,8 @@
),
);
- Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- ], tester);
- Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- ], tester);
+ Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[containerOne], tester);
+ Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne], tester);
expect(primaryAnimation[containerOne], equals(1.0));
expect(secondaryAnimation[containerOne], equals(0.0));
@@ -118,14 +102,8 @@
);
await tester.pump(const Duration(milliseconds: 40));
- primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
- secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
+ primaryAnimation = _getPrimaryAnimation(<Key>[containerOne, containerTwo], tester);
+ secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne, containerTwo], tester);
// Primary is running forward for outgoing widget.
expect(primaryAnimation[containerOne], moreOrLessEquals(0.6));
expect(secondaryAnimation[containerOne], equals(0.0));
@@ -178,12 +156,8 @@
),
);
- Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- ], tester);
- Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- ], tester);
+ Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[containerOne], tester);
+ Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne], tester);
expect(primaryAnimation[containerOne], equals(1.0));
expect(secondaryAnimation[containerOne], equals(0.0));
@@ -196,14 +170,8 @@
);
await tester.pump(const Duration(milliseconds: 40));
- primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
- secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
+ primaryAnimation = _getPrimaryAnimation(<Key>[containerOne, containerTwo], tester);
+ secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne, containerTwo], tester);
expect(secondaryAnimation[containerOne], moreOrLessEquals(0.4));
expect(primaryAnimation[containerOne], equals(1.0));
expect(secondaryAnimation[containerTwo], equals(0.0));
@@ -251,12 +219,8 @@
),
);
- Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- ], tester);
- Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- ], tester);
+ Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[containerOne], tester);
+ Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne], tester);
expect(primaryAnimation[containerOne], equals(1.0));
expect(secondaryAnimation[containerOne], equals(0.0));
@@ -270,14 +234,8 @@
);
await tester.pump(const Duration(milliseconds: 40));
- primaryAnimation = _getPrimaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
- secondaryAnimation = _getSecondaryAnimation(<Key>[
- containerOne,
- containerTwo,
- ], tester);
+ primaryAnimation = _getPrimaryAnimation(<Key>[containerOne, containerTwo], tester);
+ secondaryAnimation = _getSecondaryAnimation(<Key>[containerOne, containerTwo], tester);
// Primary is running in reverse for outgoing widget.
expect(primaryAnimation[containerOne], moreOrLessEquals(0.6));
expect(secondaryAnimation[containerOne], equals(0.0));
@@ -340,9 +298,7 @@
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),
@@ -421,9 +377,7 @@
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),
@@ -444,9 +398,7 @@
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));
@@ -455,9 +407,7 @@
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 statefulOne = UniqueKey();
final statefulTwo = UniqueKey();
final statefulThree = UniqueKey();
@@ -472,12 +422,8 @@
),
);
- Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[
- statefulOne,
- ], tester);
- Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[
- statefulOne,
- ], tester);
+ Map<Key, double> primaryAnimation = _getPrimaryAnimation(<Key>[statefulOne], tester);
+ Map<Key, double> secondaryAnimation = _getSecondaryAnimation(<Key>[statefulOne], tester);
expect(primaryAnimation[statefulOne], equals(1.0));
expect(secondaryAnimation[statefulOne], equals(0.0));
expect(StatefulTestWidgetState.generation, equals(1));
@@ -492,14 +438,8 @@
await tester.pump(const Duration(milliseconds: 50));
expect(find.byType(FadeTransition), findsNWidgets(2));
- primaryAnimation = _getPrimaryAnimation(<Key>[
- statefulOne,
- statefulTwo,
- ], tester);
- secondaryAnimation = _getSecondaryAnimation(<Key>[
- statefulOne,
- statefulTwo,
- ], tester);
+ primaryAnimation = _getPrimaryAnimation(<Key>[statefulOne, statefulTwo], tester);
+ secondaryAnimation = _getSecondaryAnimation(<Key>[statefulOne, statefulTwo], tester);
expect(primaryAnimation[statefulTwo], equals(0.5));
expect(secondaryAnimation[statefulTwo], equals(0.0));
expect(StatefulTestWidgetState.generation, equals(2));
@@ -552,102 +492,92 @@
expect(find.text('2'), findsOneWidget);
});
- testWidgets(
- 'updates previous child transitions if the transitionBuilder changes.',
- (WidgetTester tester) async {
- final containerOne = UniqueKey();
- final containerTwo = UniqueKey();
- final containerThree = UniqueKey();
+ testWidgets('updates previous child transitions if the transitionBuilder changes.', (
+ WidgetTester tester,
+ ) async {
+ final containerOne = UniqueKey();
+ final containerTwo = UniqueKey();
+ final 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)),
- ),
+ // 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.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.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));
+
+ 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<double> primary,
+ Animation<double> secondary,
+ ) {
+ return SlideTransition(
+ position: Tween<Offset>(begin: Offset.zero, end: const Offset(20, 30)).animate(primary),
+ child: SizeTransition(
+ sizeFactor: Tween<double>(begin: 10, end: 0.0).animate(secondary),
+ child: child,
),
);
+ }
- 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)),
- ),
+ // 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));
- 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));
-
- 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<double> primary,
- Animation<double> secondary,
- ) {
- return SlideTransition(
- position: Tween<Offset>(
- begin: Offset.zero,
- end: const Offset(20, 30),
- ).animate(primary),
- child: SizeTransition(
- sizeFactor: Tween<double>(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),
- ),
- ),
- ),
- );
-
- 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 {
@@ -671,11 +601,7 @@
Widget build(BuildContext context) => Container();
}
-Widget _transitionBuilder(
- Widget child,
- Animation<double> primary,
- Animation<double> secondary,
-) {
+Widget _transitionBuilder(Widget child, Animation<double> primary, Animation<double> secondary) {
return ScaleTransition(
scale: Tween<double>(begin: 0.0, end: 1.0).animate(primary),
child: FadeTransition(
@@ -702,10 +628,7 @@
final result = <Key, double>{};
for (final key in keys) {
final ScaleTransition transition = tester.firstWidget(
- find.ancestor(
- of: find.byKey(key),
- matching: find.byType(ScaleTransition),
- ),
+ find.ancestor(of: find.byKey(key), matching: find.byType(ScaleTransition)),
);
result[key] = transition.scale.value;
}
diff --git a/packages/animations/test/shared_axis_transition_test.dart b/packages/animations/test/shared_axis_transition_test.dart
index d422071..b354862 100644
--- a/packages/animations/test/shared_axis_transition_test.dart
+++ b/packages/animations/test/shared_axis_transition_test.dart
@@ -9,53 +9,32 @@
void main() {
group('SharedAxisTransitionType.horizontal', () {
- testWidgets(
- 'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition',
- (WidgetTester tester) async {
- final animation = AnimationController(vsync: const TestVSync());
- final secondaryAnimation = AnimationController(
- vsync: const TestVSync(),
- );
-
- await tester.pumpWidget(
- const SharedAxisPageTransitionsBuilder(
- transitionType: SharedAxisTransitionType.horizontal,
- ).buildTransitions<void>(
- null,
- null,
- animation,
- secondaryAnimation,
- const Placeholder(),
- ),
- );
-
- expect(find.byType(SharedAxisTransition), findsOneWidget);
- },
- );
-
- testWidgets('SharedAxisTransition runs forward', (
+ testWidgets('SharedAxisPageTransitionsBuilder builds a SharedAxisTransition', (
WidgetTester tester,
) async {
+ final animation = AnimationController(vsync: const TestVSync());
+ final secondaryAnimation = AnimationController(vsync: const TestVSync());
+
+ await tester.pumpWidget(
+ const SharedAxisPageTransitionsBuilder(
+ transitionType: SharedAxisTransitionType.horizontal,
+ ).buildTransitions<void>(null, null, animation, secondaryAnimation, const Placeholder()),
+ );
+
+ expect(find.byType(SharedAxisTransition), findsOneWidget);
+ });
+
+ testWidgets('SharedAxisTransition runs forward', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.horizontal,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.horizontal),
);
expect(find.text(bottomRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
- 0.0,
- );
+ expect(_getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal), 0.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
@@ -65,26 +44,12 @@
// Bottom route is not offset and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
- 0.0,
- );
+ 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(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.horizontal), 30.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
@@ -116,11 +81,7 @@
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), greaterThan(0));
expect(_getOpacity(topRoute, tester), lessThan(1.0));
- topOffset = _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- );
+ topOffset = _getTranslationOffset(topRoute, tester, SharedAxisTransitionType.horizontal);
expect(topOffset, greaterThan(0.0));
expect(topOffset, lessThan(30.0));
@@ -130,24 +91,13 @@
expect(find.text(bottomRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
+ _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(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.horizontal), 0.0);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
@@ -155,32 +105,20 @@
expect(find.text(topRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition runs in reverse', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition runs in reverse', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.horizontal,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.horizontal),
);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
- 0.0,
- );
+ expect(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.horizontal), 0.0);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
@@ -189,23 +127,12 @@
// Top route is is not offset and fully visible.
expect(find.text(topRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
- 0.0,
- );
+ 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,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal),
-30.0,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
@@ -221,10 +148,7 @@
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),
- );
+ expect(_getOpacity(bottomRoute, tester), moreOrLessEquals(0, epsilon: 0.005));
double? bottomOffset = _getTranslationOffset(
bottomRoute,
tester,
@@ -254,25 +178,11 @@
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(_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(_getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal), 0.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
@@ -280,18 +190,13 @@
expect(find.text(bottomRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition does not jump when interrupted', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition does not jump when interrupted', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.horizontal,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.horizontal),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
@@ -332,21 +237,13 @@
// Nothing should change.
expect(find.text(bottomRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal),
halfwayBottomOffset,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
+ _getTranslationOffset(topRoute, tester, SharedAxisTransitionType.horizontal),
halfwayTopOffset,
);
expect(_getOpacity(topRoute, tester), halfwayTopOpacity);
@@ -355,27 +252,15 @@
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal),
lessThan(0.0),
);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal),
greaterThan(-30.0),
);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.horizontal,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.horizontal),
greaterThan(halfwayBottomOffset),
);
expect(_getOpacity(bottomRoute, tester), greaterThan(0.0));
@@ -384,24 +269,10 @@
// 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(_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(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.horizontal), 30.0);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
@@ -409,9 +280,7 @@
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 navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -420,10 +289,7 @@
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
- return _StatefulTestWidget(
- key: ValueKey<String?>(settings.name),
- name: settings.name!,
- );
+ return _StatefulTestWidget(key: ValueKey<String?>(settings.name), name: settings.name!);
},
transitionType: SharedAxisTransitionType.horizontal,
),
@@ -438,64 +304,35 @@
await tester.pump();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
expect(
- tester.state(
- find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false),
- ),
+ tester.state(find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false)),
bottomState,
);
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
navigator.currentState!.pop();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
});
@@ -508,24 +345,15 @@
final Color defaultFillColor = ThemeData().canvasColor;
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.horizontal,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.horizontal),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
- .ancestor(
- matching: find.byType(ColoredBox),
- of: find.byKey(const ValueKey<String?>('/')),
- )
+ .ancestor(matching: find.byType(ColoredBox), of: find.byKey(const ValueKey<String?>('/')))
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- defaultFillColor,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, defaultFillColor);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
@@ -538,10 +366,7 @@
)
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- defaultFillColor,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, defaultFillColor);
});
testWidgets('custom fill color', (WidgetTester tester) async {
@@ -559,16 +384,10 @@
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
- .ancestor(
- matching: find.byType(ColoredBox),
- of: find.byKey(const ValueKey<String?>('/')),
- )
+ .ancestor(matching: find.byType(ColoredBox), of: find.byKey(const ValueKey<String?>('/')))
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- Colors.green,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
@@ -581,10 +400,7 @@
)
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- Colors.green,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
});
testWidgets('should keep state', (WidgetTester tester) async {
@@ -609,9 +425,7 @@
),
),
);
- final State<StatefulWidget> state = tester.state(
- find.byType(_StatefulTestWidget),
- );
+ final State<StatefulWidget> state = tester.state(find.byType(_StatefulTestWidget));
expect(state, isNotNull);
animation.forward();
@@ -657,53 +471,32 @@
});
group('SharedAxisTransitionType.vertical', () {
- testWidgets(
- 'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition',
- (WidgetTester tester) async {
- final animation = AnimationController(vsync: const TestVSync());
- final secondaryAnimation = AnimationController(
- vsync: const TestVSync(),
- );
-
- await tester.pumpWidget(
- const SharedAxisPageTransitionsBuilder(
- transitionType: SharedAxisTransitionType.vertical,
- ).buildTransitions<void>(
- null,
- null,
- animation,
- secondaryAnimation,
- const Placeholder(),
- ),
- );
-
- expect(find.byType(SharedAxisTransition), findsOneWidget);
- },
- );
-
- testWidgets('SharedAxisTransition runs forward', (
+ testWidgets('SharedAxisPageTransitionsBuilder builds a SharedAxisTransition', (
WidgetTester tester,
) async {
+ final animation = AnimationController(vsync: const TestVSync());
+ final secondaryAnimation = AnimationController(vsync: const TestVSync());
+
+ await tester.pumpWidget(
+ const SharedAxisPageTransitionsBuilder(
+ transitionType: SharedAxisTransitionType.vertical,
+ ).buildTransitions<void>(null, null, animation, secondaryAnimation, const Placeholder()),
+ );
+
+ expect(find.byType(SharedAxisTransition), findsOneWidget);
+ });
+
+ testWidgets('SharedAxisTransition runs forward', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.vertical,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.vertical),
);
expect(find.text(bottomRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
- 0.0,
- );
+ expect(_getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical), 0.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
@@ -713,26 +506,12 @@
// Bottom route is not offset and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
- 0.0,
- );
+ 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(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.vertical), 30.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
@@ -764,11 +543,7 @@
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), greaterThan(0));
expect(_getOpacity(topRoute, tester), lessThan(1.0));
- topOffset = _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.vertical,
- );
+ topOffset = _getTranslationOffset(topRoute, tester, SharedAxisTransitionType.vertical);
expect(topOffset, greaterThan(0.0));
expect(topOffset, lessThan(30.0));
@@ -777,25 +552,11 @@
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
- -30.0,
- );
+ 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(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.vertical), 0.0);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
@@ -803,32 +564,20 @@
expect(find.text(topRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition runs in reverse', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition runs in reverse', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.vertical,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.vertical),
);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
- 0.0,
- );
+ expect(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.vertical), 0.0);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
@@ -837,25 +586,11 @@
// Top route is is not offset and fully visible.
expect(find.text(topRoute), findsOneWidget);
- expect(
- _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
- 0.0,
- );
+ 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(_getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical), -30.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
@@ -869,10 +604,7 @@
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),
- );
+ expect(_getOpacity(bottomRoute, tester), moreOrLessEquals(0, epsilon: 0.005));
double? bottomOffset = _getTranslationOffset(
bottomRoute,
tester,
@@ -890,11 +622,7 @@
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), greaterThan(0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
- bottomOffset = _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- );
+ bottomOffset = _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical);
expect(bottomOffset, lessThan(0.0));
expect(bottomOffset, greaterThan(-30.0));
@@ -902,25 +630,11 @@
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(_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(_getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical), 0.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
@@ -928,18 +642,13 @@
expect(find.text(bottomRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition does not jump when interrupted', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition does not jump when interrupted', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.vertical,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.vertical),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
@@ -980,21 +689,13 @@
// Nothing should change.
expect(find.text(bottomRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical),
halfwayBottomOffset,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- topRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
+ _getTranslationOffset(topRoute, tester, SharedAxisTransitionType.vertical),
halfwayTopOffset,
);
expect(_getOpacity(topRoute, tester), halfwayTopOpacity);
@@ -1003,27 +704,15 @@
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical),
lessThan(0.0),
);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical),
greaterThan(-30.0),
);
expect(
- _getTranslationOffset(
- bottomRoute,
- tester,
- SharedAxisTransitionType.vertical,
- ),
+ _getTranslationOffset(bottomRoute, tester, SharedAxisTransitionType.vertical),
greaterThan(halfwayBottomOffset),
);
expect(_getOpacity(bottomRoute, tester), greaterThan(0.0));
@@ -1032,24 +721,10 @@
// 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(_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(_getTranslationOffset(topRoute, tester, SharedAxisTransitionType.vertical), 30.0);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
@@ -1057,9 +732,7 @@
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 navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -1068,10 +741,7 @@
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
- return _StatefulTestWidget(
- key: ValueKey<String?>(settings.name),
- name: settings.name!,
- );
+ return _StatefulTestWidget(key: ValueKey<String?>(settings.name), name: settings.name!);
},
transitionType: SharedAxisTransitionType.vertical,
),
@@ -1086,64 +756,35 @@
await tester.pump();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
expect(
- tester.state(
- find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false),
- ),
+ tester.state(find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false)),
bottomState,
);
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
navigator.currentState!.pop();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
});
@@ -1156,24 +797,15 @@
final Color defaultFillColor = ThemeData().canvasColor;
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.vertical,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.vertical),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
- .ancestor(
- matching: find.byType(ColoredBox),
- of: find.byKey(const ValueKey<String?>('/')),
- )
+ .ancestor(matching: find.byType(ColoredBox), of: find.byKey(const ValueKey<String?>('/')))
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- defaultFillColor,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, defaultFillColor);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
@@ -1186,10 +818,7 @@
)
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- defaultFillColor,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, defaultFillColor);
});
testWidgets('custom fill color', (WidgetTester tester) async {
@@ -1207,16 +836,10 @@
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
- .ancestor(
- matching: find.byType(ColoredBox),
- of: find.byKey(const ValueKey<String?>('/')),
- )
+ .ancestor(matching: find.byType(ColoredBox), of: find.byKey(const ValueKey<String?>('/')))
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- Colors.green,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
@@ -1229,10 +852,7 @@
)
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- Colors.green,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
});
testWidgets('should keep state', (WidgetTester tester) async {
@@ -1257,9 +877,7 @@
),
),
);
- final State<StatefulWidget> state = tester.state(
- find.byType(_StatefulTestWidget),
- );
+ final State<StatefulWidget> state = tester.state(find.byType(_StatefulTestWidget));
expect(state, isNotNull);
animation.forward();
@@ -1305,42 +923,28 @@
});
group('SharedAxisTransitionType.scaled', () {
- testWidgets(
- 'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition',
- (WidgetTester tester) async {
- final animation = AnimationController(vsync: const TestVSync());
- final secondaryAnimation = AnimationController(
- vsync: const TestVSync(),
- );
-
- await tester.pumpWidget(
- const SharedAxisPageTransitionsBuilder(
- transitionType: SharedAxisTransitionType.scaled,
- ).buildTransitions<void>(
- null,
- null,
- animation,
- secondaryAnimation,
- const Placeholder(),
- ),
- );
-
- expect(find.byType(SharedAxisTransition), findsOneWidget);
- },
- );
-
- testWidgets('SharedAxisTransition runs forward', (
+ testWidgets('SharedAxisPageTransitionsBuilder builds a SharedAxisTransition', (
WidgetTester tester,
) async {
+ final animation = AnimationController(vsync: const TestVSync());
+ final secondaryAnimation = AnimationController(vsync: const TestVSync());
+
+ await tester.pumpWidget(
+ const SharedAxisPageTransitionsBuilder(
+ transitionType: SharedAxisTransitionType.scaled,
+ ).buildTransitions<void>(null, null, animation, secondaryAnimation, const Placeholder()),
+ );
+
+ expect(find.byType(SharedAxisTransition), findsOneWidget);
+ });
+
+ testWidgets('SharedAxisTransition runs forward', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.scaled,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.scaled),
);
expect(find.text(bottomRoute), findsOneWidget);
@@ -1406,18 +1010,13 @@
expect(find.text(topRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition runs in reverse', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition runs in reverse', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.scaled,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.scaled),
);
navigator.currentState!.pushNamed(topRoute);
@@ -1451,10 +1050,7 @@
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),
- );
+ expect(_getOpacity(bottomRoute, tester), moreOrLessEquals(0, epsilon: 0.005));
double bottomScale = _getScale(bottomRoute, tester);
expect(bottomScale, greaterThan(1.0));
expect(bottomScale, lessThan(1.1));
@@ -1488,18 +1084,13 @@
expect(find.text(bottomRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition does not jump when interrupted', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition does not jump when interrupted', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.scaled,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.scaled),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
@@ -1560,18 +1151,13 @@
expect(find.text(bottomRoute), findsOneWidget);
});
- testWidgets('SharedAxisTransition properly disposes animation', (
- WidgetTester tester,
- ) async {
+ testWidgets('SharedAxisTransition properly disposes animation', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.scaled,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.scaled),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
@@ -1595,9 +1181,7 @@
expect(find.byType(SharedAxisTransition), findsNothing);
});
- testWidgets('State is not lost when transitioning', (
- WidgetTester tester,
- ) async {
+ testWidgets('State is not lost when transitioning', (WidgetTester tester) async {
final navigator = GlobalKey<NavigatorState>();
const bottomRoute = '/';
const topRoute = '/a';
@@ -1607,10 +1191,7 @@
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
contentBuilder: (RouteSettings settings) {
- return _StatefulTestWidget(
- key: ValueKey<String?>(settings.name),
- name: settings.name!,
- );
+ return _StatefulTestWidget(key: ValueKey<String?>(settings.name), name: settings.name!);
},
),
);
@@ -1624,64 +1205,35 @@
await tester.pump();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
expect(
- tester.state(
- find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false),
- ),
+ tester.state(find.byKey(const ValueKey<String?>(bottomRoute), skipOffstage: false)),
bottomState,
);
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
navigator.currentState!.pop();
await tester.pump();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pump(const Duration(milliseconds: 150));
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
- expect(
- tester.state(find.byKey(const ValueKey<String?>(topRoute))),
- topState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
+ expect(tester.state(find.byKey(const ValueKey<String?>(topRoute))), topState);
await tester.pumpAndSettle();
- expect(
- tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
- bottomState,
- );
+ expect(tester.state(find.byKey(const ValueKey<String?>(bottomRoute))), bottomState);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
});
@@ -1694,24 +1246,15 @@
final Color defaultFillColor = ThemeData().canvasColor;
await tester.pumpWidget(
- _TestWidget(
- navigatorKey: navigator,
- transitionType: SharedAxisTransitionType.scaled,
- ),
+ _TestWidget(navigatorKey: navigator, transitionType: SharedAxisTransitionType.scaled),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
- .ancestor(
- matching: find.byType(ColoredBox),
- of: find.byKey(const ValueKey<String?>('/')),
- )
+ .ancestor(matching: find.byType(ColoredBox), of: find.byKey(const ValueKey<String?>('/')))
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- defaultFillColor,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, defaultFillColor);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
@@ -1724,10 +1267,7 @@
)
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- defaultFillColor,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, defaultFillColor);
});
testWidgets('custom fill color', (WidgetTester tester) async {
@@ -1745,16 +1285,10 @@
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
- .ancestor(
- matching: find.byType(ColoredBox),
- of: find.byKey(const ValueKey<String?>('/')),
- )
+ .ancestor(matching: find.byType(ColoredBox), of: find.byKey(const ValueKey<String?>('/')))
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- Colors.green,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
@@ -1767,10 +1301,7 @@
)
.last;
expect(fillContainerFinder, findsOneWidget);
- expect(
- tester.widget<ColoredBox>(fillContainerFinder).color,
- Colors.green,
- );
+ expect(tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
});
testWidgets('should keep state', (WidgetTester tester) async {
@@ -1795,9 +1326,7 @@
),
),
);
- final State<StatefulWidget> state = tester.state(
- find.byType(_StatefulTestWidget),
- );
+ final State<StatefulWidget> state = tester.state(find.byType(_StatefulTestWidget));
expect(state, isNotNull);
animation.forward();
@@ -1866,28 +1395,19 @@
switch (transitionType) {
case SharedAxisTransitionType.horizontal:
- return tester.widgetList<Transform>(finder).fold<double>(0.0, (
- double a,
- Widget widget,
- ) {
+ return tester.widgetList<Transform>(finder).fold<double>(0.0, (double a, Widget widget) {
final transition = widget as Transform;
final Vector3 translation = transition.transform.getTranslation();
return a + translation.x;
});
case SharedAxisTransitionType.vertical:
- return tester.widgetList<Transform>(finder).fold<double>(0.0, (
- double a,
- Widget widget,
- ) {
+ return tester.widgetList<Transform>(finder).fold<double>(0.0, (double a, Widget widget) {
final transition = widget as Transform;
final Vector3 translation = transition.transform.getTranslation();
return a + translation.y;
});
case SharedAxisTransitionType.scaled:
- assert(
- false,
- 'SharedAxisTransitionType.scaled does not have a translation offset',
- );
+ assert(false, 'SharedAxisTransitionType.scaled does not have a translation offset');
return 0.0;
}
}
@@ -1937,10 +1457,7 @@
builder: (BuildContext context) {
return contentBuilder != null
? contentBuilder!(settings)
- : Center(
- key: ValueKey<String?>(settings.name),
- child: Text(settings.name!),
- );
+ : Center(key: ValueKey<String?>(settings.name), child: Text(settings.name!));
},
);
},
diff --git a/packages/camera/camera/example/integration_test/camera_test.dart b/packages/camera/camera/example/integration_test/camera_test.dart
index 258110e..d3de641 100644
--- a/packages/camera/camera/example/integration_test/camera_test.dart
+++ b/packages/camera/camera/example/integration_test/camera_test.dart
@@ -32,12 +32,8 @@
});
final presetExpectedSizes = <ResolutionPreset, Size>{
- ResolutionPreset.low: Platform.isAndroid
- ? const Size(240, 320)
- : const Size(288, 352),
- ResolutionPreset.medium: Platform.isAndroid
- ? const Size(480, 720)
- : const Size(480, 640),
+ ResolutionPreset.low: Platform.isAndroid ? const Size(240, 320) : const Size(288, 352),
+ ResolutionPreset.medium: Platform.isAndroid ? const Size(480, 720) : const Size(480, 640),
ResolutionPreset.high: const Size(720, 1280),
ResolutionPreset.veryHigh: const Size(1080, 1920),
ResolutionPreset.ultraHigh: const Size(2160, 3840),
@@ -76,10 +72,7 @@
// Verify image dimensions are as expected
expect(video, isNotNull);
- return assertExpectedDimensions(
- expectedSize,
- Size(video.height, video.width),
- );
+ return assertExpectedDimensions(expectedSize, Size(video.height, video.width));
}
testWidgets(
@@ -91,8 +84,7 @@
}
for (final cameraDescription in cameras) {
var previousPresetExactlySupported = true;
- for (final MapEntry<ResolutionPreset, Size> preset
- in presetExpectedSizes.entries) {
+ for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) {
final controller = CameraController(cameraDescription, preset.key);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -119,11 +111,7 @@
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -133,8 +121,7 @@
sleep(const Duration(seconds: 2));
final XFile file = await controller.stopVideoRecording();
- final int recordingTime =
- DateTime.now().millisecondsSinceEpoch - recordingStart;
+ final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart;
final videoFile = File(file.path);
final videoController = VideoPlayerController.file(videoFile);
@@ -151,11 +138,7 @@
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -179,8 +162,7 @@
}
final XFile file = await controller.stopVideoRecording();
- final int recordingTime =
- DateTime.now().millisecondsSinceEpoch - recordingStart;
+ final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart;
final videoFile = File(file.path);
final videoController = VideoPlayerController.file(videoFile);
@@ -197,11 +179,7 @@
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
var isDetecting = false;
@@ -252,9 +230,7 @@
return completer.future;
}
- testWidgets('Set description while recording captures full video', (
- WidgetTester tester,
- ) async {
+ testWidgets('Set description while recording captures full video', (WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.length < 2) {
return;
@@ -282,10 +258,7 @@
final int duration = videoController.value.duration.inMilliseconds;
await videoController.dispose();
- expect(
- duration,
- greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds),
- );
+ expect(duration, greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds));
await controller.dispose();
});
@@ -295,11 +268,7 @@
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.setDescription(cameras[1]);
@@ -307,9 +276,7 @@
expect(controller.description, cameras[1]);
});
- testWidgets('iOS image streaming with imageFormatGroup', (
- WidgetTester tester,
- ) async {
+ testWidgets('iOS image streaming with imageFormatGroup', (WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.isEmpty) {
return;
diff --git a/packages/camera/camera/example/lib/main.dart b/packages/camera/camera/example/lib/main.dart
index cbbbf24..a03ed1e 100644
--- a/packages/camera/camera/example/lib/main.dart
+++ b/packages/camera/camera/example/lib/main.dart
@@ -141,8 +141,7 @@
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
- color:
- controller != null && controller!.value.isRecordingVideo
+ color: controller != null && controller!.value.isRecordingVideo
? Colors.redAccent
: Colors.grey,
width: 3.0,
@@ -158,9 +157,7 @@
_modeControlRowWidget(),
Padding(
padding: const EdgeInsets.all(5.0),
- child: Row(
- children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()],
- ),
+ child: Row(children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()]),
),
],
),
@@ -174,11 +171,7 @@
if (cameraController == null || !cameraController.value.isInitialized) {
return const Text(
'Tap a camera',
- style: TextStyle(
- color: Colors.white,
- fontSize: 24.0,
- fontWeight: FontWeight.w900,
- ),
+ style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900),
);
} else {
return Listener(
@@ -192,8 +185,7 @@
behavior: HitTestBehavior.opaque,
onScaleStart: _handleScaleStart,
onScaleUpdate: _handleScaleUpdate,
- onTapDown: (TapDownDetails details) =>
- onViewFinderTap(details, constraints),
+ onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints),
);
},
),
@@ -212,10 +204,7 @@
return;
}
- _currentScale = (_baseScale * details.scale).clamp(
- _minAvailableZoom,
- _maxAvailableZoom,
- );
+ _currentScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom);
await controller!.setZoomLevel(_currentScale);
}
@@ -270,16 +259,12 @@
IconButton(
icon: const Icon(Icons.exposure),
color: Colors.blue,
- onPressed: controller != null
- ? onExposureModeButtonPressed
- : null,
+ onPressed: controller != null ? onExposureModeButtonPressed : null,
),
IconButton(
icon: const Icon(Icons.filter_center_focus),
color: Colors.blue,
- onPressed: controller != null
- ? onFocusModeButtonPressed
- : null,
+ onPressed: controller != null ? onFocusModeButtonPressed : null,
),
]
: <Widget>[],
@@ -295,9 +280,7 @@
: Icons.screen_rotation,
),
color: Colors.blue,
- onPressed: controller != null
- ? onCaptureOrientationLockButtonPressed
- : null,
+ onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null,
),
],
),
@@ -317,36 +300,28 @@
children: <Widget>[
IconButton(
icon: const Icon(Icons.flash_off),
- color: controller?.value.flashMode == FlashMode.off
- ? Colors.orange
- : Colors.blue,
+ 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,
+ 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,
+ 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,
+ color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue,
onPressed: controller != null
? () => onSetFlashModeButtonPressed(FlashMode.torch)
: null,
@@ -383,8 +358,7 @@
TextButton(
style: styleAuto,
onPressed: controller != null
- ? () =>
- onSetExposureModeButtonPressed(ExposureMode.auto)
+ ? () => onSetExposureModeButtonPressed(ExposureMode.auto)
: null,
onLongPress: () {
if (controller != null) {
@@ -397,17 +371,13 @@
TextButton(
style: styleLocked,
onPressed: controller != null
- ? () => onSetExposureModeButtonPressed(
- ExposureMode.locked,
- )
+ ? () => 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'),
),
],
@@ -422,9 +392,7 @@
min: _minAvailableExposureOffset,
max: _maxAvailableExposureOffset,
label: _currentExposureOffset.toString(),
- onChanged:
- _minAvailableExposureOffset ==
- _maxAvailableExposureOffset
+ onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset
? null
: setExposureOffset,
),
@@ -440,9 +408,7 @@
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
@@ -518,9 +484,7 @@
: null,
),
IconButton(
- icon:
- cameraController != null &&
- cameraController.value.isRecordingPaused
+ icon: cameraController != null && cameraController.value.isRecordingPaused
? const Icon(Icons.play_arrow)
: const Icon(Icons.pause),
color: Colors.blue,
@@ -545,13 +509,10 @@
),
IconButton(
icon: const Icon(Icons.pause_presentation),
- color:
- cameraController != null && cameraController.value.isPreviewPaused
+ color: cameraController != null && cameraController.value.isPreviewPaused
? Colors.red
: Colors.blue,
- onPressed: cameraController == null
- ? null
- : onPausePreviewButtonPressed,
+ onPressed: cameraController == null ? null : onPausePreviewButtonPressed,
),
],
);
@@ -603,9 +564,7 @@
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) {
@@ -631,9 +590,7 @@
}
}
- Future<void> _initializeCameraController(
- CameraDescription cameraDescription,
- ) async {
+ Future<void> _initializeCameraController(CameraDescription cameraDescription) async {
final cameraController = CameraController(
cameraDescription,
kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium,
@@ -649,9 +606,7 @@
setState(() {});
}
if (cameraController.value.hasError) {
- showInSnackBar(
- 'Camera error ${cameraController.value.errorDescription}',
- );
+ showInSnackBar('Camera error ${cameraController.value.errorDescription}');
}
});
@@ -669,12 +624,8 @@
),
]
: <Future<Object?>>[],
- 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) {
diff --git a/packages/camera/camera/example/test/main_test.dart b/packages/camera/camera/example/test/main_test.dart
index 9563df0..8fd39d6 100644
--- a/packages/camera/camera/example/test/main_test.dart
+++ b/packages/camera/camera/example/test/main_test.dart
@@ -15,9 +15,7 @@
expect(find.byType(SnackBar), findsOneWidget);
});
- testWidgets('CameraDescription toggles will not overflow', (
- WidgetTester tester,
- ) async {
+ testWidgets('CameraDescription toggles will not overflow', (WidgetTester tester) async {
WidgetsFlutterBinding.ensureInitialized();
// Adds 10 fake camera descriptions.
for (var i = 0; i < 10; i++) {
diff --git a/packages/camera/camera/example/test_driver/integration_test.dart b/packages/camera/camera/example/test_driver/integration_test.dart
index ef65f09..39d763c 100644
--- a/packages/camera/camera/example/test_driver/integration_test.dart
+++ b/packages/camera/camera/example/test_driver/integration_test.dart
@@ -39,10 +39,7 @@
]);
print('Starting test.');
final FlutterDriver driver = await FlutterDriver.connect();
- final String data = await driver.requestData(
- null,
- timeout: const Duration(minutes: 1),
- );
+ final String data = await driver.requestData(null, timeout: const Duration(minutes: 1));
await driver.close();
print('Test finished. Revoking camera permissions...');
Process.runSync('adb', <String>[
diff --git a/packages/camera/camera/lib/src/camera_controller.dart b/packages/camera/camera/lib/src/camera_controller.dart
index d941c2e..05d5215 100644
--- a/packages/camera/camera/lib/src/camera_controller.dart
+++ b/packages/camera/camera/lib/src/camera_controller.dart
@@ -185,8 +185,7 @@
flashMode: flashMode ?? this.flashMode,
exposureMode: exposureMode ?? this.exposureMode,
focusMode: focusMode ?? this.focusMode,
- exposurePointSupported:
- exposurePointSupported ?? this.exposurePointSupported,
+ exposurePointSupported: exposurePointSupported ?? this.exposurePointSupported,
focusPointSupported: focusPointSupported ?? this.focusPointSupported,
deviceOrientation: deviceOrientation ?? this.deviceOrientation,
lockedCaptureOrientation: lockedCaptureOrientation == null
@@ -200,8 +199,7 @@
previewPauseOrientation: previewPauseOrientation == null
? this.previewPauseOrientation
: previewPauseOrientation.orNull,
- videoStabilizationMode:
- videoStabilizationMode ?? this.videoStabilizationMode,
+ videoStabilizationMode: videoStabilizationMode ?? this.videoStabilizationMode,
);
}
@@ -272,8 +270,7 @@
/// if unavailable a lower resolution will be used.
///
/// See also: [ResolutionPreset].
- ResolutionPreset get resolutionPreset =>
- mediaSettings.resolutionPreset ?? ResolutionPreset.max;
+ ResolutionPreset get resolutionPreset => mediaSettings.resolutionPreset ?? ResolutionPreset.max;
/// Whether to include audio when recording a video.
bool get enableAudio => mediaSettings.enableAudio;
@@ -303,8 +300,7 @@
// just called). If the controller has not been initialized at least once,
// this value is null.
Future<void>? _initializeFuture;
- StreamSubscription<DeviceOrientationChangedEvent>?
- _deviceOrientationSubscription;
+ StreamSubscription<DeviceOrientationChangedEvent>? _deviceOrientationSubscription;
/// Checks whether [CameraController.dispose] has completed successfully.
///
@@ -358,9 +354,7 @@
);
unawaited(
- CameraPlatform.instance.onCameraError(_cameraId).first.then((
- CameraErrorEvent event,
- ) {
+ CameraPlatform.instance.onCameraError(_cameraId).first.then((CameraErrorEvent event) {
value = value.copyWith(errorDescription: event.description);
}),
);
@@ -374,8 +368,7 @@
isInitialized: true,
description: description,
previewSize: await initializeCompleter.future.then(
- (CameraInitializedEvent event) =>
- Size(event.previewWidth, event.previewHeight),
+ (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight),
),
exposureMode: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposureMode,
@@ -523,11 +516,11 @@
}
try {
- _imageStreamSubscription = CameraPlatform.instance
- .onStreamedFrameAvailable(_cameraId)
- .listen((CameraImageData imageData) {
- onAvailable(CameraImage.fromPlatformInterface(imageData));
- });
+ _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen(
+ (CameraImageData imageData) {
+ onAvailable(CameraImage.fromPlatformInterface(imageData));
+ },
+ );
value = value.copyWith(isStreamingImages: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
@@ -630,9 +623,7 @@
}
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<DeviceOrientation>.absent(),
@@ -742,8 +733,10 @@
}) async {
_throwIfNotInitialized('setVideoStabilizationMode');
try {
- final VideoStabilizationMode? modeToSet =
- await _getVideoStabilizationModeToSet(mode, allowFallback);
+ final VideoStabilizationMode? modeToSet = await _getVideoStabilizationModeToSet(
+ mode,
+ allowFallback,
+ );
// When _getVideoStabilizationModeToSet returns null
// it means that the device doesn't support any
@@ -754,10 +747,7 @@
if (modeToSet == null) {
return;
}
- await CameraPlatform.instance.setVideoStabilizationMode(
- _cameraId,
- modeToSet,
- );
+ await CameraPlatform.instance.setVideoStabilizationMode(_cameraId, modeToSet);
value = value.copyWith(videoStabilizationMode: modeToSet);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
@@ -768,8 +758,7 @@
VideoStabilizationMode requestedMode,
bool allowFallback,
) async {
- final Iterable<VideoStabilizationMode> supportedModes = await CameraPlatform
- .instance
+ final Iterable<VideoStabilizationMode> supportedModes = await CameraPlatform.instance
.getSupportedVideoStabilizationModes(_cameraId);
// If it can't fallback and the specific
@@ -785,9 +774,7 @@
VideoStabilizationMode? fallbackMode = requestedMode;
while (fallbackMode != null && !supportedModes.contains(fallbackMode)) {
- fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(
- fallbackMode,
- );
+ fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(fallbackMode);
}
return fallbackMode;
@@ -797,15 +784,12 @@
/// for the selected camera.
///
/// [VideoStabilizationMode.off] will always be listed.
- Future<Iterable<VideoStabilizationMode>>
- getSupportedVideoStabilizationModes() async {
+ Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes() async {
_throwIfNotInitialized('getSupportedVideoStabilizationModes');
try {
final modes = <VideoStabilizationMode>{
VideoStabilizationMode.off,
- ...await CameraPlatform.instance.getSupportedVideoStabilizationModes(
- _cameraId,
- ),
+ ...await CameraPlatform.instance.getSupportedVideoStabilizationModes(_cameraId),
};
return modes;
} on PlatformException catch (e) {
@@ -838,11 +822,8 @@
/// Supplying a `null` value will reset the exposure point to it's default
/// value.
Future<void> setExposurePoint(Offset? point) async {
- 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).',
- );
+ 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).');
}
try {
@@ -965,9 +946,7 @@
Future<void> unlockCaptureOrientation() async {
try {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
- value = value.copyWith(
- lockedCaptureOrientation: const Optional<DeviceOrientation>.absent(),
- );
+ value = value.copyWith(lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
@@ -978,11 +957,8 @@
/// Supplying a `null` value will reset the focus point to it's default
/// value.
Future<void> setFocusPoint(Offset? point) async {
- 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).',
- );
+ 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).');
}
try {
await CameraPlatform.instance.setFocusPoint(
@@ -995,8 +971,7 @@
}
/// Check whether the camera platform supports image streaming.
- bool supportsImageStreaming() =>
- CameraPlatform.instance.supportsImageStreaming();
+ bool supportsImageStreaming() => CameraPlatform.instance.supportsImageStreaming();
/// Releases the resources of this camera.
@override
@@ -1106,9 +1081,7 @@
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T value) transformer) {
- return _value == null
- ? Optional<S>.absent()
- : Optional<S>.of(transformer(_value));
+ return _value == null ? Optional<S>.absent() : Optional<S>.of(transformer(_value));
}
/// Transforms the Optional value.
@@ -1117,14 +1090,11 @@
///
/// Returns [absent()] if the transformer returns `null`.
Optional<S> transformNullable<S>(S? Function(T value) transformer) {
- return _value == null
- ? Optional<S>.absent()
- : Optional<S>.fromNullable(transformer(_value));
+ return _value == null ? Optional<S>.absent() : Optional<S>.fromNullable(transformer(_value));
}
@override
- Iterator<T> get iterator =>
- isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
+ Iterator<T> get iterator => isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
@@ -1136,8 +1106,6 @@
@override
String toString() {
- return _value == null
- ? 'Optional { absent }'
- : 'Optional { value: $_value }';
+ return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }';
}
}
diff --git a/packages/camera/camera/lib/src/camera_image.dart b/packages/camera/camera/lib/src/camera_image.dart
index f19bc67..b0fbb30 100644
--- a/packages/camera/camera/lib/src/camera_image.dart
+++ b/packages/camera/camera/lib/src/camera_image.dart
@@ -122,9 +122,7 @@
height = data.height,
width = data.width,
planes = List<Plane>.unmodifiable(
- data.planes.map<Plane>(
- (CameraImagePlane plane) => Plane._fromPlatformInterface(plane),
- ),
+ data.planes.map<Plane>((CameraImagePlane plane) => Plane._fromPlatformInterface(plane)),
),
lensAperture = data.lensAperture,
sensorExposureTime = data.sensorExposureTime,
@@ -141,8 +139,7 @@
sensorSensitivity = data['sensorSensitivity'] as double?,
planes = List<Plane>.unmodifiable(
(data['planes'] as List<dynamic>).map<Plane>(
- (dynamic planeData) =>
- Plane._fromPlatformData(planeData as Map<dynamic, dynamic>),
+ (dynamic planeData) => Plane._fromPlatformData(planeData as Map<dynamic, dynamic>),
),
);
diff --git a/packages/camera/camera/test/camera_image_stream_test.dart b/packages/camera/camera/test/camera_image_stream_test.dart
index 0a9644f..e9c12af 100644
--- a/packages/camera/camera/test/camera_image_stream_test.dart
+++ b/packages/camera/camera/test/camera_image_stream_test.dart
@@ -33,11 +33,7 @@
() => cameraController.startImageStream((CameraImage image) {}),
throwsA(
isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'Uninitialized CameraController',
- )
+ .having((CameraException error) => error.code, 'code', 'Uninitialized CameraController')
.having(
(CameraException error) => error.description,
'description',
@@ -47,64 +43,54 @@
);
});
- test(
- 'startImageStream() throws $CameraException when recording videos',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('startImageStream() throws $CameraException when recording videos', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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(
- () => cameraController.startImageStream((CameraImage image) {}),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'A video recording is already started.',
- 'startImageStream was called while a video is being recorded.',
- ),
+ expect(
+ () => cameraController.startImageStream((CameraImage image) {}),
+ throwsA(
+ isA<CameraException>().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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ ),
+ );
+ });
+ test('startImageStream() throws $CameraException when already streaming images', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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<CameraException>().having(
- (CameraException error) => error.description,
- 'A camera has started streaming images.',
- 'startImageStream was called while a camera was streaming images.',
- ),
+ cameraController.value = cameraController.value.copyWith(isStreamingImages: true);
+ expect(
+ () => cameraController.startImageStream((CameraImage image) {}),
+ throwsA(
+ isA<CameraException>().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(
@@ -140,11 +126,7 @@
cameraController.stopImageStream,
throwsA(
isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'Uninitialized CameraController',
- )
+ .having((CameraException error) => error.code, 'code', 'Uninitialized CameraController')
.having(
(CameraException error) => error.description,
'description',
@@ -154,31 +136,28 @@
);
});
- test(
- 'stopImageStream() throws $CameraException when not streaming images',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('stopImageStream() throws $CameraException when not streaming images', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
- expect(
- cameraController.stopImageStream,
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'No camera is streaming images',
- 'stopImageStream was called when no camera is streaming images.',
- ),
+ expect(
+ cameraController.stopImageStream,
+ throwsA(
+ isA<CameraException>().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(
@@ -214,14 +193,9 @@
await cameraController.initialize();
- await cameraController.startVideoRecording(
- onAvailable: (CameraImage image) {},
- );
+ await cameraController.startVideoRecording(onAvailable: (CameraImage image) {});
- expect(
- mockPlatform.streamCallLog.contains('startVideoCapturing with stream'),
- isTrue,
- );
+ expect(mockPlatform.streamCallLog.contains('startVideoCapturing with stream'), isTrue);
});
test('startVideoRecording() by default does not stream', () async {
diff --git a/packages/camera/camera/test/camera_image_test.dart b/packages/camera/camera/test/camera_image_test.dart
index 6eb5944..7771b4c 100644
--- a/packages/camera/camera/test/camera_image_test.dart
+++ b/packages/camera/camera/test/camera_image_test.dart
@@ -47,17 +47,11 @@
// Planes.
expect(image.planes.length, originalImage.planes.length);
for (var i = 0; i < image.planes.length; i++) {
- expect(
- image.planes[i].bytes.length,
- originalImage.planes[i].bytes.length,
- );
+ expect(image.planes[i].bytes.length, originalImage.planes[i].bytes.length);
for (var 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,
- );
+ expect(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);
diff --git a/packages/camera/camera/test/camera_preview_test.dart b/packages/camera/camera/test/camera_preview_test.dart
index 912a583..c5dfde4 100644
--- a/packages/camera/camera/test/camera_preview_test.dart
+++ b/packages/camera/camera/test/camera_preview_test.dart
@@ -10,8 +10,7 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
-class FakeController extends ValueNotifier<CameraValue>
- implements CameraController {
+class FakeController extends ValueNotifier<CameraValue> implements CameraController {
FakeController() : super(const CameraValue.uninitialized(fakeDescription));
static const CameraDescription fakeDescription = CameraDescription(
@@ -146,8 +145,8 @@
}) async {}
@override
- Future<Iterable<VideoStabilizationMode>>
- getSupportedVideoStabilizationModes() async => <VideoStabilizationMode>[];
+ Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes() async =>
+ <VideoStabilizationMode>[];
@override
bool supportsImageStreaming() => true;
@@ -167,10 +166,9 @@
isInitialized: true,
isRecordingVideo: true,
deviceOrientation: DeviceOrientation.portraitDown,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.landscapeRight,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.landscapeRight,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.portraitUp,
),
@@ -178,16 +176,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 0);
debugDefaultTargetPlatformOverride = null;
@@ -206,10 +199,9 @@
isInitialized: true,
isRecordingVideo: true,
deviceOrientation: DeviceOrientation.portraitUp,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.landscapeLeft,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.landscapeLeft,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.landscapeRight,
),
@@ -217,16 +209,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 1);
debugDefaultTargetPlatformOverride = null;
@@ -245,10 +232,9 @@
isInitialized: true,
isRecordingVideo: true,
deviceOrientation: DeviceOrientation.portraitUp,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.landscapeRight,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.landscapeRight,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.portraitDown,
),
@@ -256,16 +242,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 2);
debugDefaultTargetPlatformOverride = null;
@@ -284,10 +265,9 @@
isInitialized: true,
isRecordingVideo: true,
deviceOrientation: DeviceOrientation.portraitUp,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.landscapeRight,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.landscapeRight,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.landscapeLeft,
),
@@ -295,16 +275,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 3);
debugDefaultTargetPlatformOverride = null;
@@ -322,10 +297,9 @@
controller.value = controller.value.copyWith(
isInitialized: true,
deviceOrientation: DeviceOrientation.portraitDown,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.portraitUp,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.portraitUp,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.landscapeLeft,
),
@@ -333,16 +307,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 0);
debugDefaultTargetPlatformOverride = null;
@@ -360,10 +329,9 @@
controller.value = controller.value.copyWith(
isInitialized: true,
deviceOrientation: DeviceOrientation.portraitDown,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.landscapeRight,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.landscapeRight,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.landscapeLeft,
),
@@ -371,16 +339,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 1);
debugDefaultTargetPlatformOverride = null;
@@ -398,10 +361,9 @@
controller.value = controller.value.copyWith(
isInitialized: true,
deviceOrientation: DeviceOrientation.portraitUp,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.portraitDown,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.portraitDown,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.landscapeLeft,
),
@@ -409,16 +371,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 2);
debugDefaultTargetPlatformOverride = null;
@@ -436,10 +393,9 @@
controller.value = controller.value.copyWith(
isInitialized: true,
deviceOrientation: DeviceOrientation.portraitUp,
- lockedCaptureOrientation:
- const Optional<DeviceOrientation>.fromNullable(
- DeviceOrientation.landscapeRight,
- ),
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable(
+ DeviceOrientation.landscapeRight,
+ ),
recordingOrientation: const Optional<DeviceOrientation>.fromNullable(
DeviceOrientation.landscapeLeft,
),
@@ -447,16 +403,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 1);
debugDefaultTargetPlatformOverride = null;
@@ -481,16 +432,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 0);
debugDefaultTargetPlatformOverride = null;
@@ -515,16 +461,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 1);
debugDefaultTargetPlatformOverride = null;
@@ -549,16 +490,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 2);
debugDefaultTargetPlatformOverride = null;
@@ -583,16 +519,11 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsOneWidget);
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.quarterTurns, 3);
debugDefaultTargetPlatformOverride = null;
@@ -600,9 +531,7 @@
);
}, 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 controller = FakeController();
addTearDown(controller.dispose);
@@ -612,10 +541,7 @@
);
await tester.pumpWidget(
- Directionality(
- textDirection: TextDirection.ltr,
- child: CameraPreview(controller),
- ),
+ Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)),
);
expect(find.byType(RotatedBox), findsNothing);
expect(find.byType(Texture), findsOneWidget);
diff --git a/packages/camera/camera/test/camera_test.dart b/packages/camera/camera/test/camera_test.dart
index 913d339..8366e41 100644
--- a/packages/camera/camera/test/camera_test.dart
+++ b/packages/camera/camera/test/camera_test.dart
@@ -30,23 +30,14 @@
int get mockInitializeCamera => 13;
CameraInitializedEvent get mockOnCameraInitializedEvent =>
- const CameraInitializedEvent(
- 13,
- 75,
- 75,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- );
+ const CameraInitializedEvent(13, 75, 75, ExposureMode.auto, true, FocusMode.auto, true);
DeviceOrientationChangedEvent get mockOnDeviceOrientationChangedEvent =>
const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
CameraClosingEvent get mockOnCameraClosingEvent => const CameraClosingEvent(13);
-CameraErrorEvent get mockOnCameraErrorEvent =>
- const CameraErrorEvent(13, 'closing');
+CameraErrorEvent get mockOnCameraErrorEvent => const CameraErrorEvent(13, 'closing');
XFile mockTakePicture = XFile('foo/bar.png');
@@ -58,27 +49,21 @@
WidgetsFlutterBinding.ensureInitialized();
group('camera', () {
- test(
- 'debugCheckIsDisposed should not throw assertion error when disposed',
- () {
- const description = MockCameraDescription();
- final controller = CameraController(description, ResolutionPreset.low);
+ test('debugCheckIsDisposed should not throw assertion error when disposed', () {
+ const description = MockCameraDescription();
+ final 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 description = MockCameraDescription();
- final controller = CameraController(description, ResolutionPreset.low);
+ test('debugCheckIsDisposed should throw assertion error when not disposed', () {
+ const description = MockCameraDescription();
+ final controller = CameraController(description, ResolutionPreset.low);
- expect(() => controller.debugCheckIsDisposed(), throwsAssertionError);
- },
- );
+ expect(() => controller.debugCheckIsDisposed(), throwsAssertionError);
+ });
test('availableCameras() has camera', () async {
CameraPlatform.instance = MockCameraPlatform();
@@ -204,33 +189,26 @@
);
});
- test(
- 'initialize() throws $CameraException on $PlatformException ',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('initialize() throws $CameraException on $PlatformException ', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
- mockPlatformException = true;
+ mockPlatformException = true;
- expect(
- cameraController.initialize,
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'foo',
- 'bar',
- ),
- ),
- );
- mockPlatformException = false;
- },
- );
+ expect(
+ cameraController.initialize,
+ throwsA(
+ isA<CameraException>().having((CameraException error) => error.description, 'foo', 'bar'),
+ ),
+ );
+ mockPlatformException = false;
+ });
test('initialize() sets imageFormat', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
@@ -245,52 +223,45 @@
);
await cameraController.initialize();
verify(
- CameraPlatform.instance.initializeCamera(
- 13,
- imageFormatGroup: ImageFormatGroup.yuv420,
- ),
+ CameraPlatform.instance.initializeCamera(13, imageFormatGroup: ImageFormatGroup.yuv420),
).called(1);
});
- test(
- 'setDescription waits for initialize before calling dispose',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
+ test('setDescription waits for initialize before calling dispose', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ imageFormatGroup: ImageFormatGroup.bgra8888,
+ );
+
+ final initializeCompleter = Completer<void>();
+ when(
+ CameraPlatform.instance.initializeCamera(
+ mockInitializeCamera,
imageFormatGroup: ImageFormatGroup.bgra8888,
- );
+ ),
+ ).thenAnswer((_) => initializeCompleter.future);
- final initializeCompleter = Completer<void>();
- when(
- CameraPlatform.instance.initializeCamera(
- mockInitializeCamera,
- imageFormatGroup: ImageFormatGroup.bgra8888,
- ),
- ).thenAnswer((_) => initializeCompleter.future);
+ unawaited(cameraController.initialize());
- unawaited(cameraController.initialize());
+ final Future<void> setDescriptionFuture = cameraController.setDescription(
+ const CameraDescription(
+ name: 'cam2',
+ lensDirection: CameraLensDirection.front,
+ sensorOrientation: 90,
+ ),
+ );
+ verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera));
- final Future<void> setDescriptionFuture = cameraController
- .setDescription(
- const CameraDescription(
- name: 'cam2',
- lensDirection: CameraLensDirection.front,
- sensorOrientation: 90,
- ),
- );
- verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera));
+ initializeCompleter.complete();
- initializeCompleter.complete();
-
- await setDescriptionFuture;
- verify(CameraPlatform.instance.dispose(mockInitializeCamera));
- },
- );
+ await setDescriptionFuture;
+ verify(CameraPlatform.instance.dispose(mockInitializeCamera));
+ });
test('prepareForVideoRecording() calls $CameraPlatform ', () async {
final cameraController = CameraController(
@@ -335,34 +306,29 @@
);
});
- test(
- 'takePicture() throws $CameraException when takePicture is true',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('takePicture() throws $CameraException when takePicture is true', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
- cameraController.value = cameraController.value.copyWith(
- isTakingPicture: true,
- );
- expect(
- cameraController.takePicture(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'Previous capture has not returned yet.',
- 'takePicture was called before the previous capture returned.',
- ),
+ cameraController.value = cameraController.value.copyWith(isTakingPicture: true);
+ expect(
+ cameraController.takePicture(),
+ throwsA(
+ isA<CameraException>().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(
@@ -379,125 +345,107 @@
expect(xFile.path, mockTakePicture.path);
});
- test(
- 'takePicture() throws $CameraException on $PlatformException',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('takePicture() throws $CameraException on $PlatformException', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
- mockPlatformException = true;
- expect(
- cameraController.takePicture(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'foo',
- 'bar',
- ),
- ),
- );
- mockPlatformException = false;
- },
- );
+ mockPlatformException = true;
+ expect(
+ cameraController.takePicture(),
+ throwsA(
+ isA<CameraException>().having((CameraException error) => error.description, 'foo', 'bar'),
+ ),
+ );
+ mockPlatformException = false;
+ });
- test(
- 'startVideoRecording() throws $CameraException when uninitialized',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('startVideoRecording() throws $CameraException when uninitialized', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
- expect(
- cameraController.startVideoRecording(),
- throwsA(
- isA<CameraException>()
- .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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ expect(
+ cameraController.startVideoRecording(),
+ throwsA(
+ isA<CameraException>()
+ .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(
+ const CameraDescription(
+ 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(
- cameraController.startVideoRecording(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'A video recording is already started.',
- 'startVideoRecording was called when a recording is already started.',
- ),
+ expect(
+ cameraController.startVideoRecording(),
+ throwsA(
+ isA<CameraException>().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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('getMaxZoomLevel() throws $CameraException when uninitialized', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
- expect(
- cameraController.getMaxZoomLevel,
- throwsA(
- isA<CameraException>()
- .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<CameraException>()
+ .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(
@@ -516,11 +464,7 @@
cameraController.getMaxZoomLevel,
throwsA(
isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'Disposed CameraController',
- )
+ .having((CameraException error) => error.code, 'code', 'Disposed CameraController')
.having(
(CameraException error) => error.description,
'description',
@@ -530,43 +474,34 @@
);
});
- test(
- 'getMaxZoomLevel() throws $CameraException when a platform exception occured.',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('getMaxZoomLevel() throws $CameraException when a platform exception occured.', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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(
- cameraController.getMaxZoomLevel,
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'TEST_ERROR',
- )
- .having(
- (CameraException error) => error.description,
- 'description',
- 'This is a test error messge',
- ),
- ),
- );
- },
- );
+ expect(
+ cameraController.getMaxZoomLevel,
+ throwsA(
+ isA<CameraException>()
+ .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(
@@ -587,36 +522,33 @@
expect(maxZoomLevel, 42.0);
});
- test(
- 'getMinZoomLevel() throws $CameraException when uninitialized',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('getMinZoomLevel() throws $CameraException when uninitialized', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
- expect(
- cameraController.getMinZoomLevel,
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'Uninitialized CameraController',
- )
- .having(
- (CameraException error) => error.description,
- 'description',
- 'getMinZoomLevel() was called on an uninitialized CameraController.',
- ),
- ),
- );
- },
- );
+ expect(
+ cameraController.getMinZoomLevel,
+ throwsA(
+ isA<CameraException>()
+ .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(
@@ -635,11 +567,7 @@
cameraController.getMinZoomLevel,
throwsA(
isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'Disposed CameraController',
- )
+ .having((CameraException error) => error.code, 'code', 'Disposed CameraController')
.having(
(CameraException error) => error.description,
'description',
@@ -649,43 +577,34 @@
);
});
- test(
- 'getMinZoomLevel() throws $CameraException when a platform exception occured.',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('getMinZoomLevel() throws $CameraException when a platform exception occured.', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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(
- cameraController.getMinZoomLevel,
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'TEST_ERROR',
- )
- .having(
- (CameraException error) => error.description,
- 'description',
- 'This is a test error messge',
- ),
- ),
- );
- },
- );
+ expect(
+ cameraController.getMinZoomLevel,
+ throwsA(
+ isA<CameraException>()
+ .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(
@@ -751,11 +670,7 @@
() => cameraController.setZoomLevel(42.0),
throwsA(
isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'Disposed CameraController',
- )
+ .having((CameraException error) => error.code, 'code', 'Disposed CameraController')
.having(
(CameraException error) => error.description,
'description',
@@ -765,66 +680,52 @@
);
});
- test(
- 'setZoomLevel() throws $CameraException when a platform exception occured.',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('setZoomLevel() throws $CameraException when a platform exception occured.', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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(
- () => cameraController.setZoomLevel(42),
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException error) => error.code,
- 'code',
- 'TEST_ERROR',
- )
- .having(
- (CameraException error) => error.description,
- 'description',
- 'This is a test error messge',
- ),
- ),
- );
+ expect(
+ () => cameraController.setZoomLevel(42),
+ throwsA(
+ isA<CameraException>()
+ .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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('setZoomLevel() completes and calls method channel with correct value.', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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(
@@ -840,50 +741,36 @@
await cameraController.setFlashMode(FlashMode.always);
verify(
- CameraPlatform.instance.setFlashMode(
- cameraController.cameraId,
- FlashMode.always,
- ),
+ CameraPlatform.instance.setFlashMode(cameraController.cameraId, FlashMode.always),
).called(1);
});
- test(
- 'setFlashMode() throws $CameraException on $PlatformException',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('setFlashMode() throws $CameraException on $PlatformException', () async {
+ final 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',
- ),
- );
+ when(
+ CameraPlatform.instance.setFlashMode(cameraController.cameraId, FlashMode.always),
+ ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message'));
- expect(
- cameraController.setFlashMode(FlashMode.always),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.setFlashMode(FlashMode.always),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('setExposureMode() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -899,50 +786,36 @@
await cameraController.setExposureMode(ExposureMode.auto);
verify(
- CameraPlatform.instance.setExposureMode(
- cameraController.cameraId,
- ExposureMode.auto,
- ),
+ CameraPlatform.instance.setExposureMode(cameraController.cameraId, ExposureMode.auto),
).called(1);
});
- test(
- 'setExposureMode() throws $CameraException on $PlatformException',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('setExposureMode() throws $CameraException on $PlatformException', () async {
+ final 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',
- ),
- );
+ when(
+ CameraPlatform.instance.setExposureMode(cameraController.cameraId, ExposureMode.auto),
+ ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message'));
- expect(
- cameraController.setExposureMode(ExposureMode.auto),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.setExposureMode(ExposureMode.auto),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('setExposurePoint() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -965,43 +838,35 @@
).called(1);
});
- test(
- 'setExposurePoint() throws $CameraException on $PlatformException',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('setExposurePoint() throws $CameraException on $PlatformException', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
- when(
- CameraPlatform.instance.setExposurePoint(
- cameraController.cameraId,
- const Point<double>(0.5, 0.5),
- ),
- ).thenThrow(
- PlatformException(
- code: 'TEST_ERROR',
- message: 'This is a test error message',
- ),
- );
+ when(
+ CameraPlatform.instance.setExposurePoint(
+ cameraController.cameraId,
+ const Point<double>(0.5, 0.5),
+ ),
+ ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message'));
- expect(
- cameraController.setExposurePoint(const Offset(0.5, 0.5)),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.setExposurePoint(const Offset(0.5, 0.5)),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('getMinExposureOffset() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -1020,44 +885,35 @@
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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('getMinExposureOffset() throws $CameraException on $PlatformException', () async {
+ final 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'),
- );
+ when(
+ CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId),
+ ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message'));
- expect(
- cameraController.getMinExposureOffset(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.getMinExposureOffset(),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('getMaxExposureOffset() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -1076,44 +932,35 @@
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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('getMaxExposureOffset() throws $CameraException on $PlatformException', () async {
+ final 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'),
- );
+ when(
+ CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId),
+ ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message'));
- expect(
- cameraController.getMaxExposureOffset(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.getMaxExposureOffset(),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('getExposureOffsetStepSize() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -1127,53 +974,42 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getExposureOffsetStepSize(
- cameraController.cameraId,
- ),
+ CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId),
).thenAnswer((_) => Future<double>.value(0.0));
await cameraController.getExposureOffsetStepSize();
verify(
- CameraPlatform.instance.getExposureOffsetStepSize(
- cameraController.cameraId,
- ),
+ CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId),
).called(1);
});
- test(
- 'getExposureOffsetStepSize() throws $CameraException on $PlatformException',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('getExposureOffsetStepSize() throws $CameraException on $PlatformException', () async {
+ final 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'),
- );
+ when(
+ CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId),
+ ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message'));
- expect(
- cameraController.getExposureOffsetStepSize(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.getExposureOffsetStepSize(),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('setExposureOffset() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -1192,167 +1028,110 @@
CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId),
).thenAnswer((_) async => 2.0);
when(
- CameraPlatform.instance.getExposureOffsetStepSize(
- cameraController.cameraId,
- ),
+ CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId),
).thenAnswer((_) async => 1.0);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- 1.0,
- ),
+ 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(
- 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'),
- );
+ test('setExposureOffset() throws $CameraException on $PlatformException', () async {
+ final 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'));
- expect(
- cameraController.setExposureOffset(1.0),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.setExposureOffset(1.0),
+ throwsA(
+ isA<CameraException>().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(
- 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);
+ test('setExposureOffset() throws $CameraException when offset is out of bounds', () async {
+ final 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(
- cameraController.setExposureOffset(3.0),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'exposureOffsetOutOfBounds',
- 'The provided exposure offset was outside the supported range for this device.',
- ),
+ expect(
+ cameraController.setExposureOffset(3.0),
+ throwsA(
+ isA<CameraException>().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<CameraException>().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<CameraException>().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);
+ 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);
- },
- );
+ 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(
@@ -1371,52 +1150,29 @@
CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId),
).thenAnswer((_) async => 1.2);
when(
- CameraPlatform.instance.getExposureOffsetStepSize(
- cameraController.cameraId,
- ),
+ CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId),
).thenAnswer((_) async => 0.4);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- -1.2,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -1.2),
).thenAnswer((_) async => -1.2);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- -0.8,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -0.8),
).thenAnswer((_) async => -0.8);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- -0.4,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -0.4),
).thenAnswer((_) async => -0.4);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- 0.0,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.0),
).thenAnswer((_) async => 0.0);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- 0.4,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.4),
).thenAnswer((_) async => 0.4);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- 0.8,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.8),
).thenAnswer((_) async => 0.8);
when(
- CameraPlatform.instance.setExposureOffset(
- cameraController.cameraId,
- 1.2,
- ),
+ CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 1.2),
).thenAnswer((_) async => 1.2);
await cameraController.setExposureOffset(1.2);
@@ -1436,36 +1192,11 @@
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(
@@ -1483,9 +1214,7 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer((_) async => <VideoStabilizationMode>[]);
// act
@@ -1512,12 +1241,8 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
// act
final Iterable<VideoStabilizationMode> modes = await cameraController
@@ -1528,81 +1253,71 @@
},
);
- test(
- 'getSupportedVideoStabilizationModes() returns off and level1',
- () async {
- // arrange
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ test('getSupportedVideoStabilizationModes() returns off and level1', () async {
+ // arrange
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
- await cameraController.initialize();
- when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[
- VideoStabilizationMode.off,
- VideoStabilizationMode.level1,
- ],
- );
-
- // act
- final Iterable<VideoStabilizationMode> modes = await cameraController
- .getSupportedVideoStabilizationModes();
-
- // assert
- expect(modes, <VideoStabilizationMode>[
+ await cameraController.initialize();
+ when(
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer(
+ (_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
VideoStabilizationMode.level1,
- ]);
- },
- );
+ ],
+ );
- test(
- 'getSupportedVideoStabilizationModes() returns off, level1 and level2',
- () async {
- // arrange
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
+ // act
+ final Iterable<VideoStabilizationMode> modes = await cameraController
+ .getSupportedVideoStabilizationModes();
- await cameraController.initialize();
- when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[
- VideoStabilizationMode.off,
- VideoStabilizationMode.level1,
- VideoStabilizationMode.level2,
- ],
- );
+ // assert
+ expect(modes, <VideoStabilizationMode>[
+ VideoStabilizationMode.off,
+ VideoStabilizationMode.level1,
+ ]);
+ });
- // act
- final Iterable<VideoStabilizationMode> modes = await cameraController
- .getSupportedVideoStabilizationModes();
+ test('getSupportedVideoStabilizationModes() returns off, level1 and level2', () async {
+ // arrange
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
- // assert
- expect(modes, <VideoStabilizationMode>[
+ await cameraController.initialize();
+ when(
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer(
+ (_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
VideoStabilizationMode.level1,
VideoStabilizationMode.level2,
- ]);
- },
- );
+ ],
+ );
+
+ // act
+ final Iterable<VideoStabilizationMode> modes = await cameraController
+ .getSupportedVideoStabilizationModes();
+
+ // assert
+ expect(modes, <VideoStabilizationMode>[
+ VideoStabilizationMode.off,
+ VideoStabilizationMode.level1,
+ VideoStabilizationMode.level2,
+ ]);
+ });
test('getSupportedVideoStabilizationModes() returns all modes', () async {
// arrange
@@ -1617,9 +1332,7 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -1642,56 +1355,44 @@
]);
});
- test(
- 'setVideoStabilizationMode() throws $CameraException on $PlatformException',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
+ test('setVideoStabilizationMode() throws $CameraException on $PlatformException', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
- when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[
- VideoStabilizationMode.off,
- VideoStabilizationMode.level1,
- ],
- );
+ when(
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer(
+ (_) async => <VideoStabilizationMode>[
+ VideoStabilizationMode.off,
+ VideoStabilizationMode.level1,
+ ],
+ );
- when(
- CameraPlatform.instance.setVideoStabilizationMode(
- cameraController.cameraId,
- VideoStabilizationMode.level1,
- ),
- ).thenThrow(
- PlatformException(
- code: 'TEST_ERROR',
- message: 'This is a test error message',
- ),
- );
+ when(
+ CameraPlatform.instance.setVideoStabilizationMode(
+ cameraController.cameraId,
+ VideoStabilizationMode.level1,
+ ),
+ ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message'));
- expect(
- cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level1,
+ expect(
+ cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
- ),
- );
- },
- );
+ ),
+ );
+ });
test(
'setVideoStabilizationMode() with fallback never calls CameraPlatform.instance.setVideoStabilizationMode when no supported mode is available',
@@ -1712,26 +1413,16 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer((_) async => <VideoStabilizationMode>[]);
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.off,
- );
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level1,
- );
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level2,
- );
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level3,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off);
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1);
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2);
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3);
// assert
verifyNever(
@@ -1782,19 +1473,13 @@
),
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.off,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off);
// assert
verify(
@@ -1847,19 +1532,13 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level1,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1);
// assert
verify(
@@ -1911,19 +1590,13 @@
),
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level2,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2);
// assert
verify(
@@ -1975,19 +1648,13 @@
),
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level3,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3);
// assert
verify(
@@ -2039,9 +1706,7 @@
),
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2052,9 +1717,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.off,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off);
// assert
verify(
@@ -2107,9 +1770,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2119,9 +1780,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level1,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1);
// assert
verify(
@@ -2174,9 +1833,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2187,9 +1844,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level2,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2);
// assert
verify(
@@ -2242,9 +1897,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2255,9 +1908,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level3,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3);
// assert
verify(
@@ -2310,9 +1961,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2325,9 +1974,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.off,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off);
// assert
verify(
@@ -2379,9 +2026,7 @@
),
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2394,9 +2039,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level1,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1);
// assert
verify(
@@ -2449,9 +2092,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2464,9 +2105,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level2,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2);
// assert
verify(
@@ -2519,9 +2158,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -2534,9 +2171,7 @@
clearInteractions(CameraPlatform.instance);
// act
- await cameraController.setVideoStabilizationMode(
- VideoStabilizationMode.level3,
- );
+ await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3);
// assert
verify(
@@ -2582,9 +2217,7 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer((_) async => <VideoStabilizationMode>[]);
clearInteractions(CameraPlatform.instance);
@@ -2638,9 +2271,7 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer((_) async => <VideoStabilizationMode>[]);
clearInteractions(CameraPlatform.instance);
@@ -2652,13 +2283,7 @@
VideoStabilizationMode.level1,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -2704,9 +2329,7 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer((_) async => <VideoStabilizationMode>[]);
clearInteractions(CameraPlatform.instance);
@@ -2718,13 +2341,7 @@
VideoStabilizationMode.level2,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -2770,9 +2387,7 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer((_) async => <VideoStabilizationMode>[]);
clearInteractions(CameraPlatform.instance);
@@ -2784,13 +2399,7 @@
VideoStabilizationMode.level3,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -2843,12 +2452,8 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
@@ -2902,12 +2507,8 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
@@ -2918,13 +2519,7 @@
VideoStabilizationMode.level1,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -2970,12 +2565,8 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
@@ -2986,13 +2577,7 @@
VideoStabilizationMode.level2,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -3038,12 +2623,8 @@
await cameraController.initialize();
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
- ).thenAnswer(
- (_) async => <VideoStabilizationMode>[VideoStabilizationMode.off],
- );
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
+ ).thenAnswer((_) async => <VideoStabilizationMode>[VideoStabilizationMode.off]);
clearInteractions(CameraPlatform.instance);
@@ -3054,13 +2635,7 @@
VideoStabilizationMode.level3,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -3113,9 +2688,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3182,9 +2755,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3251,9 +2822,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3270,13 +2839,7 @@
VideoStabilizationMode.level2,
allowFallback: false,
),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError error) => error.name,
- 'name',
- 'mode',
- ),
- ),
+ throwsA(isA<ArgumentError>().having((ArgumentError error) => error.name, 'name', 'mode')),
);
// assert
@@ -3329,9 +2892,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3400,9 +2961,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3478,9 +3037,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3549,9 +3106,7 @@
).thenAnswer((_) => Future<void>(() {}));
when(
- CameraPlatform.instance.getSupportedVideoStabilizationModes(
- mockInitializeCamera,
- ),
+ CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera),
).thenAnswer(
(_) async => <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -3614,107 +3169,81 @@
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);
+ });
+
+ test('pausePreview() does not call $CameraPlatform when already paused', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
+ cameraController.value = cameraController.value.copyWith(isPreviewPaused: true);
+
+ await cameraController.pausePreview();
+
+ verifyNever(CameraPlatform.instance.pausePreview(cameraController.cameraId));
+ expect(cameraController.value.isPreviewPaused, equals(true));
+ });
+
+ test('pausePreview() sets previewPauseOrientation according to locked orientation', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ name: 'cam',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 90,
+ ),
+ ResolutionPreset.max,
+ );
+ await cameraController.initialize();
+ cameraController.value = cameraController.value.copyWith(
+ isPreviewPaused: false,
+ deviceOrientation: DeviceOrientation.portraitUp,
+ lockedCaptureOrientation: const Optional<DeviceOrientation>.of(
+ DeviceOrientation.landscapeRight,
+ ),
+ );
+
+ await cameraController.pausePreview();
+
+ expect(cameraController.value.deviceOrientation, equals(DeviceOrientation.portraitUp));
expect(
cameraController.value.previewPauseOrientation,
- DeviceOrientation.portraitUp,
+ equals(DeviceOrientation.landscapeRight),
);
});
- test(
- 'pausePreview() does not call $CameraPlatform when already paused',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
+ test('pausePreview() throws $CameraException on $PlatformException', () async {
+ final 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'));
+
+ expect(
+ cameraController.pausePreview(),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
- cameraController.value = cameraController.value.copyWith(
- isPreviewPaused: true,
- );
-
- await cameraController.pausePreview();
-
- verifyNever(
- CameraPlatform.instance.pausePreview(cameraController.cameraId),
- );
- expect(cameraController.value.isPreviewPaused, equals(true));
- },
- );
-
- test(
- 'pausePreview() sets previewPauseOrientation according to locked orientation',
- () async {
- final cameraController = CameraController(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
- cameraController.value = cameraController.value.copyWith(
- isPreviewPaused: false,
- deviceOrientation: DeviceOrientation.portraitUp,
- lockedCaptureOrientation: const Optional<DeviceOrientation>.of(
- DeviceOrientation.landscapeRight,
- ),
- );
-
- await cameraController.pausePreview();
-
- expect(
- cameraController.value.deviceOrientation,
- equals(DeviceOrientation.portraitUp),
- );
- expect(
- cameraController.value.previewPauseOrientation,
- equals(DeviceOrientation.landscapeRight),
- );
- },
- );
-
- test(
- 'pausePreview() throws $CameraException on $PlatformException',
- () async {
- final 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',
- ),
- );
-
- expect(
- cameraController.pausePreview(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
- ),
- );
- },
- );
+ ),
+ );
+ });
test('resumePreview() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -3726,79 +3255,58 @@
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(
- const CameraDescription(
- name: 'cam',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 90,
- ),
- ResolutionPreset.max,
- );
- await cameraController.initialize();
- cameraController.value = cameraController.value.copyWith(
- isPreviewPaused: false,
- );
+ test('resumePreview() does not call $CameraPlatform when not paused', () async {
+ final cameraController = CameraController(
+ const CameraDescription(
+ 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(
- 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',
- ),
- );
+ test('resumePreview() throws $CameraException on $PlatformException', () async {
+ final 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'));
- expect(
- cameraController.resumePreview(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.resumePreview(),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('lockCaptureOrientation() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -3812,13 +3320,8 @@
await cameraController.initialize();
await cameraController.lockCaptureOrientation();
- expect(
- cameraController.value.lockedCaptureOrientation,
- equals(DeviceOrientation.portraitUp),
- );
- await cameraController.lockCaptureOrientation(
- DeviceOrientation.landscapeRight,
- );
+ expect(cameraController.value.lockedCaptureOrientation, equals(DeviceOrientation.portraitUp));
+ await cameraController.lockCaptureOrientation(DeviceOrientation.landscapeRight);
expect(
cameraController.value.lockedCaptureOrientation,
equals(DeviceOrientation.landscapeRight),
@@ -3838,42 +3341,34 @@
).called(1);
});
- test(
- 'lockCaptureOrientation() throws $CameraException on $PlatformException',
- () async {
- final 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',
- ),
- );
+ test('lockCaptureOrientation() throws $CameraException on $PlatformException', () async {
+ final 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'));
- expect(
- cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('unlockCaptureOrientation() calls $CameraPlatform', () async {
final cameraController = CameraController(
@@ -3889,48 +3384,34 @@
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(
- 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',
- ),
- );
+ test('unlockCaptureOrientation() throws $CameraException on $PlatformException', () async {
+ final 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'));
- expect(
- cameraController.unlockCaptureOrientation(),
- throwsA(
- isA<CameraException>().having(
- (CameraException error) => error.description,
- 'TEST_ERROR',
- 'This is a test error message',
- ),
+ expect(
+ cameraController.unlockCaptureOrientation(),
+ throwsA(
+ isA<CameraException>().having(
+ (CameraException error) => error.description,
+ 'TEST_ERROR',
+ 'This is a test error message',
),
- );
- },
- );
+ ),
+ );
+ });
test('error from onCameraError is received', () async {
final cameraController = CameraController(
@@ -3944,17 +3425,12 @@
await cameraController.initialize();
expect(cameraController.value.hasError, isTrue);
- expect(
- cameraController.value.errorDescription,
- mockOnCameraErrorEvent.description,
- );
+ expect(cameraController.value.errorDescription, mockOnCameraErrorEvent.description);
});
});
}
-class MockCameraPlatform extends Mock
- with MockPlatformInterfaceMixin
- implements CameraPlatform {
+class MockCameraPlatform extends Mock with MockPlatformInterfaceMixin implements CameraPlatform {
@override
Future<void> initializeCamera(
int? cameraId, {
@@ -4005,9 +3481,7 @@
@override
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() =>
- Stream<DeviceOrientationChangedEvent>.value(
- mockOnDeviceOrientationChangedEvent,
- );
+ Stream<DeviceOrientationChangedEvent>.value(mockOnDeviceOrientationChangedEvent);
@override
Future<XFile> takePicture(int cameraId) => mockPlatformException
@@ -4033,30 +3507,20 @@
}
@override
- Future<void> lockCaptureOrientation(
- int? cameraId,
- DeviceOrientation? orientation,
- ) async => super.noSuchMethod(
- Invocation.method(#lockCaptureOrientation, <Object?>[
- cameraId,
- orientation,
- ]),
- );
+ Future<void> lockCaptureOrientation(int? cameraId, DeviceOrientation? orientation) async => super
+ .noSuchMethod(Invocation.method(#lockCaptureOrientation, <Object?>[cameraId, orientation]));
@override
Future<void> unlockCaptureOrientation(int? cameraId) async =>
- super.noSuchMethod(
- Invocation.method(#unlockCaptureOrientation, <Object?>[cameraId]),
- );
+ super.noSuchMethod(Invocation.method(#unlockCaptureOrientation, <Object?>[cameraId]));
@override
Future<void> pausePreview(int? cameraId) async =>
super.noSuchMethod(Invocation.method(#pausePreview, <Object?>[cameraId]));
@override
- Future<void> resumePreview(int? cameraId) async => super.noSuchMethod(
- Invocation.method(#resumePreview, <Object?>[cameraId]),
- );
+ Future<void> resumePreview(int? cameraId) async =>
+ super.noSuchMethod(Invocation.method(#resumePreview, <Object?>[cameraId]));
@override
Future<double> getMaxZoomLevel(int? cameraId) async =>
@@ -4076,27 +3540,19 @@
@override
Future<void> setZoomLevel(int? cameraId, double? zoom) async =>
- super.noSuchMethod(
- Invocation.method(#setZoomLevel, <Object?>[cameraId, zoom]),
- );
+ super.noSuchMethod(Invocation.method(#setZoomLevel, <Object?>[cameraId, zoom]));
@override
Future<void> setFlashMode(int? cameraId, FlashMode? mode) async =>
- super.noSuchMethod(
- Invocation.method(#setFlashMode, <Object?>[cameraId, mode]),
- );
+ super.noSuchMethod(Invocation.method(#setFlashMode, <Object?>[cameraId, mode]));
@override
Future<void> setExposureMode(int? cameraId, ExposureMode? mode) async =>
- super.noSuchMethod(
- Invocation.method(#setExposureMode, <Object?>[cameraId, mode]),
- );
+ super.noSuchMethod(Invocation.method(#setExposureMode, <Object?>[cameraId, mode]));
@override
Future<void> setExposurePoint(int? cameraId, Point<double>? point) async =>
- super.noSuchMethod(
- Invocation.method(#setExposurePoint, <Object?>[cameraId, point]),
- );
+ super.noSuchMethod(Invocation.method(#setExposurePoint, <Object?>[cameraId, point]));
@override
Future<double> getMinExposureOffset(int? cameraId) async =>
@@ -4131,37 +3587,23 @@
as Future<double>;
@override
- Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(
- int cameraId,
- ) {
+ Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(int cameraId) {
return super.noSuchMethod(
- Invocation.method(#getSupportedVideoStabilizationModes, <Object?>[
- cameraId,
- ]),
- returnValue: Future<Iterable<VideoStabilizationMode>>.value(
- <VideoStabilizationMode>[],
- ),
+ Invocation.method(#getSupportedVideoStabilizationModes, <Object?>[cameraId]),
+ returnValue: Future<Iterable<VideoStabilizationMode>>.value(<VideoStabilizationMode>[]),
)
as Future<Iterable<VideoStabilizationMode>>;
}
@override
- Future<void> setVideoStabilizationMode(
- int cameraId,
- VideoStabilizationMode mode,
- ) async => super.noSuchMethod(
- Invocation.method(#setVideoStabilizationMode, <Object?>[cameraId, mode]),
- );
+ Future<void> setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) async =>
+ super.noSuchMethod(Invocation.method(#setVideoStabilizationMode, <Object?>[cameraId, mode]));
}
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 3d52cf8..5ddcb6e 100644
--- a/packages/camera/camera/test/camera_value_test.dart
+++ b/packages/camera/camera/test/camera_value_test.dart
@@ -43,10 +43,7 @@
expect(cameraValue.exposureMode, ExposureMode.auto);
expect(cameraValue.exposurePointSupported, true);
expect(cameraValue.deviceOrientation, DeviceOrientation.portraitUp);
- expect(
- cameraValue.lockedCaptureOrientation,
- DeviceOrientation.portraitUp,
- );
+ expect(cameraValue.lockedCaptureOrientation, DeviceOrientation.portraitUp);
expect(cameraValue.recordingOrientation, DeviceOrientation.portraitUp);
expect(cameraValue.isPreviewPaused, false);
expect(cameraValue.previewPauseOrientation, DeviceOrientation.portraitUp);
@@ -54,9 +51,7 @@
});
test('Can be created as uninitialized', () {
- const cameraValue = CameraValue.uninitialized(
- FakeController.fakeDescription,
- );
+ const cameraValue = CameraValue.uninitialized(FakeController.fakeDescription);
expect(cameraValue, isA<CameraValue>());
expect(cameraValue.isInitialized, isFalse);
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 01621c3..0fc7d5c 100644
--- a/packages/camera/camera_android/example/integration_test/camera_test.dart
+++ b/packages/camera/camera_android/example/integration_test/camera_test.dart
@@ -69,24 +69,19 @@
// Verify image dimensions are as expected
expect(video, isNotNull);
- return assertExpectedDimensions(
- expectedSize,
- Size(video.height, video.width),
- );
+ return assertExpectedDimensions(expectedSize, Size(video.height, video.width));
}
testWidgets(
'Capture specific video resolutions',
(WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final cameraDescription in cameras) {
var previousPresetExactlySupported = true;
- for (final MapEntry<ResolutionPreset, Size> preset
- in presetExpectedSizes.entries) {
+ for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) {
final controller = CameraController(
cameraDescription,
mediaSettings: MediaSettings(resolutionPreset: preset.key),
@@ -111,8 +106,7 @@
);
testWidgets('Pause and resume video recording', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
@@ -146,8 +140,7 @@
sleep(const Duration(milliseconds: 500));
final XFile file = await controller.stopVideoRecording();
- final int recordingTime =
- DateTime.now().millisecondsSinceEpoch - recordingStart;
+ final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart;
final videoFile = File(file.path);
final videoController = VideoPlayerController.file(videoFile);
@@ -159,8 +152,7 @@
});
testWidgets('Set description while recording', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.length < 2) {
return;
}
@@ -196,8 +188,7 @@
});
testWidgets('Set description', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.length < 2) {
return;
}
@@ -211,8 +202,7 @@
});
testWidgets('image streaming', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
@@ -241,8 +231,7 @@
});
testWidgets('recording with image stream', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
@@ -279,14 +268,12 @@
group('Camera settings', () {
Future<CameraDescription> getCamera() async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
expect(cameras.isNotEmpty, equals(true));
// Prefer back camera, as it allows more customizations.
final CameraDescription cameraDescription = cameras.firstWhere(
- (CameraDescription description) =>
- description.lensDirection == CameraLensDirection.back,
+ (CameraDescription description) => description.lensDirection == CameraLensDirection.back,
orElse: () => cameras.first,
);
return cameraDescription;
@@ -315,10 +302,7 @@
for (final fps in <int>[10, 30]) {
final controller = CameraController(
cameraDescription,
- mediaSettings: MediaSettings(
- resolutionPreset: ResolutionPreset.medium,
- fps: fps,
- ),
+ mediaSettings: MediaSettings(resolutionPreset: ResolutionPreset.medium, fps: fps),
);
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 33cafe1..b3b96ff 100644
--- a/packages/camera/camera_android/example/lib/camera_controller.dart
+++ b/packages/camera/camera_android/example/lib/camera_controller.dart
@@ -173,9 +173,7 @@
/// 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));
@@ -196,8 +194,7 @@
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
FutureOr<bool>? _initCalled;
- StreamSubscription<DeviceOrientationChangedEvent>?
- _deviceOrientationSubscription;
+ StreamSubscription<DeviceOrientationChangedEvent>? _deviceOrientationSubscription;
/// The camera identifier with which the controller is associated.
int get cameraId => _cameraId;
@@ -208,16 +205,13 @@
Future<void> _initializeWithDescription(CameraDescription description) async {
final initializeCompleter = Completer<CameraInitializedEvent>();
- _deviceOrientationSubscription = CameraPlatform.instance
- .onDeviceOrientationChanged()
- .listen((DeviceOrientationChangedEvent event) {
- value = value.copyWith(deviceOrientation: event.orientation);
- });
+ _deviceOrientationSubscription = CameraPlatform.instance.onDeviceOrientationChanged().listen((
+ DeviceOrientationChangedEvent event,
+ ) {
+ value = value.copyWith(deviceOrientation: event.orientation);
+ });
- _cameraId = await CameraPlatform.instance.createCameraWithSettings(
- description,
- _mediaSettings,
- );
+ _cameraId = await CameraPlatform.instance.createCameraWithSettings(description, _mediaSettings);
unawaited(
CameraPlatform.instance.onCameraInitialized(_cameraId).first.then((
@@ -236,8 +230,7 @@
isInitialized: true,
description: description,
previewSize: await initializeCompleter.future.then(
- (CameraInitializedEvent event) =>
- Size(event.previewWidth, event.previewHeight),
+ (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight),
),
exposureMode: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposureMode,
@@ -302,14 +295,12 @@
}
/// Start streaming images from platform camera.
- Future<void> startImageStream(
- void Function(CameraImageData image) onAvailable,
- ) async {
- _imageStreamSubscription = CameraPlatform.instance
- .onStreamedFrameAvailable(_cameraId)
- .listen((CameraImageData imageData) {
- onAvailable(imageData);
- });
+ Future<void> startImageStream(void Function(CameraImageData image) onAvailable) async {
+ _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen((
+ CameraImageData imageData,
+ ) {
+ onAvailable(imageData);
+ });
value = value.copyWith(isStreamingImages: true);
}
@@ -324,9 +315,7 @@
///
/// The video is returned as a [XFile] after calling [stopVideoRecording].
/// Throws a [CameraException] if the capture fails.
- Future<void> startVideoRecording({
- void Function(CameraImageData image)? streamCallback,
- }) async {
+ Future<void> startVideoRecording({void Function(CameraImageData image)? streamCallback}) async {
await CameraPlatform.instance.startVideoCapturing(
VideoCaptureOptions(_cameraId, streamCallback: streamCallback),
);
@@ -348,9 +337,7 @@
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,
@@ -397,8 +384,7 @@
]);
// 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;
@@ -417,23 +403,16 @@
///
/// If [orientation] is omitted, the current device orientation is used.
Future<void> lockCaptureOrientation() async {
- await CameraPlatform.instance.lockCaptureOrientation(
- _cameraId,
- value.deviceOrientation,
- );
+ await CameraPlatform.instance.lockCaptureOrientation(_cameraId, value.deviceOrientation);
value = value.copyWith(
- lockedCaptureOrientation: Optional<DeviceOrientation>.of(
- value.deviceOrientation,
- ),
+ lockedCaptureOrientation: Optional<DeviceOrientation>.of(value.deviceOrientation),
);
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation() async {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
- value = value.copyWith(
- lockedCaptureOrientation: const Optional<DeviceOrientation>.absent(),
- );
+ value = value.copyWith(lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
}
/// Sets the focus mode for taking pictures.
@@ -535,9 +514,7 @@
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T value) transformer) {
- return _value == null
- ? Optional<S>.absent()
- : Optional<S>.of(transformer(_value as T));
+ return _value == null ? Optional<S>.absent() : Optional<S>.of(transformer(_value as T));
}
/// Transforms the Optional value.
@@ -552,8 +529,7 @@
}
@override
- Iterator<T> get iterator =>
- isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
+ Iterator<T> get iterator => isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
@@ -565,8 +541,6 @@
@override
String toString() {
- return _value == null
- ? 'Optional { absent }'
- : 'Optional { value: $_value }';
+ return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }';
}
}
diff --git a/packages/camera/camera_android/example/lib/camera_preview.dart b/packages/camera/camera_android/example/lib/camera_preview.dart
index 0a768b3..7e8d643 100644
--- a/packages/camera/camera_android/example/lib/camera_preview.dart
+++ b/packages/camera/camera_android/example/lib/camera_preview.dart
@@ -26,12 +26,9 @@
valueListenable: controller,
builder: (BuildContext context, Object? value, Widget? child) {
final double cameraAspectRatio =
- controller.value.previewSize!.width /
- controller.value.previewSize!.height;
+ controller.value.previewSize!.width / controller.value.previewSize!.height;
return AspectRatio(
- aspectRatio: _isLandscape()
- ? cameraAspectRatio
- : (1 / cameraAspectRatio),
+ aspectRatio: _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio),
child: Stack(
fit: StackFit.expand,
children: <Widget>[
diff --git a/packages/camera/camera_android/example/lib/main.dart b/packages/camera/camera_android/example/lib/main.dart
index b669f6a..3b99656 100644
--- a/packages/camera/camera_android/example/lib/main.dart
+++ b/packages/camera/camera_android/example/lib/main.dart
@@ -138,8 +138,7 @@
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
- color:
- controller != null && controller!.value.isRecordingVideo
+ color: controller != null && controller!.value.isRecordingVideo
? Colors.redAccent
: Colors.grey,
width: 3.0,
@@ -155,9 +154,7 @@
_modeControlRowWidget(),
Padding(
padding: const EdgeInsets.all(5.0),
- child: Row(
- children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()],
- ),
+ child: Row(children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()]),
),
],
),
@@ -171,11 +168,7 @@
if (cameraController == null || !cameraController.value.isInitialized) {
return const Text(
'Tap a camera',
- style: TextStyle(
- color: Colors.white,
- fontSize: 24.0,
- fontWeight: FontWeight.w900,
- ),
+ style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900),
);
} else {
return Listener(
@@ -189,8 +182,7 @@
behavior: HitTestBehavior.opaque,
onScaleStart: _handleScaleStart,
onScaleUpdate: _handleScaleUpdate,
- onTapDown: (TapDownDetails details) =>
- onViewFinderTap(details, constraints),
+ onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints),
);
},
),
@@ -209,15 +201,9 @@
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.
@@ -242,13 +228,9 @@
// pointing to a location within the browser. It may be displayed
// either with Image.network or Image.memory after loading the image
// bytes to memory.
- kIsWeb
- ? Image.network(imageFile!.path)
- : Image.file(File(imageFile!.path)))
+ kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path)))
: Container(
- decoration: BoxDecoration(
- border: Border.all(color: Colors.pink),
- ),
+ decoration: BoxDecoration(border: Border.all(color: Colors.pink)),
child: Center(
child: AspectRatio(
aspectRatio: localVideoController.value.aspectRatio,
@@ -281,16 +263,12 @@
IconButton(
icon: const Icon(Icons.exposure),
color: Colors.blue,
- onPressed: controller != null
- ? onExposureModeButtonPressed
- : null,
+ onPressed: controller != null ? onExposureModeButtonPressed : null,
),
IconButton(
icon: const Icon(Icons.filter_center_focus),
color: Colors.blue,
- onPressed: controller != null
- ? onFocusModeButtonPressed
- : null,
+ onPressed: controller != null ? onFocusModeButtonPressed : null,
),
]
: <Widget>[],
@@ -306,9 +284,7 @@
: Icons.screen_rotation,
),
color: Colors.blue,
- onPressed: controller != null
- ? onCaptureOrientationLockButtonPressed
- : null,
+ onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null,
),
],
),
@@ -328,36 +304,28 @@
children: <Widget>[
IconButton(
icon: const Icon(Icons.flash_off),
- color: controller?.value.flashMode == FlashMode.off
- ? Colors.orange
- : Colors.blue,
+ 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,
+ 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,
+ 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,
+ color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue,
onPressed: controller != null
? () => onSetFlashModeButtonPressed(FlashMode.torch)
: null,
@@ -394,15 +362,11 @@
TextButton(
style: styleAuto,
onPressed: controller != null
- ? () =>
- onSetExposureModeButtonPressed(ExposureMode.auto)
+ ? () => onSetExposureModeButtonPressed(ExposureMode.auto)
: null,
onLongPress: () {
if (controller != null) {
- CameraPlatform.instance.setExposurePoint(
- controller!.cameraId,
- null,
- );
+ CameraPlatform.instance.setExposurePoint(controller!.cameraId, null);
showInSnackBar('Resetting exposure point');
}
},
@@ -411,17 +375,13 @@
TextButton(
style: styleLocked,
onPressed: controller != null
- ? () => onSetExposureModeButtonPressed(
- ExposureMode.locked,
- )
+ ? () => 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'),
),
],
@@ -436,9 +396,7 @@
min: _minAvailableExposureOffset,
max: _maxAvailableExposureOffset,
label: _currentExposureOffset.toString(),
- onChanged:
- _minAvailableExposureOffset ==
- _maxAvailableExposureOffset
+ onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset
? null
: setExposureOffset,
),
@@ -454,9 +412,7 @@
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
@@ -482,10 +438,7 @@
: null,
onLongPress: () {
if (controller != null) {
- CameraPlatform.instance.setFocusPoint(
- controller!.cameraId,
- null,
- );
+ CameraPlatform.instance.setFocusPoint(controller!.cameraId, null);
}
showInSnackBar('Resetting focus point');
},
@@ -563,13 +516,10 @@
),
IconButton(
icon: const Icon(Icons.pause_presentation),
- color:
- cameraController != null && cameraController.value.isPreviewPaused
+ color: cameraController != null && cameraController.value.isPreviewPaused
? Colors.red
: Colors.blue,
- onPressed: cameraController == null
- ? null
- : onPausePreviewButtonPressed,
+ onPressed: cameraController == null ? null : onPausePreviewButtonPressed,
),
],
);
@@ -616,9 +566,7 @@
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) {
@@ -644,15 +592,11 @@
}
}
- Future<void> _initializeCameraController(
- CameraDescription cameraDescription,
- ) async {
+ Future<void> _initializeCameraController(CameraDescription cameraDescription) async {
final cameraController = CameraController(
cameraDescription,
mediaSettings: MediaSettings(
- resolutionPreset: kIsWeb
- ? ResolutionPreset.max
- : ResolutionPreset.medium,
+ resolutionPreset: kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium,
enableAudio: enableAudio,
),
imageFormatGroup: ImageFormatGroup.jpeg,
@@ -675,14 +619,10 @@
? <Future<Object?>>[
CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId)
- .then(
- (double value) => _minAvailableExposureOffset = value,
- ),
+ .then((double value) => _minAvailableExposureOffset = value),
CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId)
- .then(
- (double value) => _maxAvailableExposureOffset = value,
- ),
+ .then((double value) => _maxAvailableExposureOffset = value),
]
: <Future<Object?>>[],
CameraPlatform.instance
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 ef65f09..39d763c 100644
--- a/packages/camera/camera_android/example/test_driver/integration_test.dart
+++ b/packages/camera/camera_android/example/test_driver/integration_test.dart
@@ -39,10 +39,7 @@
]);
print('Starting test.');
final FlutterDriver driver = await FlutterDriver.connect();
- final String data = await driver.requestData(
- null,
- timeout: const Duration(minutes: 1),
- );
+ final String data = await driver.requestData(null, timeout: const Duration(minutes: 1));
await driver.close();
print('Test finished. Revoking camera permissions...');
Process.runSync('adb', <String>[
diff --git a/packages/camera/camera_android/lib/src/android_camera.dart b/packages/camera/camera_android/lib/src/android_camera.dart
index 9f7d580..c42e1a2 100644
--- a/packages/camera/camera_android/lib/src/android_camera.dart
+++ b/packages/camera/camera_android/lib/src/android_camera.dart
@@ -17,8 +17,7 @@
/// The Android implementation of [CameraPlatform] that uses method channels.
class AndroidCamera extends CameraPlatform {
/// Creates a new [CameraPlatform] instance.
- AndroidCamera({@visibleForTesting CameraApi? hostApi})
- : _hostApi = hostApi ?? CameraApi();
+ AndroidCamera({@visibleForTesting CameraApi? hostApi}) : _hostApi = hostApi ?? CameraApi();
/// Registers this class as the default instance of [CameraPlatform].
static void registerWith() {
@@ -30,8 +29,7 @@
/// The name of the channel that device events from the platform side are
/// sent on.
@visibleForTesting
- static const String deviceEventChannelName =
- 'plugins.flutter.io/camera_android/fromPlatform';
+ static const String deviceEventChannelName = 'plugins.flutter.io/camera_android/fromPlatform';
/// The controller we need to broadcast the different events coming
/// from handleMethodCall, specific to camera events.
@@ -51,8 +49,7 @@
/// Map of camera IDs to camera-level callback handlers listening to their
/// respective platform channels.
@visibleForTesting
- final Map<int, HostCameraMessageHandler> hostCameraHandlers =
- <int, HostCameraMessageHandler>{};
+ final Map<int, HostCameraMessageHandler> hostCameraHandlers = <int, HostCameraMessageHandler>{};
// The stream to receive frames from the native code.
StreamSubscription<dynamic>? _platformImageStreamSubscription;
@@ -60,23 +57,18 @@
// The stream for vending frames to platform interface clients.
StreamController<CameraImageData>? _frameStreamController;
- Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
- .stream
- .where((CameraEvent event) => event.cameraId == cameraId);
+ Stream<CameraEvent> _cameraEvents(int cameraId) =>
+ cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId);
@override
Future<List<CameraDescription>> availableCameras() async {
try {
final List<PlatformCameraDescription> cameraDescriptions = await _hostApi
.getAvailableCameras();
- return cameraDescriptions.map((
- PlatformCameraDescription cameraDescription,
- ) {
+ return cameraDescriptions.map((PlatformCameraDescription cameraDescription) {
return CameraDescription(
name: cameraDescription.name,
- lensDirection: cameraLensDirectionFromPlatform(
- cameraDescription.lensDirection,
- ),
+ lensDirection: cameraLensDirectionFromPlatform(cameraDescription.lensDirection),
sensorOrientation: cameraDescription.sensorOrientation,
);
}).toList();
@@ -101,10 +93,7 @@
MediaSettings? mediaSettings,
) async {
try {
- return await _hostApi.create(
- cameraDescription.name,
- mediaSettingsToPlatform(mediaSettings),
- );
+ return await _hostApi.create(cameraDescription.name, mediaSettingsToPlatform(mediaSettings));
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
@@ -139,9 +128,7 @@
@override
Future<void> dispose(int cameraId) async {
- final HostCameraMessageHandler? handler = hostCameraHandlers.remove(
- cameraId,
- );
+ final HostCameraMessageHandler? handler = hostCameraHandlers.remove(cameraId);
handler?.dispose();
await _hostApi.dispose();
@@ -179,13 +166,8 @@
}
@override
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) async {
- await _hostApi.lockCaptureOrientation(
- deviceOrientationToPlatform(orientation),
- );
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async {
+ await _hostApi.lockCaptureOrientation(deviceOrientationToPlatform(orientation));
}
@override
@@ -204,10 +186,7 @@
Future<void> prepareForVideoRecording() async {}
@override
- Future<void> startVideoRecording(
- int cameraId, {
- Duration? maxVideoDuration,
- }) async {
+ Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async {
// Ignore maxVideoDuration, as it is unimplemented and deprecated.
return startVideoCapturing(VideoCaptureOptions(cameraId));
}
@@ -229,12 +208,10 @@
}
@override
- Future<void> pauseVideoRecording(int cameraId) =>
- _hostApi.pauseVideoRecording();
+ Future<void> pauseVideoRecording(int cameraId) => _hostApi.pauseVideoRecording();
@override
- Future<void> resumeVideoRecording(int cameraId) =>
- _hostApi.resumeVideoRecording();
+ Future<void> resumeVideoRecording(int cameraId) => _hostApi.resumeVideoRecording();
@override
bool supportsImageStreaming() => true;
@@ -248,9 +225,7 @@
return _frameStreamController!.stream;
}
- StreamController<CameraImageData> _installStreamController({
- void Function()? onListen,
- }) {
+ StreamController<CameraImageData> _installStreamController({void Function()? onListen}) {
_frameStreamController = StreamController<CameraImageData>(
onListen: onListen ?? () {},
onPause: _onFrameStreamPauseResume,
@@ -270,16 +245,12 @@
}
void _startStreamListener() {
- const cameraEventChannel = EventChannel(
- 'plugins.flutter.io/camera_android/imageStream',
- );
- _platformImageStreamSubscription = cameraEventChannel
- .receiveBroadcastStream()
- .listen((dynamic imageData) {
- _frameStreamController!.add(
- cameraImageFromPlatformData(imageData as Map<dynamic, dynamic>),
- );
- });
+ const cameraEventChannel = EventChannel('plugins.flutter.io/camera_android/imageStream');
+ _platformImageStreamSubscription = cameraEventChannel.receiveBroadcastStream().listen((
+ dynamic imageData,
+ ) {
+ _frameStreamController!.add(cameraImageFromPlatformData(imageData as Map<dynamic, dynamic>));
+ });
}
FutureOr<void> _onFrameStreamCancel() async {
@@ -374,9 +345,7 @@
}
@override
- Future<void> setDescriptionWhileRecording(
- CameraDescription description,
- ) async {
+ Future<void> setDescriptionWhileRecording(CameraDescription description) async {
await _hostApi.setDescriptionWhileRecording(description.name);
}
diff --git a/packages/camera/camera_android/lib/src/messages.g.dart b/packages/camera/camera_android/lib/src/messages.g.dart
index e4c0474..8c1034b 100644
--- a/packages/camera/camera_android/lib/src/messages.g.dart
+++ b/packages/camera/camera_android/lib/src/messages.g.dart
@@ -18,11 +18,7 @@
);
}
-List<Object?> wrapResponse({
- Object? result,
- PlatformException? error,
- bool empty = false,
-}) {
+List<Object?> wrapResponse({Object? result, PlatformException? error, bool empty = false}) {
if (empty) {
return <Object?>[];
}
@@ -35,9 +31,7 @@
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 &&
@@ -54,12 +48,7 @@
enum PlatformCameraLensDirection { front, back, external }
/// Pigeon equivalent of [DeviceOrientation].
-enum PlatformDeviceOrientation {
- portraitUp,
- portraitDown,
- landscapeLeft,
- landscapeRight,
-}
+enum PlatformDeviceOrientation { portraitUp, portraitDown, landscapeLeft, landscapeRight }
/// Pigeon equivalent of [ExposureMode].
enum PlatformExposureMode { auto, locked }
@@ -115,8 +104,7 @@
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
- if (other is! PlatformCameraDescription ||
- other.runtimeType != runtimeType) {
+ if (other is! PlatformCameraDescription || other.runtimeType != runtimeType) {
return false;
}
if (identical(this, other)) {
@@ -210,10 +198,7 @@
static PlatformSize decode(Object result) {
result as List<Object?>;
- return PlatformSize(
- width: result[0]! as double,
- height: result[1]! as double,
- );
+ return PlatformSize(width: result[0]! as double, height: result[1]! as double);
}
@override
@@ -292,13 +277,7 @@
bool enableAudio;
List<Object?> _toList() {
- return <Object?>[
- resolutionPreset,
- fps,
- videoBitrate,
- audioBitrate,
- enableAudio,
- ];
+ return <Object?>[resolutionPreset, fps, videoBitrate, audioBitrate, enableAudio];
}
Object encode() {
@@ -426,13 +405,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -443,15 +420,13 @@
Future<List<PlatformCameraDescription>> getAvailableCameras() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -466,29 +441,24 @@
message: 'Host platform returned null value for non-null return value.',
);
} else {
- return (pigeonVar_replyList[0] as List<Object?>?)!
- .cast<PlatformCameraDescription>();
+ return (pigeonVar_replyList[0] as List<Object?>?)!.cast<PlatformCameraDescription>();
}
}
/// Creates a new camera with the given name and settings and returns its ID.
- Future<int> create(
- String cameraName,
- PlatformMediaSettings mediaSettings,
- ) async {
+ Future<int> create(String cameraName, PlatformMediaSettings mediaSettings) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.create$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraName, mediaSettings],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ cameraName,
+ mediaSettings,
+ ]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -511,17 +481,13 @@
Future<void> initialize(PlatformImageFormatGroup imageFormat) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.initialize$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[imageFormat],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[imageFormat]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -539,15 +505,13 @@
Future<void> dispose() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.dispose$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -562,22 +526,16 @@
}
/// Locks the camera with the given ID to the given orientation.
- Future<void> lockCaptureOrientation(
- PlatformDeviceOrientation orientation,
- ) async {
+ Future<void> lockCaptureOrientation(PlatformDeviceOrientation orientation) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[orientation],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[orientation]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -595,15 +553,13 @@
Future<void> unlockCaptureOrientation() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.unlockCaptureOrientation$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -622,15 +578,13 @@
Future<String> takePicture() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.takePicture$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -653,17 +607,13 @@
Future<void> startVideoRecording(bool enableStream) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[enableStream],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[enableStream]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -682,15 +632,13 @@
Future<String> stopVideoRecording() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -713,15 +661,13 @@
Future<void> pauseVideoRecording() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.pauseVideoRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -739,15 +685,13 @@
Future<void> resumeVideoRecording() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.resumeVideoRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -765,15 +709,13 @@
Future<void> startImageStream() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.startImageStream$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -791,15 +733,13 @@
Future<void> stopImageStream() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.stopImageStream$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -817,17 +757,13 @@
Future<void> setFlashMode(PlatformFlashMode flashMode) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setFlashMode$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[flashMode],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[flashMode]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -845,17 +781,13 @@
Future<void> setExposureMode(PlatformExposureMode exposureMode) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setExposureMode$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[exposureMode],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[exposureMode]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -875,17 +807,13 @@
Future<void> setExposurePoint(PlatformPoint? point) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setExposurePoint$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[point],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[point]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -903,15 +831,13 @@
Future<double> getMinExposureOffset() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.getMinExposureOffset$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -934,15 +860,13 @@
Future<double> getMaxExposureOffset() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.getMaxExposureOffset$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -965,15 +889,13 @@
Future<double> getExposureOffsetStepSize() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.getExposureOffsetStepSize$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -997,17 +919,13 @@
Future<double> setExposureOffset(double offset) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setExposureOffset$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[offset],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[offset]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1030,17 +948,13 @@
Future<void> setFocusMode(PlatformFocusMode focusMode) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setFocusMode$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[focusMode],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[focusMode]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1060,17 +974,13 @@
Future<void> setFocusPoint(PlatformPoint? point) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setFocusPoint$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[point],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[point]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1088,15 +998,13 @@
Future<double> getMaxZoomLevel() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.getMaxZoomLevel$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1119,15 +1027,13 @@
Future<double> getMinZoomLevel() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.getMinZoomLevel$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1150,17 +1056,13 @@
Future<void> setZoomLevel(double zoom) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setZoomLevel$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[zoom],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[zoom]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1178,15 +1080,13 @@
Future<void> pausePreview() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.pausePreview$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1204,15 +1104,13 @@
Future<void> resumePreview() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.resumePreview$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1232,17 +1130,13 @@
Future<void> setDescriptionWhileRecording(String description) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_android.CameraApi.setDescriptionWhileRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[description],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[description]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -1269,12 +1163,9 @@
BinaryMessenger? binaryMessenger,
String messageChannelSuffix = '',
}) {
- messageChannelSuffix = messageChannelSuffix.isNotEmpty
- ? '.$messageChannelSuffix'
- : '';
+ messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';
{
- final BasicMessageChannel<Object?>
- pigeonVar_channel = BasicMessageChannel<Object?>(
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix',
pigeonChannelCodec,
binaryMessenger: binaryMessenger,
@@ -1328,12 +1219,9 @@
BinaryMessenger? binaryMessenger,
String messageChannelSuffix = '',
}) {
- messageChannelSuffix = messageChannelSuffix.isNotEmpty
- ? '.$messageChannelSuffix'
- : '';
+ messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';
{
- final BasicMessageChannel<Object?>
- pigeonVar_channel = BasicMessageChannel<Object?>(
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_android.CameraEventApi.initialized$messageChannelSuffix',
pigeonChannelCodec,
binaryMessenger: binaryMessenger,
@@ -1347,8 +1235,7 @@
'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null.',
);
final List<Object?> args = (message as List<Object?>?)!;
- final PlatformCameraState? arg_initialState =
- (args[0] as PlatformCameraState?);
+ 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.',
@@ -1367,8 +1254,7 @@
}
}
{
- final BasicMessageChannel<Object?>
- pigeonVar_channel = BasicMessageChannel<Object?>(
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_android.CameraEventApi.error$messageChannelSuffix',
pigeonChannelCodec,
binaryMessenger: binaryMessenger,
@@ -1401,8 +1287,7 @@
}
}
{
- final BasicMessageChannel<Object?>
- pigeonVar_channel = BasicMessageChannel<Object?>(
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_android.CameraEventApi.closed$messageChannelSuffix',
pigeonChannelCodec,
binaryMessenger: binaryMessenger,
diff --git a/packages/camera/camera_android/lib/src/type_conversion.dart b/packages/camera/camera_android/lib/src/type_conversion.dart
index 1daa526..87d007b 100644
--- a/packages/camera/camera_android/lib/src/type_conversion.dart
+++ b/packages/camera/camera_android/lib/src/type_conversion.dart
@@ -18,9 +18,8 @@
sensorSensitivity: data['sensorSensitivity'] as double?,
planes: List<CameraImagePlane>.unmodifiable(
(data['planes'] as List<dynamic>).map<CameraImagePlane>(
- (dynamic planeData) => _cameraImagePlaneFromPlatformData(
- planeData as Map<dynamic, dynamic>,
- ),
+ (dynamic planeData) =>
+ _cameraImagePlaneFromPlatformData(planeData as Map<dynamic, dynamic>),
),
),
);
diff --git a/packages/camera/camera_android/lib/src/utils.dart b/packages/camera/camera_android/lib/src/utils.dart
index 554bf78..320a096 100644
--- a/packages/camera/camera_android/lib/src/utils.dart
+++ b/packages/camera/camera_android/lib/src/utils.dart
@@ -10,28 +10,24 @@
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,
-};
+CameraLensDirection cameraLensDirectionFromPlatform(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,
-};
+DeviceOrientation deviceOrientationFromPlatform(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,
-) {
+PlatformDeviceOrientation deviceOrientationToPlatform(DeviceOrientation orientation) {
switch (orientation) {
case DeviceOrientation.portraitUp:
return PlatformDeviceOrientation.portraitUp;
@@ -49,11 +45,10 @@
}
/// Converts a [PlatformExposureMode] to [ExposureMode].
-ExposureMode exposureModeFromPlatform(PlatformExposureMode exposureMode) =>
- switch (exposureMode) {
- PlatformExposureMode.auto => ExposureMode.auto,
- PlatformExposureMode.locked => ExposureMode.locked,
- };
+ExposureMode exposureModeFromPlatform(PlatformExposureMode exposureMode) => switch (exposureMode) {
+ PlatformExposureMode.auto => ExposureMode.auto,
+ PlatformExposureMode.locked => ExposureMode.locked,
+};
/// Converts a [ExposureMode] to [PlatformExposureMode].
PlatformExposureMode exposureModeToPlatform(ExposureMode exposureMode) {
@@ -70,11 +65,10 @@
}
/// Converts a [PlatformFocusMode] to [FocusMode].
-FocusMode focusModeFromPlatform(PlatformFocusMode focusMode) =>
- switch (focusMode) {
- PlatformFocusMode.auto => FocusMode.auto,
- PlatformFocusMode.locked => FocusMode.locked,
- };
+FocusMode focusModeFromPlatform(PlatformFocusMode focusMode) => switch (focusMode) {
+ PlatformFocusMode.auto => FocusMode.auto,
+ PlatformFocusMode.locked => FocusMode.locked,
+};
/// Converts a [FocusMode] to [PlatformFocusMode].
PlatformFocusMode focusModeToPlatform(FocusMode focusMode) {
@@ -91,26 +85,24 @@
}
/// Converts a [ResolutionPreset] to [PlatformResolutionPreset].
-PlatformResolutionPreset resolutionPresetToPlatform(ResolutionPreset? preset) =>
- switch (preset) {
- ResolutionPreset.low => PlatformResolutionPreset.low,
- ResolutionPreset.medium => PlatformResolutionPreset.medium,
- ResolutionPreset.high => PlatformResolutionPreset.high,
- ResolutionPreset.veryHigh => PlatformResolutionPreset.veryHigh,
- ResolutionPreset.ultraHigh => PlatformResolutionPreset.ultraHigh,
- ResolutionPreset.max => PlatformResolutionPreset.max,
- _ => PlatformResolutionPreset.high,
- };
+PlatformResolutionPreset resolutionPresetToPlatform(ResolutionPreset? preset) => switch (preset) {
+ ResolutionPreset.low => PlatformResolutionPreset.low,
+ ResolutionPreset.medium => PlatformResolutionPreset.medium,
+ ResolutionPreset.high => PlatformResolutionPreset.high,
+ ResolutionPreset.veryHigh => PlatformResolutionPreset.veryHigh,
+ ResolutionPreset.ultraHigh => PlatformResolutionPreset.ultraHigh,
+ ResolutionPreset.max => PlatformResolutionPreset.max,
+ _ => PlatformResolutionPreset.high,
+};
/// 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,
- );
+PlatformMediaSettings mediaSettingsToPlatform(MediaSettings? settings) => PlatformMediaSettings(
+ 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 4489fe3..4783b47 100644
--- a/packages/camera/camera_android/pigeons/messages.dart
+++ b/packages/camera/camera_android/pigeons/messages.dart
@@ -28,12 +28,7 @@
}
/// Pigeon equivalent of [DeviceOrientation].
-enum PlatformDeviceOrientation {
- portraitUp,
- portraitDown,
- landscapeLeft,
- landscapeRight,
-}
+enum PlatformDeviceOrientation { portraitUp, portraitDown, landscapeLeft, landscapeRight }
/// Pigeon equivalent of [ExposureMode].
enum PlatformExposureMode { auto, locked }
diff --git a/packages/camera/camera_android/test/android_camera_test.dart b/packages/camera/camera_android/test/android_camera_test.dart
index 8321001..d004600 100644
--- a/packages/camera/camera_android/test/android_camera_test.dart
+++ b/packages/camera/camera_android/test/android_camera_test.dart
@@ -126,90 +126,65 @@
},
);
- test(
- 'Should throw CameraException when create throws a PlatformException',
- () {
- // Arrange
- final camera = AndroidCamera(hostApi: mockCameraApi);
- when(
- mockCameraApi.create(
- 'Test',
- argThat(
- predicate(
- (PlatformMediaSettings settings) =>
- settings.resolutionPreset ==
- PlatformResolutionPreset.high &&
- !settings.enableAudio,
+ test('Should throw CameraException when create throws a PlatformException', () {
+ // Arrange
+ final 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,
+ ),
+ ResolutionPreset.high,
+ ),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
+ .having(
+ (CameraException e) => e.description,
+ 'description',
+ 'Mock error message used during testing.',
),
- ),
- ),
- ).thenThrow(
- CameraException(
- 'TESTING_ERROR_CODE',
- 'Mock error message used during testing.',
- ),
- );
+ ),
+ );
+ });
- // Act
- expect(
- () => camera.createCamera(
- const CameraDescription(
- name: 'Test',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 0,
- ),
- ResolutionPreset.high,
- ),
- throwsA(
- isA<CameraException>()
- .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 camera = AndroidCamera(hostApi: mockCameraApi);
+ when(
+ mockCameraApi.initialize(PlatformImageFormatGroup.yuv420),
+ ).thenThrow(CameraException('TESTING_ERROR_CODE', 'Mock error message used during testing.'));
- test(
- 'Should throw CameraException when initialize throws a PlatformException',
- () {
- // Arrange
- final camera = AndroidCamera(hostApi: mockCameraApi);
- when(
- mockCameraApi.initialize(PlatformImageFormatGroup.yuv420),
- ).thenThrow(
- CameraException(
- 'TESTING_ERROR_CODE',
- 'Mock error message used during testing.',
- ),
- );
-
- // Act
- expect(
- () => camera.initializeCamera(0),
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException e) => e.code,
- 'code',
- 'TESTING_ERROR_CODE',
- )
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Mock error message used during testing.',
- ),
- ),
- );
- },
- );
+ // Act
+ expect(
+ () => camera.initializeCamera(0),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
+ .having(
+ (CameraException e) => e.description,
+ 'description',
+ 'Mock error message used during testing.',
+ ),
+ ),
+ );
+ });
test('Should send initialization data', () async {
// Arrange
@@ -239,23 +214,13 @@
// Act
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ 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 {
@@ -283,15 +248,7 @@
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true),
);
await initializeFuture;
@@ -321,23 +278,14 @@
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true),
);
await initializeFuture;
});
test('Should receive initialized event', () async {
// Act
- final Stream<CameraInitializedEvent> eventStream = camera
- .onCameraInitialized(cameraId);
+ final Stream<CameraInitializedEvent> eventStream = camera.onCameraInitialized(cameraId);
final streamQueue = StreamQueue<CameraInitializedEvent>(eventStream);
// Emit test events
@@ -370,9 +318,7 @@
test('Should receive camera closing events', () async {
// Act
- final Stream<CameraClosingEvent> eventStream = camera.onCameraClosing(
- cameraId,
- );
+ final Stream<CameraClosingEvent> eventStream = camera.onCameraClosing(cameraId);
final streamQueue = StreamQueue<CameraClosingEvent>(eventStream);
// Emit test events
@@ -392,9 +338,7 @@
test('Should receive camera error events', () async {
// Act
- final Stream<CameraErrorEvent> errorStream = camera.onCameraError(
- cameraId,
- );
+ final Stream<CameraErrorEvent> errorStream = camera.onCameraError(cameraId);
final streamQueue = StreamQueue<CameraErrorEvent>(errorStream);
// Emit test events
@@ -414,18 +358,13 @@
test('Should receive device orientation change events', () async {
// Act
- final Stream<DeviceOrientationChangedEvent> eventStream = camera
- .onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
+ final Stream<DeviceOrientationChangedEvent> eventStream = camera.onDeviceOrientationChanged();
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
// Emit test events
const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
for (var i = 0; i < 3; i++) {
- camera.hostHandler.deviceOrientationChanged(
- PlatformDeviceOrientation.portraitUp,
- );
+ camera.hostHandler.deviceOrientationChanged(PlatformDeviceOrientation.portraitUp);
}
// Assert
@@ -456,95 +395,70 @@
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true),
);
await initializeFuture;
});
- test(
- 'Should fetch CameraDescription instances for available cameras',
- () async {
- // Arrange
- final returnData = <PlatformCameraDescription>[
- PlatformCameraDescription(
- name: 'Test 1',
- lensDirection: PlatformCameraLensDirection.front,
- sensorOrientation: 1,
- ),
- PlatformCameraDescription(
- name: 'Test 2',
- lensDirection: PlatformCameraLensDirection.back,
- sensorOrientation: 2,
- ),
- ];
- when(
- mockCameraApi.getAvailableCameras(),
- ).thenAnswer((_) async => returnData);
+ test('Should fetch CameraDescription instances for available cameras', () async {
+ // Arrange
+ final returnData = <PlatformCameraDescription>[
+ 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<CameraDescription> cameras = await camera.availableCameras();
+ // Act
+ final List<CameraDescription> cameras = await camera.availableCameras();
- // Assert
- expect(cameras.length, returnData.length);
- for (var i = 0; i < returnData.length; i++) {
- final PlatformCameraDescription platformCameraDescription =
- returnData[i];
- final cameraDescription = CameraDescription(
- name: platformCameraDescription.name,
- lensDirection: cameraLensDirectionFromPlatform(
- 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.',
- ),
+ // Assert
+ expect(cameras.length, returnData.length);
+ for (var i = 0; i < returnData.length; i++) {
+ final PlatformCameraDescription platformCameraDescription = returnData[i];
+ final cameraDescription = CameraDescription(
+ name: platformCameraDescription.name,
+ lensDirection: cameraLensDirectionFromPlatform(platformCameraDescription.lensDirection),
+ sensorOrientation: platformCameraDescription.sensorOrientation,
);
+ expect(cameras[i], cameraDescription);
+ }
+ });
- // Act
- expect(
- camera.availableCameras,
- throwsA(
- isA<CameraException>()
- .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 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<CameraException>()
+ .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);
@@ -568,10 +482,7 @@
// Arrange
// Act
await camera.startVideoCapturing(
- VideoCaptureOptions(
- cameraId,
- streamCallback: (CameraImageData imageData) {},
- ),
+ VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}),
);
// Assert
@@ -581,9 +492,7 @@
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);
@@ -622,9 +531,7 @@
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 {
@@ -649,12 +556,8 @@
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 {
@@ -666,11 +569,7 @@
// Assert
verify(
mockCameraApi.setExposurePoint(
- argThat(
- predicate(
- (PlatformPoint point) => point.x == 0.4 && point.y == 0.5,
- ),
- ),
+ argThat(predicate((PlatformPoint point) => point.x == 0.4 && point.y == 0.5)),
),
).called(1);
verify(mockCameraApi.setExposurePoint(null)).called(1);
@@ -681,9 +580,7 @@
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);
@@ -694,9 +591,7 @@
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);
@@ -704,9 +599,7 @@
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);
@@ -777,44 +670,30 @@
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(
- () => camera.setZoomLevel(cameraId, -1.0),
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR')
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Illegal zoom error',
- ),
- ),
- );
- },
- );
+ // Act & assert
+ expect(
+ () => camera.setZoomLevel(cameraId, -1.0),
+ throwsA(
+ isA<CameraException>()
+ .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,
- );
+ await camera.lockCaptureOrientation(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 53cd6e9..653be90 100644
--- a/packages/camera/camera_android/test/android_camera_test.mocks.dart
+++ b/packages/camera/camera_android/test/android_camera_test.mocks.dart
@@ -48,18 +48,14 @@
returnValue: _i4.Future<List<_i2.PlatformCameraDescription>>.value(
<_i2.PlatformCameraDescription>[],
),
- returnValueForMissingStub:
- _i4.Future<List<_i2.PlatformCameraDescription>>.value(
- <_i2.PlatformCameraDescription>[],
- ),
+ returnValueForMissingStub: _i4.Future<List<_i2.PlatformCameraDescription>>.value(
+ <_i2.PlatformCameraDescription>[],
+ ),
)
as _i4.Future<List<_i2.PlatformCameraDescription>>);
@override
- _i4.Future<int> create(
- String? cameraName,
- _i2.PlatformMediaSettings? mediaSettings,
- ) =>
+ _i4.Future<int> create(String? cameraName, _i2.PlatformMediaSettings? mediaSettings) =>
(super.noSuchMethod(
Invocation.method(#create, [cameraName, mediaSettings]),
returnValue: _i4.Future<int>.value(0),
@@ -86,9 +82,7 @@
as _i4.Future<void>);
@override
- _i4.Future<void> lockCaptureOrientation(
- _i2.PlatformDeviceOrientation? orientation,
- ) =>
+ _i4.Future<void> lockCaptureOrientation(_i2.PlatformDeviceOrientation? orientation) =>
(super.noSuchMethod(
Invocation.method(#lockCaptureOrientation, [orientation]),
returnValue: _i4.Future<void>.value(),
@@ -132,16 +126,10 @@
(super.noSuchMethod(
Invocation.method(#stopVideoRecording, []),
returnValue: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#stopVideoRecording, []),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#stopVideoRecording, [])),
),
returnValueForMissingStub: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#stopVideoRecording, []),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#stopVideoRecording, [])),
),
)
as _i4.Future<String>);
diff --git a/packages/camera/camera_android/test/method_channel_mock.dart b/packages/camera/camera_android/test/method_channel_mock.dart
index 8c9f5d8..a02b628 100644
--- a/packages/camera/camera_android/test/method_channel_mock.dart
+++ b/packages/camera/camera_android/test/method_channel_mock.dart
@@ -6,13 +6,12 @@
import 'package:flutter_test/flutter_test.dart';
class MethodChannelMock {
- MethodChannelMock({
- required String channelName,
- this.delay,
- required this.methods,
- }) : methodChannel = MethodChannel(channelName) {
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(methodChannel, _handler);
+ MethodChannelMock({required String channelName, this.delay, required this.methods})
+ : methodChannel = MethodChannel(channelName) {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ methodChannel,
+ _handler,
+ );
}
final Duration? delay;
diff --git a/packages/camera/camera_android/test/type_conversion_test.dart b/packages/camera/camera_android/test/type_conversion_test.dart
index 77f82a5..904332f 100644
--- a/packages/camera/camera_android/test/type_conversion_test.dart
+++ b/packages/camera/camera_android/test/type_conversion_test.dart
@@ -10,25 +10,23 @@
void main() {
test('CameraImageData can be created', () {
- final CameraImageData cameraImage = cameraImageFromPlatformData(
- <dynamic, dynamic>{
- 'format': 1,
- 'height': 1,
- 'width': 4,
- 'lensAperture': 1.8,
- 'sensorExposureTime': 9991324,
- 'sensorSensitivity': 92.0,
- 'planes': <dynamic>[
- <dynamic, dynamic>{
- 'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
- 'bytesPerPixel': 1,
- 'bytesPerRow': 4,
- 'height': 1,
- 'width': 4,
- },
- ],
- },
- );
+ final CameraImageData cameraImage = cameraImageFromPlatformData(<dynamic, dynamic>{
+ 'format': 1,
+ 'height': 1,
+ 'width': 4,
+ 'lensAperture': 1.8,
+ 'sensorExposureTime': 9991324,
+ 'sensorSensitivity': 92.0,
+ 'planes': <dynamic>[
+ <dynamic, dynamic>{
+ 'bytes': Uint8List.fromList(<int>[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);
@@ -36,48 +34,44 @@
});
test('CameraImageData has ImageFormatGroup.yuv420', () {
- final CameraImageData cameraImage = cameraImageFromPlatformData(
- <dynamic, dynamic>{
- 'format': 35,
- 'height': 1,
- 'width': 4,
- 'lensAperture': 1.8,
- 'sensorExposureTime': 9991324,
- 'sensorSensitivity': 92.0,
- 'planes': <dynamic>[
- <dynamic, dynamic>{
- 'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
- 'bytesPerPixel': 1,
- 'bytesPerRow': 4,
- 'height': 1,
- 'width': 4,
- },
- ],
- },
- );
+ final CameraImageData cameraImage = cameraImageFromPlatformData(<dynamic, dynamic>{
+ 'format': 35,
+ 'height': 1,
+ 'width': 4,
+ 'lensAperture': 1.8,
+ 'sensorExposureTime': 9991324,
+ 'sensorSensitivity': 92.0,
+ 'planes': <dynamic>[
+ <dynamic, dynamic>{
+ 'bytes': Uint8List.fromList(<int>[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(
- <dynamic, dynamic>{
- 'format': 17,
- 'height': 1,
- 'width': 4,
- 'lensAperture': 1.8,
- 'sensorExposureTime': 9991324,
- 'sensorSensitivity': 92.0,
- 'planes': <dynamic>[
- <dynamic, dynamic>{
- 'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
- 'bytesPerPixel': 1,
- 'bytesPerRow': 4,
- 'height': 1,
- 'width': 4,
- },
- ],
- },
- );
+ final CameraImageData cameraImage = cameraImageFromPlatformData(<dynamic, dynamic>{
+ 'format': 17,
+ 'height': 1,
+ 'width': 4,
+ 'lensAperture': 1.8,
+ 'sensorExposureTime': 9991324,
+ 'sensorSensitivity': 92.0,
+ 'planes': <dynamic>[
+ <dynamic, dynamic>{
+ 'bytes': Uint8List.fromList(<int>[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 ed89cb1..c8cf634 100644
--- a/packages/camera/camera_android/test/utils_test.dart
+++ b/packages/camera/camera_android/test/utils_test.dart
@@ -48,14 +48,8 @@
});
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_android_camerax/example/integration_test/integration_test.dart b/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart
index 145186e..41bf383 100644
--- a/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart
+++ b/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart
@@ -43,31 +43,23 @@
testWidgets('availableCameras only supports valid back or front cameras', (
WidgetTester tester,
) async {
- final List<CameraDescription> availableCameras = await CameraPlatform
- .instance
+ final List<CameraDescription> availableCameras = await CameraPlatform.instance
.availableCameras();
for (final cameraDescription in availableCameras) {
- expect(
- cameraDescription.lensDirection,
- isNot(CameraLensDirection.external),
- );
+ expect(cameraDescription.lensDirection, isNot(CameraLensDirection.external));
expect(cameraDescription.sensorOrientation, anyOf(0, 90, 180, 270));
}
});
- testWidgets('Preview takes expected resolution from preset', (
- WidgetTester tester,
- ) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ testWidgets('Preview takes expected resolution from preset', (WidgetTester tester) async {
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final cameraDescription in cameras) {
var previousPresetExactlySupported = true;
- for (final MapEntry<ResolutionPreset, Size> preset
- in presetExpectedSizes.entries) {
+ for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) {
final controller = CameraController(
cameraDescription,
mediaSettings: MediaSettings(resolutionPreset: preset.key),
@@ -100,15 +92,13 @@
testWidgets('Images from streaming have expected resolution from preset', (
WidgetTester tester,
) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final cameraDescription in cameras) {
var previousPresetExactlySupported = true;
- for (final MapEntry<ResolutionPreset, Size> preset
- in presetExpectedSizes.entries) {
+ for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) {
final controller = CameraController(
cameraDescription,
mediaSettings: MediaSettings(resolutionPreset: preset.key),
@@ -148,9 +138,7 @@
final controller = CameraController(
cameras[0],
- mediaSettings: const MediaSettings(
- resolutionPreset: ResolutionPreset.low,
- ),
+ mediaSettings: const MediaSettings(resolutionPreset: ResolutionPreset.low),
);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -161,8 +149,7 @@
await Future<void>.delayed(const Duration(seconds: 2));
final XFile file = await controller.stopVideoRecording();
- final int postStopTime =
- DateTime.now().millisecondsSinceEpoch - recordingStart;
+ final int postStopTime = DateTime.now().millisecondsSinceEpoch - recordingStart;
final videoFile = File(file.path);
final videoController = VideoPlayerController.file(videoFile);
@@ -181,9 +168,7 @@
final controller = CameraController(
cameras[0],
- mediaSettings: const MediaSettings(
- resolutionPreset: ResolutionPreset.low,
- ),
+ mediaSettings: const MediaSettings(resolutionPreset: ResolutionPreset.low),
);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -208,8 +193,7 @@
}
final XFile file = await controller.stopVideoRecording();
- final int recordingTime =
- DateTime.now().millisecondsSinceEpoch - recordingStart;
+ final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart;
final videoFile = File(file.path);
final videoController = VideoPlayerController.file(videoFile);
@@ -220,9 +204,7 @@
expect(duration, lessThan(recordingTime - timePaused));
});
- testWidgets('Set description while recording captures full video', (
- WidgetTester tester,
- ) async {
+ testWidgets('Set description while recording captures full video', (WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.length < 2) {
return;
@@ -258,10 +240,7 @@
final int duration = videoController.value.duration.inMilliseconds;
await videoController.dispose();
- expect(
- duration,
- greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds),
- );
+ expect(duration, greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds));
await controller.dispose();
});
}
diff --git a/packages/camera/camera_android_camerax/example/lib/camera_controller.dart b/packages/camera/camera_android_camerax/example/lib/camera_controller.dart
index 7d45604..a6f20d0 100644
--- a/packages/camera/camera_android_camerax/example/lib/camera_controller.dart
+++ b/packages/camera/camera_android_camerax/example/lib/camera_controller.dart
@@ -179,8 +179,7 @@
flashMode: flashMode ?? this.flashMode,
exposureMode: exposureMode ?? this.exposureMode,
focusMode: focusMode ?? this.focusMode,
- exposurePointSupported:
- exposurePointSupported ?? this.exposurePointSupported,
+ exposurePointSupported: exposurePointSupported ?? this.exposurePointSupported,
focusPointSupported: focusPointSupported ?? this.focusPointSupported,
deviceOrientation: deviceOrientation ?? this.deviceOrientation,
lockedCaptureOrientation: lockedCaptureOrientation == null
@@ -228,11 +227,8 @@
/// To show the camera preview on the screen use a [CameraPreview] widget.
class CameraController extends ValueNotifier<CameraValue> {
/// Creates a new camera controller in an uninitialized state.
- CameraController(
- CameraDescription description, {
- this.mediaSettings,
- this.imageFormatGroup,
- }) : super(CameraValue.uninitialized(description));
+ CameraController(CameraDescription description, {this.mediaSettings, this.imageFormatGroup})
+ : super(CameraValue.uninitialized(description));
/// The properties of the camera device controlled by this controller.
CameraDescription get description => value.description;
@@ -258,8 +254,7 @@
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
FutureOr<bool>? _initCalled;
- StreamSubscription<DeviceOrientationChangedEvent>?
- _deviceOrientationSubscription;
+ StreamSubscription<DeviceOrientationChangedEvent>? _deviceOrientationSubscription;
/// Checks whether [CameraController.dispose] has completed successfully.
///
@@ -289,11 +284,11 @@
try {
final initializeCompleter = Completer<CameraInitializedEvent>();
- _deviceOrientationSubscription = CameraPlatform.instance
- .onDeviceOrientationChanged()
- .listen((DeviceOrientationChangedEvent event) {
- value = value.copyWith(deviceOrientation: event.orientation);
- });
+ _deviceOrientationSubscription = CameraPlatform.instance.onDeviceOrientationChanged().listen((
+ DeviceOrientationChangedEvent event,
+ ) {
+ value = value.copyWith(deviceOrientation: event.orientation);
+ });
_cameraId = await CameraPlatform.instance.createCameraWithSettings(
description,
@@ -316,8 +311,7 @@
value = value.copyWith(
isInitialized: true,
previewSize: await initializeCompleter.future.then(
- (CameraInitializedEvent event) =>
- Size(event.previewWidth, event.previewHeight),
+ (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight),
),
exposureMode: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposureMode,
@@ -447,11 +441,11 @@
}
try {
- _imageStreamSubscription = CameraPlatform.instance
- .onStreamedFrameAvailable(_cameraId)
- .listen((CameraImageData imageData) {
- onAvailable(CameraImage.fromPlatformInterface(imageData));
- });
+ _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen(
+ (CameraImageData imageData) {
+ onAvailable(CameraImage.fromPlatformInterface(imageData));
+ },
+ );
value = value.copyWith(isStreamingImages: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
@@ -556,9 +550,7 @@
}
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<DeviceOrientation>.absent(),
@@ -691,11 +683,8 @@
/// Supplying a `null` value will reset the exposure point to it's default
/// value.
Future<void> setExposurePoint(Offset? point) async {
- 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).',
- );
+ 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).');
}
try {
@@ -818,9 +807,7 @@
Future<void> unlockCaptureOrientation() async {
try {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
- value = value.copyWith(
- lockedCaptureOrientation: const Optional<DeviceOrientation>.absent(),
- );
+ value = value.copyWith(lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
@@ -831,11 +818,8 @@
/// Supplying a `null` value will reset the focus point to it's default
/// value.
Future<void> setFocusPoint(Offset? point) async {
- 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).',
- );
+ 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).');
}
try {
await CameraPlatform.instance.setFocusPoint(
@@ -955,9 +939,7 @@
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T value) transformer) {
- return _value == null
- ? Optional<S>.absent()
- : Optional<S>.of(transformer(_value as T));
+ return _value == null ? Optional<S>.absent() : Optional<S>.of(transformer(_value as T));
}
/// Transforms the Optional value.
@@ -972,8 +954,7 @@
}
@override
- Iterator<T> get iterator =>
- isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
+ Iterator<T> get iterator => isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
@@ -985,8 +966,6 @@
@override
String toString() {
- return _value == null
- ? 'Optional { absent }'
- : 'Optional { value: $_value }';
+ return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }';
}
}
diff --git a/packages/camera/camera_android_camerax/example/lib/camera_image.dart b/packages/camera/camera_android_camerax/example/lib/camera_image.dart
index ff7de7a..d6c144b 100644
--- a/packages/camera/camera_android_camerax/example/lib/camera_image.dart
+++ b/packages/camera/camera_android_camerax/example/lib/camera_image.dart
@@ -122,9 +122,7 @@
height = data.height,
width = data.width,
planes = List<Plane>.unmodifiable(
- data.planes.map<Plane>(
- (CameraImagePlane plane) => Plane._fromPlatformInterface(plane),
- ),
+ data.planes.map<Plane>((CameraImagePlane plane) => Plane._fromPlatformInterface(plane)),
),
lensAperture = data.lensAperture,
sensorExposureTime = data.sensorExposureTime,
@@ -141,8 +139,7 @@
sensorSensitivity = data['sensorSensitivity'] as double?,
planes = List<Plane>.unmodifiable(
(data['planes'] as List<dynamic>).map<Plane>(
- (dynamic planeData) =>
- Plane._fromPlatformData(planeData as Map<dynamic, dynamic>),
+ (dynamic planeData) => Plane._fromPlatformData(planeData as Map<dynamic, dynamic>),
),
);
diff --git a/packages/camera/camera_android_camerax/example/lib/main.dart b/packages/camera/camera_android_camerax/example/lib/main.dart
index b108b9a..f53ed14 100644
--- a/packages/camera/camera_android_camerax/example/lib/main.dart
+++ b/packages/camera/camera_android_camerax/example/lib/main.dart
@@ -140,8 +140,7 @@
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
- color:
- controller != null && controller!.value.isRecordingVideo
+ color: controller != null && controller!.value.isRecordingVideo
? Colors.redAccent
: Colors.grey,
width: 3.0,
@@ -157,9 +156,7 @@
_modeControlRowWidget(),
Padding(
padding: const EdgeInsets.all(5.0),
- child: Row(
- children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()],
- ),
+ child: Row(children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()]),
),
],
),
@@ -173,11 +170,7 @@
if (cameraController == null || !cameraController.value.isInitialized) {
return const Text(
'Tap a camera',
- style: TextStyle(
- color: Colors.white,
- fontSize: 24.0,
- fontWeight: FontWeight.w900,
- ),
+ style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900),
);
} else {
return Listener(
@@ -191,8 +184,7 @@
behavior: HitTestBehavior.opaque,
onScaleStart: _handleScaleStart,
onScaleUpdate: _handleScaleUpdate,
- onTapDown: (TapDownDetails details) =>
- onViewFinderTap(details, constraints),
+ onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints),
);
},
),
@@ -211,10 +203,7 @@
return;
}
- _currentScale = (_baseScale * details.scale).clamp(
- _minAvailableZoom,
- _maxAvailableZoom,
- );
+ _currentScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom);
await controller!.setZoomLevel(_currentScale);
}
@@ -241,13 +230,9 @@
// pointing to a location within the browser. It may be displayed
// either with Image.network or Image.memory after loading the image
// bytes to memory.
- kIsWeb
- ? Image.network(imageFile!.path)
- : Image.file(File(imageFile!.path)))
+ kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path)))
: Container(
- decoration: BoxDecoration(
- border: Border.all(color: Colors.pink),
- ),
+ decoration: BoxDecoration(border: Border.all(color: Colors.pink)),
child: Center(
child: AspectRatio(
aspectRatio: localVideoController.value.aspectRatio,
@@ -280,16 +265,12 @@
IconButton(
icon: const Icon(Icons.exposure),
color: Colors.blue,
- onPressed: controller != null
- ? onExposureModeButtonPressed
- : null,
+ onPressed: controller != null ? onExposureModeButtonPressed : null,
),
IconButton(
icon: const Icon(Icons.filter_center_focus),
color: Colors.blue,
- onPressed: controller != null
- ? onFocusModeButtonPressed
- : null,
+ onPressed: controller != null ? onFocusModeButtonPressed : null,
),
]
: <Widget>[],
@@ -305,9 +286,7 @@
: Icons.screen_rotation,
),
color: Colors.blue,
- onPressed: controller != null
- ? onCaptureOrientationLockButtonPressed
- : null,
+ onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null,
),
],
),
@@ -327,36 +306,28 @@
children: <Widget>[
IconButton(
icon: const Icon(Icons.flash_off),
- color: controller?.value.flashMode == FlashMode.off
- ? Colors.orange
- : Colors.blue,
+ 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,
+ 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,
+ 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,
+ color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue,
onPressed: controller != null
? () => onSetFlashModeButtonPressed(FlashMode.torch)
: null,
@@ -393,15 +364,11 @@
TextButton(
style: styleAuto,
onPressed: controller != null
- ? () =>
- onSetExposureModeButtonPressed(ExposureMode.auto)
+ ? () => onSetExposureModeButtonPressed(ExposureMode.auto)
: null,
onLongPress: () {
if (controller != null) {
- CameraPlatform.instance.setExposurePoint(
- controller!.cameraId,
- null,
- );
+ CameraPlatform.instance.setExposurePoint(controller!.cameraId, null);
showInSnackBar('Resetting exposure point');
}
},
@@ -410,17 +377,13 @@
TextButton(
style: styleLocked,
onPressed: controller != null
- ? () => onSetExposureModeButtonPressed(
- ExposureMode.locked,
- )
+ ? () => 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'),
),
],
@@ -436,9 +399,7 @@
max: _maxAvailableExposureOffset,
label: _currentExposureOffset.toString(),
onChanged: (_) {},
- onChangeEnd:
- _minAvailableExposureOffset ==
- _maxAvailableExposureOffset
+ onChangeEnd: _minAvailableExposureOffset == _maxAvailableExposureOffset
? null
: setExposureOffset,
),
@@ -454,9 +415,7 @@
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
@@ -482,10 +441,7 @@
: null,
onLongPress: () {
if (controller != null) {
- CameraPlatform.instance.setFocusPoint(
- controller!.cameraId,
- null,
- );
+ CameraPlatform.instance.setFocusPoint(controller!.cameraId, null);
}
showInSnackBar('Resetting focus point');
},
@@ -527,14 +483,10 @@
IconButton(
icon: const Icon(Icons.videocam),
color: Colors.blue,
- onPressed: cameraController == null
- ? null
- : onVideoRecordButtonPressed,
+ onPressed: cameraController == null ? null : onVideoRecordButtonPressed,
),
IconButton(
- icon:
- cameraController != null &&
- cameraController.value.isRecordingPaused
+ icon: cameraController != null && cameraController.value.isRecordingPaused
? const Icon(Icons.play_arrow)
: const Icon(Icons.pause),
color: Colors.blue,
@@ -555,13 +507,10 @@
),
IconButton(
icon: const Icon(Icons.pause_presentation),
- color:
- cameraController != null && cameraController.value.isPreviewPaused
+ color: cameraController != null && cameraController.value.isPreviewPaused
? Colors.red
: Colors.blue,
- onPressed: cameraController == null
- ? null
- : onPausePreviewButtonPressed,
+ onPressed: cameraController == null ? null : onPausePreviewButtonPressed,
),
],
);
@@ -608,9 +557,7 @@
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,9 +583,7 @@
}
}
- Future<void> _initializeCameraController(
- CameraDescription cameraDescription,
- ) async {
+ Future<void> _initializeCameraController(CameraDescription cameraDescription) async {
final cameraController = CameraController(
cameraDescription,
mediaSettings: MediaSettings(
@@ -659,9 +604,7 @@
setState(() {});
}
if (cameraController.value.hasError) {
- showInSnackBar(
- 'Camera error ${cameraController.value.errorDescription}',
- );
+ showInSnackBar('Camera error ${cameraController.value.errorDescription}');
}
});
@@ -679,12 +622,8 @@
),
]
: <Future<Object?>>[],
- 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) {
diff --git a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart
index e52e4bd..0c84bdf 100644
--- a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart
+++ b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart
@@ -8,8 +8,7 @@
import 'package:async/async.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart' show Uint8List;
-import 'package:flutter/services.dart'
- show DeviceOrientation, PlatformException;
+import 'package:flutter/services.dart' show DeviceOrientation, PlatformException;
import 'package:flutter/widgets.dart' show Texture, Widget, visibleForTesting;
import 'package:stream_transform/stream_transform.dart';
import 'camerax_library.dart';
@@ -71,28 +70,24 @@
String? videoOutputPath;
/// Handles access to system resources.
- late final SystemServicesManager systemServicesManager =
- SystemServicesManager(
- onCameraError: (_, String errorDescription) {
- cameraErrorStreamController.add(errorDescription);
- },
- );
+ late final SystemServicesManager systemServicesManager = SystemServicesManager(
+ onCameraError: (_, String errorDescription) {
+ cameraErrorStreamController.add(errorDescription);
+ },
+ );
/// Handles retrieving media orientation for a device.
- late final DeviceOrientationManager deviceOrientationManager =
- DeviceOrientationManager(
- onDeviceOrientationChanged: (_, String orientation) {
- final DeviceOrientation deviceOrientation =
- _deserializeDeviceOrientation(orientation);
- deviceOrientationChangedStreamController.add(
- DeviceOrientationChangedEvent(deviceOrientation),
- );
- },
+ late final DeviceOrientationManager deviceOrientationManager = DeviceOrientationManager(
+ onDeviceOrientationChanged: (_, String orientation) {
+ final DeviceOrientation deviceOrientation = _deserializeDeviceOrientation(orientation);
+ deviceOrientationChangedStreamController.add(
+ DeviceOrientationChangedEvent(deviceOrientation),
);
+ },
+ );
/// Stream that emits an event when the corresponding video recording is finalized.
- static final StreamController<VideoRecordEvent>
- videoRecordingEventStreamController =
+ static final StreamController<VideoRecordEvent> videoRecordingEventStreamController =
StreamController<VideoRecordEvent>.broadcast();
/// Stream that emits the errors caused by camera usage on the native side.
@@ -112,12 +107,11 @@
final StreamQueue<VideoRecordEvent> videoRecordingEventStreamQueue =
StreamQueue<VideoRecordEvent>(videoRecordingEventStreamController.stream);
- late final VideoRecordEventListener _videoRecordingEventListener =
- VideoRecordEventListener(
- onEvent: (_, VideoRecordEvent event) {
- videoRecordingEventStreamController.add(event);
- },
- );
+ late final VideoRecordEventListener _videoRecordingEventListener = VideoRecordEventListener(
+ onEvent: (_, VideoRecordEvent event) {
+ videoRecordingEventStreamController.add(event);
+ },
+ );
/// Whether or not [preview] has been bound to the lifecycle of the camera by
/// [createCamera].
@@ -161,9 +155,8 @@
StreamController<CameraEvent>.broadcast();
/// The stream of camera events for the camera with ID cameraId.
- Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
- .stream
- .where((CameraEvent event) => event.cameraId == cameraId);
+ Stream<CameraEvent> _cameraEvents(int cameraId) =>
+ cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId);
/// The controller we need to stream image data.
@visibleForTesting
@@ -217,8 +210,7 @@
bool shouldSetDefaultRotation = false;
/// Error code indicating that an exposure offset value failed to be set.
- static const String setExposureOffsetFailedErrorCode =
- 'setExposureOffsetFailed';
+ static const String setExposureOffsetFailedErrorCode = 'setExposureOffsetFailed';
/// The currently set [FocusMeteringAction] used to enable auto-focus and
/// auto-exposure.
@@ -245,8 +237,7 @@
/// Error code indicating that exposure compensation is not supported by
/// CameraX for the device.
- static const String exposureCompensationNotSupported =
- 'exposureCompensationNotSupported';
+ static const String exposureCompensationNotSupported = 'exposureCompensationNotSupported';
/// Whether or not the created camera is front facing.
@visibleForTesting
@@ -299,8 +290,8 @@
final cameraDescriptions = <CameraDescription>[];
processCameraProvider ??= await ProcessCameraProvider.getInstance();
- final List<CameraInfo> cameraInfos =
- (await processCameraProvider!.getAvailableCameraInfos()).cast();
+ final List<CameraInfo> cameraInfos = (await processCameraProvider!.getAvailableCameraInfos())
+ .cast();
CameraLensDirection? cameraLensDirection;
int? cameraSensorOrientation;
@@ -321,9 +312,7 @@
}
cameraSensorOrientation = cameraInfo.sensorRotationDegrees;
- cameraName = await Camera2CameraInfo.from(
- cameraInfo: cameraInfo,
- ).getCameraId();
+ cameraName = await Camera2CameraInfo.from(cameraInfo: cameraInfo).getCameraId();
_savedCameras[cameraName] = cameraInfo;
@@ -374,8 +363,9 @@
MediaSettings? mediaSettings,
) async {
enableRecordingAudio = mediaSettings?.enableAudio ?? false;
- final CameraPermissionsError? error = await systemServicesManager
- .requestCameraPermissions(enableRecordingAudio);
+ final CameraPermissionsError? error = await systemServicesManager.requestCameraPermissions(
+ enableRecordingAudio,
+ );
if (error != null) {
throw CameraException(error.errorCode, error.description);
@@ -384,27 +374,25 @@
final CameraInfo? chosenCameraInfo = _savedCameras[cameraDescription.name];
// Save CameraSelector that matches cameraDescription.
- final LensFacing cameraSelectorLensDirection =
- _getCameraSelectorLensDirection(cameraDescription.lensDirection);
+ final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection(
+ cameraDescription.lensDirection,
+ );
cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front;
cameraSelector = CameraSelector(cameraInfoForFilter: chosenCameraInfo);
// Start listening for device orientation changes preceding camera creation.
- unawaited(
- deviceOrientationManager.startListeningForDeviceOrientationChange(),
- );
+ unawaited(deviceOrientationManager.startListeningForDeviceOrientationChange());
// Determine ResolutionSelector and QualitySelector based on
// resolutionPreset for camera UseCases.
- _presetResolutionSelector = _getResolutionSelectorFromPreset(
- mediaSettings?.resolutionPreset,
- );
+ _presetResolutionSelector = _getResolutionSelectorFromPreset(mediaSettings?.resolutionPreset);
final int? targetFps = mediaSettings?.fps;
if (targetFps != null) {
_targetFpsRange = CameraIntegerRange(lower: targetFps, upper: targetFps);
}
- final QualitySelector? presetQualitySelector =
- _getQualitySelectorFromPreset(mediaSettings?.resolutionPreset);
+ final QualitySelector? presetQualitySelector = _getQualitySelectorFromPreset(
+ mediaSettings?.resolutionPreset,
+ );
// Retrieve a fresh ProcessCameraProvider instance.
processCameraProvider ??= await ProcessCameraProvider.getInstance();
@@ -415,34 +403,27 @@
resolutionSelector: _presetResolutionSelector,
targetFpsRange: _targetFpsRange,
);
- _flutterSurfaceTextureId = await preview!.setSurfaceProvider(
- systemServicesManager,
- );
+ _flutterSurfaceTextureId = await preview!.setSurfaceProvider(systemServicesManager);
// Configure ImageCapture instance.
imageCapture = ImageCapture(
resolutionSelector: _presetResolutionSelector,
- /* use CameraX default target rotation */ targetRotation:
- await deviceOrientationManager.getDefaultDisplayRotation(),
+ /* use CameraX default target rotation */ targetRotation: await deviceOrientationManager
+ .getDefaultDisplayRotation(),
);
// Configure VideoCapture and Recorder instances.
recorder = Recorder(qualitySelector: presetQualitySelector);
- videoCapture = VideoCapture.withOutput(
- videoOutput: recorder!,
- targetFpsRange: _targetFpsRange,
- );
+ videoCapture = VideoCapture.withOutput(videoOutput: recorder!, targetFpsRange: _targetFpsRange);
// Retrieve info required for correcting the rotation of the camera preview
// if necessary.
sensorOrientationDegrees = cameraDescription.sensorOrientation.toDouble();
- _handlesCropAndRotation = await preview!
- .surfaceProducerHandlesCropAndRotation();
+ _handlesCropAndRotation = await preview!.surfaceProducerHandlesCropAndRotation();
_initialDeviceOrientation = _deserializeDeviceOrientation(
await deviceOrientationManager.getUiOrientation(),
);
- _initialDefaultDisplayRotation = await deviceOrientationManager
- .getDefaultDisplayRotation();
+ _initialDefaultDisplayRotation = await deviceOrientationManager.getDefaultDisplayRotation();
return _flutterSurfaceTextureId;
}
@@ -474,8 +455,9 @@
}
// Configure ImageAnalysis instance.
// Defaults to YUV_420_888 image format.
- _imageAnalysisOutputImageFormat =
- _imageAnalysisOutputFormatFromImageFormatGroup(imageFormatGroup);
+ _imageAnalysisOutputImageFormat = _imageAnalysisOutputFormatFromImageFormatGroup(
+ imageFormatGroup,
+ );
imageAnalysis = ImageAnalysis(
resolutionSelector: _presetResolutionSelector,
targetFpsRange: _targetFpsRange,
@@ -485,10 +467,11 @@
// Bind configured UseCases to ProcessCameraProvider instance & mark Preview
// instance as bound but not paused. Video capture is bound at first use
// instead of here.
- camera = await processCameraProvider!.bindToLifecycle(
- cameraSelector!,
- <UseCase>[preview!, imageCapture!, imageAnalysis!],
- );
+ camera = await processCameraProvider!.bindToLifecycle(cameraSelector!, <UseCase>[
+ preview!,
+ imageCapture!,
+ imageAnalysis!,
+ ]);
await _updateCameraInfoAndLiveCameraState(_flutterSurfaceTextureId);
previewInitiallyBound = true;
_previewIsPaused = false;
@@ -497,8 +480,7 @@
// configured camera:
// Retrieve preview resolution.
- final ResolutionInfo previewResolutionInfo = (await preview!
- .getResolutionInfo())!;
+ final ResolutionInfo previewResolutionInfo = (await preview!.getResolutionInfo())!;
// Mark auto-focus, auto-exposure and setting points for focus & exposure
// as available operations as CameraX does its best across devices to
@@ -554,16 +536,12 @@
/// The camera with ID [cameraId] experienced an error.
@override
Stream<CameraErrorEvent> onCameraError(int cameraId) {
- return StreamGroup.mergeBroadcast<CameraErrorEvent>(
- <Stream<CameraErrorEvent>>[
- cameraErrorStreamController.stream.map<CameraErrorEvent>((
- String errorDescription,
- ) {
- return CameraErrorEvent(cameraId, errorDescription);
- }),
- _cameraEvents(cameraId).whereType<CameraErrorEvent>(),
- ],
- );
+ return StreamGroup.mergeBroadcast<CameraErrorEvent>(<Stream<CameraErrorEvent>>[
+ cameraErrorStreamController.stream.map<CameraErrorEvent>((String errorDescription) {
+ return CameraErrorEvent(cameraId, errorDescription);
+ }),
+ _cameraEvents(cameraId).whereType<CameraErrorEvent>(),
+ ]);
}
/// The camera with ID [cameraId] finished recording a video.
@@ -574,10 +552,7 @@
/// Locks the capture orientation of camera with ID [cameraId].
@override
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) async {
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async {
// Flag that (1) default rotation for UseCases will need to be set manually
// if orientation is ever unlocked and (2) the capture orientation is locked
// and should not be changed until unlocked.
@@ -585,9 +560,7 @@
captureOrientationLocked = true;
// Get target rotation based on locked orientation.
- final int targetLockedRotation = _getRotationConstantFromDeviceOrientation(
- orientation,
- );
+ final int targetLockedRotation = _getRotationConstantFromDeviceOrientation(orientation);
// Update UseCases to use target device orientation.
await imageCapture!.setTargetRotation(targetLockedRotation);
@@ -628,16 +601,14 @@
@override
Future<double> getMinExposureOffset(int cameraId) async {
final ExposureState exposureState = cameraInfo!.exposureState;
- return exposureState.exposureCompensationRange.lower *
- exposureState.exposureCompensationStep;
+ return exposureState.exposureCompensationRange.lower * exposureState.exposureCompensationStep;
}
/// Gets the maximum supported exposure offset for the camera with ID [cameraId] in EV units.
@override
Future<double> getMaxExposureOffset(int cameraId) async {
final ExposureState exposureState = cameraInfo!.exposureState;
- return exposureState.exposureCompensationRange.upper *
- exposureState.exposureCompensationStep;
+ return exposureState.exposureCompensationRange.upper * exposureState.exposureCompensationStep;
}
/// Sets the focus mode for taking pictures with camera with ID [cameraId]
@@ -674,9 +645,7 @@
if (currentFocusMeteringAction != null) {
final List<MeteringPoint> possibleCurrentAfPoints =
currentFocusMeteringAction!.meteringPointsAf;
- lockedFocusPoint = possibleCurrentAfPoints.isEmpty
- ? null
- : possibleCurrentAfPoints.first;
+ lockedFocusPoint = possibleCurrentAfPoints.isEmpty ? null : possibleCurrentAfPoints.first;
}
// If there isn't, lock center of entire sensor area by default.
@@ -686,11 +655,7 @@
width: 1,
height: 1,
);
- lockedFocusPoint = await meteringPointFactory.createPointWithSize(
- 0.5,
- 0.5,
- 1,
- );
+ lockedFocusPoint = await meteringPointFactory.createPointWithSize(0.5, 0.5, 1);
_defaultFocusPointLocked = true;
}
@@ -715,8 +680,7 @@
// If focus mode was just locked and exposure mode is not, set auto exposure
// mode to ensure that disabling auto-cancel does not interfere with
// automatic exposure metering.
- if (_currentExposureMode == ExposureMode.auto &&
- _currentFocusMode == FocusMode.locked) {
+ if (_currentExposureMode == ExposureMode.auto && _currentFocusMode == FocusMode.locked) {
await setExposureMode(cameraId, _currentExposureMode);
}
}
@@ -727,8 +691,7 @@
@override
Future<double> getExposureOffsetStepSize(int cameraId) async {
final ExposureState exposureState = cameraInfo!.exposureState;
- final double exposureOffsetStepSize =
- exposureState.exposureCompensationStep;
+ final double exposureOffsetStepSize = exposureState.exposureCompensationStep;
if (exposureOffsetStepSize == 0) {
// CameraX returns a step size of 0 if exposure compensation is not
// supported for the device.
@@ -752,8 +715,7 @@
/// Returns the (rounded) offset value that was set.
@override
Future<double> setExposureOffset(int cameraId, double offset) async {
- final double exposureOffsetStepSize =
- cameraInfo!.exposureState.exposureCompensationStep;
+ final double exposureOffsetStepSize = cameraInfo!.exposureState.exposureCompensationStep;
if (exposureOffsetStepSize == 0) {
throw CameraException(
exposureCompensationNotSupported,
@@ -763,8 +725,7 @@
// (Exposure compensation index) * (exposure offset step size) =
// (exposure offset).
- final int roundedExposureCompensationIndex =
- (offset / exposureOffsetStepSize).round();
+ final int roundedExposureCompensationIndex = (offset / exposureOffsetStepSize).round();
try {
final int? newIndex = await cameraControl.setExposureCompensationIndex(
@@ -824,15 +785,11 @@
/// is unset by setting [ExposureMode.auto].
@override
Future<void> setExposureMode(int cameraId, ExposureMode mode) async {
- final camera2Control = Camera2CameraControl.from(
- cameraControl: cameraControl,
- );
+ final camera2Control = Camera2CameraControl.from(cameraControl: cameraControl);
final lockExposureMode = mode == ExposureMode.locked;
final captureRequestOptions = CaptureRequestOptions(
- options: <CaptureRequestKey, Object?>{
- CaptureRequest.controlAELock: lockExposureMode,
- },
+ options: <CaptureRequestKey, Object?>{CaptureRequest.controlAELock: lockExposureMode},
);
try {
@@ -895,19 +852,14 @@
}
@override
- Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(
- int cameraId,
- ) async {
+ Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(int cameraId) async {
return (await _getSupportedVideoStabilizationModeMap(cameraId)).keys;
}
/// Throws a [ArgumentError] when an unsupported [mode] is
/// supplied.
@override
- Future<void> setVideoStabilizationMode(
- int cameraId,
- VideoStabilizationMode mode,
- ) async {
+ Future<void> setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) async {
final Map<VideoStabilizationMode, int> availableModes =
await _getSupportedVideoStabilizationModeMap(cameraId);
@@ -922,16 +874,15 @@
},
);
- final camera2Control = Camera2CameraControl.from(
- cameraControl: cameraControl,
- );
+ final camera2Control = Camera2CameraControl.from(cameraControl: cameraControl);
await camera2Control.addCaptureRequestOptions(captureRequestOptions);
}
/// Gets a map of video stabilization control modes that are supported for the
/// selected camera, indexed by the respective [VideoStabilizationMode].
- Future<Map<VideoStabilizationMode, int>>
- _getSupportedVideoStabilizationModeMap(int cameraId) async {
+ Future<Map<VideoStabilizationMode, int>> _getSupportedVideoStabilizationModeMap(
+ int cameraId,
+ ) async {
if (cameraInfo == null) {
return <VideoStabilizationMode, int>{};
}
@@ -977,20 +928,17 @@
/// you must start the recording with [startVideoCapturing]
/// with `enablePersistentRecording` set to `true`.
@override
- Future<void> setDescriptionWhileRecording(
- CameraDescription description,
- ) async {
+ Future<void> setDescriptionWhileRecording(CameraDescription description) async {
if (recording == null) {
- cameraErrorStreamController.add(
- 'Camera description not set. No active video recording.',
- );
+ cameraErrorStreamController.add('Camera description not set. No active video recording.');
return;
}
final CameraInfo? chosenCameraInfo = _savedCameras[description.name];
// Save CameraSelector that matches cameraDescription.
- final LensFacing cameraSelectorLensDirection =
- _getCameraSelectorLensDirection(description.lensDirection);
+ final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection(
+ description.lensDirection,
+ );
cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front;
cameraSelector = CameraSelector(cameraInfoForFilter: chosenCameraInfo);
@@ -999,19 +947,14 @@
if (!_previewIsPaused) {
useCases.add(preview!);
}
- if (imageCapture != null &&
- await processCameraProvider!.isBound(imageCapture!)) {
+ if (imageCapture != null && await processCameraProvider!.isBound(imageCapture!)) {
useCases.add(imageCapture!);
}
- if (imageAnalysis != null &&
- await processCameraProvider!.isBound(imageAnalysis!)) {
+ if (imageAnalysis != null && await processCameraProvider!.isBound(imageAnalysis!)) {
useCases.add(imageAnalysis!);
}
await processCameraProvider?.unbindAll();
- camera = await processCameraProvider?.bindToLifecycle(
- cameraSelector!,
- useCases,
- );
+ camera = await processCameraProvider?.bindToLifecycle(cameraSelector!, useCases);
// Retrieve info required for correcting the rotation of the camera preview
sensorOrientationDegrees = description.sensorOrientation.toDouble();
@@ -1042,10 +985,9 @@
);
}
- final Stream<DeviceOrientation> deviceOrientationStream =
- onDeviceOrientationChanged().map(
- (DeviceOrientationChangedEvent e) => e.orientation,
- );
+ final Stream<DeviceOrientation> deviceOrientationStream = onDeviceOrientationChanged().map(
+ (DeviceOrientationChangedEvent e) => e.orientation,
+ );
final Widget preview = Texture(textureId: cameraId);
return RotatedPreviewDelegate(
@@ -1081,9 +1023,7 @@
);
}
- final String picturePath = await imageCapture!.takePicture(
- systemServicesManager,
- );
+ final String picturePath = await imageCapture!.takePicture(systemServicesManager);
return XFile(picturePath);
}
@@ -1145,10 +1085,7 @@
///
/// This method is deprecated in favour of [startVideoCapturing].
@override
- Future<void> startVideoRecording(
- int cameraId, {
- Duration? maxVideoDuration,
- }) async {
+ Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async {
// Ignore maxVideoDuration, as it is unimplemented and deprecated.
return startVideoCapturing(VideoCaptureOptions(cameraId));
}
@@ -1164,8 +1101,7 @@
// There is currently an active recording, so do not start a new one.
return;
}
- final dynamic Function(CameraImageData)? streamCallback =
- options.streamCallback;
+ final dynamic Function(CameraImageData)? streamCallback = options.streamCallback;
if (streamCallback == null) {
// For potential performance improvements, unbind imageAnalysis if not in use.
// See https://developer.android.com/media/camera/camerax/architecture#combine-use-cases
@@ -1183,10 +1119,7 @@
);
}
- videoOutputPath = await systemServicesManager.getTempFilePath(
- videoPrefix,
- '.mp4',
- );
+ videoOutputPath = await systemServicesManager.getTempFilePath(videoPrefix, '.mp4');
pendingRecording = await recorder!.prepareRecording(videoOutputPath!);
if (options.enablePersistentRecording) {
@@ -1251,9 +1184,7 @@
await _unbindUseCaseFromLifecycle(videoCapture!);
final videoFile = XFile(videoOutputPath!);
- cameraEventStreamController.add(
- VideoRecordedEvent(cameraId, videoFile, /* duration */ null),
- );
+ cameraEventStreamController.add(VideoRecordedEvent(cameraId, videoFile, /* duration */ null));
return videoFile;
}
@@ -1321,10 +1252,7 @@
return;
}
- camera = await processCameraProvider!.bindToLifecycle(
- cameraSelector!,
- <UseCase>[useCase],
- );
+ camera = await processCameraProvider!.bindToLifecycle(cameraSelector!, <UseCase>[useCase]);
await _updateCameraInfoAndLiveCameraState(cameraId);
}
@@ -1348,8 +1276,7 @@
final cameraImagePlanes = <CameraImagePlane>[];
// Determine image planes.
- if (_imageAnalysisOutputImageFormat ==
- imageAnalysisOutputImageFormatNv21) {
+ if (_imageAnalysisOutputImageFormat == imageAnalysisOutputImageFormatNv21) {
// Convert three generically YUV_420_888 formatted image planes into one singular
// NV21 formatted image plane if NV21 was requested for image streaming. The conversion
// should be null safe.
@@ -1383,8 +1310,7 @@
// Determine image format.
CameraImageFormat? cameraImageFormat;
- if (_imageAnalysisOutputImageFormat ==
- imageAnalysisOutputImageFormatNv21) {
+ if (_imageAnalysisOutputImageFormat == imageAnalysisOutputImageFormatNv21) {
// Manually override ImageFormat to NV21 if set for image streaming as CameraX
// still reports YUV_420_888 if the underlying format is NV21.
cameraImageFormat = const CameraImageFormat(
@@ -1411,9 +1337,7 @@
await imageProxy.close();
}
- await imageAnalysis!.setAnalyzer(
- Analyzer(analyze: (_, ImageProxy image) => analyze(image)),
- );
+ await imageAnalysis!.setAnalyzer(Analyzer(analyze: (_, ImageProxy image) => analyze(image)));
}
/// Unbinds [useCase] from camera lifecycle controlled by the
@@ -1496,9 +1420,7 @@
// Callback method used to implement the behavior described above:
void onChanged(CameraState state) {
if (state.type == CameraStateType.closing) {
- weakThis.target!.cameraEventStreamController.add(
- CameraClosingEvent(cameraId),
- );
+ weakThis.target!.cameraEventStreamController.add(CameraClosingEvent(cameraId));
}
if (state.error != null) {
late final String errorDescription;
@@ -1524,8 +1446,7 @@
errorDescription =
'The camera could not be opened because "Do Not Disturb" mode is enabled. Please disable this mode, and try opening the camera again.';
case CameraStateErrorCode.unknown:
- errorDescription =
- 'There was an unspecified issue with the current camera state.';
+ errorDescription = 'There was an unspecified issue with the current camera state.';
}
weakThis.target!.cameraEventStreamController.add(
CameraErrorEvent(cameraId, errorDescription),
@@ -1533,18 +1454,14 @@
}
}
- return Observer<CameraState>(
- onChanged: (_, CameraState value) => onChanged(value),
- );
+ return Observer<CameraState>(onChanged: (_, CameraState value) => onChanged(value));
}
// Methods for mapping Flutter camera constants to CameraX constants:
/// Returns [CameraSelector] lens direction that maps to specified
/// [CameraLensDirection].
- LensFacing _getCameraSelectorLensDirection(
- CameraLensDirection lensDirection,
- ) {
+ LensFacing _getCameraSelectorLensDirection(CameraLensDirection lensDirection) {
switch (lensDirection) {
case CameraLensDirection.front:
return LensFacing.front;
@@ -1576,9 +1493,7 @@
///
/// If the specified [preset] is unavailable, the camera will fall back to the
/// closest lower resolution available.
- ResolutionSelector? _getResolutionSelectorFromPreset(
- ResolutionPreset? preset,
- ) {
+ ResolutionSelector? _getResolutionSelectorFromPreset(ResolutionPreset? preset) {
const ResolutionStrategyFallbackRule fallbackRule =
ResolutionStrategyFallbackRule.closestLowerThenHigher;
@@ -1614,9 +1529,7 @@
boundSize: CameraSize(width: boundSize.width, height: boundSize.height),
fallbackRule: fallbackRule,
);
- final resolutionFilter = ResolutionFilter.createWithOnePreferredSize(
- preferredSize: boundSize,
- );
+ final resolutionFilter = ResolutionFilter.createWithOnePreferredSize(preferredSize: boundSize);
final AspectRatioStrategy? aspectRatioStrategy = aspectRatio == null
? null
: AspectRatioStrategy(
@@ -1658,14 +1571,9 @@
// We will choose the next highest video quality if the one desired
// is unavailable.
- final fallbackStrategy = FallbackStrategy.lowerQualityOrHigherThan(
- quality: videoQuality,
- );
+ final fallbackStrategy = FallbackStrategy.lowerQualityOrHigherThan(quality: videoQuality);
- return QualitySelector.from(
- quality: videoQuality,
- fallbackStrategy: fallbackStrategy,
- );
+ return QualitySelector.from(quality: videoQuality, fallbackStrategy: fallbackStrategy);
}
// Methods for configuring auto-focus and auto-exposure:
@@ -1733,14 +1641,14 @@
return false;
}
- final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints =
- _combineMeteringPoints(currentFocusMeteringAction!);
+ final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints = _combineMeteringPoints(
+ currentFocusMeteringAction!,
+ );
// Remove metering point with specified meteringMode from current focus
// and metering action, as only one focus or exposure point may be set
// at once in this plugin.
- final List<(MeteringPoint, MeteringMode)>
- newMeteringPointInfos = originalMeteringPoints
+ final List<(MeteringPoint, MeteringMode)> newMeteringPointInfos = originalMeteringPoints
.where(
((MeteringPoint, MeteringMode) meteringPointInfo) =>
// meteringPointInfo may technically include points without a
@@ -1768,9 +1676,7 @@
}
// Add any additional metering points in order as specified by input lists.
- newMeteringPointInfos.skip(1).forEach((
- (MeteringPoint point, MeteringMode) info,
- ) {
+ newMeteringPointInfos.skip(1).forEach(((MeteringPoint point, MeteringMode) info) {
actionBuilder.addPointWithMode(info.$1, info.$2);
});
currentFocusMeteringAction = await actionBuilder.build();
@@ -1807,17 +1713,16 @@
unawaited(actionBuilder.disableAutoCancel());
}
- newMeteringPointInfos.skip(1).forEach((
- (MeteringPoint point, MeteringMode mode) info,
- ) {
+ newMeteringPointInfos.skip(1).forEach(((MeteringPoint point, MeteringMode mode) info) {
actionBuilder.addPointWithMode(info.$1, info.$2);
});
currentFocusMeteringAction = await actionBuilder.build();
}
try {
- final FocusMeteringResult? result = await cameraControl
- .startFocusAndMetering(currentFocusMeteringAction!);
+ final FocusMeteringResult? result = await cameraControl.startFocusAndMetering(
+ currentFocusMeteringAction!,
+ );
if (result == null) {
cameraErrorStreamController.add(
@@ -1827,9 +1732,7 @@
return result?.isFocusSuccessful ?? false;
} on PlatformException catch (e) {
- cameraErrorStreamController.add(
- e.message ?? 'Starting focus and metering failed.',
- );
+ cameraErrorStreamController.add(e.message ?? 'Starting focus and metering failed.');
// Surfacing error to differentiate an operation cancellation from an
// illegal argument exception at a plugin layer.
rethrow;
@@ -1849,18 +1752,9 @@
}
return <(MeteringPoint, MeteringMode)>[
- ...toMeteringPointRecords(
- focusMeteringAction.meteringPointsAf,
- MeteringMode.af,
- ),
- ...toMeteringPointRecords(
- focusMeteringAction.meteringPointsAe,
- MeteringMode.ae,
- ),
- ...toMeteringPointRecords(
- focusMeteringAction.meteringPointsAwb,
- MeteringMode.awb,
- ),
+ ...toMeteringPointRecords(focusMeteringAction.meteringPointsAf, MeteringMode.af),
+ ...toMeteringPointRecords(focusMeteringAction.meteringPointsAe, MeteringMode.ae),
+ ...toMeteringPointRecords(focusMeteringAction.meteringPointsAwb, MeteringMode.awb),
];
}
@@ -1868,9 +1762,7 @@
try {
await cameraControl.enableTorch(value);
} on PlatformException catch (e) {
- cameraErrorStreamController.add(
- e.message ?? 'The camera was unable to change torch modes.',
- );
+ cameraErrorStreamController.add(e.message ?? 'The camera was unable to change torch modes.');
}
}
@@ -1885,9 +1777,7 @@
case 'PORTRAIT_UP':
return DeviceOrientation.portraitUp;
default:
- throw ArgumentError(
- '"$orientation" is not a valid DeviceOrientation value',
- );
+ throw ArgumentError('"$orientation" is not a valid DeviceOrientation value');
}
}
}
diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart
index 1731bca..4670a94 100644
--- a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart
+++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart
@@ -166,10 +166,7 @@
@override
// ignore: non_constant_identifier_names
LiveData<T> pigeon_copy() {
- return LiveData<T>.detached(
- type: type,
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- );
+ return LiveData<T>.detached(type: type, pigeon_binaryMessenger: pigeon_binaryMessenger);
}
}
@@ -185,10 +182,7 @@
if (GenericsPigeonOverrides.observerNew != null) {
return GenericsPigeonOverrides.observerNew!(onChanged: onChanged);
}
- return Observer<T>.pigeonNew(
- pigeon_binaryMessenger: binaryMessenger,
- onChanged: onChanged,
- );
+ return Observer<T>.pigeonNew(pigeon_binaryMessenger: binaryMessenger, onChanged: onChanged);
}
/// Constructs an [Observer].
diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart
index dca2b8d..d7be3d9 100644
--- a/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart
+++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart
@@ -21,11 +21,7 @@
);
}
-List<Object?> wrapResponse({
- Object? result,
- PlatformException? error,
- bool empty = false,
-}) {
+List<Object?> wrapResponse({Object? result, PlatformException? error, bool empty = false}) {
if (empty) {
return <Object?>[];
}
@@ -45,8 +41,7 @@
@visibleForTesting
class PigeonOverrides {
/// Overrides [CameraSize.new].
- static CameraSize Function({required int width, required int height})?
- cameraSize_new;
+ static CameraSize Function({required int width, required int height})? cameraSize_new;
/// Overrides [CameraIntegerRange.new].
static CameraIntegerRange Function({required int lower, required int upper})?
@@ -59,28 +54,19 @@
observer_new;
/// Overrides [CameraSelector.new].
- static CameraSelector Function({
- LensFacing? requireLensFacing,
- CameraInfo? cameraInfoForFilter,
- })?
+ static CameraSelector Function({LensFacing? requireLensFacing, CameraInfo? cameraInfoForFilter})?
cameraSelector_new;
/// Overrides [SystemServicesManager.new].
static SystemServicesManager Function({
- required void Function(
- SystemServicesManager pigeon_instance,
- String errorDescription,
- )
+ required void Function(SystemServicesManager pigeon_instance, String errorDescription)
onCameraError,
})?
systemServicesManager_new;
/// Overrides [DeviceOrientationManager.new].
static DeviceOrientationManager Function({
- required void Function(
- DeviceOrientationManager pigeon_instance,
- String orientation,
- )
+ required void Function(DeviceOrientationManager pigeon_instance, String orientation)
onDeviceOrientationChanged,
})?
deviceOrientationManager_new;
@@ -110,10 +96,7 @@
/// Overrides [VideoRecordEventListener.new].
static VideoRecordEventListener Function({
- required void Function(
- VideoRecordEventListener pigeon_instance,
- VideoRecordEvent event,
- )
+ required void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event)
onEvent,
})?
videoRecordEventListener_new;
@@ -205,9 +188,7 @@
focusMeteringActionBuilder_withMode;
/// Overrides [CaptureRequestOptions.new].
- static CaptureRequestOptions Function({
- required Map<CaptureRequestKey, Object?> options,
- })?
+ static CaptureRequestOptions Function({required Map<CaptureRequestKey, Object?> options})?
captureRequestOptions_new;
/// Overrides [Camera2CameraControl.from].
@@ -219,8 +200,7 @@
resolutionFilter_createWithOnePreferredSize;
/// Overrides [Camera2CameraInfo.from].
- static Camera2CameraInfo Function({required CameraInfo cameraInfo})?
- camera2CameraInfo_from;
+ static Camera2CameraInfo Function({required CameraInfo cameraInfo})? camera2CameraInfo_from;
/// Overrides [DisplayOrientedMeteringPointFactory.new].
static DisplayOrientedMeteringPointFactory Function({
@@ -240,8 +220,7 @@
static ResolutionStrategy? resolutionStrategy_highestAvailableStrategy;
/// Overrides [AspectRatioStrategy.ratio_16_9FallbackAutoStrategy].
- static AspectRatioStrategy?
- aspectRatioStrategy_ratio_16_9FallbackAutoStrategy;
+ static AspectRatioStrategy? aspectRatioStrategy_ratio_16_9FallbackAutoStrategy;
/// Overrides [AspectRatioStrategy.ratio_4_3FallbackAutoStrategy].
static AspectRatioStrategy? aspectRatioStrategy_ratio_4_3FallbackAutoStrategy;
@@ -253,27 +232,22 @@
static CaptureRequestKey? captureRequest_controlVideoStabilizationMode;
/// Overrides [CameraCharacteristics.infoSupportedHardwareLevel].
- static CameraCharacteristicsKey?
- cameraCharacteristics_infoSupportedHardwareLevel;
+ static CameraCharacteristicsKey? cameraCharacteristics_infoSupportedHardwareLevel;
/// Overrides [CameraCharacteristics.sensorOrientation].
static CameraCharacteristicsKey? cameraCharacteristics_sensorOrientation;
/// Overrides [CameraCharacteristics.controlAvailableVideoStabilizationModes].
- static CameraCharacteristicsKey?
- cameraCharacteristics_controlAvailableVideoStabilizationModes;
+ static CameraCharacteristicsKey? cameraCharacteristics_controlAvailableVideoStabilizationModes;
/// Overrides [ProcessCameraProvider.getInstance].
- static Future<ProcessCameraProvider> Function()?
- processCameraProvider_getInstance;
+ static Future<ProcessCameraProvider> Function()? processCameraProvider_getInstance;
/// Overrides [ImageProxyUtils.getNv21Buffer].
- static Future<Uint8List> Function(int, int, List<PlaneProxy>)?
- imageProxyUtils_getNv21Buffer;
+ static Future<Uint8List> Function(int, int, List<PlaneProxy>)? imageProxyUtils_getNv21Buffer;
/// Overrides [QualitySelector.getResolution].
- static Future<CameraSize?> Function(CameraInfo, VideoQuality)?
- qualitySelector_getResolution;
+ static Future<CameraSize?> Function(CameraInfo, VideoQuality)? qualitySelector_getResolution;
/// Sets all overridden ProxyApi class members to null.
static void pigeon_reset() {
@@ -333,8 +307,7 @@
PigeonInternalProxyApiBaseClass({
this.pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- }) : pigeon_instanceManager =
- pigeon_instanceManager ?? PigeonInstanceManager.instance;
+ }) : pigeon_instanceManager = pigeon_instanceManager ?? PigeonInstanceManager.instance;
/// Sends and receives binary data across the Flutter platform barrier.
///
@@ -404,8 +377,8 @@
// by calling instanceManager.getIdentifier() inside of `==` while this was a
// HashMap).
final Expando<int> _identifiers = Expando<int>();
- final Map<int, WeakReference<PigeonInternalProxyApiBaseClass>>
- _weakInstances = <int, WeakReference<PigeonInternalProxyApiBaseClass>>{};
+ final Map<int, WeakReference<PigeonInternalProxyApiBaseClass>> _weakInstances =
+ <int, WeakReference<PigeonInternalProxyApiBaseClass>>{};
final Map<int, PigeonInternalProxyApiBaseClass> _strongInstances =
<int, PigeonInternalProxyApiBaseClass>{};
late final Finalizer<int> _finalizer;
@@ -420,8 +393,7 @@
return PigeonInstanceManager(onWeakReferenceRemoved: (_) {});
}
WidgetsFlutterBinding.ensureInitialized();
- final _PigeonInternalInstanceManagerApi api =
- _PigeonInternalInstanceManagerApi();
+ final _PigeonInternalInstanceManagerApi api = _PigeonInternalInstanceManagerApi();
// Clears the native `PigeonInstanceManager` on the initial use of the Dart one.
api.clear();
final PigeonInstanceManager instanceManager = PigeonInstanceManager(
@@ -429,163 +401,59 @@
api.removeStrongReference(identifier);
},
);
- _PigeonInternalInstanceManagerApi.setUpMessageHandlers(
- instanceManager: instanceManager,
- );
- CameraSize.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ResolutionInfo.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraIntegerRange.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- VideoRecordEvent.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- VideoRecordEventStart.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- VideoRecordEventFinalize.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- MeteringPoint.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Observer.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraInfo.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraSelector.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ProcessCameraProvider.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- UseCase.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
+ _PigeonInternalInstanceManagerApi.setUpMessageHandlers(instanceManager: instanceManager);
+ CameraSize.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ResolutionInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraIntegerRange.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ VideoRecordEvent.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ VideoRecordEventStart.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ VideoRecordEventFinalize.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ MeteringPoint.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Observer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraSelector.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ProcessCameraProvider.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ UseCase.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
Camera.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
- SystemServicesManager.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraPermissionsError.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- DeviceOrientationManager.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Preview.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- VideoCapture.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- VideoOutput.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Recorder.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- VideoRecordEventListener.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- PendingRecording.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Recording.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ImageCapture.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ResolutionStrategy.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ResolutionSelector.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- AspectRatioStrategy.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraState.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ExposureState.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ZoomState.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ImageAnalysis.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Analyzer.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraStateStateError.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- LiveData.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ImageProxy.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ImageProxyUtils.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- PlaneProxy.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- QualitySelector.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- FallbackStrategy.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraControl.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- FocusMeteringActionBuilder.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- FocusMeteringAction.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- FocusMeteringResult.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CaptureRequest.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CaptureRequestKey.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CaptureRequestOptions.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Camera2CameraControl.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- ResolutionFilter.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraCharacteristicsKey.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- CameraCharacteristics.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- Camera2CameraInfo.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
- MeteringPointFactory.pigeon_setUpMessageHandlers(
- pigeon_instanceManager: instanceManager,
- );
+ SystemServicesManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraPermissionsError.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ DeviceOrientationManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Preview.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ VideoCapture.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ VideoOutput.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Recorder.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ VideoRecordEventListener.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ PendingRecording.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Recording.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ImageCapture.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ResolutionStrategy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ResolutionSelector.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ AspectRatioStrategy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraState.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ExposureState.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ZoomState.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ImageAnalysis.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Analyzer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraStateStateError.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ LiveData.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ImageProxy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ImageProxyUtils.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ PlaneProxy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ QualitySelector.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ FallbackStrategy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraControl.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ FocusMeteringActionBuilder.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ FocusMeteringAction.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ FocusMeteringResult.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CaptureRequest.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CaptureRequestKey.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CaptureRequestOptions.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Camera2CameraControl.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ ResolutionFilter.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraCharacteristicsKey.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ CameraCharacteristics.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ Camera2CameraInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
+ MeteringPointFactory.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager);
DisplayOrientedMeteringPointFactory.pigeon_setUpMessageHandlers(
pigeon_instanceManager: instanceManager,
);
@@ -605,9 +473,7 @@
final int identifier = _nextUniqueIdentifier();
_identifiers[instance] = identifier;
- _weakInstances[identifier] = WeakReference<PigeonInternalProxyApiBaseClass>(
- instance,
- );
+ _weakInstances[identifier] = WeakReference<PigeonInternalProxyApiBaseClass>(instance);
_finalizer.attach(instance, identifier, detach: instance);
final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy();
@@ -668,21 +534,15 @@
///
/// This method also expects the host `InstanceManager` to have a strong
/// reference to the instance the identifier is associated with.
- T? getInstanceWithWeakReference<T extends PigeonInternalProxyApiBaseClass>(
- int identifier,
- ) {
- final PigeonInternalProxyApiBaseClass? weakInstance =
- _weakInstances[identifier]?.target;
+ T? getInstanceWithWeakReference<T extends PigeonInternalProxyApiBaseClass>(int identifier) {
+ final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target;
if (weakInstance == null) {
- final PigeonInternalProxyApiBaseClass? strongInstance =
- _strongInstances[identifier];
+ final PigeonInternalProxyApiBaseClass? strongInstance = _strongInstances[identifier];
if (strongInstance != null) {
- final PigeonInternalProxyApiBaseClass copy = strongInstance
- .pigeon_copy();
+ final PigeonInternalProxyApiBaseClass copy = strongInstance.pigeon_copy();
_identifiers[copy] = identifier;
- _weakInstances[identifier] =
- WeakReference<PigeonInternalProxyApiBaseClass>(copy);
+ _weakInstances[identifier] = WeakReference<PigeonInternalProxyApiBaseClass>(copy);
_finalizer.attach(copy, identifier, detach: copy);
return copy as T;
}
@@ -704,10 +564,7 @@
///
/// Throws assertion error if the instance or its identifier has already been
/// added.
- void addHostCreatedInstance(
- PigeonInternalProxyApiBaseClass instance,
- int identifier,
- ) {
+ void addHostCreatedInstance(PigeonInternalProxyApiBaseClass instance, int identifier) {
assert(!containsIdentifier(identifier));
assert(getIdentifier(instance) == null);
assert(identifier >= 0);
@@ -718,8 +575,7 @@
/// Whether this manager contains the given [identifier].
bool containsIdentifier(int identifier) {
- return _weakInstances.containsKey(identifier) ||
- _strongInstances.containsKey(identifier);
+ return _weakInstances.containsKey(identifier) || _strongInstances.containsKey(identifier);
}
int _nextUniqueIdentifier() {
@@ -768,9 +624,7 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.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);
@@ -792,9 +646,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[identifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[identifier]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -853,9 +705,7 @@
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);
}
@@ -1172,14 +1022,10 @@
return value == null ? null : CameraXFlashMode.values[value];
case 137:
final value = readValue(buffer) as int?;
- return value == null
- ? null
- : ResolutionStrategyFallbackRule.values[value];
+ return value == null ? null : ResolutionStrategyFallbackRule.values[value];
case 138:
final value = readValue(buffer) as int?;
- return value == null
- ? null
- : AspectRatioStrategyFallbackRule.values[value];
+ return value == null ? null : AspectRatioStrategyFallbackRule.values[value];
case 139:
final value = readValue(buffer) as int?;
return value == null ? null : CameraStateErrorCode.values[value];
@@ -1217,10 +1063,8 @@
required this.width,
required this.height,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraSize;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSize;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_defaultConstructor';
@@ -1229,9 +1073,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, width, height],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ width,
+ height,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -1275,10 +1121,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CameraSize Function(int width, int height)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1311,17 +1156,16 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_width!, arg_height!) ??
- CameraSize.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- width: arg_width!,
- height: arg_height!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_width!, arg_height!) ??
+ CameraSize.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ width: arg_width!,
+ height: arg_height!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -1371,10 +1215,9 @@
PigeonInstanceManager? pigeon_instanceManager,
ResolutionInfo Function(CameraSize resolution)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1402,16 +1245,15 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance was null, expected non-null CameraSize.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_resolution!) ??
- ResolutionInfo.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- resolution: arg_resolution!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_resolution!) ??
+ ResolutionInfo.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ resolution: arg_resolution!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -1448,10 +1290,7 @@
required int upper,
}) {
if (PigeonOverrides.cameraIntegerRange_new != null) {
- return PigeonOverrides.cameraIntegerRange_new!(
- lower: lower,
- upper: upper,
- );
+ return PigeonOverrides.cameraIntegerRange_new!(lower: lower, upper: upper);
}
return CameraIntegerRange.pigeon_new(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -1468,10 +1307,8 @@
required this.lower,
required this.upper,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraIntegerRange;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraIntegerRange;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_defaultConstructor';
@@ -1480,9 +1317,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, lower, upper],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ lower,
+ upper,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -1511,10 +1350,8 @@
required this.upper,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecCameraIntegerRange = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraIntegerRange =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// The lower endpoint.
final int lower;
@@ -1528,10 +1365,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CameraIntegerRange Function(int lower, int upper)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1564,17 +1400,16 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_lower!, arg_upper!) ??
- CameraIntegerRange.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- lower: arg_lower!,
- upper: arg_upper!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_lower!, arg_upper!) ??
+ CameraIntegerRange.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ lower: arg_lower!,
+ upper: arg_upper!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -1608,10 +1443,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- VideoRecordEvent.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ VideoRecordEvent.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -1619,10 +1451,9 @@
PigeonInstanceManager? pigeon_instanceManager,
VideoRecordEvent Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1645,15 +1476,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- VideoRecordEvent.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ VideoRecordEvent.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);
@@ -1696,10 +1526,9 @@
PigeonInstanceManager? pigeon_instanceManager,
VideoRecordEventStart Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1722,15 +1551,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- VideoRecordEventStart.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ VideoRecordEventStart.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);
@@ -1773,10 +1601,9 @@
PigeonInstanceManager? pigeon_instanceManager,
VideoRecordEventFinalize Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1799,15 +1626,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- VideoRecordEventFinalize.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ VideoRecordEventFinalize.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);
@@ -1840,10 +1666,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- MeteringPoint.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ MeteringPoint.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecMeteringPoint =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -1854,10 +1677,9 @@
PigeonInstanceManager? pigeon_instanceManager,
MeteringPoint Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1880,15 +1702,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- MeteringPoint.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ MeteringPoint.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);
@@ -1907,19 +1728,15 @@
/// It is the percentage of the sensor width/height (or crop region
/// width/height if crop region is set).
Future<double> getSize() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecMeteringPoint;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMeteringPoint;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1973,10 +1790,8 @@
super.pigeon_instanceManager,
required this.onChanged,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecObserver;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecObserver;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Observer.pigeon_defaultConstructor';
@@ -1985,9 +1800,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -2045,10 +1860,9 @@
PigeonInstanceManager? pigeon_instanceManager,
void Function(Observer pigeon_instance, Object value)? onChanged,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -2076,10 +1890,7 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Observer.onChanged was null, expected non-null Object.',
);
try {
- (onChanged ?? arg_pigeon_instance!.onChanged).call(
- arg_pigeon_instance!,
- arg_value!,
- );
+ (onChanged ?? arg_pigeon_instance!.onChanged).call(arg_pigeon_instance!, arg_value!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -2144,10 +1955,9 @@
)?
pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -2185,22 +1995,21 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null ExposureState.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_sensorRotationDegrees!,
- arg_lensFacing!,
- arg_exposureState!,
- ) ??
- CameraInfo.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- sensorRotationDegrees: arg_sensorRotationDegrees!,
- lensFacing: arg_lensFacing!,
- exposureState: arg_exposureState!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(
+ arg_sensorRotationDegrees!,
+ arg_lensFacing!,
+ arg_exposureState!,
+ ) ??
+ CameraInfo.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ sensorRotationDegrees: arg_sensorRotationDegrees!,
+ lensFacing: arg_lensFacing!,
+ exposureState: arg_exposureState!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -2216,8 +2025,7 @@
/// A LiveData of the camera's state.
Future<LiveData> getCameraState() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraInfo;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraInfo;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getCameraState';
@@ -2226,9 +2034,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2250,8 +2056,7 @@
/// A LiveData of ZoomState.
Future<LiveData> getZoomState() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraInfo;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraInfo;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getZoomState';
@@ -2260,9 +2065,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2326,10 +2129,8 @@
LensFacing? requireLensFacing,
CameraInfo? cameraInfoForFilter,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraSelector;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSelector;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_defaultConstructor';
@@ -2338,13 +2139,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[
- pigeonVar_instanceIdentifier,
- requireLensFacing,
- cameraInfoForFilter,
- ],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ requireLensFacing,
+ cameraInfoForFilter,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -2366,21 +2165,16 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- CameraSelector.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ CameraSelector.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraSelector =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// A static `CameraSelector` that selects the default back facing camera.
- static final CameraSelector _defaultBackCamera =
- pigeonVar_defaultBackCamera();
+ static final CameraSelector _defaultBackCamera = pigeonVar_defaultBackCamera();
/// A static `CameraSelector` that selects the default front facing camera.
- static final CameraSelector _defaultFrontCamera =
- pigeonVar_defaultFrontCamera();
+ static final CameraSelector _defaultFrontCamera = pigeonVar_defaultFrontCamera();
/// A static `CameraSelector` that selects the default back facing camera.
static CameraSelector get defaultBackCamera =>
@@ -2396,10 +2190,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CameraSelector Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -2422,15 +2215,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CameraSelector.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CameraSelector.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);
@@ -2446,12 +2238,14 @@
static CameraSelector pigeonVar_defaultBackCamera() {
final CameraSelector pigeonVar_instance = CameraSelector.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultBackCamera';
@@ -2460,9 +2254,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2481,12 +2275,14 @@
static CameraSelector pigeonVar_defaultFrontCamera() {
final CameraSelector pigeonVar_instance = CameraSelector.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultFrontCamera';
@@ -2495,9 +2291,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2517,19 +2313,18 @@
/// Filters the input `CameraInfo`s using the `CameraFilter`s assigned to the
/// selector.
Future<List<CameraInfo>> filter(List<CameraInfo> cameraInfos) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraSelector;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSelector;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, cameraInfos],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ cameraInfos,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2573,10 +2368,8 @@
super.pigeon_instanceManager,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecProcessCameraProvider = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecProcessCameraProvider =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -2584,10 +2377,9 @@
PigeonInstanceManager? pigeon_instanceManager,
ProcessCameraProvider Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -2610,15 +2402,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- ProcessCameraProvider.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ ProcessCameraProvider.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);
@@ -2640,10 +2431,9 @@
if (PigeonOverrides.processCameraProvider_getInstance != null) {
return PigeonOverrides.processCameraProvider_getInstance!();
}
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getInstance';
@@ -2684,9 +2474,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2707,10 +2495,7 @@
}
/// Binds the collection of `UseCase` to a `LifecycleOwner`.
- Future<Camera> bindToLifecycle(
- CameraSelector cameraSelector,
- List<UseCase> useCases,
- ) async {
+ Future<Camera> bindToLifecycle(CameraSelector cameraSelector, List<UseCase> useCases) async {
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecProcessCameraProvider;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -2721,9 +2506,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, cameraSelector, useCases],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ cameraSelector,
+ useCases,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2755,9 +2542,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, useCase],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, useCase]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2789,9 +2574,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, useCases],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, useCases]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2819,9 +2602,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -2854,10 +2635,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- UseCase.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ UseCase.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -2865,10 +2643,9 @@
PigeonInstanceManager? pigeon_instanceManager,
UseCase Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -2891,15 +2668,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- UseCase.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ UseCase.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);
@@ -2951,10 +2727,9 @@
PigeonInstanceManager? pigeon_instanceManager,
Camera Function(CameraControl cameraControl)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -2982,16 +2757,15 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance was null, expected non-null CameraControl.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_cameraControl!) ??
- Camera.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- cameraControl: arg_cameraControl!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_cameraControl!) ??
+ Camera.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ cameraControl: arg_cameraControl!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -3007,19 +2781,15 @@
/// Returns information about this camera.
Future<CameraInfo> getCameraInfo() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCamera;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3054,16 +2824,11 @@
factory SystemServicesManager({
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- required void Function(
- SystemServicesManager pigeon_instance,
- String errorDescription,
- )
+ required void Function(SystemServicesManager pigeon_instance, String errorDescription)
onCameraError,
}) {
if (PigeonOverrides.systemServicesManager_new != null) {
- return PigeonOverrides.systemServicesManager_new!(
- onCameraError: onCameraError,
- );
+ return PigeonOverrides.systemServicesManager_new!(onCameraError: onCameraError);
}
return SystemServicesManager.pigeon_new(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -3078,8 +2843,7 @@
super.pigeon_instanceManager,
required this.onCameraError,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecSystemServicesManager;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -3090,9 +2854,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -3120,10 +2884,8 @@
required this.onCameraError,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecSystemServicesManager = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSystemServicesManager =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// Callback method.
///
@@ -3144,26 +2906,17 @@
///
/// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to
/// release the associated Native object manually.
- final void Function(
- SystemServicesManager pigeon_instance,
- String errorDescription,
- )
- onCameraError;
+ final void Function(SystemServicesManager pigeon_instance, String errorDescription) onCameraError;
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- void Function(
- SystemServicesManager pigeon_instance,
- String errorDescription,
- )?
- onCameraError,
+ void Function(SystemServicesManager pigeon_instance, String errorDescription)? onCameraError,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -3180,8 +2933,7 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null.',
);
final List<Object?> args = (message as List<Object?>?)!;
- final SystemServicesManager? arg_pigeon_instance =
- (args[0] as SystemServicesManager?);
+ final SystemServicesManager? arg_pigeon_instance = (args[0] as SystemServicesManager?);
assert(
arg_pigeon_instance != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null, expected non-null SystemServicesManager.',
@@ -3209,9 +2961,7 @@
}
}
- Future<CameraPermissionsError?> requestCameraPermissions(
- bool enableAudio,
- ) async {
+ Future<CameraPermissionsError?> requestCameraPermissions(bool enableAudio) async {
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecSystemServicesManager;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -3222,9 +2972,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, enableAudio],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ enableAudio,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3252,9 +3003,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, prefix, suffix],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ prefix,
+ suffix,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3306,13 +3059,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- CameraPermissionsError Function(String errorCode, String description)?
- pigeon_newInstance,
+ CameraPermissionsError Function(String errorCode, String description)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -3345,17 +3096,16 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance was null, expected non-null String.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_errorCode!, arg_description!) ??
- CameraPermissionsError.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- errorCode: arg_errorCode!,
- description: arg_description!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_errorCode!, arg_description!) ??
+ CameraPermissionsError.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);
@@ -3386,10 +3136,7 @@
factory DeviceOrientationManager({
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- required void Function(
- DeviceOrientationManager pigeon_instance,
- String orientation,
- )
+ required void Function(DeviceOrientationManager pigeon_instance, String orientation)
onDeviceOrientationChanged,
}) {
if (PigeonOverrides.deviceOrientationManager_new != null) {
@@ -3410,8 +3157,7 @@
super.pigeon_instanceManager,
required this.onDeviceOrientationChanged,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecDeviceOrientationManager;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -3422,9 +3168,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -3452,10 +3198,8 @@
required this.onDeviceOrientationChanged,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecDeviceOrientationManager = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecDeviceOrientationManager =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// Callback method.
///
@@ -3476,10 +3220,7 @@
///
/// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to
/// release the associated Native object manually.
- final void Function(
- DeviceOrientationManager pigeon_instance,
- String orientation,
- )
+ final void Function(DeviceOrientationManager pigeon_instance, String orientation)
onDeviceOrientationChanged;
static void pigeon_setUpMessageHandlers({
@@ -3489,10 +3230,9 @@
void Function(DeviceOrientationManager pigeon_instance, String orientation)?
onDeviceOrientationChanged,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -3521,9 +3261,10 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged was null, expected non-null String.',
);
try {
- (onDeviceOrientationChanged ??
- arg_pigeon_instance!.onDeviceOrientationChanged)
- .call(arg_pigeon_instance!, arg_orientation!);
+ (onDeviceOrientationChanged ?? arg_pigeon_instance!.onDeviceOrientationChanged).call(
+ arg_pigeon_instance!,
+ arg_orientation!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -3548,9 +3289,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3576,9 +3315,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3604,9 +3341,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3637,9 +3372,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3704,10 +3437,8 @@
int? targetRotation,
CameraIntegerRange? targetFpsRange,
}) : super.pigeon_detached() {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPreview;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_defaultConstructor';
@@ -3716,13 +3447,12 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel
- .send(<Object?>[
- pigeonVar_instanceIdentifier,
- resolutionSelector,
- targetRotation,
- targetFpsRange,
- ]);
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ resolutionSelector,
+ targetRotation,
+ targetFpsRange,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -3759,13 +3489,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- Preview Function(ResolutionSelector? resolutionSelector)?
- pigeon_newInstance,
+ Preview Function(ResolutionSelector? resolutionSelector)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -3787,19 +3515,17 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance was null, expected non-null int.',
);
- final ResolutionSelector? arg_resolutionSelector =
- (args[1] as ResolutionSelector?);
+ final ResolutionSelector? arg_resolutionSelector = (args[1] as ResolutionSelector?);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_resolutionSelector) ??
- Preview.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- resolutionSelector: arg_resolutionSelector,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_resolutionSelector) ??
+ Preview.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ resolutionSelector: arg_resolutionSelector,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -3821,11 +3547,8 @@
/// 2. Sets this method with the created `SurfaceProvider`.
/// 3. Returns the texture id of the `TextureEntry` that provided the
/// `SurfaceProducer`.
- Future<int> setSurfaceProvider(
- SystemServicesManager systemServicesManager,
- ) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPreview;
+ Future<int> setSurfaceProvider(SystemServicesManager systemServicesManager) async {
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Preview.setSurfaceProvider';
@@ -3834,9 +3557,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, systemServicesManager],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ systemServicesManager,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3859,8 +3583,7 @@
/// Releases the `SurfaceProducer` created in `setSurfaceProvider` if one was
/// created.
Future<void> releaseSurfaceProvider() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPreview;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Preview.releaseSurfaceProvider';
@@ -3869,9 +3592,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3888,8 +3609,7 @@
/// Gets selected resolution information of the `Preview`.
Future<ResolutionInfo?> getResolutionInfo() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPreview;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Preview.getResolutionInfo';
@@ -3898,9 +3618,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3917,8 +3635,7 @@
/// Sets the target rotation.
Future<void> setTargetRotation(int rotation) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPreview;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Preview.setTargetRotation';
@@ -3927,9 +3644,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, rotation],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, rotation]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -3947,8 +3662,7 @@
/// Returns whether or not the preview's surface producer handles correctly
/// rotating the camera preview automatically.
Future<bool> surfaceProducerHandlesCropAndRotation() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPreview;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Preview.surfaceProducerHandlesCropAndRotation';
@@ -3957,9 +3671,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4022,10 +3734,8 @@
required VideoOutput videoOutput,
CameraIntegerRange? targetFpsRange,
}) : super.pigeon_detached() {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecVideoCapture;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.VideoCapture.withOutput';
@@ -4034,9 +3744,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, videoOutput, targetFpsRange],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ videoOutput,
+ targetFpsRange,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -4058,10 +3770,8 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- VideoCapture.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- }) : super.pigeon_detached();
+ VideoCapture.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager})
+ : super.pigeon_detached();
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoCapture =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -4072,10 +3782,9 @@
PigeonInstanceManager? pigeon_instanceManager,
VideoCapture Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -4098,15 +3807,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- VideoCapture.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ VideoCapture.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);
@@ -4122,8 +3830,7 @@
/// Gets the VideoOutput associated with this VideoCapture.
Future<VideoOutput> getOutput() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecVideoCapture;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.VideoCapture.getOutput';
@@ -4132,9 +3839,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4156,8 +3861,7 @@
/// Sets the desired rotation of the output video.
Future<void> setTargetRotation(int rotation) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecVideoCapture;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.VideoCapture.setTargetRotation';
@@ -4166,9 +3870,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, rotation],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, rotation]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4201,10 +3903,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- VideoOutput.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ VideoOutput.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -4212,10 +3911,9 @@
PigeonInstanceManager? pigeon_instanceManager,
VideoOutput Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -4238,15 +3936,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- VideoOutput.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ VideoOutput.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);
@@ -4305,10 +4002,8 @@
int? targetVideoEncodingBitRate,
QualitySelector? qualitySelector,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecorder;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_defaultConstructor';
@@ -4317,13 +4012,12 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel
- .send(<Object?>[
- pigeonVar_instanceIdentifier,
- aspectRatio,
- targetVideoEncodingBitRate,
- qualitySelector,
- ]);
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ aspectRatio,
+ targetVideoEncodingBitRate,
+ qualitySelector,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -4345,10 +4039,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- Recorder.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ Recorder.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecRecorder =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -4359,10 +4050,9 @@
PigeonInstanceManager? pigeon_instanceManager,
Recorder Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -4385,15 +4075,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- Recorder.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ Recorder.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);
@@ -4409,8 +4098,7 @@
/// Gets the aspect ratio of this Recorder.
Future<int> getAspectRatio() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecorder;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Recorder.getAspectRatio';
@@ -4419,9 +4107,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4443,8 +4129,7 @@
/// Gets the target video encoding bitrate of this Recorder.
Future<int> getTargetVideoEncodingBitRate() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecorder;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Recorder.getTargetVideoEncodingBitRate';
@@ -4453,9 +4138,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4477,8 +4160,7 @@
/// The quality selector of this Recorder.
Future<QualitySelector> getQualitySelector() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecorder;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Recorder.getQualitySelector';
@@ -4487,9 +4169,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4511,8 +4191,7 @@
/// Prepares a recording that will be saved to a File.
Future<PendingRecording> prepareRecording(String path) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecorder;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Recorder.prepareRecording';
@@ -4521,9 +4200,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, path],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, path]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4557,10 +4234,7 @@
factory VideoRecordEventListener({
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- required void Function(
- VideoRecordEventListener pigeon_instance,
- VideoRecordEvent event,
- )
+ required void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event)
onEvent,
}) {
if (PigeonOverrides.videoRecordEventListener_new != null) {
@@ -4579,8 +4253,7 @@
super.pigeon_instanceManager,
required this.onEvent,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecVideoRecordEventListener;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -4591,9 +4264,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -4621,10 +4294,8 @@
required this.onEvent,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecVideoRecordEventListener = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoRecordEventListener =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// Callback method.
///
@@ -4645,26 +4316,17 @@
///
/// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to
/// release the associated Native object manually.
- final void Function(
- VideoRecordEventListener pigeon_instance,
- VideoRecordEvent event,
- )
- onEvent;
+ final void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event) onEvent;
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- void Function(
- VideoRecordEventListener pigeon_instance,
- VideoRecordEvent event,
- )?
- onEvent,
+ void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event)? onEvent,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -4693,10 +4355,7 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent was null, expected non-null VideoRecordEvent.',
);
try {
- (onEvent ?? arg_pigeon_instance!.onEvent).call(
- arg_pigeon_instance!,
- arg_event!,
- );
+ (onEvent ?? arg_pigeon_instance!.onEvent).call(arg_pigeon_instance!, arg_event!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -4729,10 +4388,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- PendingRecording.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ PendingRecording.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecPendingRecording =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -4743,10 +4399,9 @@
PigeonInstanceManager? pigeon_instanceManager,
PendingRecording Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -4769,15 +4424,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- PendingRecording.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ PendingRecording.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);
@@ -4793,8 +4447,7 @@
/// Enables/disables audio to be recorded for this recording.
Future<PendingRecording> withAudioEnabled(bool initialMuted) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPendingRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.PendingRecording.withAudioEnabled';
@@ -4803,9 +4456,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, initialMuted],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ initialMuted,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4835,8 +4489,7 @@
/// first create the recording as persistent recording,
/// then rebind the [VideoCapture] it's associated with to a different camera.
Future<PendingRecording> asPersistentRecording() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPendingRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.PendingRecording.asPersistentRecording';
@@ -4845,9 +4498,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4869,8 +4520,7 @@
/// Starts the recording, making it an active recording.
Future<Recording> start(VideoRecordEventListener listener) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecPendingRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.PendingRecording.start';
@@ -4879,9 +4529,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, listener],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, listener]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -4919,10 +4567,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- Recording.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ Recording.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecRecording =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -4933,10 +4578,9 @@
PigeonInstanceManager? pigeon_instanceManager,
Recording Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -4959,15 +4603,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- Recording.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ Recording.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);
@@ -4983,19 +4626,15 @@
/// Close this recording.
Future<void> close() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.Recording.close';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.close';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5012,19 +4651,15 @@
/// Pauses the current recording if active.
Future<void> pause() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.Recording.pause';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.pause';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5041,19 +4676,15 @@
/// Resumes the current recording if paused.
Future<void> resume() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.Recording.resume';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.resume';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5072,19 +4703,15 @@
///
/// This method is equivalent to calling `close`.
Future<void> stop() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecRecording;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.Recording.stop';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.stop';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5143,10 +4770,8 @@
int? targetRotation,
CameraXFlashMode? flashMode,
}) : super.pigeon_detached() {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageCapture;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_defaultConstructor';
@@ -5155,13 +4780,12 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel
- .send(<Object?>[
- pigeonVar_instanceIdentifier,
- resolutionSelector,
- targetRotation,
- flashMode,
- ]);
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ resolutionSelector,
+ targetRotation,
+ flashMode,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -5198,13 +4822,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- ImageCapture Function(ResolutionSelector? resolutionSelector)?
- pigeon_newInstance,
+ ImageCapture Function(ResolutionSelector? resolutionSelector)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -5226,19 +4848,17 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance was null, expected non-null int.',
);
- final ResolutionSelector? arg_resolutionSelector =
- (args[1] as ResolutionSelector?);
+ final ResolutionSelector? arg_resolutionSelector = (args[1] as ResolutionSelector?);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_resolutionSelector) ??
- ImageCapture.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- resolutionSelector: arg_resolutionSelector,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_resolutionSelector) ??
+ ImageCapture.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ resolutionSelector: arg_resolutionSelector,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -5254,8 +4874,7 @@
/// Set the flash mode.
Future<void> setFlashMode(CameraXFlashMode flashMode) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageCapture;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setFlashMode';
@@ -5264,9 +4883,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, flashMode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, flashMode]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5282,11 +4899,8 @@
}
/// Captures a new still image for in memory access.
- Future<String> takePicture(
- SystemServicesManager systemServicesManager,
- ) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageCapture;
+ Future<String> takePicture(SystemServicesManager systemServicesManager) async {
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageCapture.takePicture';
@@ -5295,9 +4909,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, systemServicesManager],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ systemServicesManager,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5319,8 +4934,7 @@
/// Sets the desired rotation of the output image.
Future<void> setTargetRotation(int rotation) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageCapture;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setTargetRotation';
@@ -5329,9 +4943,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, rotation],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, rotation]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5388,10 +5000,8 @@
required CameraSize boundSize,
required ResolutionStrategyFallbackRule fallbackRule,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecResolutionStrategy;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_defaultConstructor';
@@ -5400,9 +5010,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, boundSize, fallbackRule],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ boundSize,
+ fallbackRule,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -5424,24 +5036,17 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- ResolutionStrategy.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ ResolutionStrategy.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecResolutionStrategy = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionStrategy =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// A resolution strategy chooses the highest available resolution.
- static final ResolutionStrategy _highestAvailableStrategy =
- pigeonVar_highestAvailableStrategy();
+ static final ResolutionStrategy _highestAvailableStrategy = pigeonVar_highestAvailableStrategy();
/// A resolution strategy chooses the highest available resolution.
static ResolutionStrategy get highestAvailableStrategy =>
- PigeonOverrides.resolutionStrategy_highestAvailableStrategy ??
- _highestAvailableStrategy;
+ PigeonOverrides.resolutionStrategy_highestAvailableStrategy ?? _highestAvailableStrategy;
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -5449,10 +5054,9 @@
PigeonInstanceManager? pigeon_instanceManager,
ResolutionStrategy Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -5475,15 +5079,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- ResolutionStrategy.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ ResolutionStrategy.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);
@@ -5498,14 +5101,15 @@
}
static ResolutionStrategy pigeonVar_highestAvailableStrategy() {
- final ResolutionStrategy pigeonVar_instance =
- ResolutionStrategy.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final ResolutionStrategy pigeonVar_instance = ResolutionStrategy.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.highestAvailableStrategy';
@@ -5514,9 +5118,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5535,8 +5139,7 @@
/// The specified bound size.
Future<CameraSize?> getBoundSize() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecResolutionStrategy;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getBoundSize';
@@ -5545,9 +5148,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5565,8 +5166,7 @@
/// The fallback rule for choosing an alternate size when the specified bound
/// size is unavailable.
Future<ResolutionStrategyFallbackRule> getFallbackRule() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecResolutionStrategy;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getFallbackRule';
@@ -5575,9 +5175,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5642,10 +5240,8 @@
this.resolutionStrategy,
AspectRatioStrategy? aspectRatioStrategy,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecResolutionSelector;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionSelector;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_defaultConstructor';
@@ -5654,13 +5250,12 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel
- .send(<Object?>[
- pigeonVar_instanceIdentifier,
- resolutionFilter,
- resolutionStrategy,
- aspectRatioStrategy,
- ]);
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ resolutionFilter,
+ resolutionStrategy,
+ aspectRatioStrategy,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -5689,10 +5284,8 @@
this.resolutionStrategy,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecResolutionSelector = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionSelector =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// The resolution filter to output the final desired sizes list.
final ResolutionFilter? resolutionFilter;
@@ -5710,10 +5303,9 @@
)?
pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -5735,25 +5327,19 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance was null, expected non-null int.',
);
- final ResolutionFilter? arg_resolutionFilter =
- (args[1] as ResolutionFilter?);
- final ResolutionStrategy? arg_resolutionStrategy =
- (args[2] as ResolutionStrategy?);
+ final ResolutionFilter? arg_resolutionFilter = (args[1] as ResolutionFilter?);
+ final ResolutionStrategy? arg_resolutionStrategy = (args[2] as ResolutionStrategy?);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_resolutionFilter,
- arg_resolutionStrategy,
- ) ??
- ResolutionSelector.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- resolutionFilter: arg_resolutionFilter,
- resolutionStrategy: arg_resolutionStrategy,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_resolutionFilter, arg_resolutionStrategy) ??
+ ResolutionSelector.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ resolutionFilter: arg_resolutionFilter,
+ resolutionStrategy: arg_resolutionStrategy,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -5771,8 +5357,7 @@
/// `AspectRatioStrategy.ratio_4_3FallbackAutoStrategy` if none is specified
/// when creating the ResolutionSelector.
Future<AspectRatioStrategy> getAspectRatioStrategy() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecResolutionSelector;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionSelector;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.getAspectRatioStrategy';
@@ -5781,9 +5366,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -5850,10 +5433,8 @@
required AspectRatio preferredAspectRatio,
required AspectRatioStrategyFallbackRule fallbackRule,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecAspectRatioStrategy;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_defaultConstructor';
@@ -5862,13 +5443,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[
- pigeonVar_instanceIdentifier,
- preferredAspectRatio,
- fallbackRule,
- ],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ preferredAspectRatio,
+ fallbackRule,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -5890,15 +5469,10 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- AspectRatioStrategy.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ AspectRatioStrategy.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecAspectRatioStrategy = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAspectRatioStrategy =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
/// The pre-defined aspect ratio strategy that selects sizes with RATIO_16_9
/// in priority.
@@ -5928,10 +5502,9 @@
PigeonInstanceManager? pigeon_instanceManager,
AspectRatioStrategy Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -5954,15 +5527,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- AspectRatioStrategy.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ AspectRatioStrategy.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);
@@ -5977,14 +5549,15 @@
}
static AspectRatioStrategy pigeonVar_ratio_16_9FallbackAutoStrategy() {
- final AspectRatioStrategy pigeonVar_instance =
- AspectRatioStrategy.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final AspectRatioStrategy pigeonVar_instance = AspectRatioStrategy.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_16_9FallbackAutoStrategy';
@@ -5993,9 +5566,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6013,14 +5586,15 @@
}
static AspectRatioStrategy pigeonVar_ratio_4_3FallbackAutoStrategy() {
- final AspectRatioStrategy pigeonVar_instance =
- AspectRatioStrategy.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final AspectRatioStrategy pigeonVar_instance = AspectRatioStrategy.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_4_3FallbackAutoStrategy';
@@ -6029,9 +5603,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6051,8 +5625,7 @@
/// The specified fallback rule for choosing the aspect ratio when the
/// preferred aspect ratio is not available.
Future<AspectRatioStrategyFallbackRule> getFallbackRule() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecAspectRatioStrategy;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getFallbackRule';
@@ -6061,9 +5634,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6085,8 +5656,7 @@
/// The specified preferred aspect ratio.
Future<AspectRatio> getPreferredAspectRatio() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecAspectRatioStrategy;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getPreferredAspectRatio';
@@ -6095,9 +5665,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6152,13 +5720,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- CameraState Function(CameraStateType type, CameraStateStateError? error)?
- pigeon_newInstance,
+ CameraState Function(CameraStateType type, CameraStateStateError? error)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6185,20 +5751,18 @@
arg_type != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance was null, expected non-null CameraStateType.',
);
- final CameraStateStateError? arg_error =
- (args[2] as CameraStateStateError?);
+ final CameraStateStateError? arg_error = (args[2] as CameraStateStateError?);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_type!, arg_error) ??
- CameraState.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- type: arg_type!,
- error: arg_error,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_type!, arg_error) ??
+ CameraState.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ type: arg_type!,
+ error: arg_error,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -6256,10 +5820,9 @@
)?
pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6293,21 +5856,19 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance was null, expected non-null double.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_exposureCompensationRange!,
- arg_exposureCompensationStep!,
- ) ??
- ExposureState.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- exposureCompensationRange:
- arg_exposureCompensationRange!,
- exposureCompensationStep: arg_exposureCompensationStep!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(
+ arg_exposureCompensationRange!,
+ arg_exposureCompensationStep!,
+ ) ??
+ ExposureState.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ exposureCompensationRange: arg_exposureCompensationRange!,
+ exposureCompensationStep: arg_exposureCompensationStep!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -6358,13 +5919,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- ZoomState Function(double minZoomRatio, double maxZoomRatio)?
- pigeon_newInstance,
+ ZoomState Function(double minZoomRatio, double maxZoomRatio)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6397,20 +5956,16 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance was null, expected non-null double.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_minZoomRatio!,
- arg_maxZoomRatio!,
- ) ??
- ZoomState.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- minZoomRatio: arg_minZoomRatio!,
- maxZoomRatio: arg_maxZoomRatio!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_minZoomRatio!, arg_maxZoomRatio!) ??
+ ZoomState.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ minZoomRatio: arg_minZoomRatio!,
+ maxZoomRatio: arg_maxZoomRatio!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -6475,10 +6030,8 @@
CameraIntegerRange? targetFpsRange,
int? outputImageFormat,
}) : super.pigeon_detached() {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageAnalysis;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_defaultConstructor';
@@ -6487,14 +6040,13 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel
- .send(<Object?>[
- pigeonVar_instanceIdentifier,
- resolutionSelector,
- targetRotation,
- targetFpsRange,
- outputImageFormat,
- ]);
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ resolutionSelector,
+ targetRotation,
+ targetFpsRange,
+ outputImageFormat,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -6531,13 +6083,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- ImageAnalysis Function(ResolutionSelector? resolutionSelector)?
- pigeon_newInstance,
+ ImageAnalysis Function(ResolutionSelector? resolutionSelector)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6559,19 +6109,17 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance was null, expected non-null int.',
);
- final ResolutionSelector? arg_resolutionSelector =
- (args[1] as ResolutionSelector?);
+ final ResolutionSelector? arg_resolutionSelector = (args[1] as ResolutionSelector?);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_resolutionSelector) ??
- ImageAnalysis.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- resolutionSelector: arg_resolutionSelector,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_resolutionSelector) ??
+ ImageAnalysis.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ resolutionSelector: arg_resolutionSelector,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -6587,8 +6135,7 @@
/// Sets an analyzer to receive and analyze images.
Future<void> setAnalyzer(Analyzer analyzer) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageAnalysis;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setAnalyzer';
@@ -6597,9 +6144,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, analyzer],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, analyzer]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6616,8 +6161,7 @@
/// Removes a previously set analyzer.
Future<void> clearAnalyzer() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageAnalysis;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.clearAnalyzer';
@@ -6626,9 +6170,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6645,8 +6187,7 @@
/// Sets the target rotation.
Future<void> setTargetRotation(int rotation) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageAnalysis;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setTargetRotation';
@@ -6655,9 +6196,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, rotation],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, rotation]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -6707,10 +6246,8 @@
super.pigeon_instanceManager,
required this.analyze,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecAnalyzer;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAnalyzer;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Analyzer.pigeon_defaultConstructor';
@@ -6719,9 +6256,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -6779,10 +6316,9 @@
PigeonInstanceManager? pigeon_instanceManager,
void Function(Analyzer pigeon_instance, ImageProxy image)? analyze,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6810,10 +6346,7 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze was null, expected non-null ImageProxy.',
);
try {
- (analyze ?? arg_pigeon_instance!.analyze).call(
- arg_pigeon_instance!,
- arg_image!,
- );
+ (analyze ?? arg_pigeon_instance!.analyze).call(arg_pigeon_instance!, arg_image!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -6859,13 +6392,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- CameraStateStateError Function(CameraStateErrorCode code)?
- pigeon_newInstance,
+ CameraStateStateError Function(CameraStateErrorCode code)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6887,23 +6418,21 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null, expected non-null int.',
);
- final CameraStateErrorCode? arg_code =
- (args[1] as CameraStateErrorCode?);
+ final CameraStateErrorCode? arg_code = (args[1] as CameraStateErrorCode?);
assert(
arg_code != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null, expected non-null CameraStateErrorCode.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_code!) ??
- CameraStateStateError.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- code: arg_code!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_code!) ??
+ CameraStateStateError.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ code: arg_code!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -6958,10 +6487,9 @@
PigeonInstanceManager? pigeon_instanceManager,
LiveData Function(LiveDataSupportedType type)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -6983,23 +6511,21 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null, expected non-null int.',
);
- final LiveDataSupportedType? arg_type =
- (args[1] as LiveDataSupportedType?);
+ final LiveDataSupportedType? arg_type = (args[1] as LiveDataSupportedType?);
assert(
arg_type != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null, expected non-null LiveDataSupportedType.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_type!) ??
- LiveData.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- type: arg_type!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_type!) ??
+ LiveData.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ type: arg_type!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -7016,19 +6542,15 @@
/// Adds the given observer to the observers list within the lifespan of the
/// given owner.
Future<void> observe(Observer observer) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecLiveData;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.LiveData.observe';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.observe';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, observer],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, observer]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7045,8 +6567,7 @@
/// Removes all observers that are tied to the given `LifecycleOwner`.
Future<void> removeObservers() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecLiveData;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.LiveData.removeObservers';
@@ -7055,9 +6576,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7074,19 +6593,15 @@
/// Returns the current value.
Future<Object?> getValue() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecLiveData;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.LiveData.getValue';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.getValue';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7146,10 +6661,9 @@
PigeonInstanceManager? pigeon_instanceManager,
ImageProxy Function(int format, int width, int height)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -7187,22 +6701,17 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_format!,
- arg_width!,
- arg_height!,
- ) ??
- ImageProxy.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- format: arg_format!,
- width: arg_width!,
- height: arg_height!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_format!, arg_width!, arg_height!) ??
+ ImageProxy.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ format: arg_format!,
+ width: arg_width!,
+ height: arg_height!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -7218,19 +6727,15 @@
/// Returns the array of planes.
Future<List<PlaneProxy>> getPlanes() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageProxy;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageProxy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7252,19 +6757,15 @@
/// Closes the underlying `android.media.Image`.
Future<void> close() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecImageProxy;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageProxy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.close';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.close';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7298,10 +6799,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- ImageProxyUtils.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ ImageProxyUtils.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImageProxyUtils =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -7312,10 +6810,9 @@
PigeonInstanceManager? pigeon_instanceManager,
ImageProxyUtils Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -7338,15 +6835,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxyUtils.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- ImageProxyUtils.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ ImageProxyUtils.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);
@@ -7369,16 +6865,11 @@
PigeonInstanceManager? pigeon_instanceManager,
}) async {
if (PigeonOverrides.imageProxyUtils_getNv21Buffer != null) {
- return PigeonOverrides.imageProxyUtils_getNv21Buffer!(
- imageWidth,
- imageHeight,
- planes,
- );
+ return PigeonOverrides.imageProxyUtils_getNv21Buffer!(imageWidth, imageHeight, planes);
}
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ImageProxyUtils.getNv21Buffer';
@@ -7387,9 +6878,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[imageWidth, imageHeight, planes],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ imageWidth,
+ imageHeight,
+ planes,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7449,13 +6942,11 @@
bool pigeon_clearHandlers = false,
BinaryMessenger? pigeon_binaryMessenger,
PigeonInstanceManager? pigeon_instanceManager,
- PlaneProxy Function(Uint8List buffer, int pixelStride, int rowStride)?
- pigeon_newInstance,
+ PlaneProxy Function(Uint8List buffer, int pixelStride, int rowStride)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -7493,22 +6984,17 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_buffer!,
- arg_pixelStride!,
- arg_rowStride!,
- ) ??
- PlaneProxy.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- buffer: arg_buffer!,
- pixelStride: arg_pixelStride!,
- rowStride: arg_rowStride!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_buffer!, arg_pixelStride!, arg_rowStride!) ??
+ PlaneProxy.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ buffer: arg_buffer!,
+ pixelStride: arg_pixelStride!,
+ rowStride: arg_rowStride!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -7568,21 +7054,20 @@
required VideoQuality quality,
FallbackStrategy? fallbackStrategy,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecQualitySelector;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecQualitySelector;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
- const pigeonVar_channelName =
- 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.from';
+ const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.from';
final pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, quality, fallbackStrategy],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ quality,
+ fallbackStrategy,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -7628,10 +7113,8 @@
required List<VideoQuality> qualities,
FallbackStrategy? fallbackStrategy,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecQualitySelector;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecQualitySelector;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.QualitySelector.fromOrderedList';
@@ -7640,9 +7123,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, qualities, fallbackStrategy],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ qualities,
+ fallbackStrategy,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -7664,10 +7149,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- QualitySelector.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ QualitySelector.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecQualitySelector =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -7678,10 +7160,9 @@
PigeonInstanceManager? pigeon_instanceManager,
QualitySelector Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -7704,15 +7185,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- QualitySelector.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ QualitySelector.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);
@@ -7734,15 +7214,11 @@
PigeonInstanceManager? pigeon_instanceManager,
}) async {
if (PigeonOverrides.qualitySelector_getResolution != null) {
- return PigeonOverrides.qualitySelector_getResolution!(
- cameraInfo,
- quality,
- );
+ return PigeonOverrides.qualitySelector_getResolution!(cameraInfo, quality);
}
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.QualitySelector.getResolution';
@@ -7751,9 +7227,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraInfo, quality],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ cameraInfo,
+ quality,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -7791,9 +7268,7 @@
required VideoQuality quality,
}) {
if (PigeonOverrides.fallbackStrategy_higherQualityOrLowerThan != null) {
- return PigeonOverrides.fallbackStrategy_higherQualityOrLowerThan!(
- quality: quality,
- );
+ return PigeonOverrides.fallbackStrategy_higherQualityOrLowerThan!(quality: quality);
}
return FallbackStrategy.pigeon_higherQualityOrLowerThan(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -7810,10 +7285,8 @@
super.pigeon_instanceManager,
required VideoQuality quality,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecFallbackStrategy;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityOrLowerThan';
@@ -7822,9 +7295,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, quality],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ quality,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -7849,9 +7323,7 @@
required VideoQuality quality,
}) {
if (PigeonOverrides.fallbackStrategy_higherQualityThan != null) {
- return PigeonOverrides.fallbackStrategy_higherQualityThan!(
- quality: quality,
- );
+ return PigeonOverrides.fallbackStrategy_higherQualityThan!(quality: quality);
}
return FallbackStrategy.pigeon_higherQualityThan(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -7868,10 +7340,8 @@
super.pigeon_instanceManager,
required VideoQuality quality,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecFallbackStrategy;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityThan';
@@ -7880,9 +7350,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, quality],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ quality,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -7907,9 +7378,7 @@
required VideoQuality quality,
}) {
if (PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan != null) {
- return PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan!(
- quality: quality,
- );
+ return PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan!(quality: quality);
}
return FallbackStrategy.pigeon_lowerQualityOrHigherThan(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -7926,10 +7395,8 @@
super.pigeon_instanceManager,
required VideoQuality quality,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecFallbackStrategy;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityOrHigherThan';
@@ -7938,9 +7405,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, quality],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ quality,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -7965,9 +7433,7 @@
required VideoQuality quality,
}) {
if (PigeonOverrides.fallbackStrategy_lowerQualityThan != null) {
- return PigeonOverrides.fallbackStrategy_lowerQualityThan!(
- quality: quality,
- );
+ return PigeonOverrides.fallbackStrategy_lowerQualityThan!(quality: quality);
}
return FallbackStrategy.pigeon_lowerQualityThan(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -7984,10 +7450,8 @@
super.pigeon_instanceManager,
required VideoQuality quality,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecFallbackStrategy;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityThan';
@@ -7996,9 +7460,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, quality],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ quality,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -8020,10 +7485,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- FallbackStrategy.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ FallbackStrategy.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecFallbackStrategy =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -8034,10 +7496,9 @@
PigeonInstanceManager? pigeon_instanceManager,
FallbackStrategy Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -8060,15 +7521,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- FallbackStrategy.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ FallbackStrategy.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);
@@ -8102,10 +7562,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- CameraControl.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ CameraControl.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraControl =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -8116,10 +7573,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CameraControl Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -8142,15 +7598,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CameraControl.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CameraControl.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);
@@ -8166,8 +7621,7 @@
/// Enable the torch or disable the torch.
Future<void> enableTorch(bool torch) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraControl;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraControl.enableTorch';
@@ -8176,9 +7630,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, torch],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, torch]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8195,8 +7647,7 @@
/// Sets current zoom by ratio.
Future<void> setZoomRatio(double ratio) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraControl;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraControl.setZoomRatio';
@@ -8205,9 +7656,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, ratio],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, ratio]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8224,11 +7673,8 @@
/// Starts a focus and metering action configured by the
/// `FocusMeteringAction`.
- Future<FocusMeteringResult?> startFocusAndMetering(
- FocusMeteringAction action,
- ) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraControl;
+ Future<FocusMeteringResult?> startFocusAndMetering(FocusMeteringAction action) async {
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraControl.startFocusAndMetering';
@@ -8237,9 +7683,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, action],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, action]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8256,8 +7700,7 @@
/// Cancels current FocusMeteringAction and clears AF/AE/AWB regions.
Future<void> cancelFocusAndMetering() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraControl;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraControl.cancelFocusAndMetering';
@@ -8266,9 +7709,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8285,8 +7726,7 @@
/// Set the exposure compensation value for the camera.
Future<int?> setExposureCompensationIndex(int index) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCameraControl;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraControl.setExposureCompensationIndex';
@@ -8295,9 +7735,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, index],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, index]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8350,8 +7788,7 @@
super.pigeon_instanceManager,
required MeteringPoint point,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecFocusMeteringActionBuilder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -8362,9 +7799,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, point],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ point,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -8389,10 +7827,7 @@
required MeteringMode mode,
}) {
if (PigeonOverrides.focusMeteringActionBuilder_withMode != null) {
- return PigeonOverrides.focusMeteringActionBuilder_withMode!(
- point: point,
- mode: mode,
- );
+ return PigeonOverrides.focusMeteringActionBuilder_withMode!(point: point, mode: mode);
}
return FocusMeteringActionBuilder.pigeon_withMode(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -8410,8 +7845,7 @@
required MeteringPoint point,
required MeteringMode mode,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecFocusMeteringActionBuilder;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -8422,9 +7856,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, point, mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ point,
+ mode,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -8451,10 +7887,8 @@
super.pigeon_instanceManager,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecFocusMeteringActionBuilder = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecFocusMeteringActionBuilder =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -8462,10 +7896,9 @@
PigeonInstanceManager? pigeon_instanceManager,
FocusMeteringActionBuilder Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -8488,15 +7921,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- FocusMeteringActionBuilder.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ FocusMeteringActionBuilder.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);
@@ -8522,9 +7954,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, point],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, point]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8551,9 +7981,11 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, point, mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ point,
+ mode,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8580,9 +8012,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8609,9 +8039,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -8682,10 +8110,9 @@
)?
pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -8707,20 +8134,20 @@
arg_pigeon_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null int.',
);
- final List<MeteringPoint>? arg_meteringPointsAe =
- (args[1] as List<Object?>?)?.cast<MeteringPoint>();
+ final List<MeteringPoint>? arg_meteringPointsAe = (args[1] as List<Object?>?)
+ ?.cast<MeteringPoint>();
assert(
arg_meteringPointsAe != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List<MeteringPoint>.',
);
- final List<MeteringPoint>? arg_meteringPointsAf =
- (args[2] as List<Object?>?)?.cast<MeteringPoint>();
+ final List<MeteringPoint>? arg_meteringPointsAf = (args[2] as List<Object?>?)
+ ?.cast<MeteringPoint>();
assert(
arg_meteringPointsAf != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List<MeteringPoint>.',
);
- final List<MeteringPoint>? arg_meteringPointsAwb =
- (args[3] as List<Object?>?)?.cast<MeteringPoint>();
+ final List<MeteringPoint>? arg_meteringPointsAwb = (args[3] as List<Object?>?)
+ ?.cast<MeteringPoint>();
assert(
arg_meteringPointsAwb != null,
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List<MeteringPoint>.',
@@ -8731,24 +8158,23 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null bool.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(
- arg_meteringPointsAe!,
- arg_meteringPointsAf!,
- arg_meteringPointsAwb!,
- arg_isAutoCancelEnabled!,
- ) ??
- FocusMeteringAction.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- meteringPointsAe: arg_meteringPointsAe!,
- meteringPointsAf: arg_meteringPointsAf!,
- meteringPointsAwb: arg_meteringPointsAwb!,
- isAutoCancelEnabled: arg_isAutoCancelEnabled!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(
+ arg_meteringPointsAe!,
+ arg_meteringPointsAf!,
+ arg_meteringPointsAwb!,
+ arg_isAutoCancelEnabled!,
+ ) ??
+ FocusMeteringAction.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ meteringPointsAe: arg_meteringPointsAe!,
+ meteringPointsAf: arg_meteringPointsAf!,
+ meteringPointsAwb: arg_meteringPointsAwb!,
+ isAutoCancelEnabled: arg_isAutoCancelEnabled!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -8799,10 +8225,9 @@
PigeonInstanceManager? pigeon_instanceManager,
FocusMeteringResult Function(bool isFocusSuccessful)? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -8830,16 +8255,15 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance was null, expected non-null bool.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call(arg_isFocusSuccessful!) ??
- FocusMeteringResult.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- isFocusSuccessful: arg_isFocusSuccessful!,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call(arg_isFocusSuccessful!) ??
+ FocusMeteringResult.pigeon_detached(
+ pigeon_binaryMessenger: pigeon_binaryMessenger,
+ pigeon_instanceManager: pigeon_instanceManager,
+ isFocusSuccessful: arg_isFocusSuccessful!,
+ ),
+ arg_pigeon_instanceIdentifier!,
+ );
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
@@ -8873,10 +8297,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- CaptureRequest.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ CaptureRequest.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
/// Whether auto-exposure (AE) is currently locked to its latest calculated
/// values.
@@ -8918,10 +8339,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CaptureRequest Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -8944,15 +8364,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CaptureRequest.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CaptureRequest.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);
@@ -8967,14 +8386,15 @@
}
static CaptureRequestKey pigeonVar_controlAELock() {
- final CaptureRequestKey pigeonVar_instance =
- CaptureRequestKey.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final CaptureRequestKey pigeonVar_instance = CaptureRequestKey.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlAELock';
@@ -8983,9 +8403,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9003,14 +8423,15 @@
}
static CaptureRequestKey pigeonVar_controlVideoStabilizationMode() {
- final CaptureRequestKey pigeonVar_instance =
- CaptureRequestKey.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final CaptureRequestKey pigeonVar_instance = CaptureRequestKey.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlVideoStabilizationMode';
@@ -9019,9 +8440,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9057,10 +8478,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- CaptureRequestKey.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ CaptureRequestKey.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -9068,10 +8486,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CaptureRequestKey Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -9094,15 +8511,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CaptureRequestKey.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CaptureRequestKey.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);
@@ -9150,8 +8566,7 @@
super.pigeon_instanceManager,
required Map<CaptureRequestKey, Object?> options,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecCaptureRequestOptions;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -9162,9 +8577,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, options],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ options,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -9191,10 +8607,8 @@
super.pigeon_instanceManager,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecCaptureRequestOptions = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCaptureRequestOptions =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -9202,10 +8616,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CaptureRequestOptions Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -9228,15 +8641,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CaptureRequestOptions.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CaptureRequestOptions.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);
@@ -9263,9 +8675,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, key],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, key]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9301,9 +8711,7 @@
required CameraControl cameraControl,
}) {
if (PigeonOverrides.camera2CameraControl_from != null) {
- return PigeonOverrides.camera2CameraControl_from!(
- cameraControl: cameraControl,
- );
+ return PigeonOverrides.camera2CameraControl_from!(cameraControl: cameraControl);
}
return Camera2CameraControl.pigeon_from(
pigeon_binaryMessenger: pigeon_binaryMessenger,
@@ -9319,8 +8727,7 @@
super.pigeon_instanceManager,
required CameraControl cameraControl,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecCamera2CameraControl;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -9331,9 +8738,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, cameraControl],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ cameraControl,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -9360,10 +8768,8 @@
super.pigeon_instanceManager,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecCamera2CameraControl = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCamera2CameraControl =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -9371,10 +8777,9 @@
PigeonInstanceManager? pigeon_instanceManager,
Camera2CameraControl Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -9397,15 +8802,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- Camera2CameraControl.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ Camera2CameraControl.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);
@@ -9432,9 +8836,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, bundle],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, bundle]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9486,10 +8888,8 @@
super.pigeon_instanceManager,
required CameraSize preferredSize,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecResolutionFilter;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionFilter;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.createWithOnePreferredSize';
@@ -9498,9 +8898,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, preferredSize],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ preferredSize,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -9522,10 +8923,7 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- ResolutionFilter.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ ResolutionFilter.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionFilter =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
@@ -9536,10 +8934,9 @@
PigeonInstanceManager? pigeon_instanceManager,
ResolutionFilter Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -9562,15 +8959,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- ResolutionFilter.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ ResolutionFilter.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);
@@ -9614,10 +9010,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CameraCharacteristicsKey Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -9640,15 +9035,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CameraCharacteristicsKey.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CameraCharacteristicsKey.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);
@@ -9699,8 +9093,7 @@
/// Value is int.
///
/// This key is available on all devices.
- static final CameraCharacteristicsKey _sensorOrientation =
- pigeonVar_sensorOrientation();
+ static final CameraCharacteristicsKey _sensorOrientation = pigeonVar_sensorOrientation();
/// List of video stabilization modes for android.control.videoStabilizationMode
/// that are supported by this camera device.
@@ -9708,8 +9101,7 @@
/// Value is `ControlAvailableVideoStabilizationMode`.
///
/// This key is available on all devices.
- static final CameraCharacteristicsKey
- _controlAvailableVideoStabilizationModes =
+ static final CameraCharacteristicsKey _controlAvailableVideoStabilizationModes =
pigeonVar_controlAvailableVideoStabilizationModes();
/// Generally classifies the overall set of the camera device functionality.
@@ -9728,8 +9120,7 @@
///
/// This key is available on all devices.
static CameraCharacteristicsKey get sensorOrientation =>
- PigeonOverrides.cameraCharacteristics_sensorOrientation ??
- _sensorOrientation;
+ PigeonOverrides.cameraCharacteristics_sensorOrientation ?? _sensorOrientation;
/// List of video stabilization modes for android.control.videoStabilizationMode
/// that are supported by this camera device.
@@ -9738,8 +9129,7 @@
///
/// This key is available on all devices.
static CameraCharacteristicsKey get controlAvailableVideoStabilizationModes =>
- PigeonOverrides
- .cameraCharacteristics_controlAvailableVideoStabilizationModes ??
+ PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes ??
_controlAvailableVideoStabilizationModes;
static void pigeon_setUpMessageHandlers({
@@ -9748,10 +9138,9 @@
PigeonInstanceManager? pigeon_instanceManager,
CameraCharacteristics Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -9774,15 +9163,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- CameraCharacteristics.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ CameraCharacteristics.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);
@@ -9797,14 +9185,15 @@
}
static CameraCharacteristicsKey pigeonVar_infoSupportedHardwareLevel() {
- final CameraCharacteristicsKey pigeonVar_instance =
- CameraCharacteristicsKey.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final CameraCharacteristicsKey pigeonVar_instance = CameraCharacteristicsKey.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.infoSupportedHardwareLevel';
@@ -9813,9 +9202,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9833,14 +9222,15 @@
}
static CameraCharacteristicsKey pigeonVar_sensorOrientation() {
- final CameraCharacteristicsKey pigeonVar_instance =
- CameraCharacteristicsKey.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ final CameraCharacteristicsKey pigeonVar_instance = CameraCharacteristicsKey.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.sensorOrientation';
@@ -9849,9 +9239,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9868,16 +9258,16 @@
return pigeonVar_instance;
}
- static CameraCharacteristicsKey
- pigeonVar_controlAvailableVideoStabilizationModes() {
- final CameraCharacteristicsKey pigeonVar_instance =
- CameraCharacteristicsKey.pigeon_detached();
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance);
+ static CameraCharacteristicsKey pigeonVar_controlAvailableVideoStabilizationModes() {
+ final CameraCharacteristicsKey pigeonVar_instance = CameraCharacteristicsKey.pigeon_detached();
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ PigeonInstanceManager.instance,
+ );
final BinaryMessenger pigeonVar_binaryMessenger =
ServicesBinding.instance.defaultBinaryMessenger;
- final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance
- .addDartCreatedInstance(pigeonVar_instance);
+ final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance(
+ pigeonVar_instance,
+ );
() async {
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.controlAvailableVideoStabilizationModes';
@@ -9886,9 +9276,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -9941,10 +9331,8 @@
super.pigeon_instanceManager,
required CameraInfo cameraInfo,
}) {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCamera2CameraInfo;
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.from';
@@ -9953,9 +9341,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, cameraInfo],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ cameraInfo,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -9977,15 +9366,10 @@
/// This should only be used by subclasses created by this library or to
/// create copies for an [PigeonInstanceManager].
@protected
- Camera2CameraInfo.pigeon_detached({
- super.pigeon_binaryMessenger,
- super.pigeon_instanceManager,
- });
+ Camera2CameraInfo.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecCamera2CameraInfo = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCamera2CameraInfo =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -9993,10 +9377,9 @@
PigeonInstanceManager? pigeon_instanceManager,
Camera2CameraInfo Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -10019,15 +9402,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- Camera2CameraInfo.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ Camera2CameraInfo.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);
@@ -10043,8 +9425,7 @@
/// Gets the string camera ID.
Future<String> getCameraId() async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCamera2CameraInfo;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraId';
@@ -10053,9 +9434,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -10077,8 +9456,7 @@
/// Gets a camera characteristic value.
Future<Object?> getCameraCharacteristic(CameraCharacteristicsKey key) async {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _pigeonVar_codecCamera2CameraInfo;
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
const pigeonVar_channelName =
'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraCharacteristic';
@@ -10087,9 +9465,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, key],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, key]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -10127,10 +9503,8 @@
super.pigeon_instanceManager,
});
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecMeteringPointFactory = _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager,
- );
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecMeteringPointFactory =
+ _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
bool pigeon_clearHandlers = false,
@@ -10138,10 +9512,9 @@
PigeonInstanceManager? pigeon_instanceManager,
MeteringPointFactory Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -10164,15 +9537,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- MeteringPointFactory.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ MeteringPointFactory.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);
@@ -10198,9 +9570,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, x, y],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[this, x, y]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -10221,11 +9591,7 @@
}
/// Creates a MeteringPoint by x, y, size.
- Future<MeteringPoint> createPointWithSize(
- double x,
- double y,
- double size,
- ) async {
+ Future<MeteringPoint> createPointWithSize(double x, double y, double size) async {
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecMeteringPointFactory;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -10236,9 +9602,12 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[this, x, y, size],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ this,
+ x,
+ y,
+ size,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -10310,8 +9679,7 @@
required double width,
required double height,
}) : super.pigeon_detached() {
- final int pigeonVar_instanceIdentifier = pigeon_instanceManager
- .addDartCreatedInstance(this);
+ final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this);
final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
_pigeonVar_codecDisplayOrientedMeteringPointFactory;
final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger;
@@ -10322,9 +9690,12 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[pigeonVar_instanceIdentifier, cameraInfo, width, height],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ pigeonVar_instanceIdentifier,
+ cameraInfo,
+ width,
+ height,
+ ]);
() async {
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
@@ -10351,8 +9722,7 @@
super.pigeon_instanceManager,
}) : super.pigeon_detached();
- late final _PigeonInternalProxyApiBaseCodec
- _pigeonVar_codecDisplayOrientedMeteringPointFactory =
+ late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecDisplayOrientedMeteringPointFactory =
_PigeonInternalProxyApiBaseCodec(pigeon_instanceManager);
static void pigeon_setUpMessageHandlers({
@@ -10361,10 +9731,9 @@
PigeonInstanceManager? pigeon_instanceManager,
DisplayOrientedMeteringPointFactory Function()? pigeon_newInstance,
}) {
- final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec =
- _PigeonInternalProxyApiBaseCodec(
- pigeon_instanceManager ?? PigeonInstanceManager.instance,
- );
+ final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec(
+ pigeon_instanceManager ?? PigeonInstanceManager.instance,
+ );
final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger;
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -10387,15 +9756,14 @@
'Argument for dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance was null, expected non-null int.',
);
try {
- (pigeon_instanceManager ?? PigeonInstanceManager.instance)
- .addHostCreatedInstance(
- pigeon_newInstance?.call() ??
- DisplayOrientedMeteringPointFactory.pigeon_detached(
- pigeon_binaryMessenger: pigeon_binaryMessenger,
- pigeon_instanceManager: pigeon_instanceManager,
- ),
- arg_pigeon_instanceIdentifier!,
- );
+ (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance(
+ pigeon_newInstance?.call() ??
+ DisplayOrientedMeteringPointFactory.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);
diff --git a/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart b/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart
index cf79195..aa0899e 100644
--- a/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart
+++ b/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart
@@ -71,19 +71,15 @@
State<StatefulWidget> createState() => _ImageReaderRotatedPreviewState();
}
-final class _ImageReaderRotatedPreviewState
- extends State<ImageReaderRotatedPreview> {
+final class _ImageReaderRotatedPreviewState extends State<ImageReaderRotatedPreview> {
late DeviceOrientation deviceOrientation;
late Future<int> defaultDisplayRotationDegrees;
late StreamSubscription<DeviceOrientation> deviceOrientationSubscription;
Future<int> _getCurrentDefaultDisplayRotationDegrees() async {
- final int currentDefaultDisplayRotationQuarterTurns = await widget
- .deviceOrientationManager
+ final int currentDefaultDisplayRotationQuarterTurns = await widget.deviceOrientationManager
.getDefaultDisplayRotation();
- return getQuarterTurnsFromSurfaceRotationConstant(
- currentDefaultDisplayRotationQuarterTurns,
- ) *
+ return getQuarterTurnsFromSurfaceRotationConstant(currentDefaultDisplayRotationQuarterTurns) *
90;
}
@@ -91,14 +87,9 @@
void initState() {
deviceOrientation = widget.initialDeviceOrientation;
defaultDisplayRotationDegrees = Future<int>.value(
- getQuarterTurnsFromSurfaceRotationConstant(
- widget.initialDefaultDisplayRotation,
- ) *
- 90,
+ getQuarterTurnsFromSurfaceRotationConstant(widget.initialDefaultDisplayRotation) * 90,
);
- deviceOrientationSubscription = widget.deviceOrientation.listen((
- DeviceOrientation event,
- ) {
+ deviceOrientationSubscription = widget.deviceOrientation.listen((DeviceOrientation event) {
// Ensure that we aren't updating the state if the widget is being destroyed.
if (!mounted) {
return;
@@ -106,8 +97,7 @@
setState(() {
deviceOrientation = event;
- defaultDisplayRotationDegrees =
- _getCurrentDefaultDisplayRotationDegrees();
+ defaultDisplayRotationDegrees = _getCurrentDefaultDisplayRotationDegrees();
});
});
super.initState();
@@ -122,17 +112,13 @@
// Rotate the camera preview according to
// https://developer.android.com/media/camera/camera2/camera-preview#orientation_calculation.
double rotationDegrees =
- (sensorOrientationDegrees -
- currentDefaultDisplayRotationDegrees * sign +
- 360) %
- 360;
+ (sensorOrientationDegrees - currentDefaultDisplayRotationDegrees * sign + 360) % 360;
// Then, subtract the rotation already applied in the CameraPreview widget
// (see camera/camera/lib/src/camera_preview.dart) that is not correct
// for this plugin.
final double extraRotationDegrees =
- getPreAppliedQuarterTurnsRotationFromDeviceOrientation(orientation) *
- 90;
+ getPreAppliedQuarterTurnsRotationFromDeviceOrientation(orientation) * 90;
rotationDegrees -= extraRotationDegrees;
return rotationDegrees;
@@ -171,10 +157,7 @@
}
}
- return RotatedBox(
- quarterTurns: rotationDegrees ~/ 90,
- child: cameraPreview,
- );
+ return RotatedBox(quarterTurns: rotationDegrees ~/ 90, child: cameraPreview);
} else {
return const SizedBox.shrink();
}
diff --git a/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart b/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart
index ab1193f..838ef71 100644
--- a/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart
+++ b/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart
@@ -24,9 +24,7 @@
/// Returns the clockwise quarter turns applied by the CameraPreview widget
/// based on [orientation], the current device orientation (see
/// camera/camera/lib/src/camera_preview.dart).
-int getPreAppliedQuarterTurnsRotationFromDeviceOrientation(
- DeviceOrientation orientation,
-) {
+int getPreAppliedQuarterTurnsRotationFromDeviceOrientation(DeviceOrientation orientation) {
return switch (orientation) {
DeviceOrientation.portraitUp => 0,
DeviceOrientation.landscapeRight => 1,
diff --git a/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart b/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart
index ded79a0..a2a1b62 100644
--- a/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart
+++ b/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart
@@ -50,31 +50,24 @@
State<StatefulWidget> createState() => _SurfaceTextureRotatedPreviewState();
}
-final class _SurfaceTextureRotatedPreviewState
- extends State<SurfaceTextureRotatedPreview> {
+final class _SurfaceTextureRotatedPreviewState extends State<SurfaceTextureRotatedPreview> {
late StreamSubscription<DeviceOrientation> deviceOrientationSubscription;
late int preappliedRotationQuarterTurns;
late Future<int> defaultDisplayRotationQuarterTurns;
Future<int> _getCurrentDefaultDisplayRotationQuarterTurns() async {
- final int currentDefaultDisplayRotationQuarterTurns = await widget
- .deviceOrientationManager
+ final int currentDefaultDisplayRotationQuarterTurns = await widget.deviceOrientationManager
.getDefaultDisplayRotation();
- return getQuarterTurnsFromSurfaceRotationConstant(
- currentDefaultDisplayRotationQuarterTurns,
- );
+ return getQuarterTurnsFromSurfaceRotationConstant(currentDefaultDisplayRotationQuarterTurns);
}
@override
void initState() {
- preappliedRotationQuarterTurns =
- getPreAppliedQuarterTurnsRotationFromDeviceOrientation(
- widget.initialDeviceOrientation,
- );
+ preappliedRotationQuarterTurns = getPreAppliedQuarterTurnsRotationFromDeviceOrientation(
+ widget.initialDeviceOrientation,
+ );
defaultDisplayRotationQuarterTurns = Future<int>.value(
- getQuarterTurnsFromSurfaceRotationConstant(
- widget.initialDefaultDisplayRotation,
- ),
+ getQuarterTurnsFromSurfaceRotationConstant(widget.initialDefaultDisplayRotation),
);
deviceOrientationSubscription = widget.deviceOrientationStream.listen((
DeviceOrientation event,
@@ -85,10 +78,10 @@
}
setState(() {
- preappliedRotationQuarterTurns =
- getPreAppliedQuarterTurnsRotationFromDeviceOrientation(event);
- defaultDisplayRotationQuarterTurns =
- _getCurrentDefaultDisplayRotationQuarterTurns();
+ preappliedRotationQuarterTurns = getPreAppliedQuarterTurnsRotationFromDeviceOrientation(
+ event,
+ );
+ defaultDisplayRotationQuarterTurns = _getCurrentDefaultDisplayRotationQuarterTurns();
});
});
super.initState();
@@ -114,10 +107,7 @@
final int rotationCorrection =
currentDefaultDisplayRotation - preappliedRotationQuarterTurns;
- return RotatedBox(
- quarterTurns: rotationCorrection,
- child: widget.child,
- );
+ return RotatedBox(quarterTurns: rotationCorrection, child: widget.child);
} else {
return const SizedBox.shrink();
}
diff --git a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart
index 611157f..61bf6c5 100644
--- a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart
+++ b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart
@@ -10,8 +10,7 @@
PigeonOptions(
copyrightHeader: 'pigeons/copyright.txt',
dartOut: 'lib/src/camerax_library.g.dart',
- kotlinOut:
- 'android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt',
+ kotlinOut: 'android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt',
kotlinOptions: KotlinOptions(
package: 'io.flutter.plugins.camerax',
errorClassName: 'CameraXError',
@@ -21,9 +20,7 @@
/// Immutable class for describing width and height dimensions in pixels.
///
/// See https://developer.android.com/reference/android/util/Size.html.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Size'),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Size'))
abstract class CameraSize {
CameraSize();
@@ -39,9 +36,7 @@
///
/// See https://developer.android.com/reference/androidx/camera/core/ResolutionInfo.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ResolutionInfo',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ResolutionInfo'),
)
abstract class ResolutionInfo {
/// Returns the output resolution used for the use case.
@@ -120,9 +115,7 @@
/// This is the equivalent to `android.util.Range<Integer>`.
///
/// See https://developer.android.com/reference/android/util/Range.html.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Range<*>'),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Range<*>'))
abstract class CameraIntegerRange {
CameraIntegerRange();
@@ -163,9 +156,7 @@
///
/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.VideoRecordEvent',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.VideoRecordEvent'),
)
abstract class VideoRecordEvent {}
@@ -193,11 +184,7 @@
/// sensor coordinate system for focus and metering purpose.
///
/// See https://developer.android.com/reference/androidx/camera/core/MeteringPoint.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.MeteringPoint',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.MeteringPoint'))
abstract class MeteringPoint {
/// Size of the MeteringPoint width and height (ranging from 0 to 1).
///
@@ -226,11 +213,7 @@
/// A simple callback that can receive from LiveData.
///
/// See https://developer.android.com/reference/androidx/lifecycle/Observer.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.lifecycle.Observer<*>',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.lifecycle.Observer<*>'))
abstract class Observer {
Observer();
@@ -241,11 +224,7 @@
/// An interface for retrieving camera information.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.CameraInfo',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraInfo'))
abstract class CameraInfo {
/// Returns the sensor rotation in degrees, relative to the device's "natural"
/// (default) orientation.
@@ -288,15 +267,10 @@
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.CameraSelector',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraSelector'),
)
abstract class CameraSelector {
- CameraSelector(
- LensFacing? requireLensFacing,
- CameraInfo? cameraInfoForFilter,
- );
+ CameraSelector(LensFacing? requireLensFacing, CameraInfo? cameraInfoForFilter);
/// A static `CameraSelector` that selects the default back facing camera.
@static
@@ -346,11 +320,7 @@
/// The use case which all other use cases are built on top of.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/UseCase.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.UseCase',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.UseCase'))
abstract class UseCase {}
/// The camera interface is used to control the flow of data to use cases,
@@ -358,11 +328,7 @@
/// camera via CameraInfo.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/Camera.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.Camera',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.Camera'))
abstract class Camera {
/// The `CameraControl` for the Camera.
late CameraControl cameraControl;
@@ -413,11 +379,7 @@
/// A use case that provides a camera preview stream for displaying on-screen.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/Preview.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.Preview',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.Preview'))
abstract class Preview extends UseCase {
Preview(int? targetRotation, CameraIntegerRange? targetFpsRange);
@@ -452,16 +414,11 @@
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoCapture.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.VideoCapture<*>',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.VideoCapture<*>'),
)
abstract class VideoCapture extends UseCase {
/// Create a `VideoCapture` associated with the given `VideoOutput`.
- VideoCapture.withOutput(
- VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- );
+ VideoCapture.withOutput(VideoOutput videoOutput, CameraIntegerRange? targetFpsRange);
/// Gets the VideoOutput associated with this VideoCapture.
VideoOutput getOutput();
@@ -473,28 +430,16 @@
/// A class that will produce video data from a Surface.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoOutput.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.VideoOutput',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.VideoOutput'))
abstract class VideoOutput {}
/// An implementation of `VideoOutput` for starting video recordings that are
/// saved to a File, ParcelFileDescriptor, or MediaStore.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recorder.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.Recorder',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.Recorder'))
abstract class Recorder implements VideoOutput {
- Recorder(
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- );
+ Recorder(int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector);
/// Gets the aspect ratio of this Recorder.
int getAspectRatio();
@@ -521,9 +466,7 @@
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/video/PendingRecording.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.PendingRecording',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.PendingRecording'),
)
abstract class PendingRecording {
/// Enables/disables audio to be recorded for this recording.
@@ -547,11 +490,7 @@
/// Provides controls for the currently active recording.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recording.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.Recording',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.Recording'))
abstract class Recording {
/// Close this recording.
void close();
@@ -592,11 +531,7 @@
/// A use case for taking a picture.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ImageCapture',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageCapture'))
abstract class ImageCapture extends UseCase {
ImageCapture(int? targetRotation, CameraXFlashMode? flashMode);
@@ -655,10 +590,7 @@
),
)
abstract class ResolutionStrategy {
- ResolutionStrategy(
- CameraSize boundSize,
- ResolutionStrategyFallbackRule fallbackRule,
- );
+ ResolutionStrategy(CameraSize boundSize, ResolutionStrategyFallbackRule fallbackRule);
/// A resolution strategy chooses the highest available resolution.
@static
@@ -720,8 +652,7 @@
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy.
@ProxyApi(
kotlinOptions: KotlinProxyApiOptions(
- fullClassName:
- 'androidx.camera.core.resolutionselector.AspectRatioStrategy',
+ fullClassName: 'androidx.camera.core.resolutionselector.AspectRatioStrategy',
),
)
abstract class AspectRatioStrategy {
@@ -753,11 +684,7 @@
/// Represents the different states the camera can be in.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.CameraState',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraState'))
abstract class CameraState {
/// The camera's state.
late CameraStateType type;
@@ -769,11 +696,7 @@
/// An interface which contains the camera exposure related information.
///
/// See https://developer.android.com/reference/androidx/camera/core/ExposureState.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ExposureState',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ExposureState'))
abstract class ExposureState {
/// Get the maximum and minimum exposure compensation values for
/// `CameraControl.setExposureCompensationIndex`.
@@ -786,11 +709,7 @@
/// An interface which contains the zoom related information from a camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/ZoomState.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ZoomState',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ZoomState'))
abstract class ZoomState {
/// The minimum zoom ratio.
late double minZoomRatio;
@@ -803,17 +722,9 @@
/// analysis on.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ImageAnalysis',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageAnalysis'))
abstract class ImageAnalysis extends UseCase {
- ImageAnalysis(
- int? targetRotation,
- CameraIntegerRange? targetFpsRange,
- int? outputImageFormat,
- );
+ ImageAnalysis(int? targetRotation, CameraIntegerRange? targetFpsRange, int? outputImageFormat);
late final ResolutionSelector? resolutionSelector;
@@ -900,8 +811,7 @@
/// See https://developer.android.com/reference/androidx/lifecycle/LiveData.
@ProxyApi(
kotlinOptions: KotlinProxyApiOptions(
- fullClassName:
- 'io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper',
+ fullClassName: 'io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper',
),
)
abstract class LiveData {
@@ -922,11 +832,7 @@
/// An image proxy which has a similar interface as `android.media.Image`.
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ImageProxy',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageProxy'))
abstract class ImageProxy {
/// The image format.
late int format;
@@ -949,11 +855,7 @@
abstract class ImageProxyUtils {
/// Returns a single buffer that is representative of three NV21-compatible [planes].
@static
- Uint8List getNv21Buffer(
- int imageWidth,
- int imageHeight,
- List<PlaneProxy> planes,
- );
+ Uint8List getNv21Buffer(int imageWidth, int imageHeight, List<PlaneProxy> planes);
}
/// A plane proxy which has an analogous interface as
@@ -961,9 +863,7 @@
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy.PlaneProxy.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.ImageProxy.PlaneProxy',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageProxy.PlaneProxy'),
)
abstract class PlaneProxy {
/// The pixels buffer.
@@ -981,22 +881,14 @@
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/video/QualitySelector.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.QualitySelector',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.QualitySelector'),
)
abstract class QualitySelector {
/// Gets an instance of QualitySelector with a desired quality.
- QualitySelector.from(
- VideoQuality quality,
- FallbackStrategy? fallbackStrategy,
- );
+ QualitySelector.from(VideoQuality quality, FallbackStrategy? fallbackStrategy);
/// Gets an instance of QualitySelector with ordered desired qualities.
- QualitySelector.fromOrderedList(
- List<VideoQuality> qualities,
- FallbackStrategy? fallbackStrategy,
- );
+ QualitySelector.fromOrderedList(List<VideoQuality> qualities, FallbackStrategy? fallbackStrategy);
/// Gets the corresponding resolution from the input quality.
@static
@@ -1009,9 +901,7 @@
///
/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.video.FallbackStrategy',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.FallbackStrategy'),
)
abstract class FallbackStrategy {
/// Returns a fallback strategy that will choose the quality that is closest
@@ -1036,11 +926,7 @@
/// camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraControl.
-@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.CameraControl',
- ),
-)
+@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraControl'))
abstract class CameraControl {
/// Enable the torch or disable the torch.
@async
@@ -1097,9 +983,7 @@
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.FocusMeteringAction',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.FocusMeteringAction'),
)
abstract class FocusMeteringAction {
/// All MeteringPoints used for AE regions.
@@ -1119,9 +1003,7 @@
///
/// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringResult.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.FocusMeteringResult',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.FocusMeteringResult'),
)
abstract class FocusMeteringResult {
/// If auto focus is successful.
@@ -1133,9 +1015,7 @@
///
/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'android.hardware.camera2.CaptureRequest',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.hardware.camera2.CaptureRequest'),
)
abstract class CaptureRequest {
/// Whether auto-exposure (AE) is currently locked to its latest calculated
@@ -1285,9 +1165,7 @@
///
/// See https://developer.android.com/reference/androidx/camera/core/MeteringPointFactory.
@ProxyApi(
- kotlinOptions: KotlinProxyApiOptions(
- fullClassName: 'androidx.camera.core.MeteringPointFactory',
- ),
+ kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.MeteringPointFactory'),
)
abstract class MeteringPointFactory {
/// Creates a MeteringPoint by x, y.
@@ -1307,14 +1185,9 @@
fullClassName: 'androidx.camera.core.DisplayOrientedMeteringPointFactory',
),
)
-abstract class DisplayOrientedMeteringPointFactory
- extends MeteringPointFactory {
+abstract class DisplayOrientedMeteringPointFactory extends MeteringPointFactory {
/// Creates a DisplayOrientedMeteringPointFactory for converting View (x, y)
/// into a MeteringPoint based on the current display's rotation and
/// CameraInfo.
- DisplayOrientedMeteringPointFactory(
- CameraInfo cameraInfo,
- double width,
- double height,
- );
+ DisplayOrientedMeteringPointFactory(CameraInfo cameraInfo, double width, double height);
}
diff --git a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart
index 71ed3d5..afc2978 100644
--- a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart
+++ b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart
@@ -9,8 +9,7 @@
import 'package:camera_android_camerax/camera_android_camerax.dart';
import 'package:camera_android_camerax/src/camerax_library.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
-import 'package:flutter/services.dart'
- show DeviceOrientation, PlatformException, Uint8List;
+import 'package:flutter/services.dart' show DeviceOrientation, PlatformException, Uint8List;
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
@@ -78,23 +77,14 @@
final testCameraStateError = CameraStateStateError.pigeon_detached(
code: CameraStateErrorCode.doNotDisturbModeEnabled,
);
- final Stream<CameraClosingEvent> cameraClosingEventStream = camera
- .onCameraClosing(cameraId);
- final cameraClosingStreamQueue = StreamQueue<CameraClosingEvent>(
- cameraClosingEventStream,
- );
- final Stream<CameraErrorEvent> cameraErrorEventStream = camera
- .onCameraError(cameraId);
- final cameraErrorStreamQueue = StreamQueue<CameraErrorEvent>(
- cameraErrorEventStream,
- );
+ final Stream<CameraClosingEvent> cameraClosingEventStream = camera.onCameraClosing(cameraId);
+ final cameraClosingStreamQueue = StreamQueue<CameraClosingEvent>(cameraClosingEventStream);
+ final Stream<CameraErrorEvent> cameraErrorEventStream = camera.onCameraError(cameraId);
+ final cameraErrorStreamQueue = StreamQueue<CameraErrorEvent>(cameraErrorEventStream);
observer.onChanged(
observer,
- CameraState.pigeon_detached(
- type: CameraStateType.closing,
- error: testCameraStateError,
- ),
+ CameraState.pigeon_detached(type: CameraStateType.closing, error: testCameraStateError),
);
final cameraClosingEventSent =
@@ -120,10 +110,7 @@
createWithOnePreferredSizeResolutionFilter,
FallbackStrategy Function({required VideoQuality quality})?
lowerQualityOrHigherThanFallbackStrategy,
- QualitySelector Function({
- required VideoQuality quality,
- FallbackStrategy? fallbackStrategy,
- })?
+ QualitySelector Function({required VideoQuality quality, FallbackStrategy? fallbackStrategy})?
fromQualitySelector,
Preview Function({
int? targetRotation,
@@ -131,10 +118,7 @@
ResolutionSelector? resolutionSelector,
})?
newPreview,
- VideoCapture Function({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- })?
+ VideoCapture Function({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange})?
withOutputVideoCapture,
ImageAnalysis Function({
ResolutionSelector? resolutionSelector,
@@ -143,19 +127,13 @@
CameraIntegerRange? targetFpsRange,
})?
newImageAnalysis,
- Analyzer Function({required void Function(Analyzer, ImageProxy) analyze})?
- newAnalyzer,
- Future<Uint8List> Function(
- int imageWidth,
- int imageHeight,
- List<PlaneProxy> planes,
- )?
+ Analyzer Function({required void Function(Analyzer, ImageProxy) analyze})? newAnalyzer,
+ Future<Uint8List> Function(int imageWidth, int imageHeight, List<PlaneProxy> planes)?
getNv21BufferImageProxyUtils,
}) {
final AspectRatioStrategy ratio_4_3FallbackAutoStrategyAspectRatioStrategy =
MockAspectRatioStrategy();
- final ResolutionStrategy highestAvailableStrategyResolutionStrategy =
- MockResolutionStrategy();
+ final ResolutionStrategy highestAvailableStrategyResolutionStrategy = MockResolutionStrategy();
PigeonOverrides.processCameraProvider_getInstance = () async {
return mockProcessCameraProvider;
};
@@ -180,16 +158,10 @@
ResolutionSelector? resolutionSelector,
}) {
final mockPreview = MockPreview();
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
- );
- when(
- mockPreview.surfaceProducerHandlesCropAndRotation(),
- ).thenAnswer((_) async => false);
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
+ when(mockPreview.surfaceProducerHandlesCropAndRotation()).thenAnswer((_) async => false);
when(mockPreview.resolutionSelector).thenReturn(resolutionSelector);
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
return mockPreview;
};
PigeonOverrides.imageCapture_new =
@@ -199,17 +171,11 @@
ResolutionSelector? resolutionSelector,
}) {
final mockImageCapture = MockImageCapture();
- when(
- mockImageCapture.resolutionSelector,
- ).thenReturn(resolutionSelector);
+ when(mockImageCapture.resolutionSelector).thenReturn(resolutionSelector);
return mockImageCapture;
};
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) {
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) {
final mockRecorder = MockRecorder();
when(
mockRecorder.getQualitySelector(),
@@ -218,10 +184,7 @@
};
PigeonOverrides.videoCapture_withOutput =
withOutputVideoCapture ??
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) {
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
return MockVideoCapture();
};
PigeonOverrides.imageAnalysis_new =
@@ -233,23 +196,14 @@
ResolutionSelector? resolutionSelector,
}) {
final mockImageAnalysis = MockImageAnalysis();
- when(
- mockImageAnalysis.resolutionSelector,
- ).thenReturn(resolutionSelector);
+ when(mockImageAnalysis.resolutionSelector).thenReturn(resolutionSelector);
return mockImageAnalysis;
};
PigeonOverrides.resolutionStrategy_new =
- ({
- required CameraSize boundSize,
- required ResolutionStrategyFallbackRule fallbackRule,
- }) {
+ ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) {
final resolutionStrategy = MockResolutionStrategy();
- when(
- resolutionStrategy.getBoundSize(),
- ).thenAnswer((_) async => boundSize);
- when(
- resolutionStrategy.getFallbackRule(),
- ).thenAnswer((_) async => fallbackRule);
+ when(resolutionStrategy.getBoundSize()).thenAnswer((_) async => boundSize);
+ when(resolutionStrategy.getFallbackRule()).thenAnswer((_) async => fallbackRule);
return resolutionStrategy;
};
PigeonOverrides.resolutionSelector_new =
@@ -260,16 +214,10 @@
}) {
final mockResolutionSelector = MockResolutionSelector();
when(mockResolutionSelector.getAspectRatioStrategy()).thenAnswer(
- (_) async =>
- aspectRatioStrategy ??
- AspectRatioStrategy.ratio_4_3FallbackAutoStrategy,
+ (_) async => aspectRatioStrategy ?? AspectRatioStrategy.ratio_4_3FallbackAutoStrategy,
);
- when(
- mockResolutionSelector.resolutionStrategy,
- ).thenReturn(resolutionStrategy);
- when(
- mockResolutionSelector.resolutionFilter,
- ).thenReturn(resolutionFilter);
+ when(mockResolutionSelector.resolutionStrategy).thenReturn(resolutionStrategy);
+ when(mockResolutionSelector.resolutionFilter).thenReturn(resolutionFilter);
return mockResolutionSelector;
};
PigeonOverrides.qualitySelector_from =
@@ -277,21 +225,15 @@
({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) {
return MockQualitySelector();
};
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
+ GenericsPigeonOverrides.observerNew = <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
return MockSystemServicesManager();
};
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
when(manager.getUiOrientation()).thenAnswer((_) async {
return 'PORTRAIT_UP';
@@ -304,9 +246,7 @@
required AspectRatioStrategyFallbackRule fallbackRule,
}) {
final mockAspectRatioStrategy = MockAspectRatioStrategy();
- when(
- mockAspectRatioStrategy.getFallbackRule(),
- ).thenAnswer((_) async => fallbackRule);
+ when(mockAspectRatioStrategy.getFallbackRule()).thenAnswer((_) async => fallbackRule);
when(
mockAspectRatioStrategy.getPreferredAspectRatio(),
).thenAnswer((_) async => preferredAspectRatio);
@@ -317,17 +257,13 @@
({required CameraSize preferredSize}) => MockResolutionFilter();
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
final camera2cameraInfo = MockCamera2CameraInfo();
- when(
- camera2cameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => 90);
+ when(camera2cameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => 90);
return camera2cameraInfo;
};
- PigeonOverrides.cameraSize_new =
- ({required int width, required int height}) {
- return CameraSize.pigeon_detached(width: width, height: height);
- };
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- MockCameraCharacteristicsKey();
+ PigeonOverrides.cameraSize_new = ({required int width, required int height}) {
+ return CameraSize.pigeon_detached(width: width, height: height);
+ };
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = MockCameraCharacteristicsKey();
PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan =
lowerQualityOrHigherThanFallbackStrategy ??
({required VideoQuality quality}) {
@@ -337,10 +273,9 @@
highestAvailableStrategyResolutionStrategy;
PigeonOverrides.aspectRatioStrategy_ratio_4_3FallbackAutoStrategy =
ratio_4_3FallbackAutoStrategyAspectRatioStrategy;
- PigeonOverrides.fallbackStrategy_lowerQualityThan =
- ({required VideoQuality quality}) {
- return MockFallbackStrategy();
- };
+ PigeonOverrides.fallbackStrategy_lowerQualityThan = ({required VideoQuality quality}) {
+ return MockFallbackStrategy();
+ };
PigeonOverrides.analyzer_new =
newAnalyzer ??
({required void Function(Analyzer, ImageProxy) analyze}) {
@@ -358,10 +293,7 @@
/// Modifies the creation of [MeteringPoint]s and [FocusMeteringAction]s to
/// return objects detached from a native object.
void setUpOverridesForExposureAndFocus({
- FocusMeteringActionBuilder Function({
- required MeteringPoint point,
- required MeteringMode mode,
- })?
+ FocusMeteringActionBuilder Function({required MeteringPoint point, required MeteringMode mode})?
withModeFocusMeteringActionBuilder,
DisplayOrientedMeteringPointFactory Function({
required dynamic cameraInfo,
@@ -372,11 +304,7 @@
}) {
PigeonOverrides.displayOrientedMeteringPointFactory_new =
newDisplayOrientedMeteringPointFactory ??
- ({
- required dynamic cameraInfo,
- required double width,
- required double height,
- }) {
+ ({required dynamic cameraInfo, required double width, required double height}) {
final mockFactory = MockDisplayOrientedMeteringPointFactory();
when(mockFactory.createPoint(any, any)).thenAnswer(
(Invocation invocation) async => TestMeteringPoint.detached(
@@ -414,22 +342,14 @@
meteringPointsAwb.add(point);
}
- when(mockBuilder.addPointWithMode(any, any)).thenAnswer((
- Invocation invocation,
- ) async {
+ when(mockBuilder.addPointWithMode(any, any)).thenAnswer((Invocation invocation) async {
switch (invocation.positionalArguments[1]) {
case MeteringMode.ae:
- meteringPointsAe.add(
- invocation.positionalArguments.first as MeteringPoint,
- );
+ meteringPointsAe.add(invocation.positionalArguments.first as MeteringPoint);
case MeteringMode.af:
- meteringPointsAf.add(
- invocation.positionalArguments.first as MeteringPoint,
- );
+ meteringPointsAf.add(invocation.positionalArguments.first as MeteringPoint);
case MeteringMode.awb:
- meteringPointsAwb.add(
- invocation.positionalArguments.first as MeteringPoint,
- );
+ meteringPointsAwb.add(invocation.positionalArguments.first as MeteringPoint);
}
});
@@ -453,10 +373,7 @@
void setUpOverridesForSettingFocusandExposurePoints(
CameraControl cameraControlForComparison,
Camera2CameraControl camera2cameraControl, {
- FocusMeteringActionBuilder Function({
- required MeteringPoint point,
- required MeteringMode mode,
- })?
+ FocusMeteringActionBuilder Function({required MeteringPoint point, required MeteringMode mode})?
withModeFocusMeteringActionBuilder,
DisplayOrientedMeteringPointFactory Function({
required dynamic cameraInfo,
@@ -468,106 +385,86 @@
setUpOverridesForExposureAndFocus();
if (withModeFocusMeteringActionBuilder != null) {
- PigeonOverrides.focusMeteringActionBuilder_withMode =
- withModeFocusMeteringActionBuilder;
+ PigeonOverrides.focusMeteringActionBuilder_withMode = withModeFocusMeteringActionBuilder;
}
if (newDisplayOrientedMeteringPointFactory != null) {
PigeonOverrides.displayOrientedMeteringPointFactory_new =
newDisplayOrientedMeteringPointFactory;
}
- PigeonOverrides.camera2CameraControl_from =
- ({required CameraControl cameraControl}) =>
- cameraControl == cameraControlForComparison
- ? camera2cameraControl
- : Camera2CameraControl.pigeon_detached();
+ PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) =>
+ cameraControl == cameraControlForComparison
+ ? camera2cameraControl
+ : Camera2CameraControl.pigeon_detached();
- PigeonOverrides.captureRequestOptions_new =
- ({required Map<CaptureRequestKey, Object?> options}) {
- final mockCaptureRequestOptions = MockCaptureRequestOptions();
- options.forEach((CaptureRequestKey key, Object? value) {
- when(
- mockCaptureRequestOptions.getCaptureRequestOption(key),
- ).thenAnswer((_) async => value);
- });
- return mockCaptureRequestOptions;
- };
- PigeonOverrides.captureRequest_controlAELock =
- CaptureRequestKey.pigeon_detached();
+ PigeonOverrides
+ .captureRequestOptions_new = ({required Map<CaptureRequestKey, Object?> options}) {
+ final mockCaptureRequestOptions = MockCaptureRequestOptions();
+ options.forEach((CaptureRequestKey key, Object? value) {
+ when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value);
+ });
+ return mockCaptureRequestOptions;
+ };
+ PigeonOverrides.captureRequest_controlAELock = CaptureRequestKey.pigeon_detached();
}
- test(
- 'Should fetch CameraDescription instances for available cameras',
- () async {
- // Arrange
- final camera = AndroidCameraCameraX();
- final returnData = <dynamic>[
- <String, dynamic>{
- 'name': '0',
- 'lensFacing': 'back',
- 'sensorOrientation': 0,
- },
- <String, dynamic>{
- 'name': '1',
- 'lensFacing': 'front',
- 'sensorOrientation': 90,
- },
- ];
+ test('Should fetch CameraDescription instances for available cameras', () async {
+ // Arrange
+ final camera = AndroidCameraCameraX();
+ final returnData = <dynamic>[
+ <String, dynamic>{'name': '0', 'lensFacing': 'back', 'sensorOrientation': 0},
+ <String, dynamic>{'name': '1', 'lensFacing': 'front', 'sensorOrientation': 90},
+ ];
- // Create mocks to use
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockFrontCameraInfo = MockCameraInfo();
- final mockBackCameraInfo = MockCameraInfo();
+ // Create mocks to use
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockFrontCameraInfo = MockCameraInfo();
+ final mockBackCameraInfo = MockCameraInfo();
- // Tell plugin to create mock CameraSelectors for testing.
- PigeonOverrides.processCameraProvider_getInstance = () async =>
- mockProcessCameraProvider;
- PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
- final camera2cameraInfo = MockCamera2CameraInfo();
- var cameraId = '';
- if (cameraInfo == mockBackCameraInfo) {
- cameraId = '0';
- } else if (cameraInfo == mockFrontCameraInfo) {
- cameraId = '1';
- }
- when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId);
- return camera2cameraInfo;
- };
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
- return MockSystemServicesManager();
- };
-
- // Mock calls to native platform
- when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(
- (_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo],
- );
- when(mockBackCameraInfo.sensorRotationDegrees).thenReturn(0);
- when(mockBackCameraInfo.lensFacing).thenReturn(LensFacing.back);
-
- when(mockFrontCameraInfo.sensorRotationDegrees).thenReturn(90);
- when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front);
-
- final List<CameraDescription> cameraDescriptions = await camera
- .availableCameras();
-
- expect(cameraDescriptions.length, returnData.length);
- for (var i = 0; i < returnData.length; i++) {
- final Map<String, Object?> typedData =
- (returnData[i] as Map<dynamic, dynamic>).cast<String, Object?>();
- final cameraDescription = CameraDescription(
- name: typedData['name']! as String,
- lensDirection: (typedData['lensFacing']! as String) == 'front'
- ? CameraLensDirection.front
- : CameraLensDirection.back,
- sensorOrientation: typedData['sensorOrientation']! as int,
- );
- expect(cameraDescriptions[i], cameraDescription);
+ // Tell plugin to create mock CameraSelectors for testing.
+ PigeonOverrides.processCameraProvider_getInstance = () async => mockProcessCameraProvider;
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
+ final camera2cameraInfo = MockCamera2CameraInfo();
+ var cameraId = '';
+ if (cameraInfo == mockBackCameraInfo) {
+ cameraId = '0';
+ } else if (cameraInfo == mockFrontCameraInfo) {
+ cameraId = '1';
}
- },
- );
+ when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId);
+ return camera2cameraInfo;
+ };
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ return MockSystemServicesManager();
+ };
+
+ // Mock calls to native platform
+ when(
+ mockProcessCameraProvider.getAvailableCameraInfos(),
+ ).thenAnswer((_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo]);
+ when(mockBackCameraInfo.sensorRotationDegrees).thenReturn(0);
+ when(mockBackCameraInfo.lensFacing).thenReturn(LensFacing.back);
+
+ when(mockFrontCameraInfo.sensorRotationDegrees).thenReturn(90);
+ when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front);
+
+ final List<CameraDescription> cameraDescriptions = await camera.availableCameras();
+
+ expect(cameraDescriptions.length, returnData.length);
+ for (var i = 0; i < returnData.length; i++) {
+ final Map<String, Object?> typedData = (returnData[i] as Map<dynamic, dynamic>)
+ .cast<String, Object?>();
+ final cameraDescription = CameraDescription(
+ name: typedData['name']! as String,
+ lensDirection: (typedData['lensFacing']! as String) == 'front'
+ ? CameraLensDirection.front
+ : CameraLensDirection.back,
+ sensorOrientation: typedData['sensorOrientation']! as int,
+ );
+ expect(cameraDescriptions[i], cameraDescription);
+ }
+ });
test(
'createCamera requests permissions, starts listening for device orientation changes, updates camera state observers, and returns flutter surface texture ID',
@@ -634,18 +531,11 @@
return mockImageCapture;
};
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) {
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) {
return mockRecorder;
};
PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) {
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
return mockVideoCapture;
};
PigeonOverrides.imageAnalysis_new =
@@ -658,10 +548,7 @@
return mockImageAnalysis;
};
PigeonOverrides.resolutionStrategy_new =
- ({
- required CameraSize boundSize,
- required ResolutionStrategyFallbackRule fallbackRule,
- }) {
+ ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) {
return MockResolutionStrategy();
};
PigeonOverrides.resolutionSelector_new =
@@ -673,10 +560,7 @@
return MockResolutionSelector();
};
PigeonOverrides.qualitySelector_from =
- ({
- required VideoQuality quality,
- FallbackStrategy? fallbackStrategy,
- }) {
+ ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) {
return MockQualitySelector();
};
GenericsPigeonOverrides.observerNew =
@@ -684,28 +568,19 @@
return Observer<T>.detached(onChanged: onChanged);
};
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
- when(
- mockSystemServicesManager.requestCameraPermissions(any),
- ).thenAnswer((_) async {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ when(mockSystemServicesManager.requestCameraPermissions(any)).thenAnswer((_) async {
cameraPermissionsRequested = true;
return null;
});
return mockSystemServicesManager;
};
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
- when(manager.startListeningForDeviceOrientationChange()).thenAnswer(
- (_) async {
- startedListeningForDeviceOrientationChanges = true;
- },
- );
+ when(manager.startListeningForDeviceOrientationChange()).thenAnswer((_) async {
+ startedListeningForDeviceOrientationChanges = true;
+ });
when(manager.getUiOrientation()).thenAnswer((_) async {
return 'PORTRAIT_UP';
});
@@ -725,40 +600,34 @@
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
final camera2cameraInfo = MockCamera2CameraInfo();
when(
- camera2cameraInfo.getCameraCharacteristic(
- mockCameraCharacteristicsKey,
- ),
+ camera2cameraInfo.getCameraCharacteristic(mockCameraCharacteristicsKey),
).thenAnswer((_) async => testSensorOrientation);
return camera2cameraInfo;
};
- PigeonOverrides.cameraSize_new =
- ({required int width, required int height}) {
- return MockCameraSize();
- };
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- mockCameraCharacteristicsKey;
+ PigeonOverrides.cameraSize_new = ({required int width, required int height}) {
+ return MockCameraSize();
+ };
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey;
PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan =
({required VideoQuality quality}) {
return MockFallbackStrategy();
};
camera.processCameraProvider = mockProcessCameraProvider;
- PigeonOverrides.cameraIntegerRange_new =
- CameraIntegerRange.pigeon_detached;
+ PigeonOverrides.cameraIntegerRange_new = CameraIntegerRange.pigeon_detached;
when(
mockPreview.setSurfaceProvider(mockSystemServicesManager),
).thenAnswer((_) async => testSurfaceTextureId);
when(
- mockProcessCameraProvider.bindToLifecycle(
- mockBackCameraSelector,
- <UseCase>[mockPreview, mockImageCapture, mockImageAnalysis],
- ),
+ mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, <UseCase>[
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => mockLiveCameraState);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState);
expect(
await camera.createCameraWithSettings(
@@ -815,13 +684,9 @@
final mockProcessCameraProvider = MockProcessCameraProvider();
final mockCameraInfo = MockCameraInfo();
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
camera.processCameraProvider = mockProcessCameraProvider;
// Tell plugin to create mock/detached objects for testing createCamera
@@ -841,30 +706,15 @@
switch (resolutionPreset) {
case ResolutionPreset.low:
- expectedBoundSize = CameraSize.pigeon_detached(
- width: 320,
- height: 240,
- );
+ expectedBoundSize = CameraSize.pigeon_detached(width: 320, height: 240);
case ResolutionPreset.medium:
- expectedBoundSize = CameraSize.pigeon_detached(
- width: 720,
- height: 480,
- );
+ expectedBoundSize = CameraSize.pigeon_detached(width: 720, height: 480);
case ResolutionPreset.high:
- expectedBoundSize = CameraSize.pigeon_detached(
- width: 1280,
- height: 720,
- );
+ expectedBoundSize = CameraSize.pigeon_detached(width: 1280, height: 720);
case ResolutionPreset.veryHigh:
- expectedBoundSize = CameraSize.pigeon_detached(
- width: 1920,
- height: 1080,
- );
+ expectedBoundSize = CameraSize.pigeon_detached(width: 1920, height: 1080);
case ResolutionPreset.ultraHigh:
- expectedBoundSize = CameraSize.pigeon_detached(
- width: 3840,
- height: 2160,
- );
+ expectedBoundSize = CameraSize.pigeon_detached(width: 3840, height: 2160);
case ResolutionPreset.max:
continue;
}
@@ -877,8 +727,7 @@
expect(previewSize?.width, equals(expectedBoundSize.width));
expect(previewSize?.height, equals(expectedBoundSize.height));
expect(
- await camera.preview!.resolutionSelector!.resolutionStrategy!
- .getFallbackRule(),
+ await camera.preview!.resolutionSelector!.resolutionStrategy!.getFallbackRule(),
ResolutionStrategyFallbackRule.closestLowerThenHigher,
);
@@ -890,8 +739,7 @@
expect(imageCaptureSize?.width, equals(expectedBoundSize.width));
expect(imageCaptureSize?.height, equals(expectedBoundSize.height));
expect(
- await camera.imageCapture!.resolutionSelector!.resolutionStrategy!
- .getFallbackRule(),
+ await camera.imageCapture!.resolutionSelector!.resolutionStrategy!.getFallbackRule(),
ResolutionStrategyFallbackRule.closestLowerThenHigher,
);
@@ -903,18 +751,13 @@
expect(imageAnalysisSize?.width, equals(expectedBoundSize.width));
expect(imageAnalysisSize?.height, equals(expectedBoundSize.height));
expect(
- await camera.imageAnalysis!.resolutionSelector!.resolutionStrategy!
- .getFallbackRule(),
+ await camera.imageAnalysis!.resolutionSelector!.resolutionStrategy!.getFallbackRule(),
ResolutionStrategyFallbackRule.closestLowerThenHigher,
);
}
// Test max case.
- await camera.createCamera(
- testCameraDescription,
- ResolutionPreset.max,
- enableAudio: true,
- );
+ await camera.createCamera(testCameraDescription, ResolutionPreset.max, enableAudio: true);
expect(
camera.preview!.resolutionSelector!.resolutionStrategy,
@@ -930,10 +773,7 @@
);
// Test null case.
- final int flutterSurfaceTextureId = await camera.createCamera(
- testCameraDescription,
- null,
- );
+ final int flutterSurfaceTextureId = await camera.createCamera(testCameraDescription, null);
await camera.initializeCamera(flutterSurfaceTextureId);
expect(camera.preview!.resolutionSelector, isNull);
@@ -966,20 +806,15 @@
CameraSize? lastSetPreferredSize;
setUpOverridesForTestingUseCaseConfiguration(
mockProcessCameraProvider,
- createWithOnePreferredSizeResolutionFilter:
- ({required CameraSize preferredSize}) {
- lastSetPreferredSize = preferredSize;
- return MockResolutionFilter();
- },
+ createWithOnePreferredSizeResolutionFilter: ({required CameraSize preferredSize}) {
+ lastSetPreferredSize = preferredSize;
+ return MockResolutionFilter();
+ },
);
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
camera.processCameraProvider = mockProcessCameraProvider;
// Test non-null resolution presets.
@@ -995,90 +830,48 @@
switch (resolutionPreset) {
case ResolutionPreset.low:
- expectedPreferredResolution = CameraSize.pigeon_detached(
- width: 320,
- height: 240,
- );
+ expectedPreferredResolution = CameraSize.pigeon_detached(width: 320, height: 240);
case ResolutionPreset.medium:
- expectedPreferredResolution = CameraSize.pigeon_detached(
- width: 720,
- height: 480,
- );
+ expectedPreferredResolution = CameraSize.pigeon_detached(width: 720, height: 480);
case ResolutionPreset.high:
- expectedPreferredResolution = CameraSize.pigeon_detached(
- width: 1280,
- height: 720,
- );
+ expectedPreferredResolution = CameraSize.pigeon_detached(width: 1280, height: 720);
case ResolutionPreset.veryHigh:
- expectedPreferredResolution = CameraSize.pigeon_detached(
- width: 1920,
- height: 1080,
- );
+ expectedPreferredResolution = CameraSize.pigeon_detached(width: 1920, height: 1080);
case ResolutionPreset.ultraHigh:
- expectedPreferredResolution = CameraSize.pigeon_detached(
- width: 3840,
- height: 2160,
- );
+ expectedPreferredResolution = CameraSize.pigeon_detached(width: 3840, height: 2160);
case ResolutionPreset.max:
expectedPreferredResolution = null;
}
if (expectedPreferredResolution == null) {
expect(camera.preview!.resolutionSelector!.resolutionFilter, isNull);
- expect(
- camera.imageCapture!.resolutionSelector!.resolutionFilter,
- isNull,
- );
- expect(
- camera.imageAnalysis!.resolutionSelector!.resolutionFilter,
- isNull,
- );
+ expect(camera.imageCapture!.resolutionSelector!.resolutionFilter, isNull);
+ expect(camera.imageAnalysis!.resolutionSelector!.resolutionFilter, isNull);
continue;
}
- expect(
- lastSetPreferredSize?.width,
- equals(expectedPreferredResolution.width),
- );
- expect(
- lastSetPreferredSize?.height,
- equals(expectedPreferredResolution.height),
- );
+ expect(lastSetPreferredSize?.width, equals(expectedPreferredResolution.width));
+ expect(lastSetPreferredSize?.height, equals(expectedPreferredResolution.height));
final CameraSize? imageCaptureSize = await camera
.imageCapture!
.resolutionSelector!
.resolutionStrategy!
.getBoundSize();
- expect(
- imageCaptureSize?.width,
- equals(expectedPreferredResolution.width),
- );
- expect(
- imageCaptureSize?.height,
- equals(expectedPreferredResolution.height),
- );
+ expect(imageCaptureSize?.width, equals(expectedPreferredResolution.width));
+ expect(imageCaptureSize?.height, equals(expectedPreferredResolution.height));
final CameraSize? imageAnalysisSize = await camera
.imageAnalysis!
.resolutionSelector!
.resolutionStrategy!
.getBoundSize();
- expect(
- imageAnalysisSize?.width,
- equals(expectedPreferredResolution.width),
- );
- expect(
- imageAnalysisSize?.height,
- equals(expectedPreferredResolution.height),
- );
+ expect(imageAnalysisSize?.width, equals(expectedPreferredResolution.width));
+ expect(imageAnalysisSize?.height, equals(expectedPreferredResolution.height));
}
// Test null case.
- final int flutterSurfaceTextureId = await camera.createCamera(
- testCameraDescription,
- null,
- );
+ final int flutterSurfaceTextureId = await camera.createCamera(testCameraDescription, null);
await camera.initializeCamera(flutterSurfaceTextureId);
expect(camera.preview!.resolutionSelector, isNull);
@@ -1110,13 +903,9 @@
// Tell plugin to create mock/detached objects for testing createCamera
// as needed.
setUpOverridesForTestingUseCaseConfiguration(mockProcessCameraProvider);
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
camera.processCameraProvider = mockProcessCameraProvider;
// Test non-null resolution presets.
@@ -1151,21 +940,17 @@
equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy),
);
expect(
- await camera.imageCapture!.resolutionSelector!
- .getAspectRatioStrategy(),
+ await camera.imageCapture!.resolutionSelector!.getAspectRatioStrategy(),
equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy),
);
expect(
- await camera.imageAnalysis!.resolutionSelector!
- .getAspectRatioStrategy(),
+ await camera.imageAnalysis!.resolutionSelector!.getAspectRatioStrategy(),
equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy),
);
continue;
}
- final AspectRatioStrategy previewStrategy = await camera
- .preview!
- .resolutionSelector!
+ final AspectRatioStrategy previewStrategy = await camera.preview!.resolutionSelector!
.getAspectRatioStrategy();
final AspectRatioStrategy imageCaptureStrategy = await camera
.imageCapture!
@@ -1177,32 +962,14 @@
.getAspectRatioStrategy();
// Check aspect ratio.
- expect(
- await previewStrategy.getPreferredAspectRatio(),
- equals(expectedAspectRatio),
- );
- expect(
- await imageCaptureStrategy.getPreferredAspectRatio(),
- equals(expectedAspectRatio),
- );
- expect(
- await imageAnalysisStrategy.getPreferredAspectRatio(),
- equals(expectedAspectRatio),
- );
+ expect(await previewStrategy.getPreferredAspectRatio(), equals(expectedAspectRatio));
+ expect(await imageCaptureStrategy.getPreferredAspectRatio(), equals(expectedAspectRatio));
+ expect(await imageAnalysisStrategy.getPreferredAspectRatio(), equals(expectedAspectRatio));
// Check fallback rule.
- expect(
- await previewStrategy.getFallbackRule(),
- equals(expectedFallbackRule),
- );
- expect(
- await imageCaptureStrategy.getFallbackRule(),
- equals(expectedFallbackRule),
- );
- expect(
- await imageAnalysisStrategy.getFallbackRule(),
- equals(expectedFallbackRule),
- );
+ expect(await previewStrategy.getFallbackRule(), equals(expectedFallbackRule));
+ expect(await imageCaptureStrategy.getFallbackRule(), equals(expectedFallbackRule));
+ expect(await imageAnalysisStrategy.getFallbackRule(), equals(expectedFallbackRule));
}
// Test null case.
@@ -1268,12 +1035,8 @@
CameraIntegerRange? targetFpsRange,
ResolutionSelector? resolutionSelector,
}) {
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
- );
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
return mockPreview;
};
PigeonOverrides.imageCapture_new =
@@ -1285,18 +1048,11 @@
return mockImageCapture;
};
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) {
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) {
return mockRecorder;
};
PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) {
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
return mockVideoCapture;
};
PigeonOverrides.imageAnalysis_new =
@@ -1309,10 +1065,7 @@
return mockImageAnalysis;
};
PigeonOverrides.resolutionStrategy_new =
- ({
- required CameraSize boundSize,
- required ResolutionStrategyFallbackRule fallbackRule,
- }) {
+ ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) {
return MockResolutionStrategy();
};
PigeonOverrides.resolutionSelector_new =
@@ -1324,10 +1077,7 @@
return MockResolutionSelector();
};
PigeonOverrides.qualitySelector_from =
- ({
- required VideoQuality quality,
- FallbackStrategy? fallbackStrategy,
- }) {
+ ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) {
return MockQualitySelector();
};
GenericsPigeonOverrides.observerNew =
@@ -1335,16 +1085,11 @@
return Observer<T>.detached(onChanged: onChanged);
};
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
return MockSystemServicesManager();
};
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
when(manager.getUiOrientation()).thenAnswer((_) async {
return 'PORTRAIT_UP';
@@ -1364,38 +1109,32 @@
};
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
when(
- mockCamera2CameraInfo.getCameraCharacteristic(
- mockCameraCharacteristicsKey,
- ),
+ mockCamera2CameraInfo.getCameraCharacteristic(mockCameraCharacteristicsKey),
).thenAnswer((_) async => testSensorOrientation);
return mockCamera2CameraInfo;
};
- PigeonOverrides.cameraSize_new =
- ({required int width, required int height}) {
- return MockCameraSize();
- };
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- mockCameraCharacteristicsKey;
+ PigeonOverrides.cameraSize_new = ({required int width, required int height}) {
+ return MockCameraSize();
+ };
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey;
PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan =
({required VideoQuality quality}) {
return MockFallbackStrategy();
};
when(
- mockProcessCameraProvider.bindToLifecycle(
- mockBackCameraSelector,
- <UseCase>[mockPreview, mockImageCapture, mockImageAnalysis],
- ),
+ mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, <UseCase>[
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl);
camera.processCameraProvider = mockProcessCameraProvider;
- PigeonOverrides.cameraIntegerRange_new =
- CameraIntegerRange.pigeon_detached;
+ PigeonOverrides.cameraIntegerRange_new = CameraIntegerRange.pigeon_detached;
final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
testCameraDescription,
@@ -1411,10 +1150,11 @@
// Verify expected UseCases were bound.
verify(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[mockPreview, mockImageCapture, mockImageAnalysis],
- ),
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
);
// Verify the camera's CameraInfo instance got updated.
@@ -1429,547 +1169,443 @@
},
);
- test(
- 'createCamera properly sets preset resolution for video capture use case',
- () async {
- final camera = AndroidCameraCameraX();
- const CameraLensDirection testLensDirection = CameraLensDirection.back;
- const testSensorOrientation = 90;
- const testCameraDescription = CameraDescription(
- name: 'cameraName',
- lensDirection: testLensDirection,
- sensorOrientation: testSensorOrientation,
- );
- const enableAudio = true;
- final mockCamera = MockCamera();
+ test('createCamera properly sets preset resolution for video capture use case', () async {
+ final camera = AndroidCameraCameraX();
+ const CameraLensDirection testLensDirection = CameraLensDirection.back;
+ const testSensorOrientation = 90;
+ const testCameraDescription = CameraDescription(
+ name: 'cameraName',
+ lensDirection: testLensDirection,
+ sensorOrientation: testSensorOrientation,
+ );
+ const enableAudio = true;
+ final mockCamera = MockCamera();
- // Mock/Detached objects for (typically attached) objects created by
- // createCamera.
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockCameraInfo = MockCameraInfo();
+ // Mock/Detached objects for (typically attached) objects created by
+ // createCamera.
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockCameraInfo = MockCameraInfo();
- // Tell plugin to create mock/detached objects for testing createCamera
- // as needed.
- VideoQuality? fallbackStrategyVideoQuality;
- VideoQuality? qualitySelectorVideoQuality;
- FallbackStrategy? setFallbackStrategy;
- final mockFallbackStrategy = MockFallbackStrategy();
- final mockQualitySelector = MockQualitySelector();
- setUpOverridesForTestingUseCaseConfiguration(
- mockProcessCameraProvider,
- lowerQualityOrHigherThanFallbackStrategy:
- ({required VideoQuality quality}) {
- fallbackStrategyVideoQuality = quality;
- return mockFallbackStrategy;
- },
- fromQualitySelector:
- ({
- required VideoQuality quality,
- FallbackStrategy? fallbackStrategy,
- }) {
- qualitySelectorVideoQuality = quality;
- setFallbackStrategy = fallbackStrategy;
- return mockQualitySelector;
- },
- );
+ // Tell plugin to create mock/detached objects for testing createCamera
+ // as needed.
+ VideoQuality? fallbackStrategyVideoQuality;
+ VideoQuality? qualitySelectorVideoQuality;
+ FallbackStrategy? setFallbackStrategy;
+ final mockFallbackStrategy = MockFallbackStrategy();
+ final mockQualitySelector = MockQualitySelector();
+ setUpOverridesForTestingUseCaseConfiguration(
+ mockProcessCameraProvider,
+ lowerQualityOrHigherThanFallbackStrategy: ({required VideoQuality quality}) {
+ fallbackStrategyVideoQuality = quality;
+ return mockFallbackStrategy;
+ },
+ fromQualitySelector: ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) {
+ qualitySelectorVideoQuality = quality;
+ setFallbackStrategy = fallbackStrategy;
+ return mockQualitySelector;
+ },
+ );
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
- // Test non-null resolution presets.
- for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) {
- await camera.createCamera(
- testCameraDescription,
- resolutionPreset,
- enableAudio: enableAudio,
- );
+ // Test non-null resolution presets.
+ for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) {
+ await camera.createCamera(testCameraDescription, resolutionPreset, enableAudio: enableAudio);
- VideoQuality? expectedVideoQuality;
- switch (resolutionPreset) {
- case ResolutionPreset.low:
- // 240p is not supported by CameraX.
- case ResolutionPreset.medium:
- expectedVideoQuality = VideoQuality.SD;
- case ResolutionPreset.high:
- expectedVideoQuality = VideoQuality.HD;
- case ResolutionPreset.veryHigh:
- expectedVideoQuality = VideoQuality.FHD;
- case ResolutionPreset.ultraHigh:
- expectedVideoQuality = VideoQuality.UHD;
- case ResolutionPreset.max:
- expectedVideoQuality = VideoQuality.highest;
- }
-
- expect(
- await camera.recorder!.getQualitySelector(),
- mockQualitySelector,
- );
- expect(qualitySelectorVideoQuality, equals(expectedVideoQuality));
- expect(fallbackStrategyVideoQuality, equals(expectedVideoQuality));
- expect(setFallbackStrategy, equals(mockFallbackStrategy));
+ VideoQuality? expectedVideoQuality;
+ switch (resolutionPreset) {
+ case ResolutionPreset.low:
+ // 240p is not supported by CameraX.
+ case ResolutionPreset.medium:
+ expectedVideoQuality = VideoQuality.SD;
+ case ResolutionPreset.high:
+ expectedVideoQuality = VideoQuality.HD;
+ case ResolutionPreset.veryHigh:
+ expectedVideoQuality = VideoQuality.FHD;
+ case ResolutionPreset.ultraHigh:
+ expectedVideoQuality = VideoQuality.UHD;
+ case ResolutionPreset.max:
+ expectedVideoQuality = VideoQuality.highest;
}
- qualitySelectorVideoQuality = null;
- setFallbackStrategy = null;
+ expect(await camera.recorder!.getQualitySelector(), mockQualitySelector);
+ expect(qualitySelectorVideoQuality, equals(expectedVideoQuality));
+ expect(fallbackStrategyVideoQuality, equals(expectedVideoQuality));
+ expect(setFallbackStrategy, equals(mockFallbackStrategy));
+ }
- // Test null case.
- await camera.createCamera(testCameraDescription, null);
- expect(
- await camera.recorder!.getQualitySelector(),
- isNot(equals(mockQualitySelector)),
- );
- },
- );
+ qualitySelectorVideoQuality = null;
+ setFallbackStrategy = null;
- test(
- 'createCamera sets sensorOrientationDegrees and enableRecordingAudio as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const CameraLensDirection testLensDirection = CameraLensDirection.back;
- const testSensorOrientation = 90;
- const testCameraDescription = CameraDescription(
- name: 'cameraName',
- lensDirection: testLensDirection,
- sensorOrientation: testSensorOrientation,
- );
- const enableAudio = true;
- const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh;
- const testHandlesCropAndRotation = true;
+ // Test null case.
+ await camera.createCamera(testCameraDescription, null);
+ expect(await camera.recorder!.getQualitySelector(), isNot(equals(mockQualitySelector)));
+ });
- // Mock/Detached objects for (typically attached) objects created by
- // createCamera.
- final mockCamera = MockCamera();
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockCameraInfo = MockCameraInfo();
+ test('createCamera sets sensorOrientationDegrees and enableRecordingAudio as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const CameraLensDirection testLensDirection = CameraLensDirection.back;
+ const testSensorOrientation = 90;
+ const testCameraDescription = CameraDescription(
+ name: 'cameraName',
+ lensDirection: testLensDirection,
+ sensorOrientation: testSensorOrientation,
+ );
+ const enableAudio = true;
+ const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh;
+ const testHandlesCropAndRotation = true;
- // The proxy needed for this test is the same as testing resolution
- // presets except for mocking the retrieval of the sensor and current
- // UI orientation.
- setUpOverridesForTestingUseCaseConfiguration(
- mockProcessCameraProvider,
- newPreview:
- ({
- int? targetRotation,
- CameraIntegerRange? targetFpsRange,
- ResolutionSelector? resolutionSelector,
- }) {
- final mockPreview = MockPreview();
- when(
- mockPreview.surfaceProducerHandlesCropAndRotation(),
- ).thenAnswer((_) async => testHandlesCropAndRotation);
- when(
- mockPreview.resolutionSelector,
- ).thenReturn(resolutionSelector);
- return mockPreview;
- },
- );
+ // Mock/Detached objects for (typically attached) objects created by
+ // createCamera.
+ final mockCamera = MockCamera();
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockCameraInfo = MockCameraInfo();
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
-
- await camera.createCamera(
- testCameraDescription,
- testResolutionPreset,
- enableAudio: enableAudio,
- );
-
- expect(camera.sensorOrientationDegrees, testSensorOrientation);
- expect(camera.enableRecordingAudio, isTrue);
- },
- );
-
- test(
- 'createCamera and initializeCamera sets targetFps as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const CameraLensDirection testLensDirection = CameraLensDirection.back;
- const testSensorOrientation = 90;
- const testCameraDescription = CameraDescription(
- name: 'cameraName',
- lensDirection: testLensDirection,
- sensorOrientation: testSensorOrientation,
- );
- const fastTargetFps = 60;
- const testCameraId = 12;
- final mockCamera = MockCamera();
-
- // Mock/Detached objects for (typically attached) objects created by
- // createCamera.
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockCameraInfo = MockCameraInfo();
-
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
- camera.processCameraProvider = mockProcessCameraProvider;
- PigeonOverrides.cameraIntegerRange_new =
- CameraIntegerRange.pigeon_detached;
-
- CameraIntegerRange? targetPreviewFpsRange;
- CameraIntegerRange? targetVideoCaptureFpsRange;
- CameraIntegerRange? targetImageAnalysisFpsRange;
-
- setUpOverridesForTestingUseCaseConfiguration(
- mockProcessCameraProvider,
- newPreview:
- ({
- ResolutionSelector? resolutionSelector,
- CameraIntegerRange? targetFpsRange,
- int? targetRotation,
- }) {
- targetPreviewFpsRange = targetFpsRange;
- final mockPreview = MockPreview();
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
- );
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
- return mockPreview;
- },
- withOutputVideoCapture:
- ({
- CameraIntegerRange? targetFpsRange,
- required VideoOutput videoOutput,
- }) {
- targetVideoCaptureFpsRange = targetFpsRange;
- return MockVideoCapture();
- },
- newImageAnalysis:
- ({
- int? outputImageFormat,
- ResolutionSelector? resolutionSelector,
- CameraIntegerRange? targetFpsRange,
- int? targetRotation,
- }) {
- targetImageAnalysisFpsRange = targetFpsRange;
- return MockImageAnalysis();
- },
- );
-
- await camera.createCameraWithSettings(
- testCameraDescription,
- const MediaSettings(fps: fastTargetFps),
- );
- await camera.initializeCamera(testCameraId);
-
- expect(targetPreviewFpsRange?.lower, fastTargetFps);
- expect(targetPreviewFpsRange?.upper, fastTargetFps);
- expect(targetVideoCaptureFpsRange?.lower, fastTargetFps);
- expect(targetVideoCaptureFpsRange?.upper, fastTargetFps);
- expect(targetImageAnalysisFpsRange?.lower, fastTargetFps);
- expect(targetImageAnalysisFpsRange?.upper, fastTargetFps);
- },
- );
-
- test(
- 'createCamera properly selects specific back camera by specifying a CameraInfo',
- () async {
- // Arrange
- final camera = AndroidCameraCameraX();
- final returnData = <dynamic>[
- <String, dynamic>{
- 'name': '0',
- 'lensFacing': 'back',
- 'sensorOrientation': 0,
- },
- <String, dynamic>{
- 'name': '1',
- 'lensFacing': 'back',
- 'sensorOrientation': 0,
- },
- <String, dynamic>{
- 'name': '2',
- 'lensFacing': 'front',
- 'sensorOrientation': 0,
- },
- ];
-
- var mockCameraInfosList = <MockCameraInfo>[];
- final cameraNameToInfos = <String, MockCameraInfo?>{};
-
- const testSensorOrientation = 0;
-
- // Mocks for objects created by availableCameras.
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockFrontCameraSelector = MockCameraSelector();
- final mockBackCameraSelector = MockCameraSelector();
- final mockChosenCameraInfoCameraSelector = MockCameraSelector();
-
- final mockFrontCameraInfo = MockCameraInfo();
- final mockBackCameraInfoOne = MockCameraInfo();
- final mockBackCameraInfoTwo = MockCameraInfo();
-
- when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front);
- when(mockBackCameraInfoOne.lensFacing).thenReturn(LensFacing.back);
- when(mockBackCameraInfoTwo.lensFacing).thenReturn(LensFacing.back);
-
- // Mock/Detached objects for (typically attached) objects created by
- // createCamera.
- final mockPreview = MockPreview();
- final mockImageCapture = MockImageCapture();
- final mockImageAnalysis = MockImageAnalysis();
- final mockRecorder = MockRecorder();
- final mockVideoCapture = MockVideoCapture();
- final mockCamera = MockCamera();
- final mockCameraInfo = MockCameraInfo();
- final mockCameraControl = MockCameraControl();
- final mockCamera2CameraInfo = MockCamera2CameraInfo();
- final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey();
-
- // Tell plugin to create mock/detached objects and stub method calls for the
- // testing of availableCameras and createCamera.
- PigeonOverrides.processCameraProvider_getInstance = () {
- return Future<ProcessCameraProvider>.value(mockProcessCameraProvider);
- };
- PigeonOverrides.cameraSelector_new =
- ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) {
- switch (requireLensFacing) {
- case LensFacing.front:
- return mockFrontCameraSelector;
- case LensFacing.back:
- case LensFacing.external:
- case LensFacing.unknown:
- case null:
- }
- if (cameraInfoForFilter == mockBackCameraInfoOne) {
- return mockChosenCameraInfoCameraSelector;
- }
-
- return mockBackCameraSelector;
- };
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
- return MockSystemServicesManager();
- };
- PigeonOverrides.preview_new =
+ // The proxy needed for this test is the same as testing resolution
+ // presets except for mocking the retrieval of the sensor and current
+ // UI orientation.
+ setUpOverridesForTestingUseCaseConfiguration(
+ mockProcessCameraProvider,
+ newPreview:
({
int? targetRotation,
CameraIntegerRange? targetFpsRange,
ResolutionSelector? resolutionSelector,
}) {
+ final mockPreview = MockPreview();
+ when(
+ mockPreview.surfaceProducerHandlesCropAndRotation(),
+ ).thenAnswer((_) async => testHandlesCropAndRotation);
+ when(mockPreview.resolutionSelector).thenReturn(resolutionSelector);
return mockPreview;
- };
- PigeonOverrides.imageCapture_new =
+ },
+ );
+
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+
+ await camera.createCamera(
+ testCameraDescription,
+ testResolutionPreset,
+ enableAudio: enableAudio,
+ );
+
+ expect(camera.sensorOrientationDegrees, testSensorOrientation);
+ expect(camera.enableRecordingAudio, isTrue);
+ });
+
+ test('createCamera and initializeCamera sets targetFps as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const CameraLensDirection testLensDirection = CameraLensDirection.back;
+ const testSensorOrientation = 90;
+ const testCameraDescription = CameraDescription(
+ name: 'cameraName',
+ lensDirection: testLensDirection,
+ sensorOrientation: testSensorOrientation,
+ );
+ const fastTargetFps = 60;
+ const testCameraId = 12;
+ final mockCamera = MockCamera();
+
+ // Mock/Detached objects for (typically attached) objects created by
+ // createCamera.
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockCameraInfo = MockCameraInfo();
+
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+ camera.processCameraProvider = mockProcessCameraProvider;
+ PigeonOverrides.cameraIntegerRange_new = CameraIntegerRange.pigeon_detached;
+
+ CameraIntegerRange? targetPreviewFpsRange;
+ CameraIntegerRange? targetVideoCaptureFpsRange;
+ CameraIntegerRange? targetImageAnalysisFpsRange;
+
+ setUpOverridesForTestingUseCaseConfiguration(
+ mockProcessCameraProvider,
+ newPreview:
({
- int? targetRotation,
- CameraXFlashMode? flashMode,
ResolutionSelector? resolutionSelector,
- }) {
- return mockImageCapture;
- };
- PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) {
- return mockRecorder;
- };
- PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) {
- return mockRecorder;
- };
- PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
CameraIntegerRange? targetFpsRange,
- }) {
- return mockVideoCapture;
- };
- PigeonOverrides.imageAnalysis_new =
- ({
int? targetRotation,
- CameraIntegerRange? targetFpsRange,
+ }) {
+ targetPreviewFpsRange = targetFpsRange;
+ final mockPreview = MockPreview();
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
+ return mockPreview;
+ },
+ withOutputVideoCapture:
+ ({CameraIntegerRange? targetFpsRange, required VideoOutput videoOutput}) {
+ targetVideoCaptureFpsRange = targetFpsRange;
+ return MockVideoCapture();
+ },
+ newImageAnalysis:
+ ({
int? outputImageFormat,
ResolutionSelector? resolutionSelector,
+ CameraIntegerRange? targetFpsRange,
+ int? targetRotation,
}) {
- return mockImageAnalysis;
- };
- PigeonOverrides.resolutionStrategy_new =
- ({
- required CameraSize boundSize,
- required ResolutionStrategyFallbackRule fallbackRule,
- }) {
- return MockResolutionStrategy();
- };
- PigeonOverrides.resolutionSelector_new =
- ({
- AspectRatioStrategy? aspectRatioStrategy,
- ResolutionStrategy? resolutionStrategy,
- ResolutionFilter? resolutionFilter,
- }) {
- return MockResolutionSelector();
- };
- PigeonOverrides.resolutionSelector_new =
- ({
- AspectRatioStrategy? aspectRatioStrategy,
- ResolutionStrategy? resolutionStrategy,
- ResolutionFilter? resolutionFilter,
- }) {
- return MockResolutionSelector();
- };
- PigeonOverrides.qualitySelector_from =
- ({
- required VideoQuality quality,
- FallbackStrategy? fallbackStrategy,
- }) {
- return MockQualitySelector();
- };
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
- PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
- final manager = MockDeviceOrientationManager();
- when(manager.getUiOrientation()).thenAnswer((_) async {
- return 'PORTRAIT_UP';
- });
- return manager;
- };
- PigeonOverrides.aspectRatioStrategy_new =
- ({
- required AspectRatio preferredAspectRatio,
- required AspectRatioStrategyFallbackRule fallbackRule,
- }) {
- return MockAspectRatioStrategy();
- };
- PigeonOverrides.resolutionFilter_createWithOnePreferredSize =
- ({required CameraSize preferredSize}) {
- return MockResolutionFilter();
- };
- PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
- var cameraId = '';
- if (cameraInfo == mockBackCameraInfoOne) {
- cameraId = '0';
- } else if (cameraInfo == mockBackCameraInfoTwo) {
- cameraId = '1';
- } else if (cameraInfo == mockFrontCameraInfo) {
- cameraId = '2';
- }
- when(
- mockCamera2CameraInfo.getCameraId(),
- ).thenAnswer((_) async => cameraId);
- when(
- mockCamera2CameraInfo.getCameraCharacteristic(
- mockCameraCharacteristicsKey,
- ),
- ).thenAnswer((_) async => testSensorOrientation);
- return mockCamera2CameraInfo;
- };
- PigeonOverrides.cameraSize_new =
- ({required int width, required int height}) {
- return MockCameraSize();
- };
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- mockCameraCharacteristicsKey;
- PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan =
- ({required VideoQuality quality}) {
- return MockFallbackStrategy();
- };
- PigeonOverrides.cameraIntegerRange_new =
- ({required int lower, required int upper}) {
- return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0);
- };
+ targetImageAnalysisFpsRange = targetFpsRange;
+ return MockImageAnalysis();
+ },
+ );
- // Mock calls to native platform
- when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer((
- _,
- ) async {
- mockCameraInfosList = <MockCameraInfo>[
- mockBackCameraInfoOne,
- mockBackCameraInfoTwo,
- mockFrontCameraInfo,
- ];
- return <MockCameraInfo>[
- mockBackCameraInfoOne,
- mockBackCameraInfoTwo,
- mockFrontCameraInfo,
- ];
- });
+ await camera.createCameraWithSettings(
+ testCameraDescription,
+ const MediaSettings(fps: fastTargetFps),
+ );
+ await camera.initializeCamera(testCameraId);
- final List<CameraDescription> cameraDescriptions = await camera
- .availableCameras();
- expect(cameraDescriptions.length, returnData.length);
+ expect(targetPreviewFpsRange?.lower, fastTargetFps);
+ expect(targetPreviewFpsRange?.upper, fastTargetFps);
+ expect(targetVideoCaptureFpsRange?.lower, fastTargetFps);
+ expect(targetVideoCaptureFpsRange?.upper, fastTargetFps);
+ expect(targetImageAnalysisFpsRange?.lower, fastTargetFps);
+ expect(targetImageAnalysisFpsRange?.upper, fastTargetFps);
+ });
- for (var i = 0; i < returnData.length; i++) {
- final Map<String, Object?> savedData =
- (returnData[i] as Map<dynamic, dynamic>).cast<String, Object?>();
+ test('createCamera properly selects specific back camera by specifying a CameraInfo', () async {
+ // Arrange
+ final camera = AndroidCameraCameraX();
+ final returnData = <dynamic>[
+ <String, dynamic>{'name': '0', 'lensFacing': 'back', 'sensorOrientation': 0},
+ <String, dynamic>{'name': '1', 'lensFacing': 'back', 'sensorOrientation': 0},
+ <String, dynamic>{'name': '2', 'lensFacing': 'front', 'sensorOrientation': 0},
+ ];
- cameraNameToInfos[savedData['name']! as String] =
- mockCameraInfosList[i];
- final cameraDescription = CameraDescription(
- name: savedData['name']! as String,
- lensDirection: (savedData['lensFacing']! as String) == 'front'
- ? CameraLensDirection.front
- : CameraLensDirection.back,
- sensorOrientation: savedData['sensorOrientation']! as int,
- );
- expect(cameraDescriptions[i], cameraDescription);
- expect(cameraNameToInfos.containsKey(cameraDescription.name), isTrue);
+ var mockCameraInfosList = <MockCameraInfo>[];
+ final cameraNameToInfos = <String, MockCameraInfo?>{};
+
+ const testSensorOrientation = 0;
+
+ // Mocks for objects created by availableCameras.
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockFrontCameraSelector = MockCameraSelector();
+ final mockBackCameraSelector = MockCameraSelector();
+ final mockChosenCameraInfoCameraSelector = MockCameraSelector();
+
+ final mockFrontCameraInfo = MockCameraInfo();
+ final mockBackCameraInfoOne = MockCameraInfo();
+ final mockBackCameraInfoTwo = MockCameraInfo();
+
+ when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front);
+ when(mockBackCameraInfoOne.lensFacing).thenReturn(LensFacing.back);
+ when(mockBackCameraInfoTwo.lensFacing).thenReturn(LensFacing.back);
+
+ // Mock/Detached objects for (typically attached) objects created by
+ // createCamera.
+ final mockPreview = MockPreview();
+ final mockImageCapture = MockImageCapture();
+ final mockImageAnalysis = MockImageAnalysis();
+ final mockRecorder = MockRecorder();
+ final mockVideoCapture = MockVideoCapture();
+ final mockCamera = MockCamera();
+ final mockCameraInfo = MockCameraInfo();
+ final mockCameraControl = MockCameraControl();
+ final mockCamera2CameraInfo = MockCamera2CameraInfo();
+ final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey();
+
+ // Tell plugin to create mock/detached objects and stub method calls for the
+ // testing of availableCameras and createCamera.
+ PigeonOverrides.processCameraProvider_getInstance = () {
+ return Future<ProcessCameraProvider>.value(mockProcessCameraProvider);
+ };
+ PigeonOverrides.cameraSelector_new =
+ ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) {
+ switch (requireLensFacing) {
+ case LensFacing.front:
+ return mockFrontCameraSelector;
+ case LensFacing.back:
+ case LensFacing.external:
+ case LensFacing.unknown:
+ case null:
+ }
+ if (cameraInfoForFilter == mockBackCameraInfoOne) {
+ return mockChosenCameraInfoCameraSelector;
+ }
+
+ return mockBackCameraSelector;
+ };
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ return MockSystemServicesManager();
+ };
+ PigeonOverrides.preview_new =
+ ({
+ int? targetRotation,
+ CameraIntegerRange? targetFpsRange,
+ ResolutionSelector? resolutionSelector,
+ }) {
+ return mockPreview;
+ };
+ PigeonOverrides.imageCapture_new =
+ ({
+ int? targetRotation,
+ CameraXFlashMode? flashMode,
+ ResolutionSelector? resolutionSelector,
+ }) {
+ return mockImageCapture;
+ };
+ PigeonOverrides.recorder_new =
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) {
+ return mockRecorder;
+ };
+ PigeonOverrides.recorder_new =
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) {
+ return mockRecorder;
+ };
+ PigeonOverrides.videoCapture_withOutput =
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
+ return mockVideoCapture;
+ };
+ PigeonOverrides.imageAnalysis_new =
+ ({
+ int? targetRotation,
+ CameraIntegerRange? targetFpsRange,
+ int? outputImageFormat,
+ ResolutionSelector? resolutionSelector,
+ }) {
+ return mockImageAnalysis;
+ };
+ PigeonOverrides.resolutionStrategy_new =
+ ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) {
+ return MockResolutionStrategy();
+ };
+ PigeonOverrides.resolutionSelector_new =
+ ({
+ AspectRatioStrategy? aspectRatioStrategy,
+ ResolutionStrategy? resolutionStrategy,
+ ResolutionFilter? resolutionFilter,
+ }) {
+ return MockResolutionSelector();
+ };
+ PigeonOverrides.resolutionSelector_new =
+ ({
+ AspectRatioStrategy? aspectRatioStrategy,
+ ResolutionStrategy? resolutionStrategy,
+ ResolutionFilter? resolutionFilter,
+ }) {
+ return MockResolutionSelector();
+ };
+ PigeonOverrides.qualitySelector_from =
+ ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) {
+ return MockQualitySelector();
+ };
+ GenericsPigeonOverrides.observerNew = <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
+ PigeonOverrides.deviceOrientationManager_new =
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
+ final manager = MockDeviceOrientationManager();
+ when(manager.getUiOrientation()).thenAnswer((_) async {
+ return 'PORTRAIT_UP';
+ });
+ return manager;
+ };
+ PigeonOverrides.aspectRatioStrategy_new =
+ ({
+ required AspectRatio preferredAspectRatio,
+ required AspectRatioStrategyFallbackRule fallbackRule,
+ }) {
+ return MockAspectRatioStrategy();
+ };
+ PigeonOverrides.resolutionFilter_createWithOnePreferredSize =
+ ({required CameraSize preferredSize}) {
+ return MockResolutionFilter();
+ };
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
+ var cameraId = '';
+ if (cameraInfo == mockBackCameraInfoOne) {
+ cameraId = '0';
+ } else if (cameraInfo == mockBackCameraInfoTwo) {
+ cameraId = '1';
+ } else if (cameraInfo == mockFrontCameraInfo) {
+ cameraId = '2';
}
-
+ when(mockCamera2CameraInfo.getCameraId()).thenAnswer((_) async => cameraId);
when(
- mockProcessCameraProvider.bindToLifecycle(
- mockChosenCameraInfoCameraSelector,
- <UseCase>[mockPreview, mockImageCapture, mockImageAnalysis],
- ),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
- when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl);
+ mockCamera2CameraInfo.getCameraCharacteristic(mockCameraCharacteristicsKey),
+ ).thenAnswer((_) async => testSensorOrientation);
+ return mockCamera2CameraInfo;
+ };
+ PigeonOverrides.cameraSize_new = ({required int width, required int height}) {
+ return MockCameraSize();
+ };
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey;
+ PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) {
+ return MockFallbackStrategy();
+ };
+ PigeonOverrides.cameraIntegerRange_new = ({required int lower, required int upper}) {
+ return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0);
+ };
- camera.processCameraProvider = mockProcessCameraProvider;
-
- // Verify the camera name used to create camera is associated with mockBackCameraInfoOne.
- expect(
- cameraNameToInfos[cameraDescriptions[0].name],
+ // Mock calls to native platform
+ when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer((_) async {
+ mockCameraInfosList = <MockCameraInfo>[
mockBackCameraInfoOne,
- );
+ mockBackCameraInfoTwo,
+ mockFrontCameraInfo,
+ ];
+ return <MockCameraInfo>[mockBackCameraInfoOne, mockBackCameraInfoTwo, mockFrontCameraInfo];
+ });
- // Creating a camera with settings using a specific camera from
- // available cameras.
- await camera.createCameraWithSettings(
- cameraDescriptions[0],
- const MediaSettings(
- resolutionPreset: ResolutionPreset.low,
- fps: 15,
- videoBitrate: 200000,
- audioBitrate: 32000,
- enableAudio: true,
- ),
- );
+ final List<CameraDescription> cameraDescriptions = await camera.availableCameras();
+ expect(cameraDescriptions.length, returnData.length);
- // Verify CameraSelector is chosen based on specified cameraInfo.
- expect(camera.cameraSelector, equals(mockChosenCameraInfoCameraSelector));
- },
- );
+ for (var i = 0; i < returnData.length; i++) {
+ final Map<String, Object?> savedData = (returnData[i] as Map<dynamic, dynamic>)
+ .cast<String, Object?>();
+
+ cameraNameToInfos[savedData['name']! as String] = mockCameraInfosList[i];
+ final cameraDescription = CameraDescription(
+ name: savedData['name']! as String,
+ lensDirection: (savedData['lensFacing']! as String) == 'front'
+ ? CameraLensDirection.front
+ : CameraLensDirection.back,
+ sensorOrientation: savedData['sensorOrientation']! as int,
+ );
+ expect(cameraDescriptions[i], cameraDescription);
+ expect(cameraNameToInfos.containsKey(cameraDescription.name), isTrue);
+ }
+
+ when(
+ mockProcessCameraProvider.bindToLifecycle(mockChosenCameraInfoCameraSelector, <UseCase>[
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
+ ).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl);
+
+ camera.processCameraProvider = mockProcessCameraProvider;
+
+ // Verify the camera name used to create camera is associated with mockBackCameraInfoOne.
+ expect(cameraNameToInfos[cameraDescriptions[0].name], mockBackCameraInfoOne);
+
+ // Creating a camera with settings using a specific camera from
+ // available cameras.
+ await camera.createCameraWithSettings(
+ cameraDescriptions[0],
+ const MediaSettings(
+ resolutionPreset: ResolutionPreset.low,
+ fps: 15,
+ videoBitrate: 200000,
+ audioBitrate: 32000,
+ enableAudio: true,
+ ),
+ );
+
+ // Verify CameraSelector is chosen based on specified cameraInfo.
+ expect(camera.cameraSelector, equals(mockChosenCameraInfoCameraSelector));
+ });
test(
'initializeCamera throws a CameraException when createCamera has not been called before initializedCamera',
@@ -2000,23 +1636,13 @@
final mockCameraInfo = MockCameraInfo();
final mockLiveCameraState = MockLiveCameraState();
final mockPreview = MockPreview();
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
- );
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => mockLiveCameraState);
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
- when(
- mockPreview.setSurfaceProvider(any),
- ).thenAnswer((_) async => testSurfaceTextureId);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState);
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
+ when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => testSurfaceTextureId);
camera.processCameraProvider = mockProcessCameraProvider;
// Tell plugin to create mock/detached objects for testing createCamera
@@ -2043,102 +1669,83 @@
await testCameraClosingObserver(
camera,
testSurfaceTextureId,
- verify(mockLiveCameraState.observe(captureAny)).captured.single
- as Observer<CameraState>,
+ verify(mockLiveCameraState.observe(captureAny)).captured.single as Observer<CameraState>,
),
isTrue,
);
});
- test(
- 'initializeCamera sets image format of ImageAnalysis use case as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const CameraLensDirection testLensDirection = CameraLensDirection.back;
- const testSensorOrientation = 90;
- const testCameraDescription = CameraDescription(
- name: 'cameraName',
- lensDirection: testLensDirection,
- sensorOrientation: testSensorOrientation,
+ test('initializeCamera sets image format of ImageAnalysis use case as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const CameraLensDirection testLensDirection = CameraLensDirection.back;
+ const testSensorOrientation = 90;
+ const testCameraDescription = CameraDescription(
+ name: 'cameraName',
+ lensDirection: testLensDirection,
+ sensorOrientation: testSensorOrientation,
+ );
+ const enableAudio = true;
+ final mockCamera = MockCamera();
+ const testSurfaceTextureId = 244;
+
+ // Mock/Detached objects for (typically attached) objects created by
+ // createCamera.
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockCameraInfo = MockCameraInfo();
+ final mockLiveCameraState = MockLiveCameraState();
+ final mockPreview = MockPreview();
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
+ final mockImageAnalysis = MockImageAnalysis();
+
+ // Configure mocks for camera initialization.
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState);
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
+ when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => testSurfaceTextureId);
+ camera.processCameraProvider = mockProcessCameraProvider;
+
+ for (final ImageFormatGroup imageFormatGroup in ImageFormatGroup.values) {
+ // Get CameraX image format constant for imageFormatGroup.
+ final int? cameraXImageFormat = switch (imageFormatGroup) {
+ ImageFormatGroup.yuv420 => AndroidCameraCameraX.imageAnalysisOutputImageFormatYuv420_888,
+ ImageFormatGroup.nv21 => AndroidCameraCameraX.imageAnalysisOutputImageFormatNv21,
+ _ => null,
+ };
+ // Tell plugin to create mock/detached objects for testing createCamera
+ // as needed.
+ int? imageAnalysisOutputImageFormat;
+ setUpOverridesForTestingUseCaseConfiguration(
+ mockProcessCameraProvider,
+ newImageAnalysis:
+ ({
+ ResolutionSelector? resolutionSelector,
+ int? targetRotation,
+ CameraIntegerRange? targetFpsRange,
+ int? outputImageFormat,
+ }) {
+ imageAnalysisOutputImageFormat = outputImageFormat;
+ return mockImageAnalysis;
+ },
+ newPreview:
+ ({
+ ResolutionSelector? resolutionSelector,
+ int? targetRotation,
+ CameraIntegerRange? targetFpsRange,
+ }) => mockPreview,
);
- const enableAudio = true;
- final mockCamera = MockCamera();
- const testSurfaceTextureId = 244;
- // Mock/Detached objects for (typically attached) objects created by
- // createCamera.
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockCameraInfo = MockCameraInfo();
- final mockLiveCameraState = MockLiveCameraState();
- final mockPreview = MockPreview();
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
+ // Create and initialize camera.
+ await camera.createCameraWithSettings(
+ testCameraDescription,
+ const MediaSettings(enableAudio: enableAudio),
);
- final mockImageAnalysis = MockImageAnalysis();
+ await camera.initializeCamera(testSurfaceTextureId, imageFormatGroup: imageFormatGroup);
- // Configure mocks for camera initialization.
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => mockLiveCameraState);
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
- when(
- mockPreview.setSurfaceProvider(any),
- ).thenAnswer((_) async => testSurfaceTextureId);
- camera.processCameraProvider = mockProcessCameraProvider;
-
- for (final ImageFormatGroup imageFormatGroup in ImageFormatGroup.values) {
- // Get CameraX image format constant for imageFormatGroup.
- final int? cameraXImageFormat = switch (imageFormatGroup) {
- ImageFormatGroup.yuv420 =>
- AndroidCameraCameraX.imageAnalysisOutputImageFormatYuv420_888,
- ImageFormatGroup.nv21 =>
- AndroidCameraCameraX.imageAnalysisOutputImageFormatNv21,
- _ => null,
- };
- // Tell plugin to create mock/detached objects for testing createCamera
- // as needed.
- int? imageAnalysisOutputImageFormat;
- setUpOverridesForTestingUseCaseConfiguration(
- mockProcessCameraProvider,
- newImageAnalysis:
- ({
- ResolutionSelector? resolutionSelector,
- int? targetRotation,
- CameraIntegerRange? targetFpsRange,
- int? outputImageFormat,
- }) {
- imageAnalysisOutputImageFormat = outputImageFormat;
- return mockImageAnalysis;
- },
- newPreview:
- ({
- ResolutionSelector? resolutionSelector,
- int? targetRotation,
- CameraIntegerRange? targetFpsRange,
- }) => mockPreview,
- );
-
- // Create and initialize camera.
- await camera.createCameraWithSettings(
- testCameraDescription,
- const MediaSettings(enableAudio: enableAudio),
- );
- await camera.initializeCamera(
- testSurfaceTextureId,
- imageFormatGroup: imageFormatGroup,
- );
-
- // Test image format group is set as expected.
- expect(imageAnalysisOutputImageFormat, cameraXImageFormat);
- }
- },
- );
+ // Test image format group is set as expected.
+ expect(imageAnalysisOutputImageFormat, cameraXImageFormat);
+ }
+ });
test('initializeCamera sends expected CameraInitializedEvent', () async {
final camera = AndroidCameraCameraX();
@@ -2156,10 +1763,7 @@
final Camera mockCamera = MockCamera();
final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: CameraSize.pigeon_detached(
- width: resolutionWidth,
- height: resolutionHeight,
- ),
+ resolution: CameraSize.pigeon_detached(width: resolutionWidth, height: resolutionHeight),
);
// Mocks for (typically attached) objects created by createCamera.
@@ -2197,16 +1801,11 @@
ResolutionSelector? resolutionSelector,
}) => mockImageCapture;
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) => MockRecorder();
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) =>
+ MockRecorder();
PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) => MockVideoCapture();
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) =>
+ MockVideoCapture();
PigeonOverrides.imageAnalysis_new =
({
int? targetRotation,
@@ -2215,34 +1814,27 @@
ResolutionSelector? resolutionSelector,
}) => mockImageAnalysis;
PigeonOverrides.resolutionStrategy_new =
- ({
- required CameraSize boundSize,
- required ResolutionStrategyFallbackRule fallbackRule,
- }) => MockResolutionStrategy();
+ ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) =>
+ MockResolutionStrategy();
PigeonOverrides.resolutionSelector_new =
({
AspectRatioStrategy? aspectRatioStrategy,
ResolutionStrategy? resolutionStrategy,
ResolutionFilter? resolutionFilter,
}) => MockResolutionSelector();
- PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan =
- ({required VideoQuality quality}) => MockFallbackStrategy();
+ PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) =>
+ MockFallbackStrategy();
PigeonOverrides.qualitySelector_from =
({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) =>
MockQualitySelector();
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
+ GenericsPigeonOverrides.observerNew = <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) => MockSystemServicesManager();
+ ({required void Function(SystemServicesManager, String) onCameraError}) =>
+ MockSystemServicesManager();
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
when(manager.getUiOrientation()).thenAnswer((_) async {
return 'PORTRAIT_UP';
@@ -2258,19 +1850,15 @@
({required CameraSize preferredSize}) => MockResolutionFilter();
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
final mockCamera2CameraInfo = MockCamera2CameraInfo();
- when(
- mockCamera2CameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => 90);
+ when(mockCamera2CameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => 90);
return mockCamera2CameraInfo;
};
- PigeonOverrides.cameraSize_new =
- ({required int width, required int height}) => MockCameraSize();
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- MockCameraCharacteristicsKey();
- PigeonOverrides.cameraIntegerRange_new =
- ({required int lower, required int upper}) {
- return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0);
- };
+ PigeonOverrides.cameraSize_new = ({required int width, required int height}) =>
+ MockCameraSize();
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = MockCameraCharacteristicsKey();
+ PigeonOverrides.cameraIntegerRange_new = ({required int lower, required int upper}) {
+ return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0);
+ };
final testCameraInitializedEvent = CameraInitializedEvent(
cameraId,
@@ -2286,18 +1874,15 @@
when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => cameraId);
when(
- mockProcessCameraProvider.bindToLifecycle(
- mockBackCameraSelector,
- <UseCase>[mockPreview, mockImageCapture, mockImageAnalysis],
- ),
+ mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, <UseCase>[
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
await camera.createCameraWithSettings(
testCameraDescription,
@@ -2328,17 +1913,13 @@
var stoppedListeningForDeviceOrientationChange = false;
final camera = AndroidCameraCameraX();
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final mockDeviceOrientationManager = MockDeviceOrientationManager();
- when(
- mockDeviceOrientationManager
- .stopListeningForDeviceOrientationChange(),
- ).thenAnswer((_) async {
- stoppedListeningForDeviceOrientationChange = true;
- });
+ when(mockDeviceOrientationManager.stopListeningForDeviceOrientationChange()).thenAnswer(
+ (_) async {
+ stoppedListeningForDeviceOrientationChange = true;
+ },
+ );
return mockDeviceOrientationManager;
};
@@ -2360,8 +1941,7 @@
test('onCameraInitialized stream emits CameraInitializedEvents', () async {
final camera = AndroidCameraCameraX();
const cameraId = 16;
- final Stream<CameraInitializedEvent> eventStream = camera
- .onCameraInitialized(cameraId);
+ final Stream<CameraInitializedEvent> eventStream = camera.onCameraInitialized(cameraId);
final streamQueue = StreamQueue<CameraInitializedEvent>(eventStream);
const testEvent = CameraInitializedEvent(
cameraId,
@@ -2385,9 +1965,7 @@
final camera = AndroidCameraCameraX();
const cameraId = 99;
const cameraClosingEvent = CameraClosingEvent(cameraId);
- final Stream<CameraClosingEvent> eventStream = camera.onCameraClosing(
- cameraId,
- );
+ final Stream<CameraClosingEvent> eventStream = camera.onCameraClosing(cameraId);
final streamQueue = StreamQueue<CameraClosingEvent>(eventStream);
camera.cameraEventStreamController.add(cameraClosingEvent);
@@ -2404,23 +1982,14 @@
const cameraId = 27;
const firstTestErrorDescription = 'Test error description 1!';
const secondTestErrorDescription = 'Test error description 2!';
- const secondCameraErrorEvent = CameraErrorEvent(
- cameraId,
- secondTestErrorDescription,
- );
- final Stream<CameraErrorEvent> eventStream = camera.onCameraError(
- cameraId,
- );
+ const secondCameraErrorEvent = CameraErrorEvent(cameraId, secondTestErrorDescription);
+ final Stream<CameraErrorEvent> eventStream = camera.onCameraError(cameraId);
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
final mockSystemServicesManager = MockSystemServicesManager();
- when(
- mockSystemServicesManager.onCameraError,
- ).thenReturn(onCameraError);
+ when(mockSystemServicesManager.onCameraError).thenReturn(onCameraError);
return mockSystemServicesManager;
};
@@ -2444,20 +2013,12 @@
'onDeviceOrientationChanged stream emits changes in device orientation detected by system services',
() async {
final camera = AndroidCameraCameraX();
- final Stream<DeviceOrientationChangedEvent> eventStream = camera
- .onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
- const testEvent = DeviceOrientationChangedEvent(
- DeviceOrientation.portraitDown,
- );
+ final Stream<DeviceOrientationChangedEvent> eventStream = camera.onDeviceOrientationChanged();
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
+ const testEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitDown);
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final mockDeviceOrientationManager = MockDeviceOrientationManager();
when(
mockDeviceOrientationManager.onDeviceOrientationChanged,
@@ -2484,9 +2045,7 @@
camera.processCameraProvider = MockProcessCameraProvider();
camera.preview = MockPreview();
- when(
- camera.processCameraProvider!.isBound(camera.preview!),
- ).thenAnswer((_) async => true);
+ when(camera.processCameraProvider!.isBound(camera.preview!)).thenAnswer((_) async => true);
await camera.pausePreview(579);
@@ -2505,9 +2064,7 @@
await camera.pausePreview(632);
- verifyNever(
- camera.processCameraProvider!.unbind(<UseCase>[camera.preview!]),
- );
+ verifyNever(camera.processCameraProvider!.unbind(<UseCase>[camera.preview!]));
},
);
@@ -2525,28 +2082,22 @@
camera.cameraSelector = MockCameraSelector();
camera.preview = MockPreview();
- when(
- camera.processCameraProvider!.isBound(camera.preview!),
- ).thenAnswer((_) async => true);
+ when(camera.processCameraProvider!.isBound(camera.preview!)).thenAnswer((_) async => true);
when(
- mockProcessCameraProvider.bindToLifecycle(
- camera.cameraSelector,
- <UseCase>[camera.preview!],
- ),
+ mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, <UseCase>[
+ camera.preview!,
+ ]),
).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => mockLiveCameraState);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState);
await camera.resumePreview(78);
verifyNever(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.preview!],
- ),
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.preview!,
+ ]),
);
verifyNever(mockLiveCameraState.observe(any));
expect(camera.cameraInfo, isNot(mockCameraInfo));
@@ -2577,31 +2128,26 @@
};
when(
- mockProcessCameraProvider.bindToLifecycle(
- camera.cameraSelector,
- <UseCase>[camera.preview!],
- ),
+ mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, <UseCase>[
+ camera.preview!,
+ ]),
).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => mockLiveCameraState);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState);
when(mockCamera.cameraControl).thenReturn(mockCameraControl);
await camera.resumePreview(78);
verify(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.preview!],
- ),
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.preview!,
+ ]),
);
expect(
await testCameraClosingObserver(
camera,
78,
- verify(mockLiveCameraState.observe(captureAny)).captured.single
- as Observer<dynamic>,
+ verify(mockLiveCameraState.observe(captureAny)).captured.single as Observer<dynamic>,
),
isTrue,
);
@@ -2612,22 +2158,16 @@
// Further `buildPreview` testing concerning the Widget that it returns is
// located in preview_rotation_test.dart.
- test(
- 'buildPreview throws an exception if the preview is not bound to the lifecycle',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 73;
+ test('buildPreview throws an exception if the preview is not bound to the lifecycle', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 73;
- // Tell camera that createCamera has not been called and thus, preview has
- // not been bound to the lifecycle of the camera.
- camera.previewInitiallyBound = false;
+ // Tell camera that createCamera has not been called and thus, preview has
+ // not been bound to the lifecycle of the camera.
+ camera.previewInitiallyBound = false;
- expect(
- () => camera.buildPreview(cameraId),
- throwsA(isA<CameraException>()),
- );
- },
- );
+ expect(() => camera.buildPreview(cameraId), throwsA(isA<CameraException>()));
+ });
group('video recording', () {
test(
@@ -2667,27 +2207,18 @@
<T>({required void Function(Observer<T>, T) onChanged}) {
return Observer<T>.detached(onChanged: onChanged);
};
- PigeonOverrides.camera2CameraInfo_from =
- ({required dynamic cameraInfo}) => mockCamera2CameraInfo;
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) =>
+ mockCamera2CameraInfo;
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String)
- onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
final mockSystemServicesManager = MockSystemServicesManager();
when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
).thenAnswer((_) async => outputPath);
return mockSystemServicesManager;
};
PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
};
PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
@@ -2705,25 +2236,18 @@
when(
mockPendingRecording.asPersistentRecording(),
).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecordingWithAudio.start(any),
- ).thenAnswer((_) async => mockRecording);
+ when(mockPendingRecordingWithAudio.start(any)).thenAnswer((_) async => mockRecording);
when(
camera.processCameraProvider!.isBound(camera.videoCapture!),
).thenAnswer((_) async => false);
when(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.videoCapture!],
- ),
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.videoCapture!,
+ ]),
).thenAnswer((_) async => newMockCamera);
- when(
- newMockCamera.getCameraInfo(),
- ).thenAnswer((_) async => mockCameraInfo);
+ when(newMockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(newMockCamera.cameraControl).thenReturn(mockCameraControl);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => newMockLiveCameraState);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => newMockLiveCameraState);
when(
mockCamera2CameraInfo.getCameraCharacteristic(any),
).thenAnswer((_) async => InfoSupportedHardwareLevel.limited);
@@ -2738,10 +2262,9 @@
// Verify VideoCapture UseCase is bound and camera & its properties
// are updated.
verify(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.videoCapture!],
- ),
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.videoCapture!,
+ ]),
);
expect(camera.camera, equals(newMockCamera));
expect(camera.cameraInfo, equals(mockCameraInfo));
@@ -2751,8 +2274,7 @@
await testCameraClosingObserver(
camera,
cameraId,
- verify(newMockLiveCameraState.observe(captureAny)).captured.single
- as Observer<dynamic>,
+ verify(newMockLiveCameraState.observe(captureAny)).captured.single as Observer<dynamic>,
),
isTrue,
);
@@ -2763,240 +2285,201 @@
},
);
- test(
- 'startVideoCapturing binds video capture use case and starts the recording'
- ' on first call, and does nothing on second call',
- () async {
- // Set up mocks and constants.
- final camera = AndroidCameraCameraX();
- final mockPendingRecording = MockPendingRecording();
- final mockRecording = MockRecording();
- final mockCamera = MockCamera();
- final mockCameraInfo = MockCameraInfo();
- final mockCamera2CameraInfo = MockCamera2CameraInfo();
+ test('startVideoCapturing binds video capture use case and starts the recording'
+ ' on first call, and does nothing on second call', () async {
+ // Set up mocks and constants.
+ final camera = AndroidCameraCameraX();
+ final mockPendingRecording = MockPendingRecording();
+ final mockRecording = MockRecording();
+ final mockCamera = MockCamera();
+ final mockCameraInfo = MockCameraInfo();
+ final mockCamera2CameraInfo = MockCamera2CameraInfo();
- // Set directly for test versus calling createCamera.
- camera.processCameraProvider = MockProcessCameraProvider();
- camera.recorder = MockRecorder();
- camera.videoCapture = MockVideoCapture();
- camera.cameraSelector = MockCameraSelector();
- camera.cameraInfo = MockCameraInfo();
- camera.imageAnalysis = MockImageAnalysis();
- camera.enableRecordingAudio = false;
+ // Set directly for test versus calling createCamera.
+ camera.processCameraProvider = MockProcessCameraProvider();
+ camera.recorder = MockRecorder();
+ camera.videoCapture = MockVideoCapture();
+ camera.cameraSelector = MockCameraSelector();
+ camera.cameraInfo = MockCameraInfo();
+ camera.imageAnalysis = MockImageAnalysis();
+ camera.enableRecordingAudio = false;
- // Ignore setting target rotation for this test; tested seprately.
- camera.captureOrientationLocked = true;
+ // Ignore setting target rotation for this test; tested seprately.
+ camera.captureOrientationLocked = true;
- // Tell plugin to create detached Observer when camera info updated.
- const outputPath = '/temp/REC123.mp4';
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
- PigeonOverrides.camera2CameraInfo_from =
- ({required dynamic cameraInfo}) => mockCamera2CameraInfo;
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String)
- onCameraError,
- }) {
- final mockSystemServicesManager = MockSystemServicesManager();
- when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
- ).thenAnswer((_) async => outputPath);
- return mockSystemServicesManager;
- };
- PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
- return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
- };
- PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
- MockCameraCharacteristicsKey();
+ // Tell plugin to create detached Observer when camera info updated.
+ const outputPath = '/temp/REC123.mp4';
+ GenericsPigeonOverrides.observerNew =
+ <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) =>
+ mockCamera2CameraInfo;
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ final mockSystemServicesManager = MockSystemServicesManager();
+ when(
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
+ ).thenAnswer((_) async => outputPath);
+ return mockSystemServicesManager;
+ };
+ PigeonOverrides.videoRecordEventListener_new =
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
+ return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
+ };
+ PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
+ MockCameraCharacteristicsKey();
- const cameraId = 17;
+ const cameraId = 17;
- // Mock method calls.
- when(
- camera.recorder!.prepareRecording(outputPath),
- ).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio),
- ).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.asPersistentRecording(),
- ).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.start(any),
- ).thenAnswer((_) async => mockRecording);
- when(
- camera.processCameraProvider!.isBound(camera.videoCapture!),
- ).thenAnswer((_) async => false);
- when(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.videoCapture!],
- ),
- ).thenAnswer((_) async => mockCamera);
- when(
- mockCamera.getCameraInfo(),
- ).thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
- when(
- mockCamera2CameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited);
+ // Mock method calls.
+ when(
+ camera.recorder!.prepareRecording(outputPath),
+ ).thenAnswer((_) async => mockPendingRecording);
+ when(
+ mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio),
+ ).thenAnswer((_) async => mockPendingRecording);
+ when(
+ mockPendingRecording.asPersistentRecording(),
+ ).thenAnswer((_) async => mockPendingRecording);
+ when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording);
+ when(
+ camera.processCameraProvider!.isBound(camera.videoCapture!),
+ ).thenAnswer((_) async => false);
+ when(
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.videoCapture!,
+ ]),
+ ).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+ when(
+ mockCamera2CameraInfo.getCameraCharacteristic(any),
+ ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited);
- // Simulate video recording being started so startVideoRecording completes.
- AndroidCameraCameraX.videoRecordingEventStreamController.add(
- VideoRecordEventStart.pigeon_detached(),
- );
+ // Simulate video recording being started so startVideoRecording completes.
+ AndroidCameraCameraX.videoRecordingEventStreamController.add(
+ VideoRecordEventStart.pigeon_detached(),
+ );
- await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
+ await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
- verify(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.videoCapture!],
- ),
- );
- expect(camera.pendingRecording, equals(mockPendingRecording));
- expect(camera.recording, mockRecording);
+ verify(
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.videoCapture!,
+ ]),
+ );
+ expect(camera.pendingRecording, equals(mockPendingRecording));
+ expect(camera.recording, mockRecording);
- await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
- // Verify that each of these calls happened only once.
- verify(
- camera.systemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
- ).called(1);
- verifyNoMoreInteractions(camera.systemServicesManager);
- verify(camera.recorder!.prepareRecording(outputPath)).called(1);
- verifyNoMoreInteractions(camera.recorder);
- verify(mockPendingRecording.start(any)).called(1);
- verify(mockPendingRecording.withAudioEnabled(any)).called(1);
- verify(mockPendingRecording.asPersistentRecording()).called(1);
- verifyNoMoreInteractions(mockPendingRecording);
- },
- );
+ await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
+ // Verify that each of these calls happened only once.
+ verify(camera.systemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4')).called(1);
+ verifyNoMoreInteractions(camera.systemServicesManager);
+ verify(camera.recorder!.prepareRecording(outputPath)).called(1);
+ verifyNoMoreInteractions(camera.recorder);
+ verify(mockPendingRecording.start(any)).called(1);
+ verify(mockPendingRecording.withAudioEnabled(any)).called(1);
+ verify(mockPendingRecording.asPersistentRecording()).called(1);
+ verifyNoMoreInteractions(mockPendingRecording);
+ });
- test(
- 'startVideoCapturing called with stream options starts image streaming',
- () async {
- // Set up mocks and constants.
- final camera = AndroidCameraCameraX();
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final Recorder mockRecorder = MockRecorder();
- final mockPendingRecording = MockPendingRecording();
- final initialCameraInfo = MockCameraInfo();
- final mockCamera2CameraInfo = MockCamera2CameraInfo();
+ test('startVideoCapturing called with stream options starts image streaming', () async {
+ // Set up mocks and constants.
+ final camera = AndroidCameraCameraX();
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final Recorder mockRecorder = MockRecorder();
+ final mockPendingRecording = MockPendingRecording();
+ final initialCameraInfo = MockCameraInfo();
+ final mockCamera2CameraInfo = MockCamera2CameraInfo();
- // Set directly for test versus calling createCamera.
+ // Set directly for test versus calling createCamera.
- camera.processCameraProvider = mockProcessCameraProvider;
- camera.cameraSelector = MockCameraSelector();
- camera.videoCapture = MockVideoCapture();
- camera.imageAnalysis = MockImageAnalysis();
- camera.camera = MockCamera();
- camera.recorder = mockRecorder;
- camera.cameraInfo = initialCameraInfo;
- camera.imageCapture = MockImageCapture();
- camera.enableRecordingAudio = true;
+ camera.processCameraProvider = mockProcessCameraProvider;
+ camera.cameraSelector = MockCameraSelector();
+ camera.videoCapture = MockVideoCapture();
+ camera.imageAnalysis = MockImageAnalysis();
+ camera.camera = MockCamera();
+ camera.recorder = mockRecorder;
+ camera.cameraInfo = initialCameraInfo;
+ camera.imageCapture = MockImageCapture();
+ camera.enableRecordingAudio = true;
- // Ignore setting target rotation for this test; tested seprately.
- camera.captureOrientationLocked = true;
+ // Ignore setting target rotation for this test; tested seprately.
+ camera.captureOrientationLocked = true;
- // Tell plugin to create detached Analyzer for testing.
- const outputPath = '/temp/REC123.mp4';
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
- PigeonOverrides.camera2CameraInfo_from =
- ({required dynamic cameraInfo}) => mockCamera2CameraInfo;
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String)
- onCameraError,
- }) {
- final mockSystemServicesManager = MockSystemServicesManager();
- when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
- ).thenAnswer((_) async => outputPath);
- return mockSystemServicesManager;
- };
- PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
- return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
- };
- PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
- MockCameraCharacteristicsKey();
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) {
- return MockAnalyzer();
- };
+ // Tell plugin to create detached Analyzer for testing.
+ const outputPath = '/temp/REC123.mp4';
+ GenericsPigeonOverrides.observerNew =
+ <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) =>
+ mockCamera2CameraInfo;
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ final mockSystemServicesManager = MockSystemServicesManager();
+ when(
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
+ ).thenAnswer((_) async => outputPath);
+ return mockSystemServicesManager;
+ };
+ PigeonOverrides.videoRecordEventListener_new =
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
+ return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
+ };
+ PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
+ MockCameraCharacteristicsKey();
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) {
+ return MockAnalyzer();
+ };
- const cameraId = 17;
- final imageDataCompleter = Completer<CameraImageData>();
- final videoCaptureOptions = VideoCaptureOptions(
- cameraId,
- streamCallback: (CameraImageData imageData) =>
- imageDataCompleter.complete(imageData),
- );
+ const cameraId = 17;
+ final imageDataCompleter = Completer<CameraImageData>();
+ final videoCaptureOptions = VideoCaptureOptions(
+ cameraId,
+ streamCallback: (CameraImageData imageData) => imageDataCompleter.complete(imageData),
+ );
- // Mock method calls.
- when(
- camera.processCameraProvider!.isBound(camera.videoCapture!),
- ).thenAnswer((_) async => true);
- when(
- camera.processCameraProvider!.isBound(camera.imageAnalysis!),
- ).thenAnswer((_) async => true);
- when(
- camera.recorder!.prepareRecording(outputPath),
- ).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio),
- ).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.asPersistentRecording(),
- ).thenAnswer((_) async => mockPendingRecording);
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) => Future<Camera>.value(camera.camera));
- when(
- camera.camera!.getCameraInfo(),
- ).thenAnswer((_) => Future<CameraInfo>.value(MockCameraInfo()));
- when(
- mockCamera2CameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3);
+ // Mock method calls.
+ when(
+ camera.processCameraProvider!.isBound(camera.videoCapture!),
+ ).thenAnswer((_) async => true);
+ when(
+ camera.processCameraProvider!.isBound(camera.imageAnalysis!),
+ ).thenAnswer((_) async => true);
+ when(
+ camera.recorder!.prepareRecording(outputPath),
+ ).thenAnswer((_) async => mockPendingRecording);
+ when(
+ mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio),
+ ).thenAnswer((_) async => mockPendingRecording);
+ when(
+ mockPendingRecording.asPersistentRecording(),
+ ).thenAnswer((_) async => mockPendingRecording);
+ when(
+ mockProcessCameraProvider.bindToLifecycle(any, any),
+ ).thenAnswer((_) => Future<Camera>.value(camera.camera));
+ when(
+ camera.camera!.getCameraInfo(),
+ ).thenAnswer((_) => Future<CameraInfo>.value(MockCameraInfo()));
+ when(
+ mockCamera2CameraInfo.getCameraCharacteristic(any),
+ ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3);
- // Simulate video recording being started so startVideoRecording completes.
- AndroidCameraCameraX.videoRecordingEventStreamController.add(
- VideoRecordEventStart.pigeon_detached(),
- );
+ // Simulate video recording being started so startVideoRecording completes.
+ AndroidCameraCameraX.videoRecordingEventStreamController.add(
+ VideoRecordEventStart.pigeon_detached(),
+ );
- await camera.startVideoCapturing(videoCaptureOptions);
+ await camera.startVideoCapturing(videoCaptureOptions);
- final CameraImageData mockCameraImageData = MockCameraImageData();
- camera.cameraImageDataStreamController!.add(mockCameraImageData);
+ final CameraImageData mockCameraImageData = MockCameraImageData();
+ camera.cameraImageDataStreamController!.add(mockCameraImageData);
- expect(imageDataCompleter.future, isNotNull);
- await camera.cameraImageDataStreamController!.close();
- },
- );
+ expect(imageDataCompleter.future, isNotNull);
+ await camera.cameraImageDataStreamController!.close();
+ });
test(
'startVideoCapturing sets VideoCapture target rotation to current video orientation if orientation unlocked',
@@ -3026,41 +2509,28 @@
<T>({required void Function(Observer<T>, T) onChanged}) {
return Observer<T>.detached(onChanged: onChanged);
};
- PigeonOverrides.camera2CameraInfo_from =
- ({required dynamic cameraInfo}) => cameraInfo == initialCameraInfo
- ? mockCamera2CameraInfo
- : MockCamera2CameraInfo();
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) =>
+ cameraInfo == initialCameraInfo ? mockCamera2CameraInfo : MockCamera2CameraInfo();
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String)
- onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
final mockSystemServicesManager = MockSystemServicesManager();
when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
).thenAnswer((_) async => outputPath);
return mockSystemServicesManager;
};
PigeonOverrides.deviceOrientationManager_new =
({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
+ required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged,
}) {
- final mockDeviceOrientationManager =
- MockDeviceOrientationManager();
+ final mockDeviceOrientationManager = MockDeviceOrientationManager();
when(
mockDeviceOrientationManager.getDefaultDisplayRotation(),
).thenAnswer((_) async => defaultTargetRotation);
return mockDeviceOrientationManager;
};
PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
};
PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
@@ -3078,9 +2548,7 @@
when(
mockPendingRecording.asPersistentRecording(),
).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.start(any),
- ).thenAnswer((_) async => mockRecording);
+ when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording);
when(
camera.processCameraProvider!.isBound(camera.videoCapture!),
).thenAnswer((_) async => true);
@@ -3180,9 +2648,7 @@
camera.videoOutputPath = videoOutputPath;
// Tell plugin that videoCapture use case was bound to start recording.
- when(
- camera.processCameraProvider!.isBound(videoCapture),
- ).thenAnswer((_) async => true);
+ when(camera.processCameraProvider!.isBound(videoCapture)).thenAnswer((_) async => true);
// Simulate video recording being finalized so stopVideoRecording completes.
AndroidCameraCameraX.videoRecordingEventStreamController.add(
@@ -3224,9 +2690,7 @@
camera.videoCapture = mockVideoCapture;
// Tell plugin that videoCapture use case was bound to start recording.
- when(
- camera.processCameraProvider!.isBound(mockVideoCapture),
- ).thenAnswer((_) async => true);
+ when(camera.processCameraProvider!.isBound(mockVideoCapture)).thenAnswer((_) async => true);
await expectLater(() async {
// Simulate video recording being finalized so stopVideoRecording completes.
@@ -3265,39 +2729,34 @@
}, throwsA(isA<CameraException>()));
});
- test(
- 'VideoCapture use case is unbound from lifecycle when video recording stops',
- () async {
- final camera = AndroidCameraCameraX();
- final recording = MockRecording();
- final processCameraProvider = MockProcessCameraProvider();
- final videoCapture = MockVideoCapture();
- const videoOutputPath = '/test/output/path';
+ test('VideoCapture use case is unbound from lifecycle when video recording stops', () async {
+ final camera = AndroidCameraCameraX();
+ final recording = MockRecording();
+ final processCameraProvider = MockProcessCameraProvider();
+ final videoCapture = MockVideoCapture();
+ const videoOutputPath = '/test/output/path';
- // Set directly for test versus calling createCamera and startVideoCapturing.
- camera.processCameraProvider = processCameraProvider;
- camera.recording = recording;
- camera.videoCapture = videoCapture;
- camera.videoOutputPath = videoOutputPath;
+ // Set directly for test versus calling createCamera and startVideoCapturing.
+ camera.processCameraProvider = processCameraProvider;
+ camera.recording = recording;
+ camera.videoCapture = videoCapture;
+ camera.videoOutputPath = videoOutputPath;
- // Tell plugin that videoCapture use case was bound to start recording.
- when(
- camera.processCameraProvider!.isBound(videoCapture),
- ).thenAnswer((_) async => true);
+ // Tell plugin that videoCapture use case was bound to start recording.
+ when(camera.processCameraProvider!.isBound(videoCapture)).thenAnswer((_) async => true);
- // Simulate video recording being finalized so stopVideoRecording completes.
- AndroidCameraCameraX.videoRecordingEventStreamController.add(
- VideoRecordEventFinalize.pigeon_detached(),
- );
+ // Simulate video recording being finalized so stopVideoRecording completes.
+ AndroidCameraCameraX.videoRecordingEventStreamController.add(
+ VideoRecordEventFinalize.pigeon_detached(),
+ );
- await camera.stopVideoRecording(90);
- verify(processCameraProvider.unbind(<UseCase>[videoCapture]));
+ await camera.stopVideoRecording(90);
+ verify(processCameraProvider.unbind(<UseCase>[videoCapture]));
- // Verify that recording stops.
- verify(recording.close());
- verifyNoMoreInteractions(recording);
- },
- );
+ // Verify that recording stops.
+ verify(recording.close());
+ verifyNoMoreInteractions(recording);
+ });
test('setDescriptionWhileRecording changes the camera description', () async {
final camera = AndroidCameraCameraX();
@@ -3344,19 +2803,13 @@
int? targetRotation,
CameraIntegerRange? targetFpsRange,
}) {
- when(
- mockPreview.setSurfaceProvider(any),
- ).thenAnswer((_) async => 19);
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
- );
+ when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => 19);
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
when(
mockPreview.surfaceProducerHandlesCropAndRotation(),
).thenAnswer((_) async => false);
when(mockPreview.resolutionSelector).thenReturn(resolutionSelector);
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
return mockPreview;
};
PigeonOverrides.imageCapture_new =
@@ -3368,21 +2821,14 @@
return mockImageCapture;
};
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- QualitySelector? qualitySelector,
- int? targetVideoEncodingBitRate,
- }) {
+ ({int? aspectRatio, QualitySelector? qualitySelector, int? targetVideoEncodingBitRate}) {
when(
mockRecorder.prepareRecording(outputPath),
).thenAnswer((_) async => mockPendingRecording);
return mockRecorder;
};
PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) {
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
return mockVideoCapture;
};
PigeonOverrides.imageAnalysis_new =
@@ -3402,10 +2848,7 @@
return mockBackCameraSelector;
};
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
when(manager.getUiOrientation()).thenAnswer((_) async {
return 'PORTRAIT_UP';
@@ -3426,42 +2869,31 @@
).thenAnswer((_) async => InfoSupportedHardwareLevel.limited);
return camera2cameraInfo;
};
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- mockCameraCharacteristicsKey;
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey;
GenericsPigeonOverrides.observerNew =
<T>({required void Function(Observer<T>, T) onChanged}) {
return Observer<T>.detached(onChanged: onChanged);
};
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
final mockSystemServicesManager = MockSystemServicesManager();
when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
).thenAnswer((_) async => outputPath);
return mockSystemServicesManager;
};
PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
};
PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
MockCameraCharacteristicsKey();
// mock functions
- when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(
- (_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo],
- );
when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ mockProcessCameraProvider.getAvailableCameraInfos(),
+ ).thenAnswer((_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo]);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
camera.processCameraProvider = mockProcessCameraProvider;
camera.liveCameraState = mockLiveCameraState;
@@ -3472,35 +2904,22 @@
when(
mockPendingRecording.asPersistentRecording(),
).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.start(any),
- ).thenAnswer((_) async => mockRecording);
- when(
- camera.processCameraProvider!.isBound(mockImageCapture),
- ).thenAnswer((_) async => true);
- when(
- camera.processCameraProvider!.isBound(mockImageAnalysis),
- ).thenAnswer((_) async => true);
+ when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording);
+ when(camera.processCameraProvider!.isBound(mockImageCapture)).thenAnswer((_) async => true);
+ when(camera.processCameraProvider!.isBound(mockImageAnalysis)).thenAnswer((_) async => true);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl);
when(
- camera.processCameraProvider?.bindToLifecycle(
- mockFrontCameraSelector,
- <UseCase>[
- mockVideoCapture,
- mockPreview,
- mockImageCapture,
- mockImageAnalysis,
- ],
- ),
+ camera.processCameraProvider?.bindToLifecycle(mockFrontCameraSelector, <UseCase>[
+ mockVideoCapture,
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).thenAnswer((_) async => newMockCamera);
- when(
- newMockCamera.getCameraInfo(),
- ).thenAnswer((_) async => mockCameraInfo);
+ when(newMockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(newMockCamera.cameraControl).thenReturn(mockCameraControl);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => newMockLiveCameraState);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => newMockLiveCameraState);
// Simulate video recording being started so startVideoRecording completes.
AndroidCameraCameraX.videoRecordingEventStreamController.add(
@@ -3515,31 +2934,24 @@
);
await camera.initializeCamera(flutterSurfaceTextureId);
- await camera.startVideoCapturing(
- VideoCaptureOptions(flutterSurfaceTextureId),
- );
+ await camera.startVideoCapturing(VideoCaptureOptions(flutterSurfaceTextureId));
await camera.setDescriptionWhileRecording(testFrontCameraDescription);
//verify front camera selected and camera properties updated
verify(camera.processCameraProvider?.unbindAll()).called(2);
verify(
- camera.processCameraProvider?.bindToLifecycle(
- mockFrontCameraSelector,
- <UseCase>[
- mockVideoCapture,
- mockPreview,
- mockImageCapture,
- mockImageAnalysis,
- ],
- ),
+ camera.processCameraProvider?.bindToLifecycle(mockFrontCameraSelector, <UseCase>[
+ mockVideoCapture,
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).called(1);
expect(camera.camera, equals(newMockCamera));
expect(camera.cameraInfo, equals(mockCameraInfo));
expect(camera.cameraControl, equals(mockCameraControl));
verify(mockLiveCameraState.removeObservers());
- for (final Object? observer in verify(
- newMockLiveCameraState.observe(captureAny),
- ).captured) {
+ for (final Object? observer in verify(newMockLiveCameraState.observe(captureAny)).captured) {
expect(
await testCameraClosingObserver(
camera,
@@ -3553,15 +2965,12 @@
//verify back camera selected
await camera.setDescriptionWhileRecording(testBackCameraDescription);
verify(
- camera.processCameraProvider?.bindToLifecycle(
- mockBackCameraSelector,
- <UseCase>[
- mockVideoCapture,
- mockPreview,
- mockImageCapture,
- mockImageAnalysis,
- ],
- ),
+ camera.processCameraProvider?.bindToLifecycle(mockBackCameraSelector, <UseCase>[
+ mockVideoCapture,
+ mockPreview,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).called(1);
});
@@ -3607,19 +3016,13 @@
int? targetRotation,
CameraIntegerRange? targetFpsRange,
}) {
- when(
- mockPreview.setSurfaceProvider(any),
- ).thenAnswer((_) async => 19);
- final testResolutionInfo = ResolutionInfo.pigeon_detached(
- resolution: MockCameraSize(),
- );
+ when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => 19);
+ final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize());
when(
mockPreview.surfaceProducerHandlesCropAndRotation(),
).thenAnswer((_) async => false);
when(mockPreview.resolutionSelector).thenReturn(resolutionSelector);
- when(
- mockPreview.getResolutionInfo(),
- ).thenAnswer((_) async => testResolutionInfo);
+ when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo);
return mockPreview;
};
PigeonOverrides.imageCapture_new =
@@ -3631,21 +3034,14 @@
return mockImageCapture;
};
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- QualitySelector? qualitySelector,
- int? targetVideoEncodingBitRate,
- }) {
+ ({int? aspectRatio, QualitySelector? qualitySelector, int? targetVideoEncodingBitRate}) {
when(
mockRecorder.prepareRecording(outputPath),
).thenAnswer((_) async => mockPendingRecording);
return mockRecorder;
};
PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) {
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
return mockVideoCapture;
};
PigeonOverrides.imageAnalysis_new =
@@ -3665,10 +3061,7 @@
return mockBackCameraSelector;
};
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
when(manager.getUiOrientation()).thenAnswer((_) async {
return 'PORTRAIT_UP';
@@ -3689,42 +3082,31 @@
).thenAnswer((_) async => InfoSupportedHardwareLevel.limited);
return camera2cameraInfo;
};
- PigeonOverrides.cameraCharacteristics_sensorOrientation =
- mockCameraCharacteristicsKey;
+ PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey;
GenericsPigeonOverrides.observerNew =
<T>({required void Function(Observer<T>, T) onChanged}) {
return Observer<T>.detached(onChanged: onChanged);
};
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
final mockSystemServicesManager = MockSystemServicesManager();
when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
).thenAnswer((_) async => outputPath);
return mockSystemServicesManager;
};
PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
};
PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
MockCameraCharacteristicsKey();
// mock functions
- when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(
- (_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo],
- );
when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ mockProcessCameraProvider.getAvailableCameraInfos(),
+ ).thenAnswer((_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo]);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
camera.processCameraProvider = mockProcessCameraProvider;
camera.enableRecordingAudio = false;
@@ -3734,22 +3116,12 @@
when(
mockPendingRecording.asPersistentRecording(),
).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.start(any),
- ).thenAnswer((_) async => mockRecording);
- when(
- camera.processCameraProvider!.isBound(mockImageCapture),
- ).thenAnswer((_) async => true);
- when(
- camera.processCameraProvider!.isBound(mockImageAnalysis),
- ).thenAnswer((_) async => true);
+ when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording);
+ when(camera.processCameraProvider!.isBound(mockImageCapture)).thenAnswer((_) async => true);
+ when(camera.processCameraProvider!.isBound(mockImageAnalysis)).thenAnswer((_) async => true);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl);
// Simulate video recording being started so startVideoRecording completes.
@@ -3765,9 +3137,7 @@
);
await camera.initializeCamera(flutterSurfaceTextureId);
- await camera.startVideoCapturing(
- VideoCaptureOptions(flutterSurfaceTextureId),
- );
+ await camera.startVideoCapturing(VideoCaptureOptions(flutterSurfaceTextureId));
// pause the preview
await camera.pausePreview(flutterSurfaceTextureId);
@@ -3777,66 +3147,56 @@
// verify preview not bound to lifecycle
verify(camera.processCameraProvider?.unbindAll()).called(2);
verify(
- camera.processCameraProvider?.bindToLifecycle(
- mockFrontCameraSelector,
- <UseCase>[mockVideoCapture, mockImageCapture, mockImageAnalysis],
- ),
+ camera.processCameraProvider?.bindToLifecycle(mockFrontCameraSelector, <UseCase>[
+ mockVideoCapture,
+ mockImageCapture,
+ mockImageAnalysis,
+ ]),
).called(1);
});
});
- test(
- 'takePicture binds ImageCapture to lifecycle and makes call to take a picture',
- () async {
- final camera = AndroidCameraCameraX();
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockCamera = MockCamera();
- final mockCameraInfo = MockCameraInfo();
- final mockImageCapture = MockImageCapture();
- const testPicturePath = 'test/absolute/path/to/picture';
+ test('takePicture binds ImageCapture to lifecycle and makes call to take a picture', () async {
+ final camera = AndroidCameraCameraX();
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockCamera = MockCamera();
+ final mockCameraInfo = MockCameraInfo();
+ final mockImageCapture = MockImageCapture();
+ const testPicturePath = 'test/absolute/path/to/picture';
- // Set directly for test versus calling createCamera.
- camera.imageCapture = mockImageCapture;
- camera.processCameraProvider = mockProcessCameraProvider;
- camera.cameraSelector = MockCameraSelector();
+ // Set directly for test versus calling createCamera.
+ camera.imageCapture = mockImageCapture;
+ camera.processCameraProvider = mockProcessCameraProvider;
+ camera.cameraSelector = MockCameraSelector();
- // Ignore setting target rotation for this test; tested seprately.
- camera.captureOrientationLocked = true;
+ // Ignore setting target rotation for this test; tested seprately.
+ camera.captureOrientationLocked = true;
- // Tell plugin to create detached camera state observers and mock systemServicesManager.
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
- return MockSystemServicesManager();
- };
+ // Tell plugin to create detached camera state observers and mock systemServicesManager.
+ GenericsPigeonOverrides.observerNew = <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ return MockSystemServicesManager();
+ };
- when(
- mockProcessCameraProvider.isBound(camera.imageCapture),
- ).thenAnswer((_) async => false);
- when(
- mockProcessCameraProvider.bindToLifecycle(
- camera.cameraSelector,
- <UseCase>[camera.imageCapture!],
- ),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
- when(
- mockImageCapture.takePicture(argThat(isA<SystemServicesManager>())),
- ).thenAnswer((_) async => testPicturePath);
+ when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => false);
+ when(
+ mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, <UseCase>[
+ camera.imageCapture!,
+ ]),
+ ).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
+ when(
+ mockImageCapture.takePicture(argThat(isA<SystemServicesManager>())),
+ ).thenAnswer((_) async => testPicturePath);
- final XFile imageFile = await camera.takePicture(3);
+ final XFile imageFile = await camera.takePicture(3);
- expect(imageFile.path, equals(testPicturePath));
- },
- );
+ expect(imageFile.path, equals(testPicturePath));
+ });
test(
'takePicture sets ImageCapture target rotation as expected when orientation locked or unlocked',
@@ -3854,10 +3214,7 @@
// Tell plugin to mock call to get current photo orientation and systemServicesManager.
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final mockDeviceOrientationManager = MockDeviceOrientationManager();
when(
mockDeviceOrientationManager.getDefaultDisplayRotation(),
@@ -3865,15 +3222,11 @@
return mockDeviceOrientationManager;
};
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
return MockSystemServicesManager();
};
- when(
- mockProcessCameraProvider.isBound(camera.imageCapture),
- ).thenAnswer((_) async => true);
+ when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => true);
when(
mockImageCapture.takePicture(argThat(isA<SystemServicesManager>())),
).thenAnswer((_) async => 'test/absolute/path/to/picture');
@@ -3905,94 +3258,80 @@
},
);
- test(
- 'takePicture turns non-torch flash mode off when torch mode enabled',
- () async {
- final camera = AndroidCameraCameraX();
- final mockProcessCameraProvider = MockProcessCameraProvider();
- const cameraId = 77;
+ test('takePicture turns non-torch flash mode off when torch mode enabled', () async {
+ final camera = AndroidCameraCameraX();
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ const cameraId = 77;
- // Set directly for test versus calling createCamera.
- camera.imageCapture = MockImageCapture();
- camera.cameraControl = MockCameraControl();
- camera.processCameraProvider = mockProcessCameraProvider;
+ // Set directly for test versus calling createCamera.
+ camera.imageCapture = MockImageCapture();
+ camera.cameraControl = MockCameraControl();
+ camera.processCameraProvider = mockProcessCameraProvider;
- // Ignore setting target rotation for this test; tested seprately.
- camera.captureOrientationLocked = true;
+ // Ignore setting target rotation for this test; tested seprately.
+ camera.captureOrientationLocked = true;
- // Tell plugin to mock call to get systemServicesManager.
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
- return MockSystemServicesManager();
- };
+ // Tell plugin to mock call to get systemServicesManager.
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ return MockSystemServicesManager();
+ };
- when(
- mockProcessCameraProvider.isBound(camera.imageCapture),
- ).thenAnswer((_) async => true);
+ when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => true);
- await camera.setFlashMode(cameraId, FlashMode.torch);
- await camera.takePicture(cameraId);
- verify(camera.imageCapture!.setFlashMode(CameraXFlashMode.off));
- },
- );
+ await camera.setFlashMode(cameraId, FlashMode.torch);
+ await camera.takePicture(cameraId);
+ verify(camera.imageCapture!.setFlashMode(CameraXFlashMode.off));
+ });
- test(
- 'setFlashMode configures ImageCapture with expected non-torch flash mode',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 22;
- final mockCameraControl = MockCameraControl();
- final mockProcessCameraProvider = MockProcessCameraProvider();
+ test('setFlashMode configures ImageCapture with expected non-torch flash mode', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 22;
+ final mockCameraControl = MockCameraControl();
+ final mockProcessCameraProvider = MockProcessCameraProvider();
- // Set directly for test versus calling createCamera.
- camera.imageCapture = MockImageCapture();
- camera.cameraControl = mockCameraControl;
+ // Set directly for test versus calling createCamera.
+ camera.imageCapture = MockImageCapture();
+ camera.cameraControl = mockCameraControl;
- // Ignore setting target rotation for this test; tested seprately.
- camera.captureOrientationLocked = true;
- camera.processCameraProvider = mockProcessCameraProvider;
+ // Ignore setting target rotation for this test; tested seprately.
+ camera.captureOrientationLocked = true;
+ camera.processCameraProvider = mockProcessCameraProvider;
- // Tell plugin to mock call to get current photo orientation and systemServicesManager.
- PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
- return MockSystemServicesManager();
- };
+ // Tell plugin to mock call to get current photo orientation and systemServicesManager.
+ PigeonOverrides.systemServicesManager_new =
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
+ return MockSystemServicesManager();
+ };
- when(
- mockProcessCameraProvider.isBound(camera.imageCapture),
- ).thenAnswer((_) async => true);
+ when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => true);
- for (final FlashMode flashMode in FlashMode.values) {
- await camera.setFlashMode(cameraId, flashMode);
+ for (final FlashMode flashMode in FlashMode.values) {
+ await camera.setFlashMode(cameraId, flashMode);
- CameraXFlashMode? expectedFlashMode;
- switch (flashMode) {
- case FlashMode.off:
- expectedFlashMode = CameraXFlashMode.off;
- case FlashMode.auto:
- expectedFlashMode = CameraXFlashMode.auto;
- case FlashMode.always:
- expectedFlashMode = CameraXFlashMode.on;
- case FlashMode.torch:
- expectedFlashMode = null;
- }
-
- if (expectedFlashMode == null) {
- // Torch mode enabled and won't be used for configuring image capture.
- continue;
- }
-
- verifyNever(mockCameraControl.enableTorch(true));
- expect(camera.torchEnabled, isFalse);
- await camera.takePicture(cameraId);
- verify(camera.imageCapture!.setFlashMode(expectedFlashMode));
+ CameraXFlashMode? expectedFlashMode;
+ switch (flashMode) {
+ case FlashMode.off:
+ expectedFlashMode = CameraXFlashMode.off;
+ case FlashMode.auto:
+ expectedFlashMode = CameraXFlashMode.auto;
+ case FlashMode.always:
+ expectedFlashMode = CameraXFlashMode.on;
+ case FlashMode.torch:
+ expectedFlashMode = null;
}
- },
- );
+
+ if (expectedFlashMode == null) {
+ // Torch mode enabled and won't be used for configuring image capture.
+ continue;
+ }
+
+ verifyNever(mockCameraControl.enableTorch(true));
+ expect(camera.torchEnabled, isFalse);
+ await camera.takePicture(cameraId);
+ verify(camera.imageCapture!.setFlashMode(expectedFlashMode));
+ }
+ });
test('setFlashMode turns on torch mode as expected', () async {
final camera = AndroidCameraCameraX();
@@ -4008,43 +3347,37 @@
expect(camera.torchEnabled, isTrue);
});
- test(
- 'setFlashMode turns off torch mode when non-torch flash modes set',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 33;
- final mockCameraControl = MockCameraControl();
+ test('setFlashMode turns off torch mode when non-torch flash modes set', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 33;
+ final mockCameraControl = MockCameraControl();
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
- for (final FlashMode flashMode in FlashMode.values) {
- camera.torchEnabled = true;
- await camera.setFlashMode(cameraId, flashMode);
+ for (final FlashMode flashMode in FlashMode.values) {
+ camera.torchEnabled = true;
+ await camera.setFlashMode(cameraId, flashMode);
- switch (flashMode) {
- case FlashMode.off:
- case FlashMode.auto:
- case FlashMode.always:
- verify(mockCameraControl.enableTorch(false));
- expect(camera.torchEnabled, isFalse);
- case FlashMode.torch:
- verifyNever(mockCameraControl.enableTorch(true));
- expect(camera.torchEnabled, true);
- }
+ switch (flashMode) {
+ case FlashMode.off:
+ case FlashMode.auto:
+ case FlashMode.always:
+ verify(mockCameraControl.enableTorch(false));
+ expect(camera.torchEnabled, isFalse);
+ case FlashMode.torch:
+ verifyNever(mockCameraControl.enableTorch(true));
+ expect(camera.torchEnabled, true);
}
- },
- );
+ }
+ });
test('getMinExposureOffset returns expected exposure offset', () async {
final camera = AndroidCameraCameraX();
final mockCameraInfo = MockCameraInfo();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
exposureCompensationStep: 0.2,
);
@@ -4063,10 +3396,7 @@
final mockCameraInfo = MockCameraInfo();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
exposureCompensationStep: 0.2,
);
@@ -4084,10 +3414,7 @@
final mockCameraInfo = MockCameraInfo();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
exposureCompensationStep: 0.2,
);
@@ -4105,10 +3432,7 @@
final camera = AndroidCameraCameraX();
final mockCameraInfo = MockCameraInfo();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 0,
- upper: 0,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 0, upper: 0),
exposureCompensationStep: 0,
);
@@ -4126,17 +3450,12 @@
final mockCameraInfo = MockCameraInfo();
const double maxZoomRatio = 1;
final LiveData<ZoomState> mockLiveZoomState = MockLiveZoomState();
- final zoomState = ZoomState.pigeon_detached(
- maxZoomRatio: maxZoomRatio,
- minZoomRatio: 0,
- );
+ final zoomState = ZoomState.pigeon_detached(maxZoomRatio: maxZoomRatio, minZoomRatio: 0);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
- when(
- mockCameraInfo.getZoomState(),
- ).thenAnswer((_) async => mockLiveZoomState);
+ when(mockCameraInfo.getZoomState()).thenAnswer((_) async => mockLiveZoomState);
when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState);
expect(await camera.getMaxZoomLevel(55), maxZoomRatio);
@@ -4147,17 +3466,12 @@
final mockCameraInfo = MockCameraInfo();
const double minZoomRatio = 0;
final LiveData<ZoomState> mockLiveZoomState = MockLiveZoomState();
- final zoomState = ZoomState.pigeon_detached(
- maxZoomRatio: 1,
- minZoomRatio: minZoomRatio,
- );
+ final zoomState = ZoomState.pigeon_detached(maxZoomRatio: 1, minZoomRatio: minZoomRatio);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
- when(
- mockCameraInfo.getZoomState(),
- ).thenAnswer((_) async => mockLiveZoomState);
+ when(mockCameraInfo.getZoomState()).thenAnswer((_) async => mockLiveZoomState);
when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState);
expect(await camera.getMinZoomLevel(55), minZoomRatio);
@@ -4192,25 +3506,20 @@
// Tell plugin to create detached Camera2CameraControl and
// CaptureRequestOptions instances for testing.
- final controlVideoStabilizationModeKey =
- CaptureRequestKey.pigeon_detached();
- PigeonOverrides.camera2CameraControl_from =
- ({required CameraControl cameraControl}) =>
- cameraControl == mockCameraControl
- ? mockCamera2CameraControl
- : Camera2CameraControl.pigeon_detached();
- PigeonOverrides.captureRequestOptions_new =
- ({required Map<CaptureRequestKey, Object?> options}) {
- final mockCaptureRequestOptions = MockCaptureRequestOptions();
- options.forEach((CaptureRequestKey key, Object? value) {
- when(
- mockCaptureRequestOptions.getCaptureRequestOption(key),
- ).thenAnswer((_) async => value);
- });
- return mockCaptureRequestOptions;
- };
- PigeonOverrides.captureRequest_controlVideoStabilizationMode =
- controlVideoStabilizationModeKey;
+ final controlVideoStabilizationModeKey = CaptureRequestKey.pigeon_detached();
+ PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) =>
+ cameraControl == mockCameraControl
+ ? mockCamera2CameraControl
+ : Camera2CameraControl.pigeon_detached();
+ PigeonOverrides
+ .captureRequestOptions_new = ({required Map<CaptureRequestKey, Object?> options}) {
+ final mockCaptureRequestOptions = MockCaptureRequestOptions();
+ options.forEach((CaptureRequestKey key, Object? value) {
+ when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value);
+ });
+ return mockCaptureRequestOptions;
+ };
+ PigeonOverrides.captureRequest_controlVideoStabilizationMode = controlVideoStabilizationModeKey;
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
when(
@@ -4218,186 +3527,124 @@
).thenAnswer((_) async => <int>[0, 1, 2]);
return mockCamera2CameraInfo;
};
- PigeonOverrides
- .cameraCharacteristics_controlAvailableVideoStabilizationModes =
+ PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes =
MockCameraCharacteristicsKey();
// Test off.
- await camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.off,
- );
+ await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.off);
VerificationResult verificationResult = verify(
mockCamera2CameraControl.addCaptureRequestOptions(captureAny),
);
- var capturedCaptureRequestOptions =
- verificationResult.captured.single as CaptureRequestOptions;
+ var capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions;
expect(
- await capturedCaptureRequestOptions.getCaptureRequestOption(
- controlVideoStabilizationModeKey,
- ),
+ await capturedCaptureRequestOptions.getCaptureRequestOption(controlVideoStabilizationModeKey),
equals(0),
);
clearInteractions(mockCamera2CameraControl);
// Test level1.
- await camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level1,
- );
+ await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1);
- verificationResult = verify(
- mockCamera2CameraControl.addCaptureRequestOptions(captureAny),
- );
- capturedCaptureRequestOptions =
- verificationResult.captured.single as CaptureRequestOptions;
+ verificationResult = verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny));
+ capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions;
expect(
- await capturedCaptureRequestOptions.getCaptureRequestOption(
- controlVideoStabilizationModeKey,
- ),
+ await capturedCaptureRequestOptions.getCaptureRequestOption(controlVideoStabilizationModeKey),
equals(1),
);
});
- test(
- 'setVideoStabilizationMode throws ArgumentError when mode not available',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 102;
- final mockCameraControl = MockCameraControl();
- final mockCamera2CameraControl = MockCamera2CameraControl();
- final mockCameraInfo = MockCameraInfo();
- final mockCamera2CameraInfo = MockCamera2CameraInfo();
+ test('setVideoStabilizationMode throws ArgumentError when mode not available', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 102;
+ final mockCameraControl = MockCameraControl();
+ final mockCamera2CameraControl = MockCamera2CameraControl();
+ final mockCameraInfo = MockCameraInfo();
+ final mockCamera2CameraInfo = MockCamera2CameraInfo();
- // Set directly for test versus calling createCamera.
- camera.camera = MockCamera();
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = mockCameraInfo;
+ // Set directly for test versus calling createCamera.
+ camera.camera = MockCamera();
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = mockCameraInfo;
- // Tell plugin to create detached Camera2CameraControl and
- // CaptureRequestOptions instances for testing.
- final controlVideoStabilizationModeKey =
- CaptureRequestKey.pigeon_detached();
- PigeonOverrides.camera2CameraControl_from =
- ({required CameraControl cameraControl}) =>
- cameraControl == mockCameraControl
- ? mockCamera2CameraControl
- : Camera2CameraControl.pigeon_detached();
- PigeonOverrides.captureRequestOptions_new =
- ({required Map<CaptureRequestKey, Object?> options}) {
- final mockCaptureRequestOptions = MockCaptureRequestOptions();
- options.forEach((CaptureRequestKey key, Object? value) {
- when(
- mockCaptureRequestOptions.getCaptureRequestOption(key),
- ).thenAnswer((_) async => value);
- });
- return mockCaptureRequestOptions;
- };
- PigeonOverrides.captureRequest_controlVideoStabilizationMode =
- controlVideoStabilizationModeKey;
+ // Tell plugin to create detached Camera2CameraControl and
+ // CaptureRequestOptions instances for testing.
+ final controlVideoStabilizationModeKey = CaptureRequestKey.pigeon_detached();
+ PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) =>
+ cameraControl == mockCameraControl
+ ? mockCamera2CameraControl
+ : Camera2CameraControl.pigeon_detached();
+ PigeonOverrides
+ .captureRequestOptions_new = ({required Map<CaptureRequestKey, Object?> options}) {
+ final mockCaptureRequestOptions = MockCaptureRequestOptions();
+ options.forEach((CaptureRequestKey key, Object? value) {
+ when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value);
+ });
+ return mockCaptureRequestOptions;
+ };
+ PigeonOverrides.captureRequest_controlVideoStabilizationMode = controlVideoStabilizationModeKey;
- PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
- when(
- mockCamera2CameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => <int>[0]);
- return mockCamera2CameraInfo;
- };
- PigeonOverrides
- .cameraCharacteristics_controlAvailableVideoStabilizationModes =
- MockCameraCharacteristicsKey();
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level1,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- },
- );
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
+ when(mockCamera2CameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => <int>[0]);
+ return mockCamera2CameraInfo;
+ };
+ PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes =
+ MockCameraCharacteristicsKey();
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ });
- test(
- 'setVideoStabilizationMode throws ArgumentError when mode not mapped',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 102;
- final mockCameraControl = MockCameraControl();
- final mockCamera2CameraControl = MockCamera2CameraControl();
- final mockCameraInfo = MockCameraInfo();
- final mockCamera2CameraInfo = MockCamera2CameraInfo();
+ test('setVideoStabilizationMode throws ArgumentError when mode not mapped', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 102;
+ final mockCameraControl = MockCameraControl();
+ final mockCamera2CameraControl = MockCamera2CameraControl();
+ final mockCameraInfo = MockCameraInfo();
+ final mockCamera2CameraInfo = MockCamera2CameraInfo();
- // Set directly for test versus calling createCamera.
- camera.camera = MockCamera();
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = mockCameraInfo;
+ // Set directly for test versus calling createCamera.
+ camera.camera = MockCamera();
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = mockCameraInfo;
- // Tell plugin to create detached Camera2CameraControl and
- // CaptureRequestOptions instances for testing.
- final controlVideoStabilizationModeKey =
- CaptureRequestKey.pigeon_detached();
- PigeonOverrides.camera2CameraControl_from =
- ({required CameraControl cameraControl}) =>
- cameraControl == mockCameraControl
- ? mockCamera2CameraControl
- : Camera2CameraControl.pigeon_detached();
- PigeonOverrides.captureRequestOptions_new =
- ({required Map<CaptureRequestKey, Object?> options}) {
- final mockCaptureRequestOptions = MockCaptureRequestOptions();
- options.forEach((CaptureRequestKey key, Object? value) {
- when(
- mockCaptureRequestOptions.getCaptureRequestOption(key),
- ).thenAnswer((_) async => value);
- });
- return mockCaptureRequestOptions;
- };
- PigeonOverrides.captureRequest_controlVideoStabilizationMode =
- controlVideoStabilizationModeKey;
+ // Tell plugin to create detached Camera2CameraControl and
+ // CaptureRequestOptions instances for testing.
+ final controlVideoStabilizationModeKey = CaptureRequestKey.pigeon_detached();
+ PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) =>
+ cameraControl == mockCameraControl
+ ? mockCamera2CameraControl
+ : Camera2CameraControl.pigeon_detached();
+ PigeonOverrides
+ .captureRequestOptions_new = ({required Map<CaptureRequestKey, Object?> options}) {
+ final mockCaptureRequestOptions = MockCaptureRequestOptions();
+ options.forEach((CaptureRequestKey key, Object? value) {
+ when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value);
+ });
+ return mockCaptureRequestOptions;
+ };
+ PigeonOverrides.captureRequest_controlVideoStabilizationMode = controlVideoStabilizationModeKey;
- PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
- when(
- mockCamera2CameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => <int>[0, 1, 2]);
- return mockCamera2CameraInfo;
- };
- PigeonOverrides
- .cameraCharacteristics_controlAvailableVideoStabilizationModes =
- MockCameraCharacteristicsKey();
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
+ when(
+ mockCamera2CameraInfo.getCameraCharacteristic(any),
+ ).thenAnswer((_) async => <int>[0, 1, 2]);
+ return mockCamera2CameraInfo;
+ };
+ PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes =
+ MockCameraCharacteristicsKey();
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level2,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level3,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- },
- );
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level2),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level3),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ });
test('getVideoStabilizationMode returns no available mode', () async {
// Set up mocks and constants.
@@ -4409,19 +3656,17 @@
camera.cameraInfo = mockCameraInfo;
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
- when(
- mockCamera2cameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => <int>[]);
+ when(mockCamera2cameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => <int>[]);
return mockCamera2cameraInfo;
};
- PigeonOverrides
- .cameraCharacteristics_controlAvailableVideoStabilizationModes =
+ PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes =
MockCameraCharacteristicsKey();
const cameraId = 103;
- final Iterable<VideoStabilizationMode> modes = await camera
- .getSupportedVideoStabilizationModes(cameraId);
+ final Iterable<VideoStabilizationMode> modes = await camera.getSupportedVideoStabilizationModes(
+ cameraId,
+ );
expect(modes, orderedEquals(<VideoStabilizationMode>[]));
});
@@ -4442,12 +3687,12 @@
).thenAnswer((_) async => <int>[0, 1, 2]);
return mockCamera2CameraInfo;
};
- PigeonOverrides
- .cameraCharacteristics_controlAvailableVideoStabilizationModes =
+ PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes =
MockCameraCharacteristicsKey();
- final Iterable<VideoStabilizationMode> modes = await camera
- .getSupportedVideoStabilizationModes(cameraId);
+ final Iterable<VideoStabilizationMode> modes = await camera.getSupportedVideoStabilizationModes(
+ cameraId,
+ );
expect(
modes,
@@ -4473,10 +3718,9 @@
const cameraId = 22;
// Tell plugin to create detached Analyzer for testing.
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) {
- return Analyzer.pigeon_detached(analyze: analyze);
- };
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) {
+ return Analyzer.pigeon_detached(analyze: analyze);
+ };
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
@@ -4489,19 +3733,12 @@
when(
mockProcessCameraProvider.bindToLifecycle(any, any),
).thenAnswer((_) => Future<Camera>.value(mockCamera));
- when(
- mockProcessCameraProvider.isBound(camera.imageAnalysis),
- ).thenAnswer((_) async => true);
- when(
- mockCamera.getCameraInfo(),
- ).thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockProcessCameraProvider.isBound(camera.imageAnalysis)).thenAnswer((_) async => true);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
final CameraImageData mockCameraImageData = MockCameraImageData();
- final Stream<CameraImageData> imageStream = camera
- .onStreamedFrameAvailable(cameraId);
+ final Stream<CameraImageData> imageStream = camera.onStreamedFrameAvailable(cameraId);
final streamQueue = StreamQueue<CameraImageData>(imageStream);
camera.cameraImageDataStreamController!.add(mockCameraImageData);
@@ -4519,10 +3756,9 @@
const cameraId = 22;
// Tell plugin to create detached Analyzer for testing.
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) {
- return Analyzer.pigeon_detached(analyze: analyze);
- };
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) {
+ return Analyzer.pigeon_detached(analyze: analyze);
+ };
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
@@ -4532,22 +3768,19 @@
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
- when(
- mockProcessCameraProvider.isBound(camera.imageAnalysis),
- ).thenAnswer((_) async => true);
+ when(mockProcessCameraProvider.isBound(camera.imageAnalysis)).thenAnswer((_) async => true);
final CameraImageData mockCameraImageData = MockCameraImageData();
- final Stream<CameraImageData> imageStream = camera
- .onStreamedFrameAvailable(cameraId);
+ final Stream<CameraImageData> imageStream = camera.onStreamedFrameAvailable(cameraId);
// Listen to image stream.
- final StreamSubscription<CameraImageData> imageStreamSubscription =
- imageStream.listen((CameraImageData data) {});
+ final StreamSubscription<CameraImageData> imageStreamSubscription = imageStream.listen(
+ (CameraImageData data) {},
+ );
// Cancel subscription to image stream.
await imageStreamSubscription.cancel();
- final Stream<CameraImageData> imageStream2 = camera
- .onStreamedFrameAvailable(cameraId);
+ final Stream<CameraImageData> imageStream2 = camera.onStreamedFrameAvailable(cameraId);
// Listen to image stream again.
final streamQueue = StreamQueue<CameraImageData>(imageStream2);
@@ -4563,8 +3796,7 @@
() async {
final camera = AndroidCameraCameraX();
const cameraId = 33;
- final ProcessCameraProvider mockProcessCameraProvider =
- MockProcessCameraProvider();
+ final ProcessCameraProvider mockProcessCameraProvider = MockProcessCameraProvider();
final CameraSelector mockCameraSelector = MockCameraSelector();
final mockImageAnalysis = MockImageAnalysis();
final Camera mockCamera = MockCamera();
@@ -4580,10 +3812,9 @@
const imageWidth = 200;
// Tell plugin to create detached Analyzer for testing.
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) {
- return Analyzer.pigeon_detached(analyze: analyze);
- };
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) {
+ return Analyzer.pigeon_detached(analyze: analyze);
+ };
GenericsPigeonOverrides.observerNew =
<T>({required void Function(Observer<T>, T) onChanged}) {
return Observer<T>.detached(onChanged: onChanged);
@@ -4597,18 +3828,12 @@
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
+ when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => false);
when(
- mockProcessCameraProvider.isBound(mockImageAnalysis),
- ).thenAnswer((_) async => false);
- when(
- mockProcessCameraProvider.bindToLifecycle(mockCameraSelector, <UseCase>[
- mockImageAnalysis,
- ]),
+ mockProcessCameraProvider.bindToLifecycle(mockCameraSelector, <UseCase>[mockImageAnalysis]),
).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
when(
mockImageProxy.getPlanes(),
).thenAnswer((_) async => Future<List<PlaneProxy>>.value(mockPlanes));
@@ -4620,8 +3845,7 @@
when(mockImageProxy.width).thenReturn(imageWidth);
final imageDataCompleter = Completer<CameraImageData>();
- final StreamSubscription<CameraImageData>
- onStreamedFrameAvailableSubscription = camera
+ final StreamSubscription<CameraImageData> onStreamedFrameAvailableSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData imageData) {
imageDataCompleter.complete(imageData);
@@ -4630,8 +3854,7 @@
// Test ImageAnalysis use case is bound to ProcessCameraProvider.
await untilCalled(mockImageAnalysis.setAnalyzer(any));
final capturedAnalyzer =
- verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single
- as Analyzer;
+ verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single as Analyzer;
capturedAnalyzer.analyze(MockAnalyzer(), mockImageProxy);
@@ -4664,13 +3887,9 @@
final testNv21Buffer = Uint8List(10);
// Mock use case bindings and related Camera objects.
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
// Set up CameraXProxy with ImageAnalysis specifics needed for testing its Analyzer.
setUpOverridesForTestingUseCaseConfiguration(
@@ -4685,9 +3904,8 @@
int? targetRotation,
CameraIntegerRange? targetFpsRange,
}) => mockImageAnalysis,
- getNv21BufferImageProxyUtils:
- (int imageWidth, int imageHeight, List<PlaneProxy> planes) =>
- Future<Uint8List>.value(testNv21Buffer),
+ getNv21BufferImageProxyUtils: (int imageWidth, int imageHeight, List<PlaneProxy> planes) =>
+ Future<Uint8List>.value(testNv21Buffer),
);
// Create and initialize camera with NV21.
@@ -4699,10 +3917,7 @@
),
ResolutionPreset.low,
);
- await camera.initializeCamera(
- cameraId,
- imageFormatGroup: ImageFormatGroup.nv21,
- );
+ await camera.initializeCamera(cameraId, imageFormatGroup: ImageFormatGroup.nv21);
// Create mock ImageProxy with theoretical underlying NV21 format but with three
// planes still in YUV_420_888 format that should get transformed to testNv21Buffer.
@@ -4718,8 +3933,7 @@
await untilCalled(mockImageAnalysis.setAnalyzer(any));
final capturedAnalyzer =
- verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single
- as Analyzer;
+ verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single as Analyzer;
capturedAnalyzer.analyze(MockAnalyzer(), mockImageProxy);
final CameraImageData imageData = await imageDataCompleter.future;
@@ -4749,13 +3963,10 @@
camera.captureOrientationLocked = true;
// Tell plugin to create a detached analyzer for testing purposes.
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) =>
- MockAnalyzer();
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) =>
+ MockAnalyzer();
- when(
- mockProcessCameraProvider.isBound(mockImageAnalysis),
- ).thenAnswer((_) async => true);
+ when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => true);
final StreamSubscription<CameraImageData> imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
@@ -4782,14 +3993,10 @@
// Tell plugin to create a detached analyzer for testing purposes and mock
// call to get current photo orientation.
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) =>
- MockAnalyzer();
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) =>
+ MockAnalyzer();
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) {
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) {
final manager = MockDeviceOrientationManager();
when(manager.getDefaultDisplayRotation()).thenAnswer((_) async {
return defaultTargetRotation;
@@ -4797,9 +4004,7 @@
return manager;
};
- when(
- mockProcessCameraProvider.isBound(mockImageAnalysis),
- ).thenAnswer((_) async => true);
+ when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => true);
// Orientation is unlocked and plugin does not need to set default target
// rotation manually.
@@ -4838,9 +4043,7 @@
imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData data) {});
- await untilCalled(
- mockImageAnalysis.setTargetRotation(defaultTargetRotation),
- );
+ await untilCalled(mockImageAnalysis.setTargetRotation(defaultTargetRotation));
await imageStreamSubscription.cancel();
},
);
@@ -4900,163 +4103,134 @@
},
);
- test(
- 'setExposureMode sets expected controlAeLock value via Camera2 interop',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 78;
- final mockCameraControl = MockCameraControl();
- final mockCamera2CameraControl = MockCamera2CameraControl();
+ test('setExposureMode sets expected controlAeLock value via Camera2 interop', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 78;
+ final mockCameraControl = MockCameraControl();
+ final mockCamera2CameraControl = MockCamera2CameraControl();
- // Set directly for test versus calling createCamera.
- camera.camera = MockCamera();
- camera.cameraControl = mockCameraControl;
+ // Set directly for test versus calling createCamera.
+ camera.camera = MockCamera();
+ camera.cameraControl = mockCameraControl;
- // Tell plugin to create detached Camera2CameraControl and
- // CaptureRequestOptions instances for testing.
- final controlAELockKey = CaptureRequestKey.pigeon_detached();
- PigeonOverrides.camera2CameraControl_from =
- ({required CameraControl cameraControl}) =>
- cameraControl == mockCameraControl
- ? mockCamera2CameraControl
- : Camera2CameraControl.pigeon_detached();
- PigeonOverrides.captureRequestOptions_new =
- ({required Map<CaptureRequestKey, Object?> options}) {
- final mockCaptureRequestOptions = MockCaptureRequestOptions();
- options.forEach((CaptureRequestKey key, Object? value) {
- when(
- mockCaptureRequestOptions.getCaptureRequestOption(key),
- ).thenAnswer((_) async => value);
- });
- return mockCaptureRequestOptions;
- };
- PigeonOverrides.captureRequest_controlAELock = controlAELockKey;
+ // Tell plugin to create detached Camera2CameraControl and
+ // CaptureRequestOptions instances for testing.
+ final controlAELockKey = CaptureRequestKey.pigeon_detached();
+ PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) =>
+ cameraControl == mockCameraControl
+ ? mockCamera2CameraControl
+ : Camera2CameraControl.pigeon_detached();
+ PigeonOverrides
+ .captureRequestOptions_new = ({required Map<CaptureRequestKey, Object?> options}) {
+ final mockCaptureRequestOptions = MockCaptureRequestOptions();
+ options.forEach((CaptureRequestKey key, Object? value) {
+ when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value);
+ });
+ return mockCaptureRequestOptions;
+ };
+ PigeonOverrides.captureRequest_controlAELock = controlAELockKey;
- // Test auto mode.
- await camera.setExposureMode(cameraId, ExposureMode.auto);
+ // Test auto mode.
+ await camera.setExposureMode(cameraId, ExposureMode.auto);
- VerificationResult verificationResult = verify(
- mockCamera2CameraControl.addCaptureRequestOptions(captureAny),
- );
- var capturedCaptureRequestOptions =
- verificationResult.captured.single as CaptureRequestOptions;
- expect(
- await capturedCaptureRequestOptions.getCaptureRequestOption(
- controlAELockKey,
- ),
- isFalse,
- );
+ VerificationResult verificationResult = verify(
+ mockCamera2CameraControl.addCaptureRequestOptions(captureAny),
+ );
+ var capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions;
+ expect(await capturedCaptureRequestOptions.getCaptureRequestOption(controlAELockKey), isFalse);
- // Test locked mode.
- clearInteractions(mockCamera2CameraControl);
- await camera.setExposureMode(cameraId, ExposureMode.locked);
+ // Test locked mode.
+ clearInteractions(mockCamera2CameraControl);
+ await camera.setExposureMode(cameraId, ExposureMode.locked);
- verificationResult = verify(
- mockCamera2CameraControl.addCaptureRequestOptions(captureAny),
- );
- capturedCaptureRequestOptions =
- verificationResult.captured.single as CaptureRequestOptions;
- expect(
- await capturedCaptureRequestOptions.getCaptureRequestOption(
- controlAELockKey,
- ),
- isTrue,
- );
- },
- );
+ verificationResult = verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny));
+ capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions;
+ expect(await capturedCaptureRequestOptions.getCaptureRequestOption(controlAELockKey), isTrue);
+ });
- test(
- 'setExposurePoint clears current auto-exposure metering point as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 93;
- final mockCameraControl = MockCameraControl();
- final mockCameraInfo = MockCameraInfo();
+ test('setExposurePoint clears current auto-exposure metering point as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 93;
+ final mockCameraControl = MockCameraControl();
+ final mockCameraInfo = MockCameraInfo();
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = mockCameraInfo;
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = mockCameraInfo;
- final mockActionBuilder = MockFocusMeteringActionBuilder();
- when(mockActionBuilder.build()).thenAnswer(
- (_) async => FocusMeteringAction.pigeon_detached(
- meteringPointsAe: const <MeteringPoint>[],
- meteringPointsAf: const <MeteringPoint>[],
- meteringPointsAwb: const <MeteringPoint>[],
- isAutoCancelEnabled: false,
- ),
- );
- MeteringMode? actionBuilderMeteringMode;
- MeteringPoint? actionBuilderMeteringPoint;
- setUpOverridesForExposureAndFocus(
- withModeFocusMeteringActionBuilder:
- ({required MeteringMode mode, required MeteringPoint point}) {
- actionBuilderMeteringMode = mode;
- actionBuilderMeteringPoint = point;
- return mockActionBuilder;
- },
- );
-
- // Verify nothing happens if no current focus and metering action has been
- // enabled.
- await camera.setExposurePoint(cameraId, null);
- verifyNever(mockCameraControl.startFocusAndMetering(any));
- verifyNever(mockCameraControl.cancelFocusAndMetering());
-
- // Verify current auto-exposure metering point is removed if previously set.
- final originalMeteringAction = FocusMeteringAction.pigeon_detached(
- meteringPointsAe: <MeteringPoint>[MeteringPoint.pigeon_detached()],
- meteringPointsAf: <MeteringPoint>[MeteringPoint.pigeon_detached()],
- meteringPointsAwb: const <MeteringPoint>[],
- isAutoCancelEnabled: false,
- );
- camera.currentFocusMeteringAction = originalMeteringAction;
-
- await camera.setExposurePoint(cameraId, null);
-
- expect(actionBuilderMeteringMode, MeteringMode.af);
- expect(
- actionBuilderMeteringPoint,
- originalMeteringAction.meteringPointsAf.single,
- );
- verifyNever(mockActionBuilder.addPoint(any));
- verifyNever(mockActionBuilder.addPointWithMode(any, any));
-
- // Verify current focus and metering action is cleared if only previously
- // set metering point was for auto-exposure.
- camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached(
- meteringPointsAe: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ final mockActionBuilder = MockFocusMeteringActionBuilder();
+ when(mockActionBuilder.build()).thenAnswer(
+ (_) async => FocusMeteringAction.pigeon_detached(
+ meteringPointsAe: const <MeteringPoint>[],
meteringPointsAf: const <MeteringPoint>[],
meteringPointsAwb: const <MeteringPoint>[],
isAutoCancelEnabled: false,
- );
+ ),
+ );
+ MeteringMode? actionBuilderMeteringMode;
+ MeteringPoint? actionBuilderMeteringPoint;
+ setUpOverridesForExposureAndFocus(
+ withModeFocusMeteringActionBuilder:
+ ({required MeteringMode mode, required MeteringPoint point}) {
+ actionBuilderMeteringMode = mode;
+ actionBuilderMeteringPoint = point;
+ return mockActionBuilder;
+ },
+ );
- await camera.setExposurePoint(cameraId, null);
+ // Verify nothing happens if no current focus and metering action has been
+ // enabled.
+ await camera.setExposurePoint(cameraId, null);
+ verifyNever(mockCameraControl.startFocusAndMetering(any));
+ verifyNever(mockCameraControl.cancelFocusAndMetering());
- verify(mockCameraControl.cancelFocusAndMetering());
- },
- );
+ // Verify current auto-exposure metering point is removed if previously set.
+ final originalMeteringAction = FocusMeteringAction.pigeon_detached(
+ meteringPointsAe: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAf: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAwb: const <MeteringPoint>[],
+ isAutoCancelEnabled: false,
+ );
+ camera.currentFocusMeteringAction = originalMeteringAction;
- test(
- 'setExposurePoint throws CameraException if invalid point specified',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 23;
- final mockCameraControl = MockCameraControl();
- const invalidExposurePoint = Point<double>(3, -1);
+ await camera.setExposurePoint(cameraId, null);
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = MockCameraInfo();
+ expect(actionBuilderMeteringMode, MeteringMode.af);
+ expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAf.single);
+ verifyNever(mockActionBuilder.addPoint(any));
+ verifyNever(mockActionBuilder.addPointWithMode(any, any));
- setUpOverridesForExposureAndFocus();
+ // Verify current focus and metering action is cleared if only previously
+ // set metering point was for auto-exposure.
+ camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached(
+ meteringPointsAe: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAf: const <MeteringPoint>[],
+ meteringPointsAwb: const <MeteringPoint>[],
+ isAutoCancelEnabled: false,
+ );
- expect(
- () => camera.setExposurePoint(cameraId, invalidExposurePoint),
- throwsA(isA<CameraException>()),
- );
- },
- );
+ await camera.setExposurePoint(cameraId, null);
+
+ verify(mockCameraControl.cancelFocusAndMetering());
+ });
+
+ test('setExposurePoint throws CameraException if invalid point specified', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 23;
+ final mockCameraControl = MockCameraControl();
+ const invalidExposurePoint = Point<double>(3, -1);
+
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = MockCameraInfo();
+
+ setUpOverridesForExposureAndFocus();
+
+ expect(
+ () => camera.setExposurePoint(cameraId, invalidExposurePoint),
+ throwsA(isA<CameraException>()),
+ );
+ });
test(
'setExposurePoint adds new exposure point to focus metering action to start as expected when previous metering points have been set',
@@ -5086,11 +4260,7 @@
);
setUpOverridesForExposureAndFocus(
newDisplayOrientedMeteringPointFactory:
- ({
- required dynamic cameraInfo,
- required double width,
- required double height,
- }) {
+ ({required dynamic cameraInfo, required double width, required double height}) {
final mockFactory = MockDisplayOrientedMeteringPointFactory();
when(
mockFactory.createPoint(exposurePointX, exposurePointY),
@@ -5117,17 +4287,9 @@
await camera.setExposurePoint(cameraId, exposurePoint);
- expect(
- actionBuilderMeteringPoint,
- originalMeteringAction.meteringPointsAf.single,
- );
+ expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAf.single);
expect(actionBuilderMeteringMode, MeteringMode.af);
- verify(
- mockActionBuilder.addPointWithMode(
- createdMeteringPoint,
- MeteringMode.ae,
- ),
- );
+ verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.ae));
// Verify exposure point is set when no auto-exposure metering point
// previously set, but an auto-focus point metering point has been.
@@ -5144,17 +4306,9 @@
await camera.setExposurePoint(cameraId, exposurePoint);
- expect(
- actionBuilderMeteringPoint,
- originalMeteringAction.meteringPointsAf.single,
- );
+ expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAf.single);
expect(actionBuilderMeteringMode, MeteringMode.af);
- verify(
- mockActionBuilder.addPointWithMode(
- createdMeteringPoint,
- MeteringMode.ae,
- ),
- );
+ verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.ae));
},
);
@@ -5187,11 +4341,7 @@
);
setUpOverridesForExposureAndFocus(
newDisplayOrientedMeteringPointFactory:
- ({
- required dynamic cameraInfo,
- required double width,
- required double height,
- }) {
+ ({required dynamic cameraInfo, required double width, required double height}) {
final mockFactory = MockDisplayOrientedMeteringPointFactory();
when(
mockFactory.createPoint(exposurePointX, exposurePointY),
@@ -5213,83 +4363,63 @@
},
);
- test(
- 'setExposurePoint disables auto-cancel for focus and metering as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 2;
- final mockCameraControl = MockCameraControl();
- final FocusMeteringResult mockFocusMeteringResult =
- MockFocusMeteringResult();
- const exposurePoint = Point<double>(0.1, 0.2);
+ test('setExposurePoint disables auto-cancel for focus and metering as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 2;
+ final mockCameraControl = MockCameraControl();
+ final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult();
+ const exposurePoint = Point<double>(0.1, 0.2);
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = MockCameraInfo();
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
- // Make setting focus and metering action successful for test.
- when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ // Make setting focus and metering action successful for test.
+ when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
- // Test not disabling auto cancel.
- await camera.setFocusMode(cameraId, FocusMode.auto);
- clearInteractions(mockCameraControl);
- await camera.setExposurePoint(cameraId, exposurePoint);
- VerificationResult verificationResult = verify(
- mockCameraControl.startFocusAndMetering(captureAny),
- );
- var capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
- expect(capturedAction.isAutoCancelEnabled, isTrue);
+ // Test not disabling auto cancel.
+ await camera.setFocusMode(cameraId, FocusMode.auto);
+ clearInteractions(mockCameraControl);
+ await camera.setExposurePoint(cameraId, exposurePoint);
+ VerificationResult verificationResult = verify(
+ mockCameraControl.startFocusAndMetering(captureAny),
+ );
+ var capturedAction = verificationResult.captured.single as FocusMeteringAction;
+ expect(capturedAction.isAutoCancelEnabled, isTrue);
- clearInteractions(mockCameraControl);
+ clearInteractions(mockCameraControl);
- // Test disabling auto cancel.
- await camera.setFocusMode(cameraId, FocusMode.locked);
- clearInteractions(mockCameraControl);
- await camera.setExposurePoint(cameraId, exposurePoint);
- verificationResult = verify(
- mockCameraControl.startFocusAndMetering(captureAny),
- );
- capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
- expect(capturedAction.isAutoCancelEnabled, isFalse);
- },
- );
+ // Test disabling auto cancel.
+ await camera.setFocusMode(cameraId, FocusMode.locked);
+ clearInteractions(mockCameraControl);
+ await camera.setExposurePoint(cameraId, exposurePoint);
+ verificationResult = verify(mockCameraControl.startFocusAndMetering(captureAny));
+ capturedAction = verificationResult.captured.single as FocusMeteringAction;
+ expect(capturedAction.isAutoCancelEnabled, isFalse);
+ });
- test(
- 'setExposureOffset throws exception if exposure compensation not supported',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 6;
- const double offset = 2;
- final mockCameraInfo = MockCameraInfo();
- final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
- exposureCompensationStep: 0,
- );
+ test('setExposureOffset throws exception if exposure compensation not supported', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 6;
+ const double offset = 2;
+ final mockCameraInfo = MockCameraInfo();
+ final exposureState = ExposureState.pigeon_detached(
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
+ exposureCompensationStep: 0,
+ );
- // Set directly for test versus calling createCamera.
- camera.cameraInfo = mockCameraInfo;
+ // Set directly for test versus calling createCamera.
+ camera.cameraInfo = mockCameraInfo;
- when(mockCameraInfo.exposureState).thenReturn(exposureState);
+ when(mockCameraInfo.exposureState).thenReturn(exposureState);
- expect(
- () => camera.setExposureOffset(cameraId, offset),
- throwsA(isA<CameraException>()),
- );
- },
- );
+ expect(() => camera.setExposureOffset(cameraId, offset), throwsA(isA<CameraException>()));
+ });
test(
'setExposureOffset throws exception if exposure compensation could not be set for unknown reason',
@@ -5300,10 +4430,7 @@
final mockCameraInfo = MockCameraInfo();
final CameraControl mockCameraControl = MockCameraControl();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
exposureCompensationStep: 0.2,
);
@@ -5315,15 +4442,11 @@
when(mockCameraControl.setExposureCompensationIndex(15)).thenThrow(
PlatformException(
code: 'TEST_ERROR',
- message:
- 'This is a test error message indicating exposure offset could not be set.',
+ message: 'This is a test error message indicating exposure offset could not be set.',
),
);
- expect(
- () => camera.setExposureOffset(cameraId, offset),
- throwsA(isA<CameraException>()),
- );
+ expect(() => camera.setExposureOffset(cameraId, offset), throwsA(isA<CameraException>()));
},
);
@@ -5336,10 +4459,7 @@
final mockCameraInfo = MockCameraInfo();
final CameraControl mockCameraControl = MockCameraControl();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
exposureCompensationStep: 0.1,
);
final int expectedExposureCompensationIndex =
@@ -5351,15 +4471,10 @@
when(mockCameraInfo.exposureState).thenReturn(exposureState);
when(
- mockCameraControl.setExposureCompensationIndex(
- expectedExposureCompensationIndex,
- ),
+ mockCameraControl.setExposureCompensationIndex(expectedExposureCompensationIndex),
).thenAnswer((_) async => Future<int?>.value());
- expect(
- () => camera.setExposureOffset(cameraId, offset),
- throwsA(isA<CameraException>()),
- );
+ expect(() => camera.setExposureOffset(cameraId, offset), throwsA(isA<CameraException>()));
},
);
@@ -5372,10 +4487,7 @@
final mockCameraInfo = MockCameraInfo();
final CameraControl mockCameraControl = MockCameraControl();
final exposureState = ExposureState.pigeon_detached(
- exposureCompensationRange: CameraIntegerRange.pigeon_detached(
- lower: 3,
- upper: 4,
- ),
+ exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4),
exposureCompensationStep: 0.2,
);
final int expectedExposureCompensationIndex =
@@ -5387,14 +4499,10 @@
when(mockCameraInfo.exposureState).thenReturn(exposureState);
when(
- mockCameraControl.setExposureCompensationIndex(
- expectedExposureCompensationIndex,
- ),
+ mockCameraControl.setExposureCompensationIndex(expectedExposureCompensationIndex),
).thenAnswer(
(_) async => Future<int>.value(
- (expectedExposureCompensationIndex *
- exposureState.exposureCompensationStep)
- .round(),
+ (expectedExposureCompensationIndex * exposureState.exposureCompensationStep).round(),
),
);
@@ -5404,97 +4512,88 @@
},
);
- test(
- 'setFocusPoint clears current auto-exposure metering point as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 93;
- final mockCameraControl = MockCameraControl();
- final mockCameraInfo = MockCameraInfo();
+ test('setFocusPoint clears current auto-exposure metering point as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 93;
+ final mockCameraControl = MockCameraControl();
+ final mockCameraInfo = MockCameraInfo();
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = mockCameraInfo;
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = mockCameraInfo;
- final mockActionBuilder = MockFocusMeteringActionBuilder();
- when(mockActionBuilder.build()).thenAnswer(
- (_) async => FocusMeteringAction.pigeon_detached(
- meteringPointsAe: const <MeteringPoint>[],
- meteringPointsAf: const <MeteringPoint>[],
- meteringPointsAwb: const <MeteringPoint>[],
- isAutoCancelEnabled: false,
- ),
- );
- MeteringMode? actionBuilderMeteringMode;
- MeteringPoint? actionBuilderMeteringPoint;
- setUpOverridesForExposureAndFocus(
- withModeFocusMeteringActionBuilder:
- ({required MeteringMode mode, required MeteringPoint point}) {
- actionBuilderMeteringMode = mode;
- actionBuilderMeteringPoint = point;
- return mockActionBuilder;
- },
- );
-
- // Verify nothing happens if no current focus and metering action has been
- // enabled.
- await camera.setFocusPoint(cameraId, null);
- verifyNever(mockCameraControl.startFocusAndMetering(any));
- verifyNever(mockCameraControl.cancelFocusAndMetering());
-
- final originalMeteringAction = FocusMeteringAction.pigeon_detached(
- meteringPointsAe: <MeteringPoint>[MeteringPoint.pigeon_detached()],
- meteringPointsAf: <MeteringPoint>[MeteringPoint.pigeon_detached()],
- meteringPointsAwb: const <MeteringPoint>[],
- isAutoCancelEnabled: false,
- );
- camera.currentFocusMeteringAction = originalMeteringAction;
-
- await camera.setFocusPoint(cameraId, null);
-
- expect(actionBuilderMeteringMode, MeteringMode.ae);
- expect(
- actionBuilderMeteringPoint,
- originalMeteringAction.meteringPointsAe.single,
- );
- verifyNever(mockActionBuilder.addPoint(any));
- verifyNever(mockActionBuilder.addPointWithMode(any, any));
-
- // Verify current focus and metering action is cleared if only previously
- // set metering point was for auto-exposure.
- camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached(
+ final mockActionBuilder = MockFocusMeteringActionBuilder();
+ when(mockActionBuilder.build()).thenAnswer(
+ (_) async => FocusMeteringAction.pigeon_detached(
meteringPointsAe: const <MeteringPoint>[],
- meteringPointsAf: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAf: const <MeteringPoint>[],
meteringPointsAwb: const <MeteringPoint>[],
isAutoCancelEnabled: false,
- );
+ ),
+ );
+ MeteringMode? actionBuilderMeteringMode;
+ MeteringPoint? actionBuilderMeteringPoint;
+ setUpOverridesForExposureAndFocus(
+ withModeFocusMeteringActionBuilder:
+ ({required MeteringMode mode, required MeteringPoint point}) {
+ actionBuilderMeteringMode = mode;
+ actionBuilderMeteringPoint = point;
+ return mockActionBuilder;
+ },
+ );
- await camera.setFocusPoint(cameraId, null);
+ // Verify nothing happens if no current focus and metering action has been
+ // enabled.
+ await camera.setFocusPoint(cameraId, null);
+ verifyNever(mockCameraControl.startFocusAndMetering(any));
+ verifyNever(mockCameraControl.cancelFocusAndMetering());
- verify(mockCameraControl.cancelFocusAndMetering());
- },
- );
+ final originalMeteringAction = FocusMeteringAction.pigeon_detached(
+ meteringPointsAe: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAf: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAwb: const <MeteringPoint>[],
+ isAutoCancelEnabled: false,
+ );
+ camera.currentFocusMeteringAction = originalMeteringAction;
- test(
- 'setFocusPoint throws CameraException if invalid point specified',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 23;
- final mockCameraControl = MockCameraControl();
- const invalidFocusPoint = Point<double>(-3, 1);
+ await camera.setFocusPoint(cameraId, null);
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = MockCameraInfo();
+ expect(actionBuilderMeteringMode, MeteringMode.ae);
+ expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAe.single);
+ verifyNever(mockActionBuilder.addPoint(any));
+ verifyNever(mockActionBuilder.addPointWithMode(any, any));
- setUpOverridesForExposureAndFocus();
+ // Verify current focus and metering action is cleared if only previously
+ // set metering point was for auto-exposure.
+ camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached(
+ meteringPointsAe: const <MeteringPoint>[],
+ meteringPointsAf: <MeteringPoint>[MeteringPoint.pigeon_detached()],
+ meteringPointsAwb: const <MeteringPoint>[],
+ isAutoCancelEnabled: false,
+ );
- expect(
- () => camera.setFocusPoint(cameraId, invalidFocusPoint),
- throwsA(isA<CameraException>()),
- );
- },
- );
+ await camera.setFocusPoint(cameraId, null);
+
+ verify(mockCameraControl.cancelFocusAndMetering());
+ });
+
+ test('setFocusPoint throws CameraException if invalid point specified', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 23;
+ final mockCameraControl = MockCameraControl();
+ const invalidFocusPoint = Point<double>(-3, 1);
+
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = MockCameraInfo();
+
+ setUpOverridesForExposureAndFocus();
+
+ expect(
+ () => camera.setFocusPoint(cameraId, invalidFocusPoint),
+ throwsA(isA<CameraException>()),
+ );
+ });
test(
'setFocusPoint adds new focus point to focus metering action to start as expected when previous metering points have been set',
@@ -5525,11 +4624,7 @@
);
setUpOverridesForExposureAndFocus(
newDisplayOrientedMeteringPointFactory:
- ({
- required dynamic cameraInfo,
- required double width,
- required double height,
- }) {
+ ({required dynamic cameraInfo, required double width, required double height}) {
final mockFactory = MockDisplayOrientedMeteringPointFactory();
when(
mockFactory.createPoint(focusPointX, focusPointY),
@@ -5555,17 +4650,9 @@
await camera.setFocusPoint(cameraId, focusPoint);
- expect(
- actionBuilderMeteringPoint,
- originalMeteringAction.meteringPointsAe.single,
- );
+ expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAe.single);
expect(actionBuilderMeteringMode, MeteringMode.ae);
- verify(
- mockActionBuilder.addPointWithMode(
- createdMeteringPoint,
- MeteringMode.af,
- ),
- );
+ verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.af));
// Verify exposure point is set when no auto-focus metering point
// previously set, but an auto-exposure point metering point has been.
@@ -5582,17 +4669,9 @@
await camera.setFocusPoint(cameraId, focusPoint);
- expect(
- actionBuilderMeteringPoint,
- originalMeteringAction.meteringPointsAe.single,
- );
+ expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAe.single);
expect(actionBuilderMeteringMode, MeteringMode.ae);
- verify(
- mockActionBuilder.addPointWithMode(
- createdMeteringPoint,
- MeteringMode.af,
- ),
- );
+ verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.af));
},
);
@@ -5625,11 +4704,7 @@
);
setUpOverridesForExposureAndFocus(
newDisplayOrientedMeteringPointFactory:
- ({
- required dynamic cameraInfo,
- required double width,
- required double height,
- }) {
+ ({required dynamic cameraInfo, required double width, required double height}) {
final mockFactory = MockDisplayOrientedMeteringPointFactory();
when(
mockFactory.createPoint(focusPointX, focusPointY),
@@ -5651,57 +4726,47 @@
},
);
- test(
- 'setFocusPoint disables auto-cancel for focus and metering as expected',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 2;
- final mockCameraControl = MockCameraControl();
- final mockFocusMeteringResult = MockFocusMeteringResult();
- const exposurePoint = Point<double>(0.1, 0.2);
+ test('setFocusPoint disables auto-cancel for focus and metering as expected', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 2;
+ final mockCameraControl = MockCameraControl();
+ final mockFocusMeteringResult = MockFocusMeteringResult();
+ const exposurePoint = Point<double>(0.1, 0.2);
- // Set directly for test versus calling createCamera.
- camera.cameraControl = mockCameraControl;
- camera.cameraInfo = MockCameraInfo();
+ // Set directly for test versus calling createCamera.
+ camera.cameraControl = mockCameraControl;
+ camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
- // Make setting focus and metering action successful for test.
- when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ // Make setting focus and metering action successful for test.
+ when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
- // Test not disabling auto cancel.
- await camera.setFocusMode(cameraId, FocusMode.auto);
- clearInteractions(mockCameraControl);
+ // Test not disabling auto cancel.
+ await camera.setFocusMode(cameraId, FocusMode.auto);
+ clearInteractions(mockCameraControl);
- await camera.setFocusPoint(cameraId, exposurePoint);
- VerificationResult verificationResult = verify(
- mockCameraControl.startFocusAndMetering(captureAny),
- );
- var capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
- expect(capturedAction.isAutoCancelEnabled, isTrue);
+ await camera.setFocusPoint(cameraId, exposurePoint);
+ VerificationResult verificationResult = verify(
+ mockCameraControl.startFocusAndMetering(captureAny),
+ );
+ var capturedAction = verificationResult.captured.single as FocusMeteringAction;
+ expect(capturedAction.isAutoCancelEnabled, isTrue);
- clearInteractions(mockCameraControl);
+ clearInteractions(mockCameraControl);
- // Test disabling auto cancel.
- await camera.setFocusMode(cameraId, FocusMode.locked);
- clearInteractions(mockCameraControl);
+ // Test disabling auto cancel.
+ await camera.setFocusMode(cameraId, FocusMode.locked);
+ clearInteractions(mockCameraControl);
- await camera.setFocusPoint(cameraId, exposurePoint);
- verificationResult = verify(
- mockCameraControl.startFocusAndMetering(captureAny),
- );
- capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
- expect(capturedAction.isAutoCancelEnabled, isFalse);
- },
- );
+ await camera.setFocusPoint(cameraId, exposurePoint);
+ verificationResult = verify(mockCameraControl.startFocusAndMetering(captureAny));
+ capturedAction = verificationResult.captured.single as FocusMeteringAction;
+ expect(capturedAction.isAutoCancelEnabled, isFalse);
+ });
test(
'setFocusMode does nothing if setting auto-focus mode and is already using auto-focus mode',
@@ -5715,16 +4780,13 @@
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set locked focus mode and then try to re-set it.
await camera.setFocusMode(cameraId, FocusMode.locked);
@@ -5773,22 +4835,14 @@
mockCameraControl,
mockCamera2CameraControl,
newDisplayOrientedMeteringPointFactory:
- ({
- required dynamic cameraInfo,
- required double width,
- required double height,
- }) {
+ ({required dynamic cameraInfo, required double width, required double height}) {
final mockFactory = MockDisplayOrientedMeteringPointFactory();
- when(
- mockFactory.createPoint(exposurePointX, exposurePointY),
- ).thenAnswer((_) async {
+ when(mockFactory.createPoint(exposurePointX, exposurePointY)).thenAnswer((_) async {
final createdMeteringPoint = MeteringPoint.pigeon_detached();
createdMeteringPoints.add(createdMeteringPoint);
return createdMeteringPoint;
});
- when(mockFactory.createPointWithSize(0.5, 0.5, 1)).thenAnswer((
- _,
- ) async {
+ when(mockFactory.createPointWithSize(0.5, 0.5, 1)).thenAnswer((_) async {
final createdMeteringPoint = MeteringPoint.pigeon_detached();
createdMeteringPoints.add(createdMeteringPoint);
return createdMeteringPoint;
@@ -5799,15 +4853,12 @@
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure points.
- await camera.setExposurePoint(
- cameraId,
- const Point<double>(exposurePointX, exposurePointY),
- );
+ await camera.setExposurePoint(cameraId, const Point<double>(exposurePointX, exposurePointY));
// Lock focus default focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
@@ -5820,8 +4871,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isTrue);
// We expect only the previously set exposure point to be re-set.
@@ -5837,8 +4887,7 @@
final camera = AndroidCameraCameraX();
const cameraId = 5;
final mockCameraControl = MockCameraControl();
- final FocusMeteringResult mockFocusMeteringResult =
- MockFocusMeteringResult();
+ final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult();
final mockCamera2CameraControl = MockCamera2CameraControl();
// Set directly for test versus calling createCamera.
@@ -5849,16 +4898,13 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Lock focus default focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
@@ -5876,8 +4922,7 @@
final camera = AndroidCameraCameraX();
const cameraId = 6;
final mockCameraControl = MockCameraControl();
- final FocusMeteringResult mockFocusMeteringResult =
- MockFocusMeteringResult();
+ final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult();
final mockCamera2CameraControl = MockCamera2CameraControl();
const focusPointX = 0.1;
const focusPointY = 0.2;
@@ -5890,22 +4935,16 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Lock a focus point.
- await camera.setFocusPoint(
- cameraId,
- const Point<double>(focusPointX, focusPointY),
- );
+ await camera.setFocusPoint(cameraId, const Point<double>(focusPointX, focusPointY));
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
@@ -5916,14 +4955,12 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isTrue);
expect(capturedAction.meteringPointsAe.length, equals(0));
expect(capturedAction.meteringPointsAf.length, equals(1));
expect(capturedAction.meteringPointsAwb.length, equals(0));
- final focusPoint =
- capturedAction.meteringPointsAf.single as TestMeteringPoint;
+ final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint;
expect(focusPoint.x, equals(focusPointX));
expect(focusPoint.y, equals(focusPointY));
expect(focusPoint.size, isNull);
@@ -5948,16 +4985,10 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Set a focus point.
- await camera.setFocusPoint(
- cameraId,
- const Point<double>(focusPointX, focusPointY),
- );
+ await camera.setFocusPoint(cameraId, const Point<double>(focusPointX, focusPointY));
clearInteractions(mockCameraControl);
// Lock focus point.
@@ -5966,8 +4997,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isFalse);
// We expect the set focus point to be locked.
@@ -5975,8 +5005,7 @@
expect(capturedAction.meteringPointsAf.length, equals(1));
expect(capturedAction.meteringPointsAwb.length, equals(0));
- final focusPoint =
- capturedAction.meteringPointsAf.single as TestMeteringPoint;
+ final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint;
expect(focusPoint.x, equals(focusPointX));
expect(focusPoint.y, equals(focusPointY));
expect(focusPoint.size, isNull);
@@ -6003,20 +5032,11 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Set focus and exposure points.
- await camera.setFocusPoint(
- cameraId,
- const Point<double>(focusPointX, focusPointY),
- );
- await camera.setExposurePoint(
- cameraId,
- const Point<double>(exposurePointX, exposurePointY),
- );
+ await camera.setFocusPoint(cameraId, const Point<double>(focusPointX, focusPointY));
+ await camera.setExposurePoint(cameraId, const Point<double>(exposurePointX, exposurePointY));
clearInteractions(mockCameraControl);
// Lock focus point.
@@ -6025,8 +5045,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isFalse);
// We expect two MeteringPoints, the set focus point and the set exposure
@@ -6035,14 +5054,12 @@
expect(capturedAction.meteringPointsAf.length, equals(1));
expect(capturedAction.meteringPointsAwb.length, equals(0));
- final focusPoint =
- capturedAction.meteringPointsAf.single as TestMeteringPoint;
+ final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint;
expect(focusPoint.x, equals(focusPointX));
expect(focusPoint.y, equals(focusPointY));
expect(focusPoint.size, isNull);
- final exposurePoint =
- capturedAction.meteringPointsAe.single as TestMeteringPoint;
+ final exposurePoint = capturedAction.meteringPointsAe.single as TestMeteringPoint;
expect(exposurePoint.x, equals(exposurePointX));
expect(exposurePoint.y, equals(exposurePointY));
expect(exposurePoint.size, isNull);
@@ -6070,17 +5087,11 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Set an exposure point (creates a current focus and metering action
// without a focus point).
- await camera.setExposurePoint(
- cameraId,
- const Point<double>(exposurePointX, exposurePointY),
- );
+ await camera.setExposurePoint(cameraId, const Point<double>(exposurePointX, exposurePointY));
clearInteractions(mockCameraControl);
// Lock focus point.
@@ -6089,8 +5100,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isFalse);
// We expect two MeteringPoints, the default focus point and the set
@@ -6099,14 +5109,12 @@
expect(capturedAction.meteringPointsAf.length, equals(1));
expect(capturedAction.meteringPointsAwb.length, equals(0));
- final focusPoint =
- capturedAction.meteringPointsAf.single as TestMeteringPoint;
+ final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint;
expect(focusPoint.x, equals(defaultFocusPointX));
expect(focusPoint.y, equals(defaultFocusPointY));
expect(focusPoint.size, equals(defaultFocusPointSize));
- final exposurePoint =
- capturedAction.meteringPointsAe.single as TestMeteringPoint;
+ final exposurePoint = capturedAction.meteringPointsAe.single as TestMeteringPoint;
expect(exposurePoint.x, equals(exposurePointX));
expect(exposurePoint.y, equals(exposurePointY));
expect(exposurePoint.size, isNull);
@@ -6132,10 +5140,7 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Lock focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
@@ -6143,8 +5148,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isFalse);
// We expect only the default focus point to be set.
@@ -6152,8 +5156,7 @@
expect(capturedAction.meteringPointsAf.length, equals(1));
expect(capturedAction.meteringPointsAwb.length, equals(0));
- final focusPoint =
- capturedAction.meteringPointsAf.single as TestMeteringPoint;
+ final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint;
expect(focusPoint.x, equals(defaultFocusPointX));
expect(focusPoint.y, equals(defaultFocusPointY));
expect(focusPoint.size, equals(defaultFocusPointSize));
@@ -6166,8 +5169,7 @@
final camera = AndroidCameraCameraX();
const cameraId = 11;
final mockCameraControl = MockCameraControl();
- final FocusMeteringResult mockFocusMeteringResult =
- MockFocusMeteringResult();
+ final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult();
final mockCamera2CameraControl = MockCamera2CameraControl();
// Set directly for test versus calling createCamera.
@@ -6178,16 +5180,13 @@
mockCamera2CameraControl.addCaptureRequestOptions(any),
).thenAnswer((_) async => Future<void>.value());
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- mockCamera2CameraControl,
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set auto exposure mode.
await camera.setExposureMode(cameraId, ExposureMode.auto);
@@ -6202,9 +5201,7 @@
final capturedCaptureRequestOptions =
verificationResult.captured.single as CaptureRequestOptions;
expect(
- await capturedCaptureRequestOptions.getCaptureRequestOption(
- CaptureRequest.controlAELock,
- ),
+ await capturedCaptureRequestOptions.getCaptureRequestOption(CaptureRequest.controlAELock),
isFalse,
);
},
@@ -6223,17 +5220,14 @@
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful to set locked focus
// mode.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point (
// otherwise, focus and metering will be canceled altogether, which is
@@ -6258,8 +5252,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isFalse);
},
);
@@ -6277,17 +5270,14 @@
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful to set locked focus
// mode.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point (
// otherwise, focus and metering will be canceled altogether, which is
@@ -6311,8 +5301,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isFalse);
},
);
@@ -6330,17 +5319,14 @@
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action fail to test auto-cancel is not
// disabled.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point.
await camera.setExposurePoint(cameraId, const Point<double>(0.43, 0.34));
@@ -6353,8 +5339,7 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isTrue);
},
);
@@ -6372,17 +5357,14 @@
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
- setUpOverridesForSettingFocusandExposurePoints(
- mockCameraControl,
- MockCamera2CameraControl(),
- );
+ setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action fail to test auto-cancel is not
// disabled.
when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false);
- when(mockCameraControl.startFocusAndMetering(any)).thenAnswer(
- (_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult),
- );
+ when(
+ mockCameraControl.startFocusAndMetering(any),
+ ).thenAnswer((_) async => Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point.
await camera.setExposurePoint(cameraId, const Point<double>(0.5, 0.2));
@@ -6395,67 +5377,54 @@
final VerificationResult verificationResult = verify(
mockCameraControl.startFocusAndMetering(captureAny),
);
- final capturedAction =
- verificationResult.captured.single as FocusMeteringAction;
+ final capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.isAutoCancelEnabled, isTrue);
},
);
- test(
- 'onStreamedFrameAvailable binds ImageAnalysis use case when not already bound',
- () async {
- final camera = AndroidCameraCameraX();
- const cameraId = 22;
- final mockImageAnalysis = MockImageAnalysis();
- final mockProcessCameraProvider = MockProcessCameraProvider();
- final mockCamera = MockCamera();
- final mockCameraInfo = MockCameraInfo();
+ test('onStreamedFrameAvailable binds ImageAnalysis use case when not already bound', () async {
+ final camera = AndroidCameraCameraX();
+ const cameraId = 22;
+ final mockImageAnalysis = MockImageAnalysis();
+ final mockProcessCameraProvider = MockProcessCameraProvider();
+ final mockCamera = MockCamera();
+ final mockCameraInfo = MockCameraInfo();
- // Set directly for test versus calling createCamera.
- camera.imageAnalysis = mockImageAnalysis;
- camera.processCameraProvider = mockProcessCameraProvider;
- camera.cameraSelector = MockCameraSelector();
+ // Set directly for test versus calling createCamera.
+ camera.imageAnalysis = mockImageAnalysis;
+ camera.processCameraProvider = mockProcessCameraProvider;
+ camera.cameraSelector = MockCameraSelector();
- // Ignore setting target rotation for this test; tested seprately.
- camera.captureOrientationLocked = true;
+ // Ignore setting target rotation for this test; tested seprately.
+ camera.captureOrientationLocked = true;
- // Tell plugin to create a detached analyzer for testing purposes.
- PigeonOverrides.analyzer_new =
- ({required void Function(Analyzer, ImageProxy) analyze}) =>
- MockAnalyzer();
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
+ // Tell plugin to create a detached analyzer for testing purposes.
+ PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) =>
+ MockAnalyzer();
+ GenericsPigeonOverrides.observerNew = <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
- when(
- mockProcessCameraProvider.isBound(mockImageAnalysis),
- ).thenAnswer((_) async => false);
- when(
- mockProcessCameraProvider.bindToLifecycle(any, <UseCase>[
- mockImageAnalysis,
- ]),
- ).thenAnswer((_) async => mockCamera);
- when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => false);
+ when(
+ mockProcessCameraProvider.bindToLifecycle(any, <UseCase>[mockImageAnalysis]),
+ ).thenAnswer((_) async => mockCamera);
+ when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
- final StreamSubscription<CameraImageData> imageStreamSubscription = camera
- .onStreamedFrameAvailable(cameraId)
- .listen((CameraImageData data) {});
+ final StreamSubscription<CameraImageData> imageStreamSubscription = camera
+ .onStreamedFrameAvailable(cameraId)
+ .listen((CameraImageData data) {});
- await untilCalled(mockImageAnalysis.setAnalyzer(any));
- verify(
- mockProcessCameraProvider.bindToLifecycle(
- camera.cameraSelector,
- <UseCase>[mockImageAnalysis],
- ),
- );
+ await untilCalled(mockImageAnalysis.setAnalyzer(any));
+ verify(
+ mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, <UseCase>[
+ mockImageAnalysis,
+ ]),
+ );
- await imageStreamSubscription.cancel();
- },
- );
+ await imageStreamSubscription.cancel();
+ });
test(
'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback not specified',
@@ -6486,26 +5455,18 @@
<T>({required void Function(Observer<T>, T) onChanged}) {
return Observer<T>.detached(onChanged: onChanged);
};
- PigeonOverrides.camera2CameraInfo_from =
- ({required dynamic cameraInfo}) => mockCamera2CameraInfo;
+ PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) =>
+ mockCamera2CameraInfo;
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
final mockSystemServicesManager = MockSystemServicesManager();
when(
- mockSystemServicesManager.getTempFilePath(
- camera.videoPrefix,
- '.mp4',
- ),
+ mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'),
).thenAnswer((_) async => outputPath);
return mockSystemServicesManager;
};
PigeonOverrides.videoRecordEventListener_new =
- ({
- required void Function(VideoRecordEventListener, VideoRecordEvent)
- onEvent,
- }) {
+ ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) {
return VideoRecordEventListener.pigeon_detached(onEvent: onEvent);
};
PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel =
@@ -6523,9 +5484,7 @@
when(
mockPendingRecording.asPersistentRecording(),
).thenAnswer((_) async => mockPendingRecording);
- when(
- mockPendingRecording.start(any),
- ).thenAnswer((_) async => mockRecording);
+ when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording);
when(
camera.processCameraProvider!.isBound(camera.videoCapture!),
).thenAnswer((_) async => false);
@@ -6533,17 +5492,12 @@
camera.processCameraProvider!.isBound(camera.imageAnalysis!),
).thenAnswer((_) async => true);
when(
- camera.processCameraProvider!.bindToLifecycle(
- camera.cameraSelector!,
- <UseCase>[camera.videoCapture!],
- ),
+ camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, <UseCase>[
+ camera.videoCapture!,
+ ]),
).thenAnswer((_) async => mockCamera);
- when(
- mockCamera.getCameraInfo(),
- ).thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCamera.getCameraInfo()).thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
when(
mockCamera2CameraInfo.getCameraCharacteristic(any),
).thenAnswer((_) async => InfoSupportedHardwareLevel.level3);
@@ -6555,9 +5509,7 @@
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
- verify(
- camera.processCameraProvider!.unbind(<UseCase>[camera.imageAnalysis!]),
- );
+ verify(camera.processCameraProvider!.unbind(<UseCase>[camera.imageAnalysis!]));
},
);
diff --git a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart
index aa997ef..28eb56c 100644
--- a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart
+++ b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart
@@ -8,8 +8,7 @@
import 'package:camera_android_camerax/src/camerax_library.dart' as _i3;
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2;
-import 'package:camera_platform_interface/camera_platform_interface.dart'
- as _i4;
+import 'package:camera_platform_interface/camera_platform_interface.dart' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i6;
@@ -28,19 +27,16 @@
// ignore_for_file: subtype_of_sealed_class
// ignore_for_file: invalid_use_of_internal_member
-class _FakePigeonInstanceManager_0 extends _i1.SmartFake
- implements _i2.PigeonInstanceManager {
+class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager {
_FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeAnalyzer_1 extends _i1.SmartFake implements _i2.Analyzer {
- _FakeAnalyzer_1(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeAnalyzer_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakeAspectRatioStrategy_2 extends _i1.SmartFake
- implements _i2.AspectRatioStrategy {
+class _FakeAspectRatioStrategy_2 extends _i1.SmartFake implements _i2.AspectRatioStrategy {
_FakeAspectRatioStrategy_2(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -51,13 +47,11 @@
}
class _FakeCameraInfo_4 extends _i1.SmartFake implements _i2.CameraInfo {
- _FakeCameraInfo_4(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeCameraInfo_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeCamera_5 extends _i1.SmartFake implements _i2.Camera {
- _FakeCamera_5(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeCamera_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeExposureState_6 extends _i1.SmartFake implements _i2.ExposureState {
@@ -66,13 +60,11 @@
}
class _FakeLiveData_7<T> extends _i1.SmartFake implements _i3.LiveData<T> {
- _FakeLiveData_7(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeLiveData_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeCameraInfo_8 extends _i1.SmartFake implements _i3.CameraInfo {
- _FakeCameraInfo_8(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeCameraInfo_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeCameraCharacteristicsKey_9 extends _i1.SmartFake
@@ -82,36 +74,30 @@
}
class _FakeCameraSize_10 extends _i1.SmartFake implements _i2.CameraSize {
- _FakeCameraSize_10(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeCameraSize_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakeCamera2CameraControl_11 extends _i1.SmartFake
- implements _i2.Camera2CameraControl {
+class _FakeCamera2CameraControl_11 extends _i1.SmartFake implements _i2.Camera2CameraControl {
_FakeCamera2CameraControl_11(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeCamera2CameraInfo_12 extends _i1.SmartFake
- implements _i2.Camera2CameraInfo {
+class _FakeCamera2CameraInfo_12 extends _i1.SmartFake implements _i2.Camera2CameraInfo {
_FakeCamera2CameraInfo_12(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeCameraImageFormat_13 extends _i1.SmartFake
- implements _i4.CameraImageFormat {
+class _FakeCameraImageFormat_13 extends _i1.SmartFake implements _i4.CameraImageFormat {
_FakeCameraImageFormat_13(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeCameraSelector_14 extends _i1.SmartFake
- implements _i2.CameraSelector {
+class _FakeCameraSelector_14 extends _i1.SmartFake implements _i2.CameraSelector {
_FakeCameraSelector_14(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeCaptureRequestOptions_15 extends _i1.SmartFake
- implements _i2.CaptureRequestOptions {
+class _FakeCaptureRequestOptions_15 extends _i1.SmartFake implements _i2.CaptureRequestOptions {
_FakeCaptureRequestOptions_15(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -124,10 +110,8 @@
class _FakeDisplayOrientedMeteringPointFactory_17 extends _i1.SmartFake
implements _i2.DisplayOrientedMeteringPointFactory {
- _FakeDisplayOrientedMeteringPointFactory_17(
- Object parent,
- Invocation parentInvocation,
- ) : super(parent, parentInvocation);
+ _FakeDisplayOrientedMeteringPointFactory_17(Object parent, Invocation parentInvocation)
+ : super(parent, parentInvocation);
}
class _FakeMeteringPoint_18 extends _i1.SmartFake implements _i2.MeteringPoint {
@@ -135,20 +119,17 @@
: super(parent, parentInvocation);
}
-class _FakeCameraIntegerRange_19 extends _i1.SmartFake
- implements _i2.CameraIntegerRange {
+class _FakeCameraIntegerRange_19 extends _i1.SmartFake implements _i2.CameraIntegerRange {
_FakeCameraIntegerRange_19(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeFallbackStrategy_20 extends _i1.SmartFake
- implements _i2.FallbackStrategy {
+class _FakeFallbackStrategy_20 extends _i1.SmartFake implements _i2.FallbackStrategy {
_FakeFallbackStrategy_20(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeFocusMeteringAction_21 extends _i1.SmartFake
- implements _i2.FocusMeteringAction {
+class _FakeFocusMeteringAction_21 extends _i1.SmartFake implements _i2.FocusMeteringAction {
_FakeFocusMeteringAction_21(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -159,8 +140,7 @@
: super(parent, parentInvocation);
}
-class _FakeFocusMeteringResult_23 extends _i1.SmartFake
- implements _i2.FocusMeteringResult {
+class _FakeFocusMeteringResult_23 extends _i1.SmartFake implements _i2.FocusMeteringResult {
_FakeFocusMeteringResult_23(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -176,80 +156,66 @@
}
class _FakeImageProxy_26 extends _i1.SmartFake implements _i2.ImageProxy {
- _FakeImageProxy_26(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeImageProxy_26(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeObserver_27<T> extends _i1.SmartFake implements _i3.Observer<T> {
- _FakeObserver_27(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeObserver_27(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakePendingRecording_28 extends _i1.SmartFake
- implements _i2.PendingRecording {
+class _FakePendingRecording_28 extends _i1.SmartFake implements _i2.PendingRecording {
_FakePendingRecording_28(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeRecording_29 extends _i1.SmartFake implements _i2.Recording {
- _FakeRecording_29(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeRecording_29(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakePlaneProxy_30 extends _i1.SmartFake implements _i2.PlaneProxy {
- _FakePlaneProxy_30(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakePlaneProxy_30(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakePreview_31 extends _i1.SmartFake implements _i2.Preview {
- _FakePreview_31(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakePreview_31(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakeProcessCameraProvider_32 extends _i1.SmartFake
- implements _i2.ProcessCameraProvider {
+class _FakeProcessCameraProvider_32 extends _i1.SmartFake implements _i2.ProcessCameraProvider {
_FakeProcessCameraProvider_32(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeQualitySelector_33 extends _i1.SmartFake
- implements _i2.QualitySelector {
+class _FakeQualitySelector_33 extends _i1.SmartFake implements _i2.QualitySelector {
_FakeQualitySelector_33(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeRecorder_34 extends _i1.SmartFake implements _i2.Recorder {
- _FakeRecorder_34(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeRecorder_34(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakeResolutionFilter_35 extends _i1.SmartFake
- implements _i2.ResolutionFilter {
+class _FakeResolutionFilter_35 extends _i1.SmartFake implements _i2.ResolutionFilter {
_FakeResolutionFilter_35(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeResolutionSelector_36 extends _i1.SmartFake
- implements _i2.ResolutionSelector {
+class _FakeResolutionSelector_36 extends _i1.SmartFake implements _i2.ResolutionSelector {
_FakeResolutionSelector_36(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeResolutionStrategy_37 extends _i1.SmartFake
- implements _i2.ResolutionStrategy {
+class _FakeResolutionStrategy_37 extends _i1.SmartFake implements _i2.ResolutionStrategy {
_FakeResolutionStrategy_37(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeSystemServicesManager_38 extends _i1.SmartFake
- implements _i2.SystemServicesManager {
+class _FakeSystemServicesManager_38 extends _i1.SmartFake implements _i2.SystemServicesManager {
_FakeSystemServicesManager_38(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeVideoOutput_39 extends _i1.SmartFake implements _i2.VideoOutput {
- _FakeVideoOutput_39(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeVideoOutput_39(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeVideoCapture_40 extends _i1.SmartFake implements _i2.VideoCapture {
@@ -258,8 +224,7 @@
}
class _FakeZoomState_41 extends _i1.SmartFake implements _i2.ZoomState {
- _FakeZoomState_41(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeZoomState_41(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
/// A class which mocks [Analyzer].
@@ -270,10 +235,8 @@
void Function(_i2.Analyzer, _i2.ImageProxy) get analyze =>
(super.noSuchMethod(
Invocation.getter(#analyze),
- returnValue:
- (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {},
- returnValueForMissingStub:
- (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {},
+ returnValue: (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {},
+ returnValueForMissingStub: (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {},
)
as void Function(_i2.Analyzer, _i2.ImageProxy));
@@ -296,14 +259,8 @@
_i2.Analyzer pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeAnalyzer_1(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakeAnalyzer_1(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeAnalyzer_1(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakeAnalyzer_1(this, Invocation.method(#pigeon_copy, [])),
)
as _i2.Analyzer);
}
@@ -311,8 +268,7 @@
/// A class which mocks [AspectRatioStrategy].
///
/// See the documentation for Mockito's code generation for more information.
-class MockAspectRatioStrategy extends _i1.Mock
- implements _i2.AspectRatioStrategy {
+class MockAspectRatioStrategy extends _i1.Mock implements _i2.AspectRatioStrategy {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -335,10 +291,9 @@
returnValue: _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value(
_i2.AspectRatioStrategyFallbackRule.auto,
),
- returnValueForMissingStub:
- _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value(
- _i2.AspectRatioStrategyFallbackRule.auto,
- ),
+ returnValueForMissingStub: _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value(
+ _i2.AspectRatioStrategyFallbackRule.auto,
+ ),
)
as _i5.Future<_i2.AspectRatioStrategyFallbackRule>);
@@ -346,9 +301,7 @@
_i5.Future<_i2.AspectRatio> getPreferredAspectRatio() =>
(super.noSuchMethod(
Invocation.method(#getPreferredAspectRatio, []),
- returnValue: _i5.Future<_i2.AspectRatio>.value(
- _i2.AspectRatio.ratio16To9,
- ),
+ returnValue: _i5.Future<_i2.AspectRatio>.value(_i2.AspectRatio.ratio16To9),
returnValueForMissingStub: _i5.Future<_i2.AspectRatio>.value(
_i2.AspectRatio.ratio16To9,
),
@@ -359,10 +312,7 @@
_i2.AspectRatioStrategy pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeAspectRatioStrategy_2(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeAspectRatioStrategy_2(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeAspectRatioStrategy_2(
this,
Invocation.method(#pigeon_copy, []),
@@ -379,10 +329,7 @@
_i2.CameraControl get cameraControl =>
(super.noSuchMethod(
Invocation.getter(#cameraControl),
- returnValue: _FakeCameraControl_3(
- this,
- Invocation.getter(#cameraControl),
- ),
+ returnValue: _FakeCameraControl_3(this, Invocation.getter(#cameraControl)),
returnValueForMissingStub: _FakeCameraControl_3(
this,
Invocation.getter(#cameraControl),
@@ -422,14 +369,8 @@
_i2.Camera pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCamera_5(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakeCamera_5(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCamera_5(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakeCamera_5(this, Invocation.method(#pigeon_copy, [])),
)
as _i2.Camera);
}
@@ -460,10 +401,7 @@
_i2.ExposureState get exposureState =>
(super.noSuchMethod(
Invocation.getter(#exposureState),
- returnValue: _FakeExposureState_6(
- this,
- Invocation.getter(#exposureState),
- ),
+ returnValue: _FakeExposureState_6(this, Invocation.getter(#exposureState)),
returnValueForMissingStub: _FakeExposureState_6(
this,
Invocation.getter(#exposureState),
@@ -491,18 +429,11 @@
(super.noSuchMethod(
Invocation.method(#getCameraState, []),
returnValue: _i5.Future<_i3.LiveData<_i2.CameraState>>.value(
- _FakeLiveData_7<_i2.CameraState>(
- this,
- Invocation.method(#getCameraState, []),
- ),
+ _FakeLiveData_7<_i2.CameraState>(this, Invocation.method(#getCameraState, [])),
),
- returnValueForMissingStub:
- _i5.Future<_i3.LiveData<_i2.CameraState>>.value(
- _FakeLiveData_7<_i2.CameraState>(
- this,
- Invocation.method(#getCameraState, []),
- ),
- ),
+ returnValueForMissingStub: _i5.Future<_i3.LiveData<_i2.CameraState>>.value(
+ _FakeLiveData_7<_i2.CameraState>(this, Invocation.method(#getCameraState, [])),
+ ),
)
as _i5.Future<_i3.LiveData<_i2.CameraState>>);
@@ -511,18 +442,11 @@
(super.noSuchMethod(
Invocation.method(#getZoomState, []),
returnValue: _i5.Future<_i3.LiveData<_i2.ZoomState>>.value(
- _FakeLiveData_7<_i2.ZoomState>(
- this,
- Invocation.method(#getZoomState, []),
- ),
+ _FakeLiveData_7<_i2.ZoomState>(this, Invocation.method(#getZoomState, [])),
),
- returnValueForMissingStub:
- _i5.Future<_i3.LiveData<_i2.ZoomState>>.value(
- _FakeLiveData_7<_i2.ZoomState>(
- this,
- Invocation.method(#getZoomState, []),
- ),
- ),
+ returnValueForMissingStub: _i5.Future<_i3.LiveData<_i2.ZoomState>>.value(
+ _FakeLiveData_7<_i2.ZoomState>(this, Invocation.method(#getZoomState, [])),
+ ),
)
as _i5.Future<_i3.LiveData<_i2.ZoomState>>);
@@ -530,14 +454,8 @@
_i3.CameraInfo pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCameraInfo_8(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakeCameraInfo_8(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCameraInfo_8(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakeCameraInfo_8(this, Invocation.method(#pigeon_copy, [])),
)
as _i3.CameraInfo);
}
@@ -545,8 +463,7 @@
/// A class which mocks [CameraCharacteristicsKey].
///
/// See the documentation for Mockito's code generation for more information.
-class MockCameraCharacteristicsKey extends _i1.Mock
- implements _i2.CameraCharacteristicsKey {
+class MockCameraCharacteristicsKey extends _i1.Mock implements _i2.CameraCharacteristicsKey {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -566,10 +483,7 @@
_i2.CameraCharacteristicsKey pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCameraCharacteristicsKey_9(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCameraCharacteristicsKey_9(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCameraCharacteristicsKey_9(
this,
Invocation.method(#pigeon_copy, []),
@@ -616,14 +530,11 @@
as _i5.Future<void>);
@override
- _i5.Future<_i2.FocusMeteringResult?> startFocusAndMetering(
- _i2.FocusMeteringAction? action,
- ) =>
+ _i5.Future<_i2.FocusMeteringResult?> startFocusAndMetering(_i2.FocusMeteringAction? action) =>
(super.noSuchMethod(
Invocation.method(#startFocusAndMetering, [action]),
returnValue: _i5.Future<_i2.FocusMeteringResult?>.value(),
- returnValueForMissingStub:
- _i5.Future<_i2.FocusMeteringResult?>.value(),
+ returnValueForMissingStub: _i5.Future<_i2.FocusMeteringResult?>.value(),
)
as _i5.Future<_i2.FocusMeteringResult?>);
@@ -649,10 +560,7 @@
_i2.CameraControl pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCameraControl_3(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCameraControl_3(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCameraControl_3(
this,
Invocation.method(#pigeon_copy, []),
@@ -667,20 +575,12 @@
class MockCameraSize extends _i1.Mock implements _i2.CameraSize {
@override
int get width =>
- (super.noSuchMethod(
- Invocation.getter(#width),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
int get height =>
- (super.noSuchMethod(
- Invocation.getter(#height),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
@@ -702,10 +602,7 @@
_i2.CameraSize pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCameraSize_10(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCameraSize_10(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCameraSize_10(
this,
Invocation.method(#pigeon_copy, []),
@@ -717,8 +614,7 @@
/// A class which mocks [Camera2CameraControl].
///
/// See the documentation for Mockito's code generation for more information.
-class MockCamera2CameraControl extends _i1.Mock
- implements _i2.Camera2CameraControl {
+class MockCamera2CameraControl extends _i1.Mock implements _i2.Camera2CameraControl {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -735,9 +631,7 @@
as _i2.PigeonInstanceManager);
@override
- _i5.Future<void> addCaptureRequestOptions(
- _i2.CaptureRequestOptions? bundle,
- ) =>
+ _i5.Future<void> addCaptureRequestOptions(_i2.CaptureRequestOptions? bundle) =>
(super.noSuchMethod(
Invocation.method(#addCaptureRequestOptions, [bundle]),
returnValue: _i5.Future<void>.value(),
@@ -749,10 +643,7 @@
_i2.Camera2CameraControl pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCamera2CameraControl_11(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCamera2CameraControl_11(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCamera2CameraControl_11(
this,
Invocation.method(#pigeon_copy, []),
@@ -794,9 +685,7 @@
as _i5.Future<String>);
@override
- _i5.Future<Object?> getCameraCharacteristic(
- _i2.CameraCharacteristicsKey? key,
- ) =>
+ _i5.Future<Object?> getCameraCharacteristic(_i2.CameraCharacteristicsKey? key) =>
(super.noSuchMethod(
Invocation.method(#getCameraCharacteristic, [key]),
returnValue: _i5.Future<Object?>.value(),
@@ -808,10 +697,7 @@
_i2.Camera2CameraInfo pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCamera2CameraInfo_12(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCamera2CameraInfo_12(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCamera2CameraInfo_12(
this,
Invocation.method(#pigeon_copy, []),
@@ -829,33 +715,19 @@
_i4.CameraImageFormat get format =>
(super.noSuchMethod(
Invocation.getter(#format),
- returnValue: _FakeCameraImageFormat_13(
- this,
- Invocation.getter(#format),
- ),
- returnValueForMissingStub: _FakeCameraImageFormat_13(
- this,
- Invocation.getter(#format),
- ),
+ returnValue: _FakeCameraImageFormat_13(this, Invocation.getter(#format)),
+ returnValueForMissingStub: _FakeCameraImageFormat_13(this, Invocation.getter(#format)),
)
as _i4.CameraImageFormat);
@override
int get height =>
- (super.noSuchMethod(
- Invocation.getter(#height),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
int get width =>
- (super.noSuchMethod(
- Invocation.getter(#width),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
@@ -891,12 +763,8 @@
_i5.Future<List<_i2.CameraInfo>> filter(List<_i2.CameraInfo>? cameraInfos) =>
(super.noSuchMethod(
Invocation.method(#filter, [cameraInfos]),
- returnValue: _i5.Future<List<_i2.CameraInfo>>.value(
- <_i2.CameraInfo>[],
- ),
- returnValueForMissingStub: _i5.Future<List<_i2.CameraInfo>>.value(
- <_i2.CameraInfo>[],
- ),
+ returnValue: _i5.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]),
+ returnValueForMissingStub: _i5.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]),
)
as _i5.Future<List<_i2.CameraInfo>>);
@@ -904,10 +772,7 @@
_i2.CameraSelector pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCameraSelector_14(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCameraSelector_14(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCameraSelector_14(
this,
Invocation.method(#pigeon_copy, []),
@@ -919,8 +784,7 @@
/// A class which mocks [CaptureRequestOptions].
///
/// See the documentation for Mockito's code generation for more information.
-class MockCaptureRequestOptions extends _i1.Mock
- implements _i2.CaptureRequestOptions {
+class MockCaptureRequestOptions extends _i1.Mock implements _i2.CaptureRequestOptions {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -949,10 +813,7 @@
_i2.CaptureRequestOptions pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeCaptureRequestOptions_15(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeCaptureRequestOptions_15(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeCaptureRequestOptions_15(
this,
Invocation.method(#pigeon_copy, []),
@@ -964,23 +825,14 @@
/// A class which mocks [DeviceOrientationManager].
///
/// See the documentation for Mockito's code generation for more information.
-class MockDeviceOrientationManager extends _i1.Mock
- implements _i2.DeviceOrientationManager {
+class MockDeviceOrientationManager extends _i1.Mock implements _i2.DeviceOrientationManager {
@override
- void Function(_i2.DeviceOrientationManager, String)
- get onDeviceOrientationChanged =>
+ void Function(_i2.DeviceOrientationManager, String) get onDeviceOrientationChanged =>
(super.noSuchMethod(
Invocation.getter(#onDeviceOrientationChanged),
- returnValue:
- (
- _i2.DeviceOrientationManager pigeon_instance,
- String orientation,
- ) {},
+ returnValue: (_i2.DeviceOrientationManager pigeon_instance, String orientation) {},
returnValueForMissingStub:
- (
- _i2.DeviceOrientationManager pigeon_instance,
- String orientation,
- ) {},
+ (_i2.DeviceOrientationManager pigeon_instance, String orientation) {},
)
as void Function(_i2.DeviceOrientationManager, String));
@@ -1031,16 +883,10 @@
(super.noSuchMethod(
Invocation.method(#getUiOrientation, []),
returnValue: _i5.Future<String>.value(
- _i6.dummyValue<String>(
- this,
- Invocation.method(#getUiOrientation, []),
- ),
+ _i6.dummyValue<String>(this, Invocation.method(#getUiOrientation, [])),
),
returnValueForMissingStub: _i5.Future<String>.value(
- _i6.dummyValue<String>(
- this,
- Invocation.method(#getUiOrientation, []),
- ),
+ _i6.dummyValue<String>(this, Invocation.method(#getUiOrientation, [])),
),
)
as _i5.Future<String>);
@@ -1089,11 +935,10 @@
this,
Invocation.method(#pigeon_copy, []),
),
- returnValueForMissingStub:
- _FakeDisplayOrientedMeteringPointFactory_17(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValueForMissingStub: _FakeDisplayOrientedMeteringPointFactory_17(
+ this,
+ Invocation.method(#pigeon_copy, []),
+ ),
)
as _i2.DisplayOrientedMeteringPointFactory);
@@ -1102,39 +947,23 @@
(super.noSuchMethod(
Invocation.method(#createPoint, [x, y]),
returnValue: _i5.Future<_i2.MeteringPoint>.value(
- _FakeMeteringPoint_18(
- this,
- Invocation.method(#createPoint, [x, y]),
- ),
+ _FakeMeteringPoint_18(this, Invocation.method(#createPoint, [x, y])),
),
returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value(
- _FakeMeteringPoint_18(
- this,
- Invocation.method(#createPoint, [x, y]),
- ),
+ _FakeMeteringPoint_18(this, Invocation.method(#createPoint, [x, y])),
),
)
as _i5.Future<_i2.MeteringPoint>);
@override
- _i5.Future<_i2.MeteringPoint> createPointWithSize(
- double? x,
- double? y,
- double? size,
- ) =>
+ _i5.Future<_i2.MeteringPoint> createPointWithSize(double? x, double? y, double? size) =>
(super.noSuchMethod(
Invocation.method(#createPointWithSize, [x, y, size]),
returnValue: _i5.Future<_i2.MeteringPoint>.value(
- _FakeMeteringPoint_18(
- this,
- Invocation.method(#createPointWithSize, [x, y, size]),
- ),
+ _FakeMeteringPoint_18(this, Invocation.method(#createPointWithSize, [x, y, size])),
),
returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value(
- _FakeMeteringPoint_18(
- this,
- Invocation.method(#createPointWithSize, [x, y, size]),
- ),
+ _FakeMeteringPoint_18(this, Invocation.method(#createPointWithSize, [x, y, size])),
),
)
as _i5.Future<_i2.MeteringPoint>);
@@ -1187,10 +1016,7 @@
_i2.ExposureState pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeExposureState_6(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeExposureState_6(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeExposureState_6(
this,
Invocation.method(#pigeon_copy, []),
@@ -1222,10 +1048,7 @@
_i2.FallbackStrategy pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeFallbackStrategy_20(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeFallbackStrategy_20(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeFallbackStrategy_20(
this,
Invocation.method(#pigeon_copy, []),
@@ -1237,8 +1060,7 @@
/// A class which mocks [FocusMeteringActionBuilder].
///
/// See the documentation for Mockito's code generation for more information.
-class MockFocusMeteringActionBuilder extends _i1.Mock
- implements _i2.FocusMeteringActionBuilder {
+class MockFocusMeteringActionBuilder extends _i1.Mock implements _i2.FocusMeteringActionBuilder {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -1264,10 +1086,7 @@
as _i5.Future<void>);
@override
- _i5.Future<void> addPointWithMode(
- _i2.MeteringPoint? point,
- _i2.MeteringMode? mode,
- ) =>
+ _i5.Future<void> addPointWithMode(_i2.MeteringPoint? point, _i2.MeteringMode? mode) =>
(super.noSuchMethod(
Invocation.method(#addPointWithMode, [point, mode]),
returnValue: _i5.Future<void>.value(),
@@ -1291,13 +1110,9 @@
returnValue: _i5.Future<_i2.FocusMeteringAction>.value(
_FakeFocusMeteringAction_21(this, Invocation.method(#build, [])),
),
- returnValueForMissingStub:
- _i5.Future<_i2.FocusMeteringAction>.value(
- _FakeFocusMeteringAction_21(
- this,
- Invocation.method(#build, []),
- ),
- ),
+ returnValueForMissingStub: _i5.Future<_i2.FocusMeteringAction>.value(
+ _FakeFocusMeteringAction_21(this, Invocation.method(#build, [])),
+ ),
)
as _i5.Future<_i2.FocusMeteringAction>);
@@ -1320,8 +1135,7 @@
/// A class which mocks [FocusMeteringResult].
///
/// See the documentation for Mockito's code generation for more information.
-class MockFocusMeteringResult extends _i1.Mock
- implements _i2.FocusMeteringResult {
+class MockFocusMeteringResult extends _i1.Mock implements _i2.FocusMeteringResult {
@override
bool get isFocusSuccessful =>
(super.noSuchMethod(
@@ -1350,10 +1164,7 @@
_i2.FocusMeteringResult pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeFocusMeteringResult_23(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeFocusMeteringResult_23(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeFocusMeteringResult_23(
this,
Invocation.method(#pigeon_copy, []),
@@ -1412,10 +1223,7 @@
_i2.ImageAnalysis pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeImageAnalysis_24(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeImageAnalysis_24(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeImageAnalysis_24(
this,
Invocation.method(#pigeon_copy, []),
@@ -1453,9 +1261,7 @@
as _i5.Future<void>);
@override
- _i5.Future<String> takePicture(
- _i2.SystemServicesManager? systemServicesManager,
- ) =>
+ _i5.Future<String> takePicture(_i2.SystemServicesManager? systemServicesManager) =>
(super.noSuchMethod(
Invocation.method(#takePicture, [systemServicesManager]),
returnValue: _i5.Future<String>.value(
@@ -1486,10 +1292,7 @@
_i2.ImageCapture pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeImageCapture_25(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeImageCapture_25(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeImageCapture_25(
this,
Invocation.method(#pigeon_copy, []),
@@ -1504,29 +1307,17 @@
class MockImageProxy extends _i1.Mock implements _i2.ImageProxy {
@override
int get format =>
- (super.noSuchMethod(
- Invocation.getter(#format),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#format), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
int get width =>
- (super.noSuchMethod(
- Invocation.getter(#width),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
int get height =>
- (super.noSuchMethod(
- Invocation.getter(#height),
- returnValue: 0,
- returnValueForMissingStub: 0,
- )
+ (super.noSuchMethod(Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0)
as int);
@override
@@ -1548,12 +1339,8 @@
_i5.Future<List<_i2.PlaneProxy>> getPlanes() =>
(super.noSuchMethod(
Invocation.method(#getPlanes, []),
- returnValue: _i5.Future<List<_i2.PlaneProxy>>.value(
- <_i2.PlaneProxy>[],
- ),
- returnValueForMissingStub: _i5.Future<List<_i2.PlaneProxy>>.value(
- <_i2.PlaneProxy>[],
- ),
+ returnValue: _i5.Future<List<_i2.PlaneProxy>>.value(<_i2.PlaneProxy>[]),
+ returnValueForMissingStub: _i5.Future<List<_i2.PlaneProxy>>.value(<_i2.PlaneProxy>[]),
)
as _i5.Future<List<_i2.PlaneProxy>>);
@@ -1570,10 +1357,7 @@
_i2.ImageProxy pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeImageProxy_26(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeImageProxy_26(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeImageProxy_26(
this,
Invocation.method(#pigeon_copy, []),
@@ -1591,8 +1375,7 @@
(super.noSuchMethod(
Invocation.getter(#onChanged),
returnValue: (_i2.Observer pigeon_instance, Object value) {},
- returnValueForMissingStub:
- (_i2.Observer pigeon_instance, Object value) {},
+ returnValueForMissingStub: (_i2.Observer pigeon_instance, Object value) {},
)
as void Function(_i2.Observer, Object));
@@ -1651,16 +1434,10 @@
(super.noSuchMethod(
Invocation.method(#withAudioEnabled, [initialMuted]),
returnValue: _i5.Future<_i2.PendingRecording>.value(
- _FakePendingRecording_28(
- this,
- Invocation.method(#withAudioEnabled, [initialMuted]),
- ),
+ _FakePendingRecording_28(this, Invocation.method(#withAudioEnabled, [initialMuted])),
),
returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value(
- _FakePendingRecording_28(
- this,
- Invocation.method(#withAudioEnabled, [initialMuted]),
- ),
+ _FakePendingRecording_28(this, Invocation.method(#withAudioEnabled, [initialMuted])),
),
)
as _i5.Future<_i2.PendingRecording>);
@@ -1670,16 +1447,10 @@
(super.noSuchMethod(
Invocation.method(#asPersistentRecording, []),
returnValue: _i5.Future<_i2.PendingRecording>.value(
- _FakePendingRecording_28(
- this,
- Invocation.method(#asPersistentRecording, []),
- ),
+ _FakePendingRecording_28(this, Invocation.method(#asPersistentRecording, [])),
),
returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value(
- _FakePendingRecording_28(
- this,
- Invocation.method(#asPersistentRecording, []),
- ),
+ _FakePendingRecording_28(this, Invocation.method(#asPersistentRecording, [])),
),
)
as _i5.Future<_i2.PendingRecording>);
@@ -1701,10 +1472,7 @@
_i2.PendingRecording pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakePendingRecording_28(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakePendingRecording_28(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakePendingRecording_28(
this,
Invocation.method(#pigeon_copy, []),
@@ -1763,10 +1531,7 @@
_i2.PlaneProxy pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakePlaneProxy_30(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakePlaneProxy_30(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakePlaneProxy_30(
this,
Invocation.method(#pigeon_copy, []),
@@ -1795,9 +1560,7 @@
as _i2.PigeonInstanceManager);
@override
- _i5.Future<int> setSurfaceProvider(
- _i2.SystemServicesManager? systemServicesManager,
- ) =>
+ _i5.Future<int> setSurfaceProvider(_i2.SystemServicesManager? systemServicesManager) =>
(super.noSuchMethod(
Invocation.method(#setSurfaceProvider, [systemServicesManager]),
returnValue: _i5.Future<int>.value(0),
@@ -1845,14 +1608,8 @@
_i2.Preview pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakePreview_31(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakePreview_31(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakePreview_31(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakePreview_31(this, Invocation.method(#pigeon_copy, [])),
)
as _i2.Preview);
}
@@ -1860,8 +1617,7 @@
/// A class which mocks [ProcessCameraProvider].
///
/// See the documentation for Mockito's code generation for more information.
-class MockProcessCameraProvider extends _i1.Mock
- implements _i2.ProcessCameraProvider {
+class MockProcessCameraProvider extends _i1.Mock implements _i2.ProcessCameraProvider {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -1881,12 +1637,8 @@
_i5.Future<List<_i2.CameraInfo>> getAvailableCameraInfos() =>
(super.noSuchMethod(
Invocation.method(#getAvailableCameraInfos, []),
- returnValue: _i5.Future<List<_i2.CameraInfo>>.value(
- <_i2.CameraInfo>[],
- ),
- returnValueForMissingStub: _i5.Future<List<_i2.CameraInfo>>.value(
- <_i2.CameraInfo>[],
- ),
+ returnValue: _i5.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]),
+ returnValueForMissingStub: _i5.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]),
)
as _i5.Future<List<_i2.CameraInfo>>);
@@ -1898,16 +1650,10 @@
(super.noSuchMethod(
Invocation.method(#bindToLifecycle, [cameraSelector, useCases]),
returnValue: _i5.Future<_i2.Camera>.value(
- _FakeCamera_5(
- this,
- Invocation.method(#bindToLifecycle, [cameraSelector, useCases]),
- ),
+ _FakeCamera_5(this, Invocation.method(#bindToLifecycle, [cameraSelector, useCases])),
),
returnValueForMissingStub: _i5.Future<_i2.Camera>.value(
- _FakeCamera_5(
- this,
- Invocation.method(#bindToLifecycle, [cameraSelector, useCases]),
- ),
+ _FakeCamera_5(this, Invocation.method(#bindToLifecycle, [cameraSelector, useCases])),
),
)
as _i5.Future<_i2.Camera>);
@@ -1943,10 +1689,7 @@
_i2.ProcessCameraProvider pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeProcessCameraProvider_32(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeProcessCameraProvider_32(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeProcessCameraProvider_32(
this,
Invocation.method(#pigeon_copy, []),
@@ -1978,10 +1721,7 @@
_i2.QualitySelector pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeQualitySelector_33(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeQualitySelector_33(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeQualitySelector_33(
this,
Invocation.method(#pigeon_copy, []),
@@ -2032,16 +1772,10 @@
(super.noSuchMethod(
Invocation.method(#getQualitySelector, []),
returnValue: _i5.Future<_i2.QualitySelector>.value(
- _FakeQualitySelector_33(
- this,
- Invocation.method(#getQualitySelector, []),
- ),
+ _FakeQualitySelector_33(this, Invocation.method(#getQualitySelector, [])),
),
returnValueForMissingStub: _i5.Future<_i2.QualitySelector>.value(
- _FakeQualitySelector_33(
- this,
- Invocation.method(#getQualitySelector, []),
- ),
+ _FakeQualitySelector_33(this, Invocation.method(#getQualitySelector, [])),
),
)
as _i5.Future<_i2.QualitySelector>);
@@ -2051,16 +1785,10 @@
(super.noSuchMethod(
Invocation.method(#prepareRecording, [path]),
returnValue: _i5.Future<_i2.PendingRecording>.value(
- _FakePendingRecording_28(
- this,
- Invocation.method(#prepareRecording, [path]),
- ),
+ _FakePendingRecording_28(this, Invocation.method(#prepareRecording, [path])),
),
returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value(
- _FakePendingRecording_28(
- this,
- Invocation.method(#prepareRecording, [path]),
- ),
+ _FakePendingRecording_28(this, Invocation.method(#prepareRecording, [path])),
),
)
as _i5.Future<_i2.PendingRecording>);
@@ -2069,14 +1797,8 @@
_i2.Recorder pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeRecorder_34(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakeRecorder_34(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeRecorder_34(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakeRecorder_34(this, Invocation.method(#pigeon_copy, [])),
)
as _i2.Recorder);
}
@@ -2104,10 +1826,7 @@
_i2.ResolutionFilter pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeResolutionFilter_35(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeResolutionFilter_35(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeResolutionFilter_35(
this,
Invocation.method(#pigeon_copy, []),
@@ -2119,8 +1838,7 @@
/// A class which mocks [ResolutionSelector].
///
/// See the documentation for Mockito's code generation for more information.
-class MockResolutionSelector extends _i1.Mock
- implements _i2.ResolutionSelector {
+class MockResolutionSelector extends _i1.Mock implements _i2.ResolutionSelector {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -2141,18 +1859,11 @@
(super.noSuchMethod(
Invocation.method(#getAspectRatioStrategy, []),
returnValue: _i5.Future<_i2.AspectRatioStrategy>.value(
- _FakeAspectRatioStrategy_2(
- this,
- Invocation.method(#getAspectRatioStrategy, []),
- ),
+ _FakeAspectRatioStrategy_2(this, Invocation.method(#getAspectRatioStrategy, [])),
),
- returnValueForMissingStub:
- _i5.Future<_i2.AspectRatioStrategy>.value(
- _FakeAspectRatioStrategy_2(
- this,
- Invocation.method(#getAspectRatioStrategy, []),
- ),
- ),
+ returnValueForMissingStub: _i5.Future<_i2.AspectRatioStrategy>.value(
+ _FakeAspectRatioStrategy_2(this, Invocation.method(#getAspectRatioStrategy, [])),
+ ),
)
as _i5.Future<_i2.AspectRatioStrategy>);
@@ -2160,10 +1871,7 @@
_i2.ResolutionSelector pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeResolutionSelector_36(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeResolutionSelector_36(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeResolutionSelector_36(
this,
Invocation.method(#pigeon_copy, []),
@@ -2175,8 +1883,7 @@
/// A class which mocks [ResolutionStrategy].
///
/// See the documentation for Mockito's code generation for more information.
-class MockResolutionStrategy extends _i1.Mock
- implements _i2.ResolutionStrategy {
+class MockResolutionStrategy extends _i1.Mock implements _i2.ResolutionStrategy {
@override
_i2.PigeonInstanceManager get pigeon_instanceManager =>
(super.noSuchMethod(
@@ -2208,10 +1915,9 @@
returnValue: _i5.Future<_i2.ResolutionStrategyFallbackRule>.value(
_i2.ResolutionStrategyFallbackRule.closestHigher,
),
- returnValueForMissingStub:
- _i5.Future<_i2.ResolutionStrategyFallbackRule>.value(
- _i2.ResolutionStrategyFallbackRule.closestHigher,
- ),
+ returnValueForMissingStub: _i5.Future<_i2.ResolutionStrategyFallbackRule>.value(
+ _i2.ResolutionStrategyFallbackRule.closestHigher,
+ ),
)
as _i5.Future<_i2.ResolutionStrategyFallbackRule>);
@@ -2219,10 +1925,7 @@
_i2.ResolutionStrategy pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeResolutionStrategy_37(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeResolutionStrategy_37(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeResolutionStrategy_37(
this,
Invocation.method(#pigeon_copy, []),
@@ -2290,14 +1993,8 @@
_i2.Recording pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeRecording_29(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakeRecording_29(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeRecording_29(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakeRecording_29(this, Invocation.method(#pigeon_copy, [])),
)
as _i2.Recording);
}
@@ -2305,22 +2002,14 @@
/// A class which mocks [SystemServicesManager].
///
/// See the documentation for Mockito's code generation for more information.
-class MockSystemServicesManager extends _i1.Mock
- implements _i2.SystemServicesManager {
+class MockSystemServicesManager extends _i1.Mock implements _i2.SystemServicesManager {
@override
void Function(_i2.SystemServicesManager, String) get onCameraError =>
(super.noSuchMethod(
Invocation.getter(#onCameraError),
- returnValue:
- (
- _i2.SystemServicesManager pigeon_instance,
- String errorDescription,
- ) {},
+ returnValue: (_i2.SystemServicesManager pigeon_instance, String errorDescription) {},
returnValueForMissingStub:
- (
- _i2.SystemServicesManager pigeon_instance,
- String errorDescription,
- ) {},
+ (_i2.SystemServicesManager pigeon_instance, String errorDescription) {},
)
as void Function(_i2.SystemServicesManager, String));
@@ -2340,14 +2029,11 @@
as _i2.PigeonInstanceManager);
@override
- _i5.Future<_i2.CameraPermissionsError?> requestCameraPermissions(
- bool? enableAudio,
- ) =>
+ _i5.Future<_i2.CameraPermissionsError?> requestCameraPermissions(bool? enableAudio) =>
(super.noSuchMethod(
Invocation.method(#requestCameraPermissions, [enableAudio]),
returnValue: _i5.Future<_i2.CameraPermissionsError?>.value(),
- returnValueForMissingStub:
- _i5.Future<_i2.CameraPermissionsError?>.value(),
+ returnValueForMissingStub: _i5.Future<_i2.CameraPermissionsError?>.value(),
)
as _i5.Future<_i2.CameraPermissionsError?>);
@@ -2356,16 +2042,10 @@
(super.noSuchMethod(
Invocation.method(#getTempFilePath, [prefix, suffix]),
returnValue: _i5.Future<String>.value(
- _i6.dummyValue<String>(
- this,
- Invocation.method(#getTempFilePath, [prefix, suffix]),
- ),
+ _i6.dummyValue<String>(this, Invocation.method(#getTempFilePath, [prefix, suffix])),
),
returnValueForMissingStub: _i5.Future<String>.value(
- _i6.dummyValue<String>(
- this,
- Invocation.method(#getTempFilePath, [prefix, suffix]),
- ),
+ _i6.dummyValue<String>(this, Invocation.method(#getTempFilePath, [prefix, suffix])),
),
)
as _i5.Future<String>);
@@ -2374,10 +2054,7 @@
_i2.SystemServicesManager pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeSystemServicesManager_38(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeSystemServicesManager_38(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeSystemServicesManager_38(
this,
Invocation.method(#pigeon_copy, []),
@@ -2431,10 +2108,7 @@
_i2.VideoCapture pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeVideoCapture_40(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeVideoCapture_40(this, Invocation.method(#pigeon_copy, [])),
returnValueForMissingStub: _FakeVideoCapture_40(
this,
Invocation.method(#pigeon_copy, []),
@@ -2484,14 +2158,8 @@
_i2.ZoomState pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeZoomState_41(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
- returnValueForMissingStub: _FakeZoomState_41(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeZoomState_41(this, Invocation.method(#pigeon_copy, [])),
+ returnValueForMissingStub: _FakeZoomState_41(this, Invocation.method(#pigeon_copy, [])),
)
as _i2.ZoomState);
}
@@ -2499,8 +2167,7 @@
/// A class which mocks [LiveData].
///
/// See the documentation for Mockito's code generation for more information.
-class MockLiveCameraState extends _i1.Mock
- implements _i3.LiveData<_i2.CameraState> {
+class MockLiveCameraState extends _i1.Mock implements _i3.LiveData<_i2.CameraState> {
MockLiveCameraState() {
_i1.throwOnMissingStub(this);
}
@@ -2565,8 +2232,7 @@
/// A class which mocks [LiveData].
///
/// See the documentation for Mockito's code generation for more information.
-class MockLiveZoomState extends _i1.Mock
- implements _i3.LiveData<_i2.ZoomState> {
+class MockLiveZoomState extends _i1.Mock implements _i3.LiveData<_i2.ZoomState> {
MockLiveZoomState() {
_i1.throwOnMissingStub(this);
}
@@ -2611,10 +2277,7 @@
_i3.LiveData<_i2.ZoomState> pigeon_copy() =>
(super.noSuchMethod(
Invocation.method(#pigeon_copy, []),
- returnValue: _FakeLiveData_7<_i2.ZoomState>(
- this,
- Invocation.method(#pigeon_copy, []),
- ),
+ returnValue: _FakeLiveData_7<_i2.ZoomState>(this, Invocation.method(#pigeon_copy, [])),
)
as _i3.LiveData<_i2.ZoomState>);
diff --git a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart
index cfc6b2d..93ff9e9 100644
--- a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart
+++ b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart
@@ -6,8 +6,7 @@
import 'package:camera_android_camerax/src/camerax_library.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/services.dart';
-import 'package:flutter/widgets.dart'
- show MatrixUtils, RotatedBox, Texture, Transform;
+import 'package:flutter/widgets.dart' show MatrixUtils, RotatedBox, Texture, Transform;
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
@@ -61,9 +60,7 @@
final mockCamera = MockCamera();
// Mock retrieving available test camera.
- when(
- mockProcessCameraProvider.bindToLifecycle(any, any),
- ).thenAnswer((_) async => mockCamera);
+ when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(
mockProcessCameraProvider.getAvailableCameraInfos(),
@@ -71,15 +68,11 @@
when(
mockCameraInfo.lensFacing,
).thenReturn(isCameraFrontFacing ? LensFacing.front : LensFacing.back);
- when(
- mockCameraInfo.sensorRotationDegrees,
- ).thenReturn(sensorRotationDegrees);
+ when(mockCameraInfo.sensorRotationDegrees).thenReturn(sensorRotationDegrees);
// Mock additional ProcessCameraProvider operation that is irrelevant
// for the tests in this file.
- when(
- mockCameraInfo.getCameraState(),
- ).thenAnswer((_) async => MockLiveCameraState());
+ when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState());
return mockProcessCameraProvider;
}
@@ -92,15 +85,11 @@
void setUpOverridesForCreatingTestCameraWithDeviceOrientationManager(
DeviceOrientationManager deviceOrientationManager, {
required MockProcessCameraProvider mockProcessCameraProvider,
- required CameraSelector Function({
- LensFacing? requireLensFacing,
- dynamic cameraInfoForFilter,
- })
+ required CameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter})
createCameraSelector,
required bool handlesCropAndRotation,
}) {
- PigeonOverrides.processCameraProvider_getInstance = () async =>
- mockProcessCameraProvider;
+ PigeonOverrides.processCameraProvider_getInstance = () async => mockProcessCameraProvider;
PigeonOverrides.cameraSelector_new = createCameraSelector;
PigeonOverrides.preview_new =
({
@@ -112,10 +101,9 @@
when(
preview.surfaceProducerHandlesCropAndRotation(),
).thenAnswer((_) async => handlesCropAndRotation);
- when(preview.getResolutionInfo()).thenAnswer(
- (_) async =>
- ResolutionInfo.pigeon_detached(resolution: MockCameraSize()),
- );
+ when(
+ preview.getResolutionInfo(),
+ ).thenAnswer((_) async => ResolutionInfo.pigeon_detached(resolution: MockCameraSize()));
return preview;
};
PigeonOverrides.imageCapture_new =
@@ -125,16 +113,10 @@
ResolutionSelector? resolutionSelector,
}) => MockImageCapture();
PigeonOverrides.recorder_new =
- ({
- int? aspectRatio,
- int? targetVideoEncodingBitRate,
- QualitySelector? qualitySelector,
- }) => MockRecorder();
+ ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) =>
+ MockRecorder();
PigeonOverrides.videoCapture_withOutput =
- ({
- required VideoOutput videoOutput,
- CameraIntegerRange? targetFpsRange,
- }) {
+ ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) {
return MockVideoCapture();
};
PigeonOverrides.imageAnalysis_new =
@@ -147,10 +129,7 @@
return MockImageAnalysis();
};
PigeonOverrides.resolutionStrategy_new =
- ({
- required CameraSize boundSize,
- required ResolutionStrategyFallbackRule fallbackRule,
- }) {
+ ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) {
return MockResolutionStrategy();
};
PigeonOverrides.resolutionSelector_new =
@@ -161,49 +140,38 @@
}) {
return MockResolutionSelector();
};
- PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan =
- ({required VideoQuality quality}) {
- return MockFallbackStrategy();
- };
- PigeonOverrides.fallbackStrategy_lowerQualityThan =
- ({required VideoQuality quality}) {
- return MockFallbackStrategy();
- };
+ PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) {
+ return MockFallbackStrategy();
+ };
+ PigeonOverrides.fallbackStrategy_lowerQualityThan = ({required VideoQuality quality}) {
+ return MockFallbackStrategy();
+ };
PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) {
final camera2cameraInfo = MockCamera2CameraInfo();
- when(
- camera2cameraInfo.getCameraCharacteristic(any),
- ).thenAnswer((_) async => 90);
+ when(camera2cameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => 90);
return camera2cameraInfo;
};
PigeonOverrides.qualitySelector_from =
({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) {
return MockQualitySelector();
};
- GenericsPigeonOverrides.observerNew =
- <T>({required void Function(Observer<T>, T) onChanged}) {
- return Observer<T>.detached(onChanged: onChanged);
- };
+ GenericsPigeonOverrides.observerNew = <T>({required void Function(Observer<T>, T) onChanged}) {
+ return Observer<T>.detached(onChanged: onChanged);
+ };
PigeonOverrides.systemServicesManager_new =
- ({
- required void Function(SystemServicesManager, String) onCameraError,
- }) {
+ ({required void Function(SystemServicesManager, String) onCameraError}) {
return MockSystemServicesManager();
};
PigeonOverrides.deviceOrientationManager_new =
- ({
- required void Function(DeviceOrientationManager, String)
- onDeviceOrientationChanged,
- }) => deviceOrientationManager;
+ ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) =>
+ deviceOrientationManager;
PigeonOverrides.aspectRatioStrategy_new =
({
required AspectRatio preferredAspectRatio,
required AspectRatioStrategyFallbackRule fallbackRule,
}) {
final mockAspectRatioStrategy = MockAspectRatioStrategy();
- when(
- mockAspectRatioStrategy.getFallbackRule(),
- ).thenAnswer((_) async => fallbackRule);
+ when(mockAspectRatioStrategy.getFallbackRule()).thenAnswer((_) async => fallbackRule);
when(
mockAspectRatioStrategy.getPreferredAspectRatio(),
).thenAnswer((_) async => preferredAspectRatio);
@@ -223,19 +191,14 @@
/// Useful for tests that do not need a reference to a DeviceOrientationManager.
void setUpOverridesForCreatingTestCamera({
required MockProcessCameraProvider mockProcessCameraProvider,
- required CameraSelector Function({
- LensFacing? requireLensFacing,
- dynamic cameraInfoForFilter,
- })
+ required CameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter})
createCameraSelector,
required bool handlesCropAndRotation,
required Future<String> Function() getUiOrientation,
required Future<int> Function() getDefaultDisplayRotation,
}) {
final deviceOrientationManager = MockDeviceOrientationManager();
- when(
- deviceOrientationManager.getUiOrientation(),
- ).thenAnswer((_) => getUiOrientation());
+ when(deviceOrientationManager.getUiOrientation()).thenAnswer((_) => getUiOrientation());
when(
deviceOrientationManager.getDefaultDisplayRotation(),
).thenAnswer((_) => getDefaultDisplayRotation());
@@ -248,10 +211,7 @@
}
/// Returns function that a CameraXProxy can use to select the front camera.
- MockCameraSelector Function({
- LensFacing? requireLensFacing,
- dynamic cameraInfoForFilter,
- })
+ MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter})
createCameraSelectorForFrontCamera(MockCameraSelector mockCameraSelector) {
return ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) {
switch (requireLensFacing) {
@@ -267,10 +227,7 @@
}
/// Returns function that a CameraXProxy can use to select the back camera.
- MockCameraSelector Function({
- LensFacing? requireLensFacing,
- dynamic cameraInfoForFilter,
- })
+ MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter})
createCameraSelectorForBackCamera(MockCameraSelector mockCameraSelector) {
return ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) {
switch (requireLensFacing) {
@@ -286,10 +243,7 @@
}
/// Error message for detecting an incorrect preview rotation.
- String getExpectedRotationTestFailureReason(
- int expectedQuarterTurns,
- int actualQuarterTurns,
- ) =>
+ String getExpectedRotationTestFailureReason(int expectedQuarterTurns, int actualQuarterTurns) =>
'Expected the preview to be rotated by $expectedQuarterTurns quarter turns (which is ${expectedQuarterTurns * 90} degrees clockwise) but instead was rotated $actualQuarterTurns quarter turns.';
/// Checks that the transform matrix (Matrix4) mirrors across the x-axis by
@@ -318,10 +272,7 @@
1.0,
);
- expect(
- MatrixUtils.matrixEquals(mirrorAcrossXMatrix, transformationMatrix),
- isTrue,
- );
+ expect(MatrixUtils.matrixEquals(mirrorAcrossXMatrix, transformationMatrix), isTrue);
}
/// Checks that the transform matrix (Matrix4) mirrors across the y-axis by
@@ -350,10 +301,7 @@
1.0,
);
- expect(
- MatrixUtils.matrixEquals(mirrorAcrossYMatrix, transformationMatrix),
- isTrue,
- );
+ expect(MatrixUtils.matrixEquals(mirrorAcrossYMatrix, transformationMatrix), isTrue);
}
group('when handlesCropAndRotation is true', () {
@@ -364,10 +312,7 @@
late int cameraId;
late DeviceOrientation testInitialDeviceOrientation;
late MockProcessCameraProvider mockProcessCameraProvider;
- late MockCameraSelector Function({
- LensFacing? requireLensFacing,
- dynamic cameraInfoForFilter,
- })
+ late MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter})
fakeCreateCameraSelector;
late MediaSettings testMediaSettings;
@@ -385,9 +330,7 @@
sensorRotationDegrees: /* irrelevant for test */ 90,
isCameraFrontFacing: false,
);
- fakeCreateCameraSelector = createCameraSelectorForBackCamera(
- mockCameraSelector,
- );
+ fakeCreateCameraSelector = createCameraSelectorForBackCamera(mockCameraSelector);
// Media settings to create camera; irrelevant for test.
testMediaSettings = const MediaSettings();
@@ -402,21 +345,17 @@
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: fakeCreateCameraSelector,
handlesCropAndRotation: true,
- getUiOrientation: () async =>
- _serializeDeviceOrientation(testInitialDeviceOrientation),
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation0),
+ getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation0),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -430,9 +369,7 @@
// Verify Texture is rotated by 0 - 90 = -90 degrees clockwise = 270 degrees clockwise.
const int expectedQuarterTurns = _270DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4;
expect(rotatedBox.child, isA<Texture>());
@@ -457,21 +394,17 @@
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: fakeCreateCameraSelector,
handlesCropAndRotation: true,
- getUiOrientation: () async =>
- _serializeDeviceOrientation(testInitialDeviceOrientation),
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation90),
+ getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation90),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -485,9 +418,7 @@
// Verify Texture is rotated by 270 - 90 = 180 degrees clockwise.
const int expectedQuarterTurns = _180DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -510,21 +441,17 @@
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: fakeCreateCameraSelector,
handlesCropAndRotation: true,
- getUiOrientation: () async =>
- _serializeDeviceOrientation(testInitialDeviceOrientation),
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation180),
+ getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation180),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -538,9 +465,7 @@
// Verify Texture is rotated by 180 - 90 = 90 degrees clockwise.
const int expectedQuarterTurns = _90DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -563,21 +488,17 @@
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: fakeCreateCameraSelector,
handlesCropAndRotation: true,
- getUiOrientation: () async =>
- _serializeDeviceOrientation(testInitialDeviceOrientation),
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation270),
+ getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation270),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -591,9 +512,7 @@
// Verify Texture is rotated by 90 - 90 = 0 degrees.
const int expectedQuarterTurns = _0DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -616,10 +535,7 @@
late int cameraId;
late int testInitialDefaultDisplayRotation;
late MockProcessCameraProvider mockProcessCameraProvider;
- late MockCameraSelector Function({
- LensFacing? requireLensFacing,
- dynamic cameraInfoForFilter,
- })
+ late MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter})
fakeCreateCameraSelector;
late MediaSettings testMediaSettings;
@@ -637,9 +553,7 @@
sensorRotationDegrees: /* irrelevant for test */ 90,
isCameraFrontFacing: false,
);
- fakeCreateCameraSelector = createCameraSelectorForBackCamera(
- mockCameraSelector,
- );
+ fakeCreateCameraSelector = createCameraSelectorForBackCamera(mockCameraSelector);
// Media settings to create camera; irrelevant for test.
testMediaSettings = const MediaSettings();
@@ -654,21 +568,17 @@
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: fakeCreateCameraSelector,
handlesCropAndRotation: true,
- getUiOrientation: () async =>
- _serializeDeviceOrientation(DeviceOrientation.portraitUp),
- getDefaultDisplayRotation: () =>
- Future<int>.value(testInitialDefaultDisplayRotation),
+ getUiOrientation: () async => _serializeDeviceOrientation(DeviceOrientation.portraitUp),
+ getDefaultDisplayRotation: () => Future<int>.value(testInitialDefaultDisplayRotation),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -682,9 +592,7 @@
// Verify Texture is rotated by 270 - 0 = 270 degrees clockwise.
const int expectedQuarterTurns = _270DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -709,19 +617,16 @@
handlesCropAndRotation: true,
getUiOrientation: () async =>
_serializeDeviceOrientation(DeviceOrientation.landscapeLeft),
- getDefaultDisplayRotation: () =>
- Future<int>.value(testInitialDefaultDisplayRotation),
+ getDefaultDisplayRotation: () => Future<int>.value(testInitialDefaultDisplayRotation),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -735,9 +640,7 @@
// Verify Texture is rotated by 270 - 270 = 0 degrees.
const int expectedQuarterTurns = _0DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -762,19 +665,16 @@
handlesCropAndRotation: true,
getUiOrientation: () async =>
_serializeDeviceOrientation(DeviceOrientation.portraitDown),
- getDefaultDisplayRotation: () =>
- Future<int>.value(testInitialDefaultDisplayRotation),
+ getDefaultDisplayRotation: () => Future<int>.value(testInitialDefaultDisplayRotation),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -788,9 +688,7 @@
// Verify Texture is rotated by 270 - 180 = 90 degrees clockwise.
const int expectedQuarterTurns = _90DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -815,19 +713,16 @@
handlesCropAndRotation: true,
getUiOrientation: () async =>
_serializeDeviceOrientation(DeviceOrientation.landscapeRight),
- getDefaultDisplayRotation: () =>
- Future<int>.value(testInitialDefaultDisplayRotation),
+ getDefaultDisplayRotation: () => Future<int>.value(testInitialDefaultDisplayRotation),
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -841,9 +736,7 @@
// Verify Texture is rotated by 270 - 90 = 180 degrees clockwise.
const int expectedQuarterTurns = _180DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -865,8 +758,7 @@
(WidgetTester tester) async {
final camera = AndroidCameraCameraX();
const cameraId = 11;
- const DeviceOrientation testDeviceOrientation =
- DeviceOrientation.portraitDown;
+ const DeviceOrientation testDeviceOrientation = DeviceOrientation.portraitDown;
// Create and set up mock CameraSelector, mock ProcessCameraProvider, and media settings for test front camera.
// These settings do not matter for this test.
@@ -875,10 +767,10 @@
LensFacing? requireLensFacing,
dynamic cameraInfoForFilter,
})
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
- final MockProcessCameraProvider
- mockProcessCameraProviderForFrontCamera =
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
+ final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockFrontCameraSelector,
sensorRotationDegrees: 270,
@@ -890,9 +782,7 @@
// to portrait down, set initial default display rotation to 0 degrees clockwise.
final mockDeviceOrientationManager = MockDeviceOrientationManager();
when(mockDeviceOrientationManager.getUiOrientation()).thenAnswer(
- (_) => Future<String>.value(
- _serializeDeviceOrientation(testDeviceOrientation),
- ),
+ (_) => Future<String>.value(_serializeDeviceOrientation(testDeviceOrientation)),
);
when(
mockDeviceOrientationManager.getDefaultDisplayRotation(),
@@ -906,14 +796,12 @@
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Calculated according to: counterClockwiseCurrentDefaultDisplayRotation - cameraPreviewPreAppliedRotation,
@@ -936,21 +824,15 @@
mockDeviceOrientationManager.getDefaultDisplayRotation(),
).thenAnswer((_) => Future<int>.value(currentDefaultDisplayRotation));
- const testEvent = DeviceOrientationChangedEvent(
- testDeviceOrientation,
- );
- AndroidCameraCameraX.deviceOrientationChangedStreamController.add(
- testEvent,
- );
+ const testEvent = DeviceOrientationChangedEvent(testDeviceOrientation);
+ AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent);
await tester.pumpAndSettle();
// Verify Texture is rotated by expected clockwise degrees.
final int expectedQuarterTurns =
expectedRotationPerDefaultDisplayRotation[currentDefaultDisplayRotation]!;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
final int clockwiseQuarterTurns = rotatedBox.quarterTurns < 0
? rotatedBox.quarterTurns + 4
: rotatedBox.quarterTurns;
@@ -981,10 +863,10 @@
LensFacing? requireLensFacing,
dynamic cameraInfoForFilter,
})
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
- final MockProcessCameraProvider
- mockProcessCameraProviderForFrontCamera =
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
+ final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockFrontCameraSelector,
sensorRotationDegrees: 270,
@@ -998,22 +880,18 @@
mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
handlesCropAndRotation: true,
- getUiOrientation: /* initial device orientation is irrelevant */
- () async =>
- _serializeDeviceOrientation(DeviceOrientation.portraitUp),
- getDefaultDisplayRotation: () =>
- Future<int>.value(testInitialDefaultDisplayRotation),
+ getUiOrientation: /* initial device orientation is irrelevant */ () async =>
+ _serializeDeviceOrientation(DeviceOrientation.portraitUp),
+ getDefaultDisplayRotation: () => Future<int>.value(testInitialDefaultDisplayRotation),
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Calculated according to: counterClockwiseCurrentDefaultDisplayRotation - cameraPreviewPreAppliedRotation,
@@ -1032,21 +910,15 @@
for (final DeviceOrientation currentDeviceOrientation
in expectedRotationPerDeviceOrientation.keys) {
- final testEvent = DeviceOrientationChangedEvent(
- currentDeviceOrientation,
- );
- AndroidCameraCameraX.deviceOrientationChangedStreamController.add(
- testEvent,
- );
+ final testEvent = DeviceOrientationChangedEvent(currentDeviceOrientation);
+ AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent);
await tester.pumpAndSettle();
// Verify Texture is rotated by expected clockwise degrees.
final int expectedQuarterTurns =
expectedRotationPerDeviceOrientation[currentDeviceOrientation]!;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
final int clockwiseQuarterTurns = rotatedBox.quarterTurns < 0
? rotatedBox.quarterTurns + 4
: rotatedBox.quarterTurns;
@@ -1088,16 +960,16 @@
// with sensor orientation degrees 270. Also, set up function to mock initial default display
// of 0.
mockFrontCameraSelector = MockCameraSelector();
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
mockProcessCameraProviderForFrontCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockFrontCameraSelector,
sensorRotationDegrees: 270,
isCameraFrontFacing: true,
);
- proxyGetDefaultDisplayRotation = () =>
- Future<int>.value(Surface.rotation0);
+ proxyGetDefaultDisplayRotation = () => Future<int>.value(Surface.rotation0);
// Media settings to create camera; irrelevant for test.
testMediaSettings = const MediaSettings();
@@ -1109,8 +981,7 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial device orientation to portrait up.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
getDefaultDisplayRotation: proxyGetDefaultDisplayRotation,
handlesCropAndRotation: false,
@@ -1119,14 +990,12 @@
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1136,9 +1005,7 @@
// Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 0 = 270 degrees.
const int expectedQuarterTurns = _270DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1146,8 +1013,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in portrait mode, we expect the camera
// preview to be mirrored across the y-axis.
@@ -1170,8 +1036,7 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial device orientation to landscape right.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
getDefaultDisplayRotation: proxyGetDefaultDisplayRotation,
handlesCropAndRotation: false,
@@ -1180,14 +1045,12 @@
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1197,9 +1060,7 @@
// Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 90 = 180 degrees.
const int expectedQuarterTurns = _180DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1207,8 +1068,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -1231,8 +1091,7 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial device orientation to portrait down.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
getDefaultDisplayRotation: proxyGetDefaultDisplayRotation,
handlesCropAndRotation: false,
@@ -1241,14 +1100,12 @@
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1258,9 +1115,7 @@
// Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 180 = 90 degrees clockwise.
const int expectedQuarterTurns = _90DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1268,8 +1123,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in portrait mode, we expect the camera
// preview to be mirrored across the y-axis.
@@ -1292,8 +1146,7 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial device orientation to landscape left.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
getDefaultDisplayRotation: proxyGetDefaultDisplayRotation,
handlesCropAndRotation: false,
@@ -1302,14 +1155,12 @@
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1319,9 +1170,7 @@
// Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 270 = 0 degrees clockwise.
const int expectedQuarterTurns = _0DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1329,8 +1178,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -1373,8 +1221,9 @@
// with sensor orientation degrees 270. Also, set up function to mock initial default display
// of 0.
mockFrontCameraSelector = MockCameraSelector();
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
mockProcessCameraProviderForFrontCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockFrontCameraSelector,
@@ -1394,24 +1243,20 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial default display rotation to 0 degrees.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation0),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation0),
handlesCropAndRotation: false,
getUiOrientation: proxyGetUiOrientation,
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1421,9 +1266,7 @@
// Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 270 = 0 degrees.
const int expectedQuarterTurns = _0DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1431,8 +1274,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -1455,24 +1297,20 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial default display rotation to 0 degrees.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation90),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation90),
handlesCropAndRotation: false,
getUiOrientation: proxyGetUiOrientation,
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1484,9 +1322,7 @@
// 270 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the
// default display rotation.
const int expectedQuarterTurns = _90DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1494,8 +1330,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -1520,24 +1355,20 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial default display rotation to 0 degrees.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation180),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation180),
handlesCropAndRotation: false,
getUiOrientation: proxyGetUiOrientation,
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1547,9 +1378,7 @@
// Verify Texture is rotated by ((270 - 180 * 1 + 360) % 360) - 270 = -180 degrees clockwise = 180 degrees clockwise.
const int expectedQuarterTurns = _180DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1557,8 +1386,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -1583,24 +1411,20 @@
// Set up test to use front camera, tell camera that handlesCropAndRotation is false,
// set camera initial default display rotation to 0 degrees.
setUpOverridesForCreatingTestCamera(
- mockProcessCameraProvider:
- mockProcessCameraProviderForFrontCamera,
+ mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation270),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation270),
handlesCropAndRotation: false,
getUiOrientation: proxyGetUiOrientation,
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1612,9 +1436,7 @@
// 90 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the
// default display rotation.
const int expectedQuarterTurns = _270DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1622,8 +1444,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -1650,8 +1471,7 @@
(WidgetTester tester) async {
final camera = AndroidCameraCameraX();
const cameraId = 11;
- const DeviceOrientation testDeviceOrientation =
- DeviceOrientation.landscapeRight;
+ const DeviceOrientation testDeviceOrientation = DeviceOrientation.landscapeRight;
// Create and set up mock front camera CameraSelector, mock ProcessCameraProvider, 270 degree sensor orientation,
// media settings for test front camera.
@@ -1660,10 +1480,10 @@
LensFacing? requireLensFacing,
dynamic cameraInfoForFilter,
})
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
- final MockProcessCameraProvider
- mockProcessCameraProviderForFrontCamera =
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
+ final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockFrontCameraSelector,
sensorRotationDegrees: 270,
@@ -1675,9 +1495,7 @@
// to portrait down, set initial default display rotation to 0 degrees clockwise.
final mockDeviceOrientationManager = MockDeviceOrientationManager();
when(mockDeviceOrientationManager.getUiOrientation()).thenAnswer(
- (_) => Future<String>.value(
- _serializeDeviceOrientation(testDeviceOrientation),
- ),
+ (_) => Future<String>.value(_serializeDeviceOrientation(testDeviceOrientation)),
);
when(
mockDeviceOrientationManager.getDefaultDisplayRotation(),
@@ -1690,14 +1508,12 @@
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Calculated according to: ((270 - counterClockwiseDefaultDisplayRotation * 1 + 360) % 360) - 90.
@@ -1720,21 +1536,15 @@
mockDeviceOrientationManager.getDefaultDisplayRotation(),
).thenAnswer((_) async => currentDefaultDisplayRotation);
- const testEvent = DeviceOrientationChangedEvent(
- testDeviceOrientation,
- );
- AndroidCameraCameraX.deviceOrientationChangedStreamController.add(
- testEvent,
- );
+ const testEvent = DeviceOrientationChangedEvent(testDeviceOrientation);
+ AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent);
await tester.pumpAndSettle();
// Verify Texture is rotated by expected clockwise degrees.
final int expectedQuarterTurns =
expectedRotationPerDefaultDisplayRotation[currentDefaultDisplayRotation]!;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1776,10 +1586,10 @@
LensFacing? requireLensFacing,
dynamic cameraInfoForFilter,
})
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
- final MockProcessCameraProvider
- mockProcessCameraProviderForFrontCamera =
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
+ final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockFrontCameraSelector,
sensorRotationDegrees: 90,
@@ -1796,22 +1606,18 @@
mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
handlesCropAndRotation: false,
- getUiOrientation: /* initial device orientation irrelevant for test */
- () async =>
- _serializeDeviceOrientation(DeviceOrientation.landscapeLeft),
- getDefaultDisplayRotation: () =>
- Future<int>.value(Surface.rotation90),
+ getUiOrientation: /* initial device orientation irrelevant for test */ () async =>
+ _serializeDeviceOrientation(DeviceOrientation.landscapeLeft),
+ getDefaultDisplayRotation: () => Future<int>.value(Surface.rotation90),
);
// Get and create test front camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Calculated according to: ((90 - 270 * 1 + 360) % 360) - cameraPreviewPreAppliedRotation.
@@ -1829,21 +1635,15 @@
for (final DeviceOrientation currentDeviceOrientation
in expectedRotationPerDeviceOrientation.keys) {
- final testEvent = DeviceOrientationChangedEvent(
- currentDeviceOrientation,
- );
- AndroidCameraCameraX.deviceOrientationChangedStreamController.add(
- testEvent,
- );
+ final testEvent = DeviceOrientationChangedEvent(currentDeviceOrientation);
+ AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent);
await tester.pumpAndSettle();
// Verify Texture is rotated by expected clockwise degrees.
final int expectedQuarterTurns =
expectedRotationPerDeviceOrientation[currentDeviceOrientation]!;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -1904,10 +1704,10 @@
// Create and set up mock CameraSelector and mock ProcessCameraProvider for test back camera
// with sensor orientation degrees 270.
mockBackCameraSelector = MockCameraSelector();
- proxyCreateCameraSelectorForBackCamera =
- createCameraSelectorForBackCamera(mockBackCameraSelector);
- proxyGetDefaultDisplayRotation = () =>
- Future<int>.value(Surface.rotation270);
+ proxyCreateCameraSelectorForBackCamera = createCameraSelectorForBackCamera(
+ mockBackCameraSelector,
+ );
+ proxyGetDefaultDisplayRotation = () => Future<int>.value(Surface.rotation270);
testMediaSettings = const MediaSettings();
});
@@ -1917,8 +1717,7 @@
(WidgetTester tester) async {
// Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees
// 90 is available.
- final MockProcessCameraProvider
- mockProcessCameraProviderForBackCamera =
+ final MockProcessCameraProvider mockProcessCameraProviderForBackCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockBackCameraSelector,
sensorRotationDegrees: 90,
@@ -1937,14 +1736,12 @@
);
// Get and create test back camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -1956,9 +1753,7 @@
// 90 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the
// default display rotation.
const int expectedQuarterTurns = _270DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4;
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -1978,8 +1773,7 @@
(WidgetTester tester) async {
// Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees
// 270 is available.
- final MockProcessCameraProvider
- mockProcessCameraProviderForBackCamera =
+ final MockProcessCameraProvider mockProcessCameraProviderForBackCamera =
setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera(
mockCameraSelector: mockBackCameraSelector,
sensorRotationDegrees: 270,
@@ -1998,14 +1792,12 @@
);
// Get and create test back camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -2017,9 +1809,7 @@
// 90 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the
// default display rotation.
const int expectedQuarterTurns = _90DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4;
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
@@ -2056,8 +1846,7 @@
testSensorOrientation = 90;
// Create mock for seting initial default display rotation to 180 degrees.
- proxyGetDefaultDisplayRotation = () =>
- Future<int>.value(Surface.rotation90);
+ proxyGetDefaultDisplayRotation = () => Future<int>.value(Surface.rotation90);
// Media settings to create camera; irrelevant for test.
testMediaSettings = const MediaSettings();
@@ -2079,8 +1868,9 @@
LensFacing? requireLensFacing,
dynamic cameraInfoForFilter,
})
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForFrontCamera(mockFrontCameraSelector);
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(
+ mockFrontCameraSelector,
+ );
setUpOverridesForCreatingTestCamera(
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
@@ -2091,14 +1881,12 @@
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -2110,9 +1898,7 @@
// 270 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the
// default display rotation.
const int expectedQuarterTurns = _90DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
// We expect a Transform widget to wrap the RotatedBox with the camera
// preview to mirror the preview, since the front camera is being
@@ -2120,8 +1906,7 @@
expect(rotatedBox.child, isA<Transform>());
final transformedPreview = rotatedBox.child! as Transform;
- final Matrix4 transformedPreviewMatrix =
- transformedPreview.transform;
+ final Matrix4 transformedPreviewMatrix = transformedPreview.transform;
// Since the front camera is in landscape mode, we expect the camera
// preview to be mirrored across the x-axis.
@@ -2155,8 +1940,9 @@
LensFacing? requireLensFacing,
dynamic cameraInfoForFilter,
})
- proxyCreateCameraSelectorForFrontCamera =
- createCameraSelectorForBackCamera(mockBackCameraSelector);
+ proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForBackCamera(
+ mockBackCameraSelector,
+ );
setUpOverridesForCreatingTestCamera(
mockProcessCameraProvider: mockProcessCameraProvider,
createCameraSelector: proxyCreateCameraSelectorForFrontCamera,
@@ -2167,14 +1953,12 @@
);
// Get and create test camera.
- final List<CameraDescription> availableCameras = await camera
- .availableCameras();
+ final List<CameraDescription> availableCameras = await camera.availableCameras();
expect(availableCameras.length, 1);
- final int flutterSurfaceTextureId = await camera
- .createCameraWithSettings(
- availableCameras.first,
- testMediaSettings,
- );
+ final int flutterSurfaceTextureId = await camera.createCameraWithSettings(
+ availableCameras.first,
+ testMediaSettings,
+ );
await camera.initializeCamera(flutterSurfaceTextureId);
// Put camera preview in widget tree and pump one frame so that Future to retrieve
@@ -2186,9 +1970,7 @@
// 270 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the
// default display rotation.
const int expectedQuarterTurns = _270DegreesClockwise;
- final RotatedBox rotatedBox = tester.widget<RotatedBox>(
- find.byType(RotatedBox),
- );
+ final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox));
final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4;
expect(rotatedBox.child, isA<Texture>());
expect((rotatedBox.child! as Texture).textureId, cameraId);
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 bb48c3a..5c7fbaf 100644
--- a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart
+++ b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart
@@ -73,18 +73,14 @@
);
}
- testWidgets('Capture specific image resolutions', (
- WidgetTester tester,
- ) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ testWidgets('Capture specific image resolutions', (WidgetTester tester) async {
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final cameraDescription in cameras) {
var previousPresetExactlySupported = true;
- for (final MapEntry<ResolutionPreset, Size> preset
- in presetExpectedSizes.entries) {
+ for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) {
final controller = CameraController(cameraDescription, preset.key);
await controller.initialize();
final bool presetExactlySupported = await testCaptureImageResolution(
@@ -123,24 +119,17 @@
// Verify image dimensions are as expected
expect(video, isNotNull);
- return assertExpectedDimensions(
- expectedSize,
- Size(video.height, video.width),
- );
+ return assertExpectedDimensions(expectedSize, Size(video.height, video.width));
}
- testWidgets('Capture specific video resolutions', (
- WidgetTester tester,
- ) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ testWidgets('Capture specific video resolutions', (WidgetTester tester) async {
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final cameraDescription in cameras) {
var previousPresetExactlySupported = true;
- for (final MapEntry<ResolutionPreset, Size> preset
- in presetExpectedSizes.entries) {
+ for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) {
final controller = CameraController(cameraDescription, preset.key);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -159,17 +148,12 @@
});
testWidgets('Pause and resume video recording', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -198,8 +182,7 @@
sleep(const Duration(milliseconds: 500));
final XFile file = await controller.stopVideoRecording();
- final int recordingTime =
- DateTime.now().millisecondsSinceEpoch - recordingStart;
+ final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart;
final videoFile = File(file.path);
final videoController = VideoPlayerController.file(videoFile);
@@ -211,17 +194,12 @@
});
testWidgets('Set description while recording', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.length < 2) {
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -233,17 +211,12 @@
});
testWidgets('Set description', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.length < 2) {
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.setDescription(cameras[1]);
@@ -279,11 +252,8 @@
return completer.future;
}
- testWidgets('image streaming with imageFormatGroup', (
- WidgetTester tester,
- ) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ testWidgets('image streaming with imageFormatGroup', (WidgetTester tester) async {
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
@@ -305,17 +275,12 @@
});
testWidgets('Recording with video streaming', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
- final controller = CameraController(
- cameras[0],
- ResolutionPreset.low,
- enableAudio: false,
- );
+ final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -335,20 +300,14 @@
});
// Test fileFormat is respected when taking a picture.
- testWidgets('Capture specific image output formats', (
- WidgetTester tester,
- ) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ testWidgets('Capture specific image output formats', (WidgetTester tester) async {
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final cameraDescription in cameras) {
for (final ImageFileFormat fileFormat in ImageFileFormat.values) {
- final controller = CameraController(
- cameraDescription,
- ResolutionPreset.low,
- );
+ final controller = CameraController(cameraDescription, ResolutionPreset.low);
await controller.initialize();
await controller.setImageFileFormat(fileFormat);
final XFile file = await controller.takePicture();
@@ -360,8 +319,7 @@
group('Camera settings', () {
testWidgets('Control FPS', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
@@ -370,10 +328,7 @@
for (final fps in <int>[10, 30]) {
final controller = CameraController.withSettings(
cameras.first,
- mediaSettings: MediaSettings(
- resolutionPreset: ResolutionPreset.medium,
- fps: fps,
- ),
+ mediaSettings: MediaSettings(resolutionPreset: ResolutionPreset.medium, fps: fps),
);
await controller.initialize();
await controller.prepareForVideoRecording();
@@ -401,8 +356,7 @@
});
testWidgets('Control video bitrate', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
@@ -443,8 +397,7 @@
});
testWidgets('Control audio bitrate', (WidgetTester tester) async {
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
diff --git a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart
index ed3a8e5..662f5bf 100644
--- a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart
+++ b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart
@@ -178,10 +178,7 @@
ImageFormatGroup? imageFormatGroup,
}) => CameraController.withSettings(
cameraDescription,
- mediaSettings: MediaSettings(
- resolutionPreset: resolutionPreset,
- enableAudio: enableAudio,
- ),
+ mediaSettings: MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio),
imageFormatGroup: imageFormatGroup,
);
@@ -212,8 +209,7 @@
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
FutureOr<bool>? _initCalled;
- StreamSubscription<DeviceOrientationChangedEvent>?
- _deviceOrientationSubscription;
+ StreamSubscription<DeviceOrientationChangedEvent>? _deviceOrientationSubscription;
/// The camera identifier with which the controller is associated.
int get cameraId => _cameraId;
@@ -224,16 +220,13 @@
Future<void> _initializeWithDescription(CameraDescription description) async {
final initializeCompleter = Completer<CameraInitializedEvent>();
- _deviceOrientationSubscription = CameraPlatform.instance
- .onDeviceOrientationChanged()
- .listen((DeviceOrientationChangedEvent event) {
- value = value.copyWith(deviceOrientation: event.orientation);
- });
+ _deviceOrientationSubscription = CameraPlatform.instance.onDeviceOrientationChanged().listen((
+ DeviceOrientationChangedEvent event,
+ ) {
+ value = value.copyWith(deviceOrientation: event.orientation);
+ });
- _cameraId = await CameraPlatform.instance.createCameraWithSettings(
- description,
- mediaSettings,
- );
+ _cameraId = await CameraPlatform.instance.createCameraWithSettings(description, mediaSettings);
unawaited(
CameraPlatform.instance.onCameraInitialized(_cameraId).first.then((
@@ -252,8 +245,7 @@
isInitialized: true,
description: description,
previewSize: await initializeCompleter.future.then(
- (CameraInitializedEvent event) =>
- Size(event.previewWidth, event.previewHeight),
+ (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight),
),
exposureMode: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposureMode,
@@ -318,14 +310,12 @@
}
/// Start streaming images from platform camera.
- Future<void> startImageStream(
- void Function(CameraImageData image) onAvailable,
- ) async {
- _imageStreamSubscription = CameraPlatform.instance
- .onStreamedFrameAvailable(_cameraId)
- .listen((CameraImageData imageData) {
- onAvailable(imageData);
- });
+ Future<void> startImageStream(void Function(CameraImageData image) onAvailable) async {
+ _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen((
+ CameraImageData imageData,
+ ) {
+ onAvailable(imageData);
+ });
value = value.copyWith(isStreamingImages: true);
}
@@ -340,9 +330,7 @@
///
/// The video is returned as a [XFile] after calling [stopVideoRecording].
/// Throws a [CameraException] if the capture fails.
- Future<void> startVideoRecording({
- void Function(CameraImageData image)? streamCallback,
- }) async {
+ Future<void> startVideoRecording({void Function(CameraImageData image)? streamCallback}) async {
await CameraPlatform.instance.startVideoCapturing(
VideoCaptureOptions(_cameraId, streamCallback: streamCallback),
);
@@ -364,9 +352,7 @@
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<DeviceOrientation>.absent(),
@@ -416,8 +402,7 @@
]);
// 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;
@@ -436,23 +421,16 @@
///
/// If [orientation] is omitted, the current device orientation is used.
Future<void> lockCaptureOrientation() async {
- await CameraPlatform.instance.lockCaptureOrientation(
- _cameraId,
- value.deviceOrientation,
- );
+ await CameraPlatform.instance.lockCaptureOrientation(_cameraId, value.deviceOrientation);
value = value.copyWith(
- lockedCaptureOrientation: Optional<DeviceOrientation>.of(
- value.deviceOrientation,
- ),
+ lockedCaptureOrientation: Optional<DeviceOrientation>.of(value.deviceOrientation),
);
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation() async {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
- value = value.copyWith(
- lockedCaptureOrientation: const Optional<DeviceOrientation>.absent(),
- );
+ value = value.copyWith(lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
}
/// Sets the focus mode for taking pictures.
@@ -559,9 +537,7 @@
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T? value) transformer) {
- return _value == null
- ? Optional<S>.absent()
- : Optional<S>.of(transformer(_value));
+ return _value == null ? Optional<S>.absent() : Optional<S>.of(transformer(_value));
}
/// Transforms the Optional value.
@@ -570,14 +546,11 @@
///
/// Returns [absent()] if the transformer returns `null`.
Optional<S> transformNullable<S>(S? Function(T? value) transformer) {
- return _value == null
- ? Optional<S>.absent()
- : Optional<S>.fromNullable(transformer(_value));
+ return _value == null ? Optional<S>.absent() : Optional<S>.fromNullable(transformer(_value));
}
@override
- Iterator<T> get iterator =>
- isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
+ Iterator<T> get iterator => isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
@@ -589,8 +562,6 @@
@override
String toString() {
- return _value == null
- ? 'Optional { absent }'
- : 'Optional { value: $_value }';
+ return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }';
}
}
diff --git a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart
index 0a768b3..7e8d643 100644
--- a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart
+++ b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart
@@ -26,12 +26,9 @@
valueListenable: controller,
builder: (BuildContext context, Object? value, Widget? child) {
final double cameraAspectRatio =
- controller.value.previewSize!.width /
- controller.value.previewSize!.height;
+ controller.value.previewSize!.width / controller.value.previewSize!.height;
return AspectRatio(
- aspectRatio: _isLandscape()
- ? cameraAspectRatio
- : (1 / cameraAspectRatio),
+ aspectRatio: _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio),
child: Stack(
fit: StackFit.expand,
children: <Widget>[
diff --git a/packages/camera/camera_avfoundation/example/lib/main.dart b/packages/camera/camera_avfoundation/example/lib/main.dart
index f9576b9..4268285 100644
--- a/packages/camera/camera_avfoundation/example/lib/main.dart
+++ b/packages/camera/camera_avfoundation/example/lib/main.dart
@@ -138,8 +138,7 @@
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
- color:
- controller != null && controller!.value.isRecordingVideo
+ color: controller != null && controller!.value.isRecordingVideo
? Colors.redAccent
: Colors.grey,
width: 3.0,
@@ -155,9 +154,7 @@
_modeControlRowWidget(),
Padding(
padding: const EdgeInsets.all(5.0),
- child: Row(
- children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()],
- ),
+ child: Row(children: <Widget>[_cameraTogglesRowWidget(), _thumbnailWidget()]),
),
],
),
@@ -171,11 +168,7 @@
if (cameraController == null || !cameraController.value.isInitialized) {
return const Text(
'Tap a camera',
- style: TextStyle(
- color: Colors.white,
- fontSize: 24.0,
- fontWeight: FontWeight.w900,
- ),
+ style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900),
);
} else {
return Listener(
@@ -189,8 +182,7 @@
behavior: HitTestBehavior.opaque,
onScaleStart: _handleScaleStart,
onScaleUpdate: _handleScaleUpdate,
- onTapDown: (TapDownDetails details) =>
- onViewFinderTap(details, constraints),
+ onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints),
);
},
),
@@ -209,15 +201,9 @@
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.
@@ -242,13 +228,9 @@
// pointing to a location within the browser. It may be displayed
// either with Image.network or Image.memory after loading the image
// bytes to memory.
- kIsWeb
- ? Image.network(imageFile!.path)
- : Image.file(File(imageFile!.path)))
+ kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path)))
: Container(
- decoration: BoxDecoration(
- border: Border.all(color: Colors.pink),
- ),
+ decoration: BoxDecoration(border: Border.all(color: Colors.pink)),
child: Center(
child: AspectRatio(
aspectRatio: localVideoController.value.aspectRatio,
@@ -281,16 +263,12 @@
IconButton(
icon: const Icon(Icons.exposure),
color: Colors.blue,
- onPressed: controller != null
- ? onExposureModeButtonPressed
- : null,
+ onPressed: controller != null ? onExposureModeButtonPressed : null,
),
IconButton(
icon: const Icon(Icons.filter_center_focus),
color: Colors.blue,
- onPressed: controller != null
- ? onFocusModeButtonPressed
- : null,
+ onPressed: controller != null ? onFocusModeButtonPressed : null,
),
]
: <Widget>[],
@@ -306,9 +284,7 @@
: Icons.screen_rotation,
),
color: Colors.blue,
- onPressed: controller != null
- ? onCaptureOrientationLockButtonPressed
- : null,
+ onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null,
),
],
),
@@ -328,36 +304,28 @@
children: <Widget>[
IconButton(
icon: const Icon(Icons.flash_off),
- color: controller?.value.flashMode == FlashMode.off
- ? Colors.orange
- : Colors.blue,
+ 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,
+ 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,
+ 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,
+ color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue,
onPressed: controller != null
? () => onSetFlashModeButtonPressed(FlashMode.torch)
: null,
@@ -394,15 +362,11 @@
TextButton(
style: styleAuto,
onPressed: controller != null
- ? () =>
- onSetExposureModeButtonPressed(ExposureMode.auto)
+ ? () => onSetExposureModeButtonPressed(ExposureMode.auto)
: null,
onLongPress: () {
if (controller != null) {
- CameraPlatform.instance.setExposurePoint(
- controller!.cameraId,
- null,
- );
+ CameraPlatform.instance.setExposurePoint(controller!.cameraId, null);
showInSnackBar('Resetting exposure point');
}
},
@@ -411,17 +375,13 @@
TextButton(
style: styleLocked,
onPressed: controller != null
- ? () => onSetExposureModeButtonPressed(
- ExposureMode.locked,
- )
+ ? () => 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'),
),
],
@@ -436,9 +396,7 @@
min: _minAvailableExposureOffset,
max: _maxAvailableExposureOffset,
label: _currentExposureOffset.toString(),
- onChanged:
- _minAvailableExposureOffset ==
- _maxAvailableExposureOffset
+ onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset
? null
: setExposureOffset,
),
@@ -454,9 +412,7 @@
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
@@ -482,10 +438,7 @@
: null,
onLongPress: () {
if (controller != null) {
- CameraPlatform.instance.setFocusPoint(
- controller!.cameraId,
- null,
- );
+ CameraPlatform.instance.setFocusPoint(controller!.cameraId, null);
}
showInSnackBar('Resetting focus point');
},
@@ -563,13 +516,10 @@
),
IconButton(
icon: const Icon(Icons.pause_presentation),
- color:
- cameraController != null && cameraController.value.isPreviewPaused
+ color: cameraController != null && cameraController.value.isPreviewPaused
? Colors.red
: Colors.blue,
- onPressed: cameraController == null
- ? null
- : onPausePreviewButtonPressed,
+ onPressed: cameraController == null ? null : onPausePreviewButtonPressed,
),
],
);
@@ -615,9 +565,7 @@
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) {
@@ -643,9 +591,7 @@
}
}
- Future<void> _initializeCameraController(
- CameraDescription cameraDescription,
- ) async {
+ Future<void> _initializeCameraController(CameraDescription cameraDescription) async {
final cameraController = CameraController(
cameraDescription,
kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium,
@@ -670,14 +616,10 @@
? <Future<Object?>>[
CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId)
- .then(
- (double value) => _minAvailableExposureOffset = value,
- ),
+ .then((double value) => _minAvailableExposureOffset = value),
CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId)
- .then(
- (double value) => _maxAvailableExposureOffset = value,
- ),
+ .then((double value) => _maxAvailableExposureOffset = value),
]
: <Future<Object?>>[],
CameraPlatform.instance
diff --git a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart
index 3907ed8..aea36cd 100644
--- a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart
+++ b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart
@@ -18,8 +18,7 @@
/// An iOS implementation of [CameraPlatform] based on AVFoundation.
class AVFoundationCamera extends CameraPlatform {
/// Creates a new AVFoundation-based [CameraPlatform] implementation instance.
- AVFoundationCamera({@visibleForTesting CameraApi? api})
- : _hostApi = api ?? CameraApi();
+ AVFoundationCamera({@visibleForTesting CameraApi? api}) : _hostApi = api ?? CameraApi();
/// Registers this class as the default instance of [CameraPlatform].
static void registerWith() {
@@ -51,8 +50,7 @@
/// The per-camera handlers for messages that should be rebroadcast to
/// clients as [CameraEvent]s.
@visibleForTesting
- final Map<int, HostCameraMessageHandler> hostCameraHandlers =
- <int, HostCameraMessageHandler>{};
+ final Map<int, HostCameraMessageHandler> hostCameraHandlers = <int, HostCameraMessageHandler>{};
// The stream to receive frames from the native code.
StreamSubscription<dynamic>? _platformImageStreamSubscription;
@@ -60,16 +58,13 @@
// The stream for vending frames to platform interface clients.
StreamController<CameraImageData>? _frameStreamController;
- Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
- .stream
- .where((CameraEvent event) => event.cameraId == cameraId);
+ Stream<CameraEvent> _cameraEvents(int cameraId) =>
+ cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId);
@override
Future<List<CameraDescription>> availableCameras() async {
try {
- return (await _hostApi.getAvailableCameras())
- .map(cameraDescriptionFromPlatform)
- .toList();
+ return (await _hostApi.getAvailableCameras()).map(cameraDescriptionFromPlatform).toList();
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
@@ -94,9 +89,7 @@
return await _hostApi.create(
cameraDescription.name,
PlatformMediaSettings(
- resolutionPreset: _pigeonResolutionPreset(
- mediaSettings?.resolutionPreset,
- ),
+ resolutionPreset: _pigeonResolutionPreset(mediaSettings?.resolutionPreset),
framesPerSecond: mediaSettings?.fps,
videoBitrate: mediaSettings?.videoBitrate,
audioBitrate: mediaSettings?.audioBitrate,
@@ -137,9 +130,7 @@
@override
Future<void> dispose(int cameraId) async {
- final HostCameraMessageHandler? handler = hostCameraHandlers.remove(
- cameraId,
- );
+ final HostCameraMessageHandler? handler = hostCameraHandlers.remove(cameraId);
handler?.dispose();
await _hostApi.dispose(cameraId);
@@ -177,13 +168,8 @@
}
@override
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) async {
- await _hostApi.lockCaptureOrientation(
- serializeDeviceOrientation(orientation),
- );
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async {
+ await _hostApi.lockCaptureOrientation(serializeDeviceOrientation(orientation));
}
@override
@@ -203,10 +189,7 @@
}
@override
- Future<void> startVideoRecording(
- int cameraId, {
- Duration? maxVideoDuration,
- }) async {
+ Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async {
// Ignore maxVideoDuration, as it is unimplemented and deprecated.
return startVideoCapturing(VideoCaptureOptions(cameraId));
}
@@ -247,15 +230,11 @@
int cameraId, {
CameraImageStreamOptions? options,
}) {
- _frameStreamController = _createStreamController(
- onListen: _onFrameStreamListen,
- );
+ _frameStreamController = _createStreamController(onListen: _onFrameStreamListen);
return _frameStreamController!.stream;
}
- StreamController<CameraImageData> _createStreamController({
- void Function()? onListen,
- }) {
+ StreamController<CameraImageData> _createStreamController({void Function()? onListen}) {
return StreamController<CameraImageData>(
onListen: onListen ?? () {},
onPause: _onFrameStreamPauseResume,
@@ -376,13 +355,10 @@
}
@override
- Future<void> setVideoStabilizationMode(
- int cameraId,
- VideoStabilizationMode mode,
- ) async {
+ Future<void> setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) async {
try {
- final Map<VideoStabilizationMode, PlatformVideoStabilizationMode>
- availableModes = await _getSupportedVideoStabilizationModeMap(cameraId);
+ final Map<VideoStabilizationMode, PlatformVideoStabilizationMode> availableModes =
+ await _getSupportedVideoStabilizationModeMap(cameraId);
final PlatformVideoStabilizationMode? platformMode = availableModes[mode];
if (platformMode == null) {
@@ -395,9 +371,7 @@
}
@override
- Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(
- int cameraId,
- ) async {
+ Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(int cameraId) async {
return (await _getSupportedVideoStabilizationModeMap(cameraId)).keys;
}
@@ -406,11 +380,9 @@
final ret = <VideoStabilizationMode, PlatformVideoStabilizationMode>{};
for (final VideoStabilizationMode mode in VideoStabilizationMode.values) {
- final PlatformVideoStabilizationMode? platformMode =
- _pigeonVideoStabilizationMode(mode);
+ final PlatformVideoStabilizationMode? platformMode = _pigeonVideoStabilizationMode(mode);
if (platformMode != null) {
- final bool isSupported = await _hostApi
- .isVideoStabilizationModeSupported(platformMode);
+ final bool isSupported = await _hostApi.isVideoStabilizationModeSupported(platformMode);
if (isSupported) {
ret[mode] = platformMode;
}
@@ -431,9 +403,7 @@
}
@override
- Future<void> setDescriptionWhileRecording(
- CameraDescription description,
- ) async {
+ Future<void> setDescriptionWhileRecording(CameraDescription description) async {
await _hostApi.updateDescriptionWhileRecording(description.name);
}
@@ -503,9 +473,7 @@
}
/// Returns a [ResolutionPreset]'s Pigeon representation.
- PlatformResolutionPreset _pigeonResolutionPreset(
- ResolutionPreset? resolutionPreset,
- ) {
+ PlatformResolutionPreset _pigeonResolutionPreset(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_avfoundation/lib/src/messages.g.dart b/packages/camera/camera_avfoundation/lib/src/messages.g.dart
index 46c94d5..348ae53 100644
--- a/packages/camera/camera_avfoundation/lib/src/messages.g.dart
+++ b/packages/camera/camera_avfoundation/lib/src/messages.g.dart
@@ -18,11 +18,7 @@
);
}
-List<Object?> wrapResponse({
- Object? result,
- PlatformException? error,
- bool empty = false,
-}) {
+List<Object?> wrapResponse({Object? result, PlatformException? error, bool empty = false}) {
if (empty) {
return <Object?>[];
}
@@ -35,9 +31,7 @@
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 &&
@@ -75,12 +69,7 @@
unknown,
}
-enum PlatformDeviceOrientation {
- portraitUp,
- landscapeLeft,
- portraitDown,
- landscapeRight,
-}
+enum PlatformDeviceOrientation { portraitUp, landscapeLeft, portraitDown, landscapeRight }
enum PlatformExposureMode { auto, locked }
@@ -95,12 +84,7 @@
enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max }
-enum PlatformVideoStabilizationMode {
- off,
- standard,
- cinematic,
- cinematicExtended,
-}
+enum PlatformVideoStabilizationMode { off, standard, cinematic, cinematicExtended }
class PlatformCameraDescription {
PlatformCameraDescription({
@@ -138,8 +122,7 @@
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
- if (other is! PlatformCameraDescription ||
- other.runtimeType != runtimeType) {
+ if (other is! PlatformCameraDescription || other.runtimeType != runtimeType) {
return false;
}
if (identical(this, other)) {
@@ -328,8 +311,7 @@
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
- if (other is! PlatformCameraImagePlane ||
- other.runtimeType != runtimeType) {
+ if (other is! PlatformCameraImagePlane || other.runtimeType != runtimeType) {
return false;
}
if (identical(this, other)) {
@@ -363,13 +345,7 @@
bool enableAudio;
List<Object?> _toList() {
- return <Object?>[
- resolutionPreset,
- framesPerSecond,
- videoBitrate,
- audioBitrate,
- enableAudio,
- ];
+ return <Object?>[resolutionPreset, framesPerSecond, videoBitrate, audioBitrate, enableAudio];
}
Object encode() {
@@ -458,10 +434,7 @@
static PlatformSize decode(Object result) {
result as List<Object?>;
- return PlatformSize(
- width: result[0]! as double,
- height: result[1]! as double,
- );
+ return PlatformSize(width: result[0]! as double, height: result[1]! as double);
}
@override
@@ -576,9 +549,7 @@
return value == null ? null : PlatformResolutionPreset.values[value];
case 138:
final value = readValue(buffer) as int?;
- return value == null
- ? null
- : PlatformVideoStabilizationMode.values[value];
+ return value == null ? null : PlatformVideoStabilizationMode.values[value];
case 139:
return PlatformCameraDescription.decode(readValue(buffer)!);
case 140:
@@ -599,21 +570,17 @@
}
}
-const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec(
- _PigeonCodec(),
-);
+const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec(_PigeonCodec());
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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -645,8 +612,7 @@
message: 'Host platform returned null value for non-null return value.',
);
} else {
- return (pigeonVar_replyList[0] as List<Object?>?)!
- .cast<PlatformCameraDescription>();
+ return (pigeonVar_replyList[0] as List<Object?>?)!.cast<PlatformCameraDescription>();
}
}
@@ -659,9 +625,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraName, settings],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ cameraName,
+ settings,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -682,10 +649,7 @@
}
/// Initializes the camera with the given ID.
- Future<void> initialize(
- int cameraId,
- PlatformImageFormatGroup imageFormat,
- ) async {
+ Future<void> initialize(int cameraId, PlatformImageFormatGroup imageFormat) async {
final pigeonVar_channelName =
'dev.flutter.pigeon.camera_avfoundation.CameraApi.initialize$pigeonVar_messageChannelSuffix';
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -693,9 +657,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId, imageFormat],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ cameraId,
+ imageFormat,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -795,9 +760,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -813,9 +776,7 @@
}
/// Locks the camera capture to the current device orientation.
- Future<void> lockCaptureOrientation(
- PlatformDeviceOrientation orientation,
- ) async {
+ Future<void> lockCaptureOrientation(PlatformDeviceOrientation orientation) async {
final pigeonVar_channelName =
'dev.flutter.pigeon.camera_avfoundation.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix';
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -823,9 +784,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[orientation],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[orientation]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -929,9 +888,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[enableStream],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[enableStream]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1032,9 +989,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[mode]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1058,9 +1013,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[mode]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1086,9 +1039,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[point],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[point]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1170,9 +1121,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[offset],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[offset]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1196,9 +1145,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[mode]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1224,9 +1171,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[point],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[point]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1308,9 +1253,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[zoom],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[zoom]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1326,9 +1269,7 @@
}
/// Sets the video stabilization mode.
- Future<void> setVideoStabilizationMode(
- PlatformVideoStabilizationMode mode,
- ) async {
+ Future<void> setVideoStabilizationMode(PlatformVideoStabilizationMode mode) async {
final pigeonVar_channelName =
'dev.flutter.pigeon.camera_avfoundation.CameraApi.setVideoStabilizationMode$pigeonVar_messageChannelSuffix';
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1336,9 +1277,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[mode]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1354,9 +1293,7 @@
}
/// Gets if the given video stabilization mode is supported.
- Future<bool> isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode mode,
- ) async {
+ Future<bool> isVideoStabilizationModeSupported(PlatformVideoStabilizationMode mode) async {
final pigeonVar_channelName =
'dev.flutter.pigeon.camera_avfoundation.CameraApi.isVideoStabilizationModeSupported$pigeonVar_messageChannelSuffix';
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -1364,9 +1301,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[mode],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[mode]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1445,9 +1380,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraName],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraName]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1471,9 +1404,7 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[format],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[format]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
@@ -1514,9 +1445,7 @@
BinaryMessenger? binaryMessenger,
String messageChannelSuffix = '',
}) {
- messageChannelSuffix = messageChannelSuffix.isNotEmpty
- ? '.$messageChannelSuffix'
- : '';
+ messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix',
@@ -1574,9 +1503,7 @@
BinaryMessenger? binaryMessenger,
String messageChannelSuffix = '',
}) {
- messageChannelSuffix = messageChannelSuffix.isNotEmpty
- ? '.$messageChannelSuffix'
- : '';
+ messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';
{
final pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized$messageChannelSuffix',
@@ -1592,8 +1519,7 @@
'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null.',
);
final List<Object?> args = (message as List<Object?>?)!;
- final PlatformCameraState? arg_initialState =
- (args[0] as PlatformCameraState?);
+ 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.',
diff --git a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart
index 7753f05..213b355 100644
--- a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart
+++ b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart
@@ -18,18 +18,14 @@
sensorSensitivity: data.sensorSensitivity,
planes: List<CameraImagePlane>.unmodifiable(
data.planes.map<CameraImagePlane>(
- (PlatformCameraImagePlane planeData) =>
- _cameraImagePlaneFromPlatformData(planeData),
+ (PlatformCameraImagePlane planeData) => _cameraImagePlaneFromPlatformData(planeData),
),
),
);
}
CameraImageFormat _cameraImageFormatFromPlatformImageFormat(int data) {
- return CameraImageFormat(
- _imageFormatGroupFromPlatformImageFormat(data),
- raw: data,
- );
+ return CameraImageFormat(_imageFormatGroupFromPlatformImageFormat(data), raw: data);
}
ImageFormatGroup _imageFormatGroupFromPlatformImageFormat(int data) {
@@ -44,9 +40,7 @@
return ImageFormatGroup.unknown;
}
-CameraImagePlane _cameraImagePlaneFromPlatformData(
- PlatformCameraImagePlane data,
-) {
+CameraImagePlane _cameraImagePlaneFromPlatformData(PlatformCameraImagePlane data) {
return CameraImagePlane(
bytes: data.bytes,
bytesPerRow: data.bytesPerRow,
diff --git a/packages/camera/camera_avfoundation/lib/src/utils.dart b/packages/camera/camera_avfoundation/lib/src/utils.dart
index 3308bcc..4e883cd 100644
--- a/packages/camera/camera_avfoundation/lib/src/utils.dart
+++ b/packages/camera/camera_avfoundation/lib/src/utils.dart
@@ -8,9 +8,7 @@
import 'messages.g.dart';
/// Creates a [CameraDescription] from a Pigeon [PlatformCameraDescription].
-CameraDescription cameraDescriptionFromPlatform(
- PlatformCameraDescription camera,
-) {
+CameraDescription cameraDescriptionFromPlatform(PlatformCameraDescription camera) {
return CameraDescription(
name: camera.name,
lensDirection: cameraLensDirectionFromPlatform(camera.lensDirection),
@@ -20,9 +18,7 @@
}
/// Converts a Pigeon [PlatformCameraLensDirection] to a [CameraLensDirection].
-CameraLensDirection cameraLensDirectionFromPlatform(
- PlatformCameraLensDirection direction,
-) {
+CameraLensDirection cameraLensDirectionFromPlatform(PlatformCameraLensDirection direction) {
return switch (direction) {
PlatformCameraLensDirection.front => CameraLensDirection.front,
PlatformCameraLensDirection.back => CameraLensDirection.back,
@@ -41,9 +37,7 @@
}
/// Convents the given device orientation to Pigeon.
-PlatformDeviceOrientation serializeDeviceOrientation(
- DeviceOrientation orientation,
-) {
+PlatformDeviceOrientation serializeDeviceOrientation(DeviceOrientation orientation) {
switch (orientation) {
case DeviceOrientation.portraitUp:
return PlatformDeviceOrientation.portraitUp;
@@ -64,15 +58,12 @@
}
/// Converts a Pigeon [PlatformDeviceOrientation] to a [DeviceOrientation].
-DeviceOrientation deviceOrientationFromPlatform(
- PlatformDeviceOrientation orientation,
-) {
+DeviceOrientation deviceOrientationFromPlatform(PlatformDeviceOrientation orientation) {
return switch (orientation) {
PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp,
PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown,
PlatformDeviceOrientation.landscapeLeft => DeviceOrientation.landscapeLeft,
- PlatformDeviceOrientation.landscapeRight =>
- DeviceOrientation.landscapeRight,
+ PlatformDeviceOrientation.landscapeRight => DeviceOrientation.landscapeRight,
};
}
diff --git a/packages/camera/camera_avfoundation/pigeons/messages.dart b/packages/camera/camera_avfoundation/pigeons/messages.dart
index b497675..1a1208d 100644
--- a/packages/camera/camera_avfoundation/pigeons/messages.dart
+++ b/packages/camera/camera_avfoundation/pigeons/messages.dart
@@ -7,8 +7,7 @@
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
- swiftOut:
- 'ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift',
+ swiftOut: 'ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift',
copyrightHeader: 'pigeons/copyright.txt',
),
)
@@ -40,12 +39,7 @@
}
// Pigeon version of DeviceOrientation.
-enum PlatformDeviceOrientation {
- portraitUp,
- landscapeLeft,
- portraitDown,
- landscapeRight,
-}
+enum PlatformDeviceOrientation { portraitUp, landscapeLeft, portraitDown, landscapeRight }
// Pigeon version of ExposureMode.
enum PlatformExposureMode { auto, locked }
@@ -65,12 +59,7 @@
// Pigeon version of ResolutionPreset.
enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max }
-enum PlatformVideoStabilizationMode {
- off,
- standard,
- cinematic,
- cinematicExtended,
-}
+enum PlatformVideoStabilizationMode { off, standard, cinematic, cinematicExtended }
// Pigeon version of CameraDescription.
class PlatformCameraDescription {
diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart
index 53d7965..f9a844c 100644
--- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart
+++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart
@@ -46,9 +46,7 @@
);
// Assert
- final VerificationResult verification = verify(
- mockApi.create(captureAny, captureAny),
- );
+ final VerificationResult verification = verify(mockApi.create(captureAny, captureAny));
expect(verification.captured[0], cameraName);
final settings = verification.captured[1] as PlatformMediaSettings?;
expect(settings, isNotNull);
@@ -85,9 +83,7 @@
);
// Assert
- final VerificationResult verification = verify(
- mockApi.create(captureAny, captureAny),
- );
+ final VerificationResult verification = verify(mockApi.create(captureAny, captureAny));
expect(verification.captured[0], cameraName);
final settings = verification.captured[1] as PlatformMediaSettings?;
expect(settings, isNotNull);
@@ -100,78 +96,58 @@
},
);
- test(
- 'Should throw CameraException when create throws a PlatformException',
- () {
- // Arrange
- const exceptionCode = 'TESTING_ERROR_CODE';
- const exceptionMessage = 'Mock error message used during testing.';
- final mockApi = MockCameraApi();
- when(mockApi.create(any, any)).thenAnswer((_) async {
- throw PlatformException(
- code: exceptionCode,
- message: exceptionMessage,
- );
- });
- final camera = AVFoundationCamera(api: mockApi);
+ test('Should throw CameraException when create throws a PlatformException', () {
+ // Arrange
+ const exceptionCode = 'TESTING_ERROR_CODE';
+ const exceptionMessage = 'Mock error message used during testing.';
+ final mockApi = MockCameraApi();
+ when(mockApi.create(any, any)).thenAnswer((_) async {
+ throw PlatformException(code: exceptionCode, message: exceptionMessage);
+ });
+ final camera = AVFoundationCamera(api: mockApi);
- // Act
- expect(
- () => camera.createCamera(
- const CameraDescription(
- name: 'Test',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 0,
- ),
- ResolutionPreset.high,
+ // Act
+ expect(
+ () => camera.createCamera(
+ const CameraDescription(
+ name: 'Test',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 0,
),
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', exceptionCode)
- .having(
- (CameraException e) => e.description,
- 'description',
- exceptionMessage,
- ),
- ),
- );
- },
- );
+ ResolutionPreset.high,
+ ),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', exceptionCode)
+ .having((CameraException e) => e.description, 'description', exceptionMessage),
+ ),
+ );
+ });
- test(
- 'Should throw CameraException when initialize throws a PlatformException',
- () {
- // Arrange
- const exceptionCode = 'TESTING_ERROR_CODE';
- const exceptionMessage = 'Mock error message used during testing.';
- final mockApi = MockCameraApi();
- when(mockApi.initialize(any, any)).thenAnswer((_) async {
- throw PlatformException(
- code: exceptionCode,
- message: exceptionMessage,
- );
- });
- final camera = AVFoundationCamera(api: mockApi);
+ test('Should throw CameraException when initialize throws a PlatformException', () {
+ // Arrange
+ const exceptionCode = 'TESTING_ERROR_CODE';
+ const exceptionMessage = 'Mock error message used during testing.';
+ final mockApi = MockCameraApi();
+ when(mockApi.initialize(any, any)).thenAnswer((_) async {
+ throw PlatformException(code: exceptionCode, message: exceptionMessage);
+ });
+ final camera = AVFoundationCamera(api: mockApi);
- // Act
- expect(
- () => camera.initializeCamera(0),
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException e) => e.code,
- 'code',
- 'TESTING_ERROR_CODE',
- )
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Mock error message used during testing.',
- ),
- ),
- );
- },
- );
+ // Act
+ expect(
+ () => camera.initializeCamera(0),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
+ .having(
+ (CameraException e) => e.description,
+ 'description',
+ 'Mock error message used during testing.',
+ ),
+ ),
+ );
+ });
test('Should send initialization data', () async {
// Arrange
@@ -189,22 +165,12 @@
// Act
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ 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);
@@ -224,15 +190,7 @@
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true),
);
await initializeFuture;
@@ -240,9 +198,7 @@
await camera.dispose(cameraId);
// Assert
- final VerificationResult verification = verify(
- mockApi.dispose(captureAny),
- );
+ final VerificationResult verification = verify(mockApi.dispose(captureAny));
expect(verification.captured[0], cameraId);
});
});
@@ -264,23 +220,14 @@
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true),
);
await initializeFuture;
});
test('Should receive initialized event', () async {
// Act
- final Stream<CameraInitializedEvent> eventStream = camera
- .onCameraInitialized(cameraId);
+ final Stream<CameraInitializedEvent> eventStream = camera.onCameraInitialized(cameraId);
final streamQueue = StreamQueue<CameraInitializedEvent>(eventStream);
final previewSize = PlatformSize(width: 3840, height: 2160);
@@ -313,9 +260,7 @@
test('Should receive camera error events', () async {
// Act
- final Stream<CameraErrorEvent> errorStream = camera.onCameraError(
- cameraId,
- );
+ final Stream<CameraErrorEvent> errorStream = camera.onCameraError(cameraId);
final streamQueue = StreamQueue<CameraErrorEvent>(errorStream);
// Emit test events
@@ -336,18 +281,13 @@
test('Should receive device orientation change events', () async {
// Act
- final Stream<DeviceOrientationChangedEvent> eventStream = camera
- .onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
+ final Stream<DeviceOrientationChangedEvent> eventStream = camera.onDeviceOrientationChanged();
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
// Emit test events
const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
for (var i = 0; i < 3; i++) {
- camera.hostHandler.deviceOrientationChanged(
- PlatformDeviceOrientation.portraitUp,
- );
+ camera.hostHandler.deviceOrientationChanged(PlatformDeviceOrientation.portraitUp);
}
// Assert
@@ -379,78 +319,57 @@
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
- CameraInitializedEvent(
- cameraId,
- 1920,
- 1080,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- ),
+ CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true),
);
await initializeFuture;
});
- test(
- 'Should fetch CameraDescription instances for available cameras',
- () async {
- final returnData = <PlatformCameraDescription>[
- PlatformCameraDescription(
- name: 'Test 1',
- lensDirection: PlatformCameraLensDirection.front,
- lensType: PlatformCameraLensType.ultraWide,
- ),
- PlatformCameraDescription(
- name: 'Test 2',
- lensDirection: PlatformCameraLensDirection.back,
- lensType: PlatformCameraLensType.telephoto,
- ),
- ];
- when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData);
+ test('Should fetch CameraDescription instances for available cameras', () async {
+ final returnData = <PlatformCameraDescription>[
+ PlatformCameraDescription(
+ name: 'Test 1',
+ lensDirection: PlatformCameraLensDirection.front,
+ lensType: PlatformCameraLensType.ultraWide,
+ ),
+ PlatformCameraDescription(
+ name: 'Test 2',
+ lensDirection: PlatformCameraLensDirection.back,
+ lensType: PlatformCameraLensType.telephoto,
+ ),
+ ];
+ when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData);
- final List<CameraDescription> cameras = await camera.availableCameras();
+ final List<CameraDescription> cameras = await camera.availableCameras();
- expect(cameras.length, returnData.length);
- for (var i = 0; i < returnData.length; i++) {
- expect(cameras[i].name, returnData[i].name);
- expect(
- cameras[i].lensDirection,
- cameraLensDirectionFromPlatform(returnData[i].lensDirection),
- );
- expect(
- cameras[i].lensType,
- cameraLensTypeFromPlatform(returnData[i].lensType),
- );
- // 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 code = 'TESTING_ERROR_CODE';
- const message = 'Mock error message used during testing.';
- when(mockApi.getAvailableCameras()).thenAnswer(
- (_) async => throw PlatformException(code: code, message: message),
- );
-
+ expect(cameras.length, returnData.length);
+ for (var i = 0; i < returnData.length; i++) {
+ expect(cameras[i].name, returnData[i].name);
expect(
- camera.availableCameras,
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', code)
- .having(
- (CameraException e) => e.description,
- 'description',
- message,
- ),
- ),
+ cameras[i].lensDirection,
+ cameraLensDirectionFromPlatform(returnData[i].lensDirection),
);
- },
- );
+ expect(cameras[i].lensType, cameraLensTypeFromPlatform(returnData[i].lensType));
+ // 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 code = 'TESTING_ERROR_CODE';
+ const message = 'Mock error message used during testing.';
+ when(
+ mockApi.getAvailableCameras(),
+ ).thenAnswer((_) async => throw PlatformException(code: code, message: message));
+
+ expect(
+ camera.availableCameras,
+ throwsA(
+ isA<CameraException>()
+ .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 stubPath = '/test/path.jpg';
@@ -477,10 +396,7 @@
'Should pass enableStream if callback is passed when starting recording a video',
() async {
await camera.startVideoCapturing(
- VideoCaptureOptions(
- cameraId,
- streamCallback: (CameraImageData imageData) {},
- ),
+ VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}),
);
verify(mockApi.startVideoRecording(true));
@@ -560,9 +476,7 @@
const point = Point<double>(0.4, 0.6);
await camera.setExposurePoint(cameraId, point);
- final VerificationResult verification = verify(
- mockApi.setExposurePoint(captureAny),
- );
+ final VerificationResult verification = verify(mockApi.setExposurePoint(captureAny));
final passedPoint = verification.captured[0] as PlatformPoint?;
expect(passedPoint?.x, point.x);
expect(passedPoint?.y, point.y);
@@ -571,35 +485,25 @@
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 passedPoint = verification.captured[0] as PlatformPoint?;
expect(passedPoint, null);
});
test('Should get the min exposure offset', () async {
const 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 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);
});
@@ -635,9 +539,7 @@
const point = Point<double>(0.4, 0.6);
await camera.setFocusPoint(cameraId, point);
- final VerificationResult verification = verify(
- mockApi.setFocusPoint(captureAny),
- );
+ final VerificationResult verification = verify(mockApi.setFocusPoint(captureAny));
final passedPoint = verification.captured[0] as PlatformPoint?;
expect(passedPoint?.x, point.x);
expect(passedPoint?.y, point.y);
@@ -646,9 +548,7 @@
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 passedPoint = verification.captured[0] as PlatformPoint?;
expect(passedPoint, null);
});
@@ -686,108 +586,65 @@
verify(mockApi.setZoomLevel(zoom));
});
- test(
- 'Should throw CameraException when illegal zoom level is supplied',
- () async {
- const code = 'ZOOM_ERROR';
- const 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 code = 'ZOOM_ERROR';
+ const message = 'Illegal zoom error';
+ when(
+ mockApi.setZoomLevel(any),
+ ).thenAnswer((_) async => throw PlatformException(code: code, message: message));
- expect(
- () => camera.setZoomLevel(cameraId, -1.0),
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', code)
- .having(
- (CameraException e) => e.description,
- 'description',
- message,
- ),
- ),
- );
- },
- );
+ expect(
+ () => camera.setZoomLevel(cameraId, -1.0),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', code)
+ .having((CameraException e) => e.description, 'description', message),
+ ),
+ );
+ });
test('Should set video stabilization mode to off', () async {
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.off,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.off),
).thenAnswer((_) async => true);
- await camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.off,
- );
+ await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.off);
- verify(
- mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.off),
- );
+ verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.off));
});
test('Should set video stabilization mode to level1', () async {
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.standard,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.standard),
).thenAnswer((_) async => true);
- await camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level1,
- );
+ await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1);
- verify(
- mockApi.setVideoStabilizationMode(
- PlatformVideoStabilizationMode.standard,
- ),
- );
+ verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.standard));
});
test('Should set video stabilization mode to cinematic', () async {
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.cinematic,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematic),
).thenAnswer((_) async => true);
- await camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level2,
- );
+ await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level2);
- verify(
- mockApi.setVideoStabilizationMode(
- PlatformVideoStabilizationMode.cinematic,
- ),
- );
+ verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.cinematic));
});
test('Should set video stabilization mode to cinematicExtended', () async {
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.cinematicExtended,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematicExtended),
).thenAnswer((_) async => true);
- await camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level3,
- );
+ await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level3);
- verify(
- mockApi.setVideoStabilizationMode(
- PlatformVideoStabilizationMode.cinematicExtended,
- ),
- );
+ verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.cinematicExtended));
});
test('Should get no video stabilization mode', () async {
- when(
- mockApi.isVideoStabilizationModeSupported(any),
- ).thenAnswer((_) async => false);
+ when(mockApi.isVideoStabilizationModeSupported(any)).thenAnswer((_) async => false);
final Iterable<VideoStabilizationMode> modes = await camera
.getSupportedVideoStabilizationModes(cameraId);
@@ -797,28 +654,21 @@
test('Should get off and standard video stabilization modes', () async {
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.off,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.off),
).thenAnswer((_) async => true);
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.standard,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.standard),
).thenAnswer((_) async => true);
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.cinematic,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematic),
).thenAnswer((_) async => false);
when(
- mockApi.isVideoStabilizationModeSupported(
- PlatformVideoStabilizationMode.cinematicExtended,
- ),
+ mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematicExtended),
).thenAnswer((_) async => false);
- final List<VideoStabilizationMode> modes =
- (await camera.getSupportedVideoStabilizationModes(cameraId)).toList();
+ final List<VideoStabilizationMode> modes = (await camera.getSupportedVideoStabilizationModes(
+ cameraId,
+ )).toList();
expect(modes, <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -827,12 +677,11 @@
});
test('Should get all video stabilization modes', () async {
- when(
- mockApi.isVideoStabilizationModeSupported(any),
- ).thenAnswer((_) async => true);
+ when(mockApi.isVideoStabilizationModeSupported(any)).thenAnswer((_) async => true);
- final List<VideoStabilizationMode> modes =
- (await camera.getSupportedVideoStabilizationModes(cameraId)).toList();
+ final List<VideoStabilizationMode> modes = (await camera.getSupportedVideoStabilizationModes(
+ cameraId,
+ )).toList();
expect(modes, <VideoStabilizationMode>[
VideoStabilizationMode.off,
@@ -842,101 +691,48 @@
]);
});
- test(
- 'Should throw ArgumentError when unavailable video stabilization mode is set',
- () async {
- when(
- mockApi.isVideoStabilizationModeSupported(any),
- ).thenAnswer((_) async => false);
+ test('Should throw ArgumentError when unavailable video stabilization mode is set', () async {
+ when(mockApi.isVideoStabilizationModeSupported(any)).thenAnswer((_) async => false);
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.off,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level1,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level2,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- expect(
- () => camera.setVideoStabilizationMode(
- cameraId,
- VideoStabilizationMode.level3,
- ),
- throwsA(
- isA<ArgumentError>().having(
- (ArgumentError e) => e.name,
- 'name',
- 'mode',
- ),
- ),
- );
- },
- );
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.off),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level2),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ expect(
+ () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level3),
+ throwsA(isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'mode')),
+ );
+ });
- test(
- 'Should throw CameraException when illegal zoom level is supplied',
- () async {
- const code = 'ZOOM_ERROR';
- const 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 code = 'ZOOM_ERROR';
+ const message = 'Illegal zoom error';
+ when(
+ mockApi.setZoomLevel(any),
+ ).thenAnswer((_) async => throw PlatformException(code: code, message: message));
- expect(
- () => camera.setZoomLevel(cameraId, -1.0),
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', code)
- .having(
- (CameraException e) => e.description,
- 'description',
- message,
- ),
- ),
- );
- },
- );
+ expect(
+ () => camera.setZoomLevel(cameraId, -1.0),
+ throwsA(
+ isA<CameraException>()
+ .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,
- );
+ await camera.lockCaptureOrientation(cameraId, DeviceOrientation.portraitUp);
- verify(
- mockApi.lockCaptureOrientation(PlatformDeviceOrientation.portraitUp),
- );
+ verify(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 225eac9..0bea181 100644
--- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart
+++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart
@@ -49,18 +49,14 @@
returnValue: _i4.Future<List<_i2.PlatformCameraDescription>>.value(
<_i2.PlatformCameraDescription>[],
),
- returnValueForMissingStub:
- _i4.Future<List<_i2.PlatformCameraDescription>>.value(
- <_i2.PlatformCameraDescription>[],
- ),
+ returnValueForMissingStub: _i4.Future<List<_i2.PlatformCameraDescription>>.value(
+ <_i2.PlatformCameraDescription>[],
+ ),
)
as _i4.Future<List<_i2.PlatformCameraDescription>>);
@override
- _i4.Future<int> create(
- String? cameraName,
- _i2.PlatformMediaSettings? settings,
- ) =>
+ _i4.Future<int> create(String? cameraName, _i2.PlatformMediaSettings? settings) =>
(super.noSuchMethod(
Invocation.method(#create, [cameraName, settings]),
returnValue: _i4.Future<int>.value(0),
@@ -69,10 +65,7 @@
as _i4.Future<int>);
@override
- _i4.Future<void> initialize(
- int? cameraId,
- _i2.PlatformImageFormatGroup? imageFormat,
- ) =>
+ _i4.Future<void> initialize(int? cameraId, _i2.PlatformImageFormatGroup? imageFormat) =>
(super.noSuchMethod(
Invocation.method(#initialize, [cameraId, imageFormat]),
returnValue: _i4.Future<void>.value(),
@@ -117,9 +110,7 @@
as _i4.Future<void>);
@override
- _i4.Future<void> lockCaptureOrientation(
- _i2.PlatformDeviceOrientation? orientation,
- ) =>
+ _i4.Future<void> lockCaptureOrientation(_i2.PlatformDeviceOrientation? orientation) =>
(super.noSuchMethod(
Invocation.method(#lockCaptureOrientation, [orientation]),
returnValue: _i4.Future<void>.value(),
@@ -172,16 +163,10 @@
(super.noSuchMethod(
Invocation.method(#stopVideoRecording, []),
returnValue: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#stopVideoRecording, []),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#stopVideoRecording, [])),
),
returnValueForMissingStub: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#stopVideoRecording, []),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#stopVideoRecording, [])),
),
)
as _i4.Future<String>);
@@ -304,9 +289,7 @@
as _i4.Future<void>);
@override
- _i4.Future<void> setVideoStabilizationMode(
- _i2.PlatformVideoStabilizationMode? mode,
- ) =>
+ _i4.Future<void> setVideoStabilizationMode(_i2.PlatformVideoStabilizationMode? mode) =>
(super.noSuchMethod(
Invocation.method(#setVideoStabilizationMode, [mode]),
returnValue: _i4.Future<void>.value(),
@@ -315,9 +298,7 @@
as _i4.Future<void>);
@override
- _i4.Future<bool> isVideoStabilizationModeSupported(
- _i2.PlatformVideoStabilizationMode? mode,
- ) =>
+ _i4.Future<bool> isVideoStabilizationModeSupported(_i2.PlatformVideoStabilizationMode? mode) =>
(super.noSuchMethod(
Invocation.method(#isVideoStabilizationModeSupported, [mode]),
returnValue: _i4.Future<bool>.value(false),
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 78cd0ac..06cbdaf 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
@@ -35,9 +35,7 @@
@override
bool operator ==(Object other) =>
identical(this, other) ||
- other is CameraEvent &&
- runtimeType == other.runtimeType &&
- cameraId == other.cameraId;
+ other is CameraEvent && runtimeType == other.runtimeType && cameraId == other.cameraId;
@override
int get hashCode => cameraId.hashCode;
@@ -66,8 +64,7 @@
: previewWidth = json['previewWidth']! as double,
previewHeight = json['previewHeight']! as double,
exposureMode = deserializeExposureMode(json['exposureMode']! as String),
- exposurePointSupported =
- (json['exposurePointSupported'] as bool?) ?? false,
+ exposurePointSupported = (json['exposurePointSupported'] as bool?) ?? false,
focusMode = deserializeFocusMode(json['focusMode']! as String),
focusPointSupported = (json['focusPointSupported'] as bool?) ?? false,
super(json['cameraId']! as int);
@@ -134,11 +131,7 @@
///
/// The `captureWidth` represents the width of the resulting image in pixels.
/// The `captureHeight` represents the height of the resulting image in pixels.
- const CameraResolutionChangedEvent(
- super.cameraId,
- this.captureWidth,
- this.captureHeight,
- );
+ const CameraResolutionChangedEvent(super.cameraId, this.captureWidth, this.captureHeight);
/// Converts the supplied [Map] to an instance of the
/// [CameraResolutionChangedEvent] class.
@@ -182,8 +175,7 @@
/// Converts the supplied [Map] to an instance of the [CameraClosingEvent]
/// class.
- CameraClosingEvent.fromJson(Map<String, dynamic> json)
- : super(json['cameraId']! as int);
+ CameraClosingEvent.fromJson(Map<String, dynamic> json) : super(json['cameraId']! as int);
/// Converts the [CameraClosingEvent] instance into a [Map] instance that can
/// be serialized to JSON.
@@ -192,9 +184,7 @@
@override
bool operator ==(Object other) =>
identical(this, other) ||
- super == other &&
- other is CameraClosingEvent &&
- runtimeType == other.runtimeType;
+ super == other && other is CameraClosingEvent && runtimeType == other.runtimeType;
@override
// This is here even though it just calls super to make it less likely that
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 1751363..7b3975e 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,9 +34,7 @@
/// Converts the supplied [Map] to an instance of the [DeviceOrientationChangedEvent]
/// class.
DeviceOrientationChangedEvent.fromJson(Map<String, dynamic> json)
- : orientation = deserializeDeviceOrientation(
- json['orientation']! as String,
- );
+ : orientation = deserializeDeviceOrientation(json['orientation']! as String);
/// The new orientation of the device
final DeviceOrientation orientation;
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 97c4107..7423ebb 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
@@ -21,9 +21,7 @@
/// Construct a new method channel camera instance.
MethodChannelCamera() {
const channel = MethodChannel('flutter.io/cameraPlugin/device');
- channel.setMethodCallHandler(
- (MethodCall call) => handleDeviceMethodCall(call),
- );
+ channel.setMethodCallHandler((MethodCall call) => handleDeviceMethodCall(call));
}
final Map<int, MethodChannel> _channels = <int, MethodChannel>{};
@@ -56,9 +54,8 @@
// The stream for vending frames to platform interface clients.
StreamController<CameraImageData>? _frameStreamController;
- Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
- .stream
- .where((CameraEvent event) => event.cameraId == cameraId);
+ Stream<CameraEvent> _cameraEvents(int cameraId) =>
+ cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId);
@override
Future<List<CameraDescription>> availableCameras() async {
@@ -73,9 +70,7 @@
return cameras.map((Map<dynamic, dynamic> 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();
@@ -126,9 +121,7 @@
}) {
_channels.putIfAbsent(cameraId, () {
final channel = MethodChannel('flutter.io/cameraPlugin/camera$cameraId');
- channel.setMethodCallHandler(
- (MethodCall call) => handleCameraMethodCall(call, cameraId),
- );
+ channel.setMethodCallHandler((MethodCall call) => handleCameraMethodCall(call, cameraId));
return channel;
});
@@ -153,10 +146,7 @@
// ignore: only_throw_errors
throw error;
}
- completer.completeError(
- CameraException(error.code, error.message),
- stackTrace,
- );
+ completer.completeError(CameraException(error.code, error.message), stackTrace);
},
);
@@ -171,9 +161,7 @@
_channels.remove(cameraId);
}
- await _channel.invokeMethod<void>('dispose', <String, dynamic>{
- 'cameraId': cameraId,
- });
+ await _channel.invokeMethod<void>('dispose', <String, dynamic>{'cameraId': cameraId});
}
@override
@@ -203,38 +191,29 @@
@override
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() {
- return deviceEventStreamController.stream
- .whereType<DeviceOrientationChangedEvent>();
+ return deviceEventStreamController.stream.whereType<DeviceOrientationChangedEvent>();
}
@override
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) async {
- await _channel.invokeMethod<String>(
- 'lockCaptureOrientation',
- <String, dynamic>{
- 'cameraId': cameraId,
- 'orientation': serializeDeviceOrientation(orientation),
- },
- );
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async {
+ await _channel.invokeMethod<String>('lockCaptureOrientation', <String, dynamic>{
+ 'cameraId': cameraId,
+ 'orientation': serializeDeviceOrientation(orientation),
+ });
}
@override
Future<void> unlockCaptureOrientation(int cameraId) async {
- await _channel.invokeMethod<String>(
- 'unlockCaptureOrientation',
- <String, dynamic>{'cameraId': cameraId},
- );
+ await _channel.invokeMethod<String>('unlockCaptureOrientation', <String, dynamic>{
+ 'cameraId': cameraId,
+ });
}
@override
Future<XFile> takePicture(int cameraId) async {
- final String? path = await _channel.invokeMethod<String>(
- 'takePicture',
- <String, dynamic>{'cameraId': cameraId},
- );
+ final String? path = await _channel.invokeMethod<String>('takePicture', <String, dynamic>{
+ 'cameraId': cameraId,
+ });
if (path == null) {
throw CameraException(
@@ -251,13 +230,8 @@
_channel.invokeMethod<void>('prepareForVideoRecording');
@override
- Future<void> startVideoRecording(
- int cameraId, {
- Duration? maxVideoDuration,
- }) async {
- return startVideoCapturing(
- VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration),
- );
+ Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async {
+ return startVideoCapturing(VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration));
}
@override
@@ -292,16 +266,12 @@
}
@override
- Future<void> pauseVideoRecording(int cameraId) => _channel.invokeMethod<void>(
- 'pauseVideoRecording',
- <String, dynamic>{'cameraId': cameraId},
- );
+ Future<void> pauseVideoRecording(int cameraId) =>
+ _channel.invokeMethod<void>('pauseVideoRecording', <String, dynamic>{'cameraId': cameraId});
@override
Future<void> resumeVideoRecording(int cameraId) =>
- _channel.invokeMethod<void>('resumeVideoRecording', <String, dynamic>{
- 'cameraId': cameraId,
- });
+ _channel.invokeMethod<void>('resumeVideoRecording', <String, dynamic>{'cameraId': cameraId});
@override
Stream<CameraImageData> onStreamedFrameAvailable(
@@ -312,9 +282,7 @@
return _frameStreamController!.stream;
}
- StreamController<CameraImageData> _installStreamController({
- void Function()? onListen,
- }) {
+ StreamController<CameraImageData> _installStreamController({void Function()? onListen}) {
_frameStreamController = StreamController<CameraImageData>(
onListen: onListen ?? () {},
onPause: _onFrameStreamPauseResume,
@@ -334,23 +302,19 @@
}
void _startStreamListener() {
- const cameraEventChannel = EventChannel(
- 'plugins.flutter.io/camera/imageStream',
- );
- _platformImageStreamSubscription = cameraEventChannel
- .receiveBroadcastStream()
- .listen((dynamic imageData) {
- if (defaultTargetPlatform == TargetPlatform.iOS) {
- try {
- _channel.invokeMethod<void>('receivedImageStreamData');
- } on PlatformException catch (e) {
- throw CameraException(e.code, e.message);
- }
- }
- _frameStreamController!.add(
- cameraImageFromPlatformData(imageData as Map<dynamic, dynamic>),
- );
- });
+ const cameraEventChannel = EventChannel('plugins.flutter.io/camera/imageStream');
+ _platformImageStreamSubscription = cameraEventChannel.receiveBroadcastStream().listen((
+ dynamic imageData,
+ ) {
+ if (defaultTargetPlatform == TargetPlatform.iOS) {
+ try {
+ _channel.invokeMethod<void>('receivedImageStreamData');
+ } on PlatformException catch (e) {
+ throw CameraException(e.code, e.message);
+ }
+ }
+ _frameStreamController!.add(cameraImageFromPlatformData(imageData as Map<dynamic, dynamic>));
+ });
}
FutureOr<void> _onFrameStreamCancel() async {
@@ -368,18 +332,16 @@
}
@override
- Future<void> setFlashMode(int cameraId, FlashMode mode) =>
- _channel.invokeMethod<void>('setFlashMode', <String, dynamic>{
- 'cameraId': cameraId,
- 'mode': _serializeFlashMode(mode),
- });
+ Future<void> setFlashMode(int cameraId, FlashMode mode) => _channel.invokeMethod<void>(
+ 'setFlashMode',
+ <String, dynamic>{'cameraId': cameraId, 'mode': _serializeFlashMode(mode)},
+ );
@override
- Future<void> setExposureMode(int cameraId, ExposureMode mode) =>
- _channel.invokeMethod<void>('setExposureMode', <String, dynamic>{
- 'cameraId': cameraId,
- 'mode': serializeExposureMode(mode),
- });
+ Future<void> setExposureMode(int cameraId, ExposureMode mode) => _channel.invokeMethod<void>(
+ 'setExposureMode',
+ <String, dynamic>{'cameraId': cameraId, 'mode': serializeExposureMode(mode)},
+ );
@override
Future<void> setExposurePoint(int cameraId, Point<double>? point) {
@@ -435,11 +397,10 @@
}
@override
- Future<void> setFocusMode(int cameraId, FocusMode mode) =>
- _channel.invokeMethod<void>('setFocusMode', <String, dynamic>{
- 'cameraId': cameraId,
- 'mode': serializeFocusMode(mode),
- });
+ Future<void> setFocusMode(int cameraId, FocusMode mode) => _channel.invokeMethod<void>(
+ 'setFocusMode',
+ <String, dynamic>{'cameraId': cameraId, 'mode': serializeFocusMode(mode)},
+ );
@override
Future<void> setFocusPoint(int cameraId, Point<double>? point) {
@@ -488,26 +449,19 @@
@override
Future<void> pausePreview(int cameraId) async {
- await _channel.invokeMethod<double>('pausePreview', <String, dynamic>{
- 'cameraId': cameraId,
- });
+ await _channel.invokeMethod<double>('pausePreview', <String, dynamic>{'cameraId': cameraId});
}
@override
Future<void> resumePreview(int cameraId) async {
- await _channel.invokeMethod<double>('resumePreview', <String, dynamic>{
- 'cameraId': cameraId,
- });
+ await _channel.invokeMethod<double>('resumePreview', <String, dynamic>{'cameraId': cameraId});
}
@override
- Future<void> setDescriptionWhileRecording(
- CameraDescription description,
- ) async {
- await _channel.invokeMethod<double>(
- 'setDescriptionWhileRecording',
- <String, dynamic>{'cameraName': description.name},
- );
+ Future<void> setDescriptionWhileRecording(CameraDescription description) async {
+ await _channel.invokeMethod<double>('setDescriptionWhileRecording', <String, dynamic>{
+ 'cameraName': description.name,
+ });
}
@override
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 457d7d0..b7eaa0b 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
@@ -18,9 +18,8 @@
sensorSensitivity: data['sensorSensitivity'] as double?,
planes: List<CameraImagePlane>.unmodifiable(
(data['planes'] as List<dynamic>).map<CameraImagePlane>(
- (dynamic planeData) => _cameraImagePlaneFromPlatformData(
- planeData as Map<dynamic, dynamic>,
- ),
+ (dynamic planeData) =>
+ _cameraImagePlaneFromPlatformData(planeData as Map<dynamic, dynamic>),
),
),
);
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 192bce8..efb1576 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
@@ -113,16 +113,11 @@
/// Implementations for this:
/// - Should support all 4 orientations.
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() {
- throw UnimplementedError(
- 'onDeviceOrientationChanged() is not implemented.',
- );
+ throw UnimplementedError('onDeviceOrientationChanged() is not implemented.');
}
/// Locks the capture orientation.
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) {
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) {
throw UnimplementedError('lockCaptureOrientation() is not implemented.');
}
@@ -146,9 +141,7 @@
/// This method is deprecated in favour of [startVideoCapturing].
Future<void> startVideoRecording(
int cameraId, {
- @Deprecated(
- 'This parameter is unused, and will be ignored on all platforms',
- )
+ @Deprecated('This parameter is unused, and will be ignored on all platforms')
Duration? maxVideoDuration,
}) {
throw UnimplementedError('startVideoRecording() is not implemented.');
@@ -282,15 +275,11 @@
}
/// Gets a list of video stabilization modes that are supported for the selected camera.
- Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(
- int cameraId,
- ) => Future<List<VideoStabilizationMode>>.value(<VideoStabilizationMode>[]);
+ Future<Iterable<VideoStabilizationMode>> getSupportedVideoStabilizationModes(int cameraId) =>
+ Future<List<VideoStabilizationMode>>.value(<VideoStabilizationMode>[]);
/// Sets the video stabilization mode for the selected camera.
- Future<void> setVideoStabilizationMode(
- int cameraId,
- VideoStabilizationMode mode,
- ) {
+ Future<void> setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) {
throw UnimplementedError('setVideoStabilizationMode() is not implemented.');
}
@@ -298,9 +287,7 @@
///
/// This method returns the video stabilization mode that [setVideoStabilizationMode]
/// should set when the device does not support the given [mode].
- static VideoStabilizationMode? getFallbackVideoStabilizationMode(
- VideoStabilizationMode mode,
- ) {
+ static VideoStabilizationMode? getFallbackVideoStabilizationMode(VideoStabilizationMode mode) {
return switch (mode) {
VideoStabilizationMode.off => null,
VideoStabilizationMode.level1 => VideoStabilizationMode.off,
@@ -325,9 +312,7 @@
/// with `enablePersistentRecording` set to `true`
/// to avoid cancelling any active recording.
Future<void> setDescriptionWhileRecording(CameraDescription description) {
- throw UnimplementedError(
- 'setDescriptionWhileRecording() is not implemented.',
- );
+ throw UnimplementedError('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 579f7b8..8f84e8f 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
@@ -61,13 +61,7 @@
}
@override
- int get hashCode => Object.hash(
- resolutionPreset,
- fps,
- videoBitrate,
- audioBitrate,
- enableAudio,
- );
+ int get hashCode => Object.hash(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 dda06fb..d5e38e8 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
@@ -12,10 +12,7 @@
/// Constructs a new instance.
const VideoCaptureOptions(
this.cameraId, {
- @Deprecated(
- 'This parameter is unused, and will be ignored on all platforms',
- )
- this.maxDuration,
+ @Deprecated('This parameter is unused, and will be ignored on all platforms') this.maxDuration,
this.streamCallback,
this.streamOptions,
this.enablePersistentRecording = true,
@@ -67,11 +64,6 @@
enablePersistentRecording == other.enablePersistentRecording;
@override
- int get hashCode => Object.hash(
- cameraId,
- maxDuration,
- streamCallback,
- streamOptions,
- enablePersistentRecording,
- );
+ int get hashCode =>
+ Object.hash(cameraId, maxDuration, streamCallback, streamOptions, enablePersistentRecording);
}
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 8453772..787122c 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
@@ -32,72 +32,45 @@
CameraPlatform.instance = ExtendsCameraPlatform();
});
- test(
- 'Default implementation of availableCameras() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of availableCameras() should throw unimplemented error', () {
+ // Arrange
+ final cameraPlatform = ExtendsCameraPlatform();
- // Act & Assert
- expect(
- () => cameraPlatform.availableCameras(),
- throwsUnimplementedError,
- );
- },
- );
+ // Act & Assert
+ expect(() => cameraPlatform.availableCameras(), throwsUnimplementedError);
+ });
- test(
- 'Default implementation of onCameraInitialized() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of onCameraInitialized() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of onResolutionChanged() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of onCameraClosing() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of onCameraError() should throw unimplemented error', () {
+ // Arrange
+ final 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',
@@ -106,29 +79,20 @@
final cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
- expect(
- () => cameraPlatform.onDeviceOrientationChanged(),
- throwsUnimplementedError,
- );
+ expect(() => cameraPlatform.onDeviceOrientationChanged(), throwsUnimplementedError);
},
);
- test(
- 'Default implementation of lockCaptureOrientation() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of lockCaptureOrientation() should throw unimplemented error', () {
+ // Arrange
+ final 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',
@@ -137,44 +101,35 @@
final cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
- expect(
- () => cameraPlatform.unlockCaptureOrientation(1),
- throwsUnimplementedError,
- );
+ expect(() => cameraPlatform.unlockCaptureOrientation(1), throwsUnimplementedError);
},
);
- test(
- 'Default implementation of dispose() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of dispose() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of createCamera() should throw unimplemented error', () {
+ // Arrange
+ final cameraPlatform = ExtendsCameraPlatform();
- // Act & Assert
- expect(
- () => cameraPlatform.createCamera(
- const CameraDescription(
- name: 'back',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 0,
- ),
- ResolutionPreset.low,
+ // Act & Assert
+ expect(
+ () => cameraPlatform.createCamera(
+ const CameraDescription(
+ name: 'back',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 0,
),
- throwsUnimplementedError,
- );
- },
- );
+ ResolutionPreset.low,
+ ),
+ throwsUnimplementedError,
+ );
+ });
test(
'Default implementation of createCameraWithSettings() should call createCamera() passing parameters',
@@ -201,30 +156,19 @@
ResolutionPreset? resolutionPresetArg,
bool enableAudioArg,
) {
- expect(
- cameraDescriptionArg,
- cameraDescription,
- reason: 'should pass camera description',
- );
+ 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',
- );
+ expect(enableAudioArg, mediaSettings.enableAudio, reason: 'should pass enableAudio');
createCameraCalled = true;
});
// Act & Assert
- cameraPlatform.createCameraWithSettings(
- cameraDescription,
- mediaSettings,
- );
+ cameraPlatform.createCameraWithSettings(cameraDescription, mediaSettings);
expect(
createCameraCalled,
@@ -235,33 +179,21 @@
},
);
- test(
- 'Default implementation of initializeCamera() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of initializeCamera() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of pauseVideoRecording() should throw unimplemented error', () {
+ // Arrange
+ final 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',
@@ -270,96 +202,57 @@
final cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
- expect(
- () => cameraPlatform.prepareForVideoRecording(),
- throwsUnimplementedError,
- );
+ expect(() => cameraPlatform.prepareForVideoRecording(), throwsUnimplementedError);
},
);
- test(
- 'Default implementation of resumeVideoRecording() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of resumeVideoRecording() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setFlashMode() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setExposureMode() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setExposurePoint() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of getMinExposureOffset() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of getMaxExposureOffset() should throw unimplemented error', () {
+ // Arrange
+ final 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',
@@ -368,221 +261,142 @@
final cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
- expect(
- () => cameraPlatform.getExposureOffsetStepSize(1),
- throwsUnimplementedError,
- );
+ expect(() => cameraPlatform.getExposureOffsetStepSize(1), throwsUnimplementedError);
},
);
- test(
- 'Default implementation of setExposureOffset() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setExposureOffset() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setFocusMode() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setFocusPoint() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of startVideoRecording() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of stopVideoRecording() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of takePicture() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of getMaxZoomLevel() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of getMinZoomLevel() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setZoomLevel() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of pausePreview() should throw unimplemented error', () {
+ // Arrange
+ final 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 cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of resumePreview() should throw unimplemented error', () {
+ // Arrange
+ final cameraPlatform = ExtendsCameraPlatform();
- // Act & Assert
- expect(() => cameraPlatform.resumePreview(1), throwsUnimplementedError);
- },
- );
+ // Act & Assert
+ expect(() => cameraPlatform.resumePreview(1), throwsUnimplementedError);
+ });
- test(
- 'Default implementation of setJpegImageQuality() should throw unimplemented error',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of setJpegImageQuality() should throw unimplemented error', () {
+ // Arrange
+ final cameraPlatform = ExtendsCameraPlatform();
- // Act & Assert
- expect(
- () => cameraPlatform.setJpegImageQuality(1, 50),
- throwsUnimplementedError,
- );
- },
- );
+ // Act & Assert
+ expect(() => cameraPlatform.setJpegImageQuality(1, 50), throwsUnimplementedError);
+ });
- test(
- 'Default implementation of supportsImageStreaming() should return false',
- () {
- // Arrange
- final cameraPlatform = ExtendsCameraPlatform();
+ test('Default implementation of supportsImageStreaming() should return false', () {
+ // Arrange
+ final cameraPlatform = ExtendsCameraPlatform();
- // Act & Assert
- expect(cameraPlatform.supportsImageStreaming(), false);
- },
- );
+ // Act & Assert
+ expect(cameraPlatform.supportsImageStreaming(), false);
+ });
- test(
- 'getFallbackVideoStabilizationMode returns level2 for mode level3',
- () {
- final VideoStabilizationMode? fallbackMode =
- CameraPlatform.getFallbackVideoStabilizationMode(
- VideoStabilizationMode.level3,
- );
+ test('getFallbackVideoStabilizationMode returns level2 for mode level3', () {
+ final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(
+ VideoStabilizationMode.level3,
+ );
- expect(fallbackMode, VideoStabilizationMode.level2);
- },
- );
+ expect(fallbackMode, VideoStabilizationMode.level2);
+ });
- test(
- 'getFallbackVideoStabilizationMode returns level1 for mode level2',
- () {
- final VideoStabilizationMode? fallbackMode =
- CameraPlatform.getFallbackVideoStabilizationMode(
- VideoStabilizationMode.level2,
- );
+ test('getFallbackVideoStabilizationMode returns level1 for mode level2', () {
+ final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(
+ VideoStabilizationMode.level2,
+ );
- expect(fallbackMode, VideoStabilizationMode.level1);
- },
- );
+ expect(fallbackMode, VideoStabilizationMode.level1);
+ });
test('getFallbackVideoStabilizationMode returns off for mode level1', () {
- final VideoStabilizationMode? fallbackMode =
- CameraPlatform.getFallbackVideoStabilizationMode(
- VideoStabilizationMode.level1,
- );
+ final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(
+ VideoStabilizationMode.level1,
+ );
expect(fallbackMode, VideoStabilizationMode.off);
});
test('getFallbackVideoStabilizationMode returns null for mode off', () {
- final VideoStabilizationMode? fallbackMode =
- CameraPlatform.getFallbackVideoStabilizationMode(
- VideoStabilizationMode.off,
- );
+ final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(
+ VideoStabilizationMode.off,
+ );
expect(fallbackMode, null);
});
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 58ace30..55cd347 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
@@ -187,31 +187,28 @@
expect(firstEvent == secondEvent, false);
});
- test(
- 'equals should return false if exposurePointSupported is different',
- () {
- const firstEvent = CameraInitializedEvent(
- 1,
- 1024,
- 640,
- ExposureMode.auto,
- true,
- FocusMode.auto,
- true,
- );
- const secondEvent = CameraInitializedEvent(
- 1,
- 1024,
- 640,
- ExposureMode.auto,
- false,
- FocusMode.auto,
- true,
- );
+ test('equals should return false if exposurePointSupported is different', () {
+ const firstEvent = CameraInitializedEvent(
+ 1,
+ 1024,
+ 640,
+ ExposureMode.auto,
+ true,
+ FocusMode.auto,
+ true,
+ );
+ const secondEvent = CameraInitializedEvent(
+ 1,
+ 1024,
+ 640,
+ ExposureMode.auto,
+ false,
+ FocusMode.auto,
+ true,
+ );
- expect(firstEvent == secondEvent, false);
- },
- );
+ expect(firstEvent == secondEvent, false);
+ });
test('equals should return false if focusMode is different', () {
const firstEvent = CameraInitializedEvent(
@@ -293,13 +290,11 @@
});
test('fromJson should initialize all properties', () {
- final event = CameraResolutionChangedEvent.fromJson(
- const <String, dynamic>{
- 'cameraId': 1,
- 'captureWidth': 1024.0,
- 'captureHeight': 640.0,
- },
- );
+ final event = CameraResolutionChangedEvent.fromJson(const <String, dynamic>{
+ 'cameraId': 1,
+ 'captureWidth': 1024.0,
+ 'captureHeight': 640.0,
+ });
expect(event.cameraId, 1);
expect(event.captureWidth, 1024);
@@ -365,9 +360,7 @@
});
test('fromJson should initialize all properties', () {
- final event = CameraClosingEvent.fromJson(const <String, dynamic>{
- 'cameraId': 1,
- });
+ final event = CameraClosingEvent.fromJson(const <String, dynamic>{'cameraId': 1});
expect(event.cameraId, 1);
});
@@ -454,10 +447,7 @@
test('hashCode should match hashCode of all properties', () {
const 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 794a301..59a0a3a 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
@@ -17,9 +17,9 @@
});
test('fromJson should initialize all properties', () {
- final event = DeviceOrientationChangedEvent.fromJson(
- const <String, dynamic>{'orientation': 'portraitUp'},
- );
+ final event = DeviceOrientationChangedEvent.fromJson(const <String, dynamic>{
+ 'orientation': 'portraitUp',
+ });
expect(event.orientation, DeviceOrientation.portraitUp);
});
@@ -34,23 +34,15 @@
});
test('equals should return true if objects are the same', () {
- const firstEvent = DeviceOrientationChangedEvent(
- DeviceOrientation.portraitUp,
- );
- const secondEvent = DeviceOrientationChangedEvent(
- DeviceOrientation.portraitUp,
- );
+ const firstEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
+ const secondEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if orientation is different', () {
- const firstEvent = DeviceOrientationChangedEvent(
- DeviceOrientation.portraitUp,
- );
- const secondEvent = DeviceOrientationChangedEvent(
- DeviceOrientation.landscapeLeft,
- );
+ const firstEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
+ const secondEvent = DeviceOrientationChangedEvent(DeviceOrientation.landscapeLeft);
expect(firstEvent == secondEvent, false);
});
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 a52d725..cd592fc 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
@@ -25,10 +25,7 @@
final cameraMockChannel = MethodChannelMock(
channelName: 'plugins.flutter.io/camera',
methods: <String, dynamic>{
- 'create': <String, dynamic>{
- 'cameraId': 1,
- 'imageFormatGroup': 'unknown',
- },
+ 'create': <String, dynamic>{'cameraId': 1, 'imageFormatGroup': 'unknown'},
},
);
final camera = MethodChannelCamera();
@@ -65,146 +62,122 @@
expect(cameraId, 1);
});
- test(
- 'Should throw CameraException when create throws a PlatformException',
- () {
- // Arrange
- MethodChannelMock(
- channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- 'create': PlatformException(
- code: 'TESTING_ERROR_CODE',
- message: 'Mock error message used during testing.',
- ),
- },
- );
- final camera = MethodChannelCamera();
-
- // 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,
- ),
+ test('Should throw CameraException when create throws a PlatformException', () {
+ // Arrange
+ MethodChannelMock(
+ channelName: 'plugins.flutter.io/camera',
+ methods: <String, dynamic>{
+ 'create': PlatformException(
+ code: 'TESTING_ERROR_CODE',
+ message: 'Mock error message used during testing.',
),
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException e) => e.code,
- 'code',
- 'TESTING_ERROR_CODE',
- )
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Mock error message used during testing.',
- ),
- ),
- );
- },
- );
+ },
+ );
+ final camera = MethodChannelCamera();
- test(
- 'Should throw CameraException when create throws a PlatformException',
- () {
- // Arrange
- MethodChannelMock(
- channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- 'create': PlatformException(
- code: 'TESTING_ERROR_CODE',
- message: 'Mock error message used during testing.',
- ),
- },
- );
- final camera = MethodChannelCamera();
-
- // 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,
- ),
+ // Act
+ expect(
+ () => camera.createCameraWithSettings(
+ const CameraDescription(
+ name: 'Test',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 0,
),
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException e) => e.code,
- 'code',
- 'TESTING_ERROR_CODE',
- )
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Mock error message used during testing.',
- ),
+ const MediaSettings(
+ resolutionPreset: ResolutionPreset.low,
+ fps: 15,
+ videoBitrate: 200000,
+ audioBitrate: 32000,
+ enableAudio: true,
),
- );
- },
- );
+ ),
+ throwsA(
+ isA<CameraException>()
+ .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
- MethodChannelMock(
- channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- 'initialize': PlatformException(
- code: 'TESTING_ERROR_CODE',
- message: 'Mock error message used during testing.',
- ),
- },
- );
- final camera = MethodChannelCamera();
-
- // Act
- expect(
- () => camera.initializeCamera(0),
- throwsA(
- isA<CameraException>()
- .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(
+ channelName: 'plugins.flutter.io/camera',
+ methods: <String, dynamic>{
+ 'create': PlatformException(
+ code: 'TESTING_ERROR_CODE',
+ message: 'Mock error message used during testing.',
),
- );
- },
- );
+ },
+ );
+ final camera = MethodChannelCamera();
+
+ // 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,
+ ),
+ ),
+ throwsA(
+ isA<CameraException>()
+ .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
+ MethodChannelMock(
+ channelName: 'plugins.flutter.io/camera',
+ methods: <String, dynamic>{
+ 'initialize': PlatformException(
+ code: 'TESTING_ERROR_CODE',
+ message: 'Mock error message used during testing.',
+ ),
+ },
+ );
+ final camera = MethodChannelCamera();
+
+ // Act
+ expect(
+ () => camera.initializeCamera(0),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
+ .having(
+ (CameraException e) => e.description,
+ 'description',
+ 'Mock error message used during testing.',
+ ),
+ ),
+ );
+ });
test('Should send initialization data', () async {
// Arrange
final cameraMockChannel = MethodChannelMock(
channelName: 'plugins.flutter.io/camera',
methods: <String, dynamic>{
- 'create': <String, dynamic>{
- 'cameraId': 1,
- 'imageFormatGroup': 'unknown',
- },
+ 'create': <String, dynamic>{'cameraId': 1, 'imageFormatGroup': 'unknown'},
'initialize': null,
},
);
@@ -245,10 +218,7 @@
anything,
isMethodCall(
'initialize',
- arguments: <String, Object?>{
- 'cameraId': 1,
- 'imageFormatGroup': 'unknown',
- },
+ arguments: <String, Object?>{'cameraId': 1, 'imageFormatGroup': 'unknown'},
),
]);
});
@@ -349,8 +319,7 @@
test('Should receive initialized event', () async {
// Act
- final Stream<CameraInitializedEvent> eventStream = camera
- .onCameraInitialized(cameraId);
+ final Stream<CameraInitializedEvent> eventStream = camera.onCameraInitialized(cameraId);
final streamQueue = StreamQueue<CameraInitializedEvent>(eventStream);
// Emit test events
@@ -363,10 +332,7 @@
FocusMode.auto,
true,
);
- await camera.handleCameraMethodCall(
- MethodCall('initialized', event.toJson()),
- cameraId,
- );
+ await camera.handleCameraMethodCall(MethodCall('initialized', event.toJson()), cameraId);
// Assert
expect(await streamQueue.next, event);
@@ -379,9 +345,7 @@
// Act
final Stream<CameraResolutionChangedEvent> resolutionStream = camera
.onCameraResolutionChanged(cameraId);
- final streamQueue = StreamQueue<CameraResolutionChangedEvent>(
- resolutionStream,
- );
+ final streamQueue = StreamQueue<CameraResolutionChangedEvent>(resolutionStream);
// Emit test events
final fhdEvent = CameraResolutionChangedEvent(cameraId, 1920, 1080);
@@ -415,25 +379,14 @@
test('Should receive camera closing events', () async {
// Act
- final Stream<CameraClosingEvent> eventStream = camera.onCameraClosing(
- cameraId,
- );
+ final Stream<CameraClosingEvent> eventStream = camera.onCameraClosing(cameraId);
final streamQueue = StreamQueue<CameraClosingEvent>(eventStream);
// Emit test events
final event = CameraClosingEvent(cameraId);
- await camera.handleCameraMethodCall(
- MethodCall('camera_closing', event.toJson()),
- cameraId,
- );
- await camera.handleCameraMethodCall(
- MethodCall('camera_closing', event.toJson()),
- cameraId,
- );
- await camera.handleCameraMethodCall(
- MethodCall('camera_closing', event.toJson()),
- cameraId,
- );
+ await camera.handleCameraMethodCall(MethodCall('camera_closing', event.toJson()), cameraId);
+ await camera.handleCameraMethodCall(MethodCall('camera_closing', event.toJson()), cameraId);
+ await camera.handleCameraMethodCall(MethodCall('camera_closing', event.toJson()), cameraId);
// Assert
expect(await streamQueue.next, event);
@@ -446,25 +399,14 @@
test('Should receive camera error events', () async {
// Act
- final Stream<CameraErrorEvent> errorStream = camera.onCameraError(
- cameraId,
- );
+ final Stream<CameraErrorEvent> errorStream = camera.onCameraError(cameraId);
final streamQueue = StreamQueue<CameraErrorEvent>(errorStream);
// Emit test events
final event = CameraErrorEvent(cameraId, 'Error Description');
- await camera.handleCameraMethodCall(
- MethodCall('error', event.toJson()),
- cameraId,
- );
- await camera.handleCameraMethodCall(
- MethodCall('error', event.toJson()),
- cameraId,
- );
- await camera.handleCameraMethodCall(
- MethodCall('error', event.toJson()),
- cameraId,
- );
+ await camera.handleCameraMethodCall(MethodCall('error', event.toJson()), cameraId);
+ await camera.handleCameraMethodCall(MethodCall('error', event.toJson()), cameraId);
+ await camera.handleCameraMethodCall(MethodCall('error', event.toJson()), cameraId);
// Assert
expect(await streamQueue.next, event);
@@ -479,23 +421,13 @@
// Act
final Stream<DeviceOrientationChangedEvent> eventStream = camera
.onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
// Emit test events
- const event = DeviceOrientationChangedEvent(
- DeviceOrientation.portraitUp,
- );
- await camera.handleDeviceMethodCall(
- MethodCall('orientation_changed', event.toJson()),
- );
- await camera.handleDeviceMethodCall(
- MethodCall('orientation_changed', event.toJson()),
- );
- await camera.handleDeviceMethodCall(
- MethodCall('orientation_changed', event.toJson()),
- );
+ const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
+ await camera.handleDeviceMethodCall(MethodCall('orientation_changed', event.toJson()));
+ await camera.handleDeviceMethodCall(MethodCall('orientation_changed', event.toJson()));
+ await camera.handleDeviceMethodCall(MethodCall('orientation_changed', event.toJson()));
// Assert
expect(await streamQueue.next, event);
@@ -549,85 +481,61 @@
await initializeFuture;
});
- test(
- 'Should fetch CameraDescription instances for available cameras',
- () async {
- // Arrange
- final returnData = <dynamic>[
- <String, dynamic>{
- 'name': 'Test 1',
- 'lensFacing': 'front',
- 'sensorOrientation': 1,
- },
- <String, dynamic>{
- 'name': 'Test 2',
- 'lensFacing': 'back',
- 'sensorOrientation': 2,
- },
- ];
- final channel = MethodChannelMock(
- channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{'availableCameras': returnData},
+ test('Should fetch CameraDescription instances for available cameras', () async {
+ // Arrange
+ final returnData = <dynamic>[
+ <String, dynamic>{'name': 'Test 1', 'lensFacing': 'front', 'sensorOrientation': 1},
+ <String, dynamic>{'name': 'Test 2', 'lensFacing': 'back', 'sensorOrientation': 2},
+ ];
+ final channel = MethodChannelMock(
+ channelName: 'plugins.flutter.io/camera',
+ methods: <String, dynamic>{'availableCameras': returnData},
+ );
+
+ // Act
+ final List<CameraDescription> cameras = await camera.availableCameras();
+
+ // Assert
+ expect(channel.log, <Matcher>[isMethodCall('availableCameras', arguments: null)]);
+ expect(cameras.length, returnData.length);
+ for (var i = 0; i < returnData.length; i++) {
+ final Map<String, Object?> typedData = (returnData[i] as Map<dynamic, dynamic>)
+ .cast<String, Object?>();
+ final cameraDescription = CameraDescription(
+ name: typedData['name']! as String,
+ lensDirection: parseCameraLensDirection(typedData['lensFacing']! as String),
+ sensorOrientation: typedData['sensorOrientation']! as int,
);
+ expect(cameras[i], cameraDescription);
+ }
+ });
- // Act
- final List<CameraDescription> cameras = await camera
- .availableCameras();
-
- // Assert
- expect(channel.log, <Matcher>[
- isMethodCall('availableCameras', arguments: null),
- ]);
- expect(cameras.length, returnData.length);
- for (var i = 0; i < returnData.length; i++) {
- final Map<String, Object?> typedData =
- (returnData[i] as Map<dynamic, dynamic>)
- .cast<String, Object?>();
- final 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(
- channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- 'availableCameras': PlatformException(
- code: 'TESTING_ERROR_CODE',
- message: 'Mock error message used during testing.',
- ),
- },
- );
-
- // Act
- expect(
- camera.availableCameras,
- throwsA(
- isA<CameraException>()
- .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 availableCameras throws a PlatformException', () {
+ // Arrange
+ MethodChannelMock(
+ channelName: 'plugins.flutter.io/camera',
+ methods: <String, dynamic>{
+ 'availableCameras': PlatformException(
+ code: 'TESTING_ERROR_CODE',
+ message: 'Mock error message used during testing.',
),
- );
- },
- );
+ },
+ );
+
+ // Act
+ expect(
+ camera.availableCameras,
+ throwsA(
+ isA<CameraException>()
+ .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
@@ -641,10 +549,7 @@
// Assert
expect(channel.log, <Matcher>[
- isMethodCall(
- 'takePicture',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('takePicture', arguments: <String, Object?>{'cameraId': cameraId}),
]);
expect(file.path, '/test/path.jpg');
});
@@ -660,9 +565,7 @@
await camera.prepareForVideoRecording();
// Assert
- expect(channel.log, <Matcher>[
- isMethodCall('prepareForVideoRecording', arguments: null),
- ]);
+ expect(channel.log, <Matcher>[isMethodCall('prepareForVideoRecording', arguments: null)]);
});
test('Should start recording a video', () async {
@@ -724,10 +627,7 @@
// Assert
expect(channel.log, <Matcher>[
- isMethodCall(
- 'stopVideoRecording',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('stopVideoRecording', arguments: <String, Object?>{'cameraId': cameraId}),
]);
expect(file.path, '/test/path.mp4');
});
@@ -744,10 +644,7 @@
// Assert
expect(channel.log, <Matcher>[
- isMethodCall(
- 'pauseVideoRecording',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('pauseVideoRecording', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -763,10 +660,7 @@
// Assert
expect(channel.log, <Matcher>[
- isMethodCall(
- 'resumeVideoRecording',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('resumeVideoRecording', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -791,10 +685,7 @@
),
isMethodCall(
'setFlashMode',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'mode': 'always',
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'always'},
),
isMethodCall(
'setFlashMode',
@@ -826,10 +717,7 @@
),
isMethodCall(
'setExposureMode',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'mode': 'locked',
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'locked'},
),
]);
});
@@ -849,21 +737,11 @@
expect(channel.log, <Matcher>[
isMethodCall(
'setExposurePoint',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'x': 0.5,
- 'y': 0.5,
- 'reset': false,
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'x': 0.5, 'y': 0.5, 'reset': false},
),
isMethodCall(
'setExposurePoint',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'x': null,
- 'y': null,
- 'reset': true,
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'x': null, 'y': null, 'reset': true},
),
]);
});
@@ -876,17 +754,12 @@
);
// Act
- final double minExposureOffset = await camera.getMinExposureOffset(
- cameraId,
- );
+ final double minExposureOffset = await camera.getMinExposureOffset(cameraId);
// Assert
expect(minExposureOffset, 2.0);
expect(channel.log, <Matcher>[
- isMethodCall(
- 'getMinExposureOffset',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('getMinExposureOffset', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -898,17 +771,12 @@
);
// Act
- final double maxExposureOffset = await camera.getMaxExposureOffset(
- cameraId,
- );
+ final double maxExposureOffset = await camera.getMaxExposureOffset(cameraId);
// Assert
expect(maxExposureOffset, 2.0);
expect(channel.log, <Matcher>[
- isMethodCall(
- 'getMaxExposureOffset',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('getMaxExposureOffset', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -920,9 +788,7 @@
);
// Act
- final double stepSize = await camera.getExposureOffsetStepSize(
- cameraId,
- );
+ final double stepSize = await camera.getExposureOffsetStepSize(cameraId);
// Assert
expect(stepSize, 0.25);
@@ -942,10 +808,7 @@
);
// Act
- final double actualOffset = await camera.setExposureOffset(
- cameraId,
- 0.5,
- );
+ final double actualOffset = await camera.setExposureOffset(cameraId, 0.5);
// Assert
expect(actualOffset, 0.6);
@@ -976,10 +839,7 @@
),
isMethodCall(
'setFocusMode',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'mode': 'locked',
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'locked'},
),
]);
});
@@ -999,21 +859,11 @@
expect(channel.log, <Matcher>[
isMethodCall(
'setFocusPoint',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'x': 0.5,
- 'y': 0.5,
- 'reset': false,
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'x': 0.5, 'y': 0.5, 'reset': false},
),
isMethodCall(
'setFocusPoint',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'x': null,
- 'y': null,
- 'reset': true,
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'x': null, 'y': null, 'reset': true},
),
]);
});
@@ -1027,20 +877,14 @@
expect((widget as Texture).textureId, cameraId);
});
- test(
- 'Should throw MissingPluginException when handling unknown method',
- () {
- final camera = MethodChannelCamera();
+ test('Should throw MissingPluginException when handling unknown method', () {
+ final camera = MethodChannelCamera();
- expect(
- () => camera.handleCameraMethodCall(
- const MethodCall('unknown_method'),
- 1,
- ),
- throwsA(isA<MissingPluginException>()),
- );
- },
- );
+ expect(
+ () => camera.handleCameraMethodCall(const MethodCall('unknown_method'), 1),
+ throwsA(isA<MissingPluginException>()),
+ );
+ });
test('Should get the max zoom level', () async {
// Arrange
@@ -1055,10 +899,7 @@
// Assert
expect(maxZoomLevel, 10.0);
expect(channel.log, <Matcher>[
- isMethodCall(
- 'getMaxZoomLevel',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('getMaxZoomLevel', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -1075,10 +916,7 @@
// Assert
expect(maxZoomLevel, 1.0);
expect(channel.log, <Matcher>[
- isMethodCall(
- 'getMinZoomLevel',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('getMinZoomLevel', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -1101,35 +939,25 @@
]);
});
- test(
- 'Should throw CameraException when illegal zoom level is supplied',
- () async {
- // Arrange
- MethodChannelMock(
- channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- '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: <String, dynamic>{
+ 'setZoomLevel': PlatformException(code: 'ZOOM_ERROR', message: 'Illegal zoom error'),
+ },
+ );
- // Act & assert
- expect(
- () => camera.setZoomLevel(cameraId, -1.0),
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR')
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Illegal zoom error',
- ),
- ),
- );
- },
- );
+ // Act & assert
+ expect(
+ () => camera.setZoomLevel(cameraId, -1.0),
+ throwsA(
+ isA<CameraException>()
+ .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
@@ -1139,19 +967,13 @@
);
// Act
- await camera.lockCaptureOrientation(
- cameraId,
- DeviceOrientation.portraitUp,
- );
+ await camera.lockCaptureOrientation(cameraId, DeviceOrientation.portraitUp);
// Assert
expect(channel.log, <Matcher>[
isMethodCall(
'lockCaptureOrientation',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'orientation': 'portraitUp',
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'orientation': 'portraitUp'},
),
]);
});
@@ -1187,10 +1009,7 @@
// Assert
expect(channel.log, <Matcher>[
- isMethodCall(
- 'pausePreview',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('pausePreview', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -1206,10 +1025,7 @@
// Assert
expect(channel.log, <Matcher>[
- isMethodCall(
- 'resumePreview',
- arguments: <String, Object?>{'cameraId': cameraId},
- ),
+ isMethodCall('resumePreview', arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
@@ -1217,10 +1033,7 @@
// Arrange
final channel = MethodChannelMock(
channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- 'startImageStream': null,
- 'stopImageStream': null,
- },
+ methods: <String, dynamic>{'startImageStream': null, 'stopImageStream': null},
);
// Act
@@ -1229,9 +1042,7 @@
.listen((CameraImageData imageData) {});
// Assert
- expect(channel.log, <Matcher>[
- isMethodCall('startImageStream', arguments: null),
- ]);
+ expect(channel.log, <Matcher>[isMethodCall('startImageStream', arguments: null)]);
await subscription.cancel();
});
@@ -1240,10 +1051,7 @@
// Arrange
final channel = MethodChannelMock(
channelName: 'plugins.flutter.io/camera',
- methods: <String, dynamic>{
- 'startImageStream': null,
- 'stopImageStream': null,
- },
+ methods: <String, dynamic>{'startImageStream': null, 'stopImageStream': null},
);
// Act
@@ -1273,10 +1081,7 @@
expect(channel.log, <Matcher>[
isMethodCall(
'setImageFileFormat',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'fileFormat': 'heif',
- },
+ arguments: <String, Object?>{'cameraId': cameraId, 'fileFormat': 'heif'},
),
]);
});
@@ -1295,10 +1100,7 @@
expect(channel.log, <Matcher>[
isMethodCall(
'setImageFileFormat',
- arguments: <String, Object?>{
- 'cameraId': cameraId,
- 'fileFormat': 'jpeg',
- },
+ arguments: <String, Object?>{'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 5e578b9..f3650bd 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,25 +9,23 @@
void main() {
test('CameraImageData can be created', () {
- final CameraImageData cameraImage = cameraImageFromPlatformData(
- <dynamic, dynamic>{
- 'format': 35,
- 'height': 1,
- 'width': 4,
- 'lensAperture': 1.8,
- 'sensorExposureTime': 9991324,
- 'sensorSensitivity': 92.0,
- 'planes': <dynamic>[
- <dynamic, dynamic>{
- 'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
- 'bytesPerPixel': 1,
- 'bytesPerRow': 4,
- 'height': 1,
- 'width': 4,
- },
- ],
- },
- );
+ final CameraImageData cameraImage = cameraImageFromPlatformData(<dynamic, dynamic>{
+ 'format': 35,
+ 'height': 1,
+ 'width': 4,
+ 'lensAperture': 1.8,
+ 'sensorExposureTime': 9991324,
+ 'sensorSensitivity': 92.0,
+ 'planes': <dynamic>[
+ <dynamic, dynamic>{
+ 'bytes': Uint8List.fromList(<int>[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);
@@ -37,50 +35,46 @@
test('CameraImageData has ImageFormatGroup.yuv420 for iOS', () {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
- final CameraImageData cameraImage = cameraImageFromPlatformData(
- <dynamic, dynamic>{
- 'format': 875704438,
- 'height': 1,
- 'width': 4,
- 'lensAperture': 1.8,
- 'sensorExposureTime': 9991324,
- 'sensorSensitivity': 92.0,
- 'planes': <dynamic>[
- <dynamic, dynamic>{
- 'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
- 'bytesPerPixel': 1,
- 'bytesPerRow': 4,
- 'height': 1,
- 'width': 4,
- },
- ],
- },
- );
+ final CameraImageData cameraImage = cameraImageFromPlatformData(<dynamic, dynamic>{
+ 'format': 875704438,
+ 'height': 1,
+ 'width': 4,
+ 'lensAperture': 1.8,
+ 'sensorExposureTime': 9991324,
+ 'sensorSensitivity': 92.0,
+ 'planes': <dynamic>[
+ <dynamic, dynamic>{
+ 'bytes': Uint8List.fromList(<int>[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(
- <dynamic, dynamic>{
- 'format': 35,
- 'height': 1,
- 'width': 4,
- 'lensAperture': 1.8,
- 'sensorExposureTime': 9991324,
- 'sensorSensitivity': 92.0,
- 'planes': <dynamic>[
- <dynamic, dynamic>{
- 'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
- 'bytesPerPixel': 1,
- 'bytesPerRow': 4,
- 'height': 1,
- 'width': 4,
- },
- ],
- },
- );
+ final CameraImageData cameraImage = cameraImageFromPlatformData(<dynamic, dynamic>{
+ 'format': 35,
+ 'height': 1,
+ 'width': 4,
+ 'lensAperture': 1.8,
+ 'sensorExposureTime': 9991324,
+ 'sensorSensitivity': 92.0,
+ 'planes': <dynamic>[
+ <dynamic, dynamic>{
+ 'bytes': Uint8List.fromList(<int>[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 6bf9ee3..97cd240 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,24 +107,21 @@
expect(firstDescription == secondDescription, true);
});
- test(
- 'hashCode should match hashCode of all equality-tested properties',
- () {
- const description = CameraDescription(
- name: 'Test',
- lensDirection: CameraLensDirection.front,
- sensorOrientation: 0,
- lensType: CameraLensType.ultraWide,
- );
- final int expectedHashCode = Object.hash(
- description.name,
- description.lensDirection,
- description.lensType,
- );
+ test('hashCode should match hashCode of all equality-tested properties', () {
+ const 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);
- },
- );
+ expect(description.hashCode, expectedHashCode);
+ });
test('toString should return correct string representation', () {
const description = CameraDescription(
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 65f619b..19c44df 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
@@ -8,46 +8,39 @@
import 'package:flutter_test/flutter_test.dart';
void main() {
- test(
- 'MediaSettings non-parametrized constructor should have correct initial values',
- () {
- const settingsWithNoParameters = MediaSettings();
+ test('MediaSettings non-parametrized constructor should have correct initial values', () {
+ const 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 settings = MediaSettings(
@@ -61,15 +54,10 @@
expect(
settings.resolutionPreset,
ResolutionPreset.low,
- reason:
- 'MediaSettings constructor should hold resolutionPreset parameter',
+ reason: 'MediaSettings constructor should hold resolutionPreset parameter',
);
- expect(
- settings.fps,
- 20,
- reason: 'MediaSettings constructor should hold fps parameter',
- );
+ expect(settings.fps, 20, reason: 'MediaSettings constructor should hold fps parameter');
expect(
settings.videoBitrate,
@@ -102,8 +90,7 @@
expect(
settings.hashCode,
Object.hash(ResolutionPreset.low, 20, 128000, 32000, true),
- reason:
- 'MediaSettings hash() should be equal to Object.hash of parameters',
+ reason: 'MediaSettings hash() should be equal to Object.hash of parameters',
);
});
@@ -207,8 +194,7 @@
expect(
settings1 == settingsIdentical,
isTrue,
- reason:
- 'MediaSettings == operator should return true for identical objects',
+ reason: 'MediaSettings == operator should return true for identical objects',
);
});
@@ -216,8 +202,7 @@
expect(
settings1 == Object(),
isFalse,
- reason:
- 'MediaSettings == operator should return false for objects of different types',
+ reason: 'MediaSettings == operator should return false for objects of different types',
);
});
});
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 8c9f5d8..a02b628 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
@@ -6,13 +6,12 @@
import 'package:flutter_test/flutter_test.dart';
class MethodChannelMock {
- MethodChannelMock({
- required String channelName,
- this.delay,
- required this.methods,
- }) : methodChannel = MethodChannel(channelName) {
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(methodChannel, _handler);
+ MethodChannelMock({required String channelName, this.delay, required this.methods})
+ : methodChannel = MethodChannel(channelName) {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ methodChannel,
+ _handler,
+ );
}
final Duration? delay;
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 316a329..6d3a6c8 100644
--- a/packages/camera/camera_platform_interface/test/utils/utils_test.dart
+++ b/packages/camera/camera_platform_interface/test/utils/utils_test.dart
@@ -14,59 +14,29 @@
() {
expect(parseCameraLensDirection('back'), CameraLensDirection.back);
expect(parseCameraLensDirection('front'), CameraLensDirection.front);
- expect(
- parseCameraLensDirection('external'),
- CameraLensDirection.external,
- );
+ expect(parseCameraLensDirection('external'), CameraLensDirection.external);
},
);
test(
'Should throw ArgumentException when invalid value is supplied when parsing camera lens direction',
() {
- expect(
- () => parseCameraLensDirection('test'),
- throwsA(isArgumentError),
- );
+ expect(() => parseCameraLensDirection('test'), throwsA(isArgumentError));
},
);
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',
- );
+ 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/example/integration_test/camera_bitrate_test.dart b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart
index 371f23d..412fdd0 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,9 +45,7 @@
}
}
- 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 supportedVideoType = 'video/webm;codecs="vp9,opus"';
bool isVideoTypeSupported(String type) => type == supportedVideoType;
@@ -59,8 +57,7 @@
final window = createJSInteropWrapper(mockWindow) as Window;
final navigator = createJSInteropWrapper(mockNavigator) as Navigator;
- final mediaDevices =
- createJSInteropWrapper(mockMediaDevices) as MediaDevices;
+ final mediaDevices = createJSInteropWrapper(mockMediaDevices) as MediaDevices;
mockWindow.navigator = navigator;
mockNavigator.mediaDevices = mediaDevices;
@@ -74,8 +71,7 @@
final cameraService = MockCameraService();
- CameraPlatform.instance = CameraPlugin(cameraService: cameraService)
- ..window = window;
+ CameraPlatform.instance = CameraPlugin(cameraService: cameraService)..window = window;
final options = CameraOptions(
audio: const AudioConstraints(),
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 8b80cbc..4219616 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
@@ -18,10 +18,7 @@
group('CameraErrorCode', () {
group('toString returns a correct type for', () {
testWidgets('notSupported', (WidgetTester tester) async {
- expect(
- CameraErrorCode.notSupported.toString(),
- equals('cameraNotSupported'),
- );
+ expect(CameraErrorCode.notSupported.toString(), equals('cameraNotSupported'));
});
testWidgets('notFound', (WidgetTester tester) async {
@@ -29,24 +26,15 @@
});
testWidgets('notReadable', (WidgetTester tester) async {
- expect(
- CameraErrorCode.notReadable.toString(),
- equals('cameraNotReadable'),
- );
+ expect(CameraErrorCode.notReadable.toString(), equals('cameraNotReadable'));
});
testWidgets('overconstrained', (WidgetTester tester) async {
- expect(
- CameraErrorCode.overconstrained.toString(),
- equals('cameraOverconstrained'),
- );
+ expect(CameraErrorCode.overconstrained.toString(), equals('cameraOverconstrained'));
});
testWidgets('permissionDenied', (WidgetTester tester) async {
- expect(
- CameraErrorCode.permissionDenied.toString(),
- equals('CameraAccessDenied'),
- );
+ expect(CameraErrorCode.permissionDenied.toString(), equals('CameraAccessDenied'));
});
testWidgets('type', (WidgetTester tester) async {
@@ -62,10 +50,7 @@
});
testWidgets('missingMetadata', (WidgetTester tester) async {
- expect(
- CameraErrorCode.missingMetadata.toString(),
- equals('cameraMissingMetadata'),
- );
+ expect(CameraErrorCode.missingMetadata.toString(), equals('cameraMissingMetadata'));
});
testWidgets('orientationNotSupported', (WidgetTester tester) async {
@@ -76,31 +61,19 @@
});
testWidgets('torchModeNotSupported', (WidgetTester tester) async {
- expect(
- CameraErrorCode.torchModeNotSupported.toString(),
- equals('torchModeNotSupported'),
- );
+ expect(CameraErrorCode.torchModeNotSupported.toString(), equals('torchModeNotSupported'));
});
testWidgets('zoomLevelNotSupported', (WidgetTester tester) async {
- expect(
- CameraErrorCode.zoomLevelNotSupported.toString(),
- equals('zoomLevelNotSupported'),
- );
+ expect(CameraErrorCode.zoomLevelNotSupported.toString(), equals('zoomLevelNotSupported'));
});
testWidgets('zoomLevelInvalid', (WidgetTester tester) async {
- expect(
- CameraErrorCode.zoomLevelInvalid.toString(),
- equals('zoomLevelInvalid'),
- );
+ expect(CameraErrorCode.zoomLevelInvalid.toString(), equals('zoomLevelInvalid'));
});
testWidgets('notStarted', (WidgetTester tester) async {
- expect(
- CameraErrorCode.notStarted.toString(),
- equals('cameraNotStarted'),
- );
+ expect(CameraErrorCode.notStarted.toString(), equals('cameraNotStarted'));
});
testWidgets('videoRecordingNotStarted', (WidgetTester tester) async {
@@ -118,10 +91,7 @@
testWidgets('with aborted error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
- createJSInteropWrapper(
- FakeMediaError(MediaError.MEDIA_ERR_ABORTED),
- )
- as MediaError,
+ createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_ABORTED)) as MediaError,
).toString(),
equals('mediaErrorAborted'),
);
@@ -130,10 +100,7 @@
testWidgets('with network error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
- createJSInteropWrapper(
- FakeMediaError(MediaError.MEDIA_ERR_NETWORK),
- )
- as MediaError,
+ createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_NETWORK)) as MediaError,
).toString(),
equals('mediaErrorNetwork'),
);
@@ -142,23 +109,16 @@
testWidgets('with decode error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
- createJSInteropWrapper(
- FakeMediaError(MediaError.MEDIA_ERR_DECODE),
- )
- as MediaError,
+ createJSInteropWrapper(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),
- )
+ createJSInteropWrapper(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 a59518c..c9383a5 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
@@ -14,9 +14,7 @@
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment'),
- equals(
- const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment'),
- ),
+ equals(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 75d7210..fc7fb16 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
@@ -16,9 +16,7 @@
testWidgets('serializes correctly', (WidgetTester tester) async {
final cameraOptions = CameraOptions(
audio: const AudioConstraints(enabled: true),
- video: VideoConstraints(
- facingMode: FacingModeConstraint.exact(CameraType.user),
- ),
+ video: VideoConstraints(facingMode: FacingModeConstraint.exact(CameraType.user)),
);
expect(
@@ -36,16 +34,8 @@
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',
),
),
@@ -54,16 +44,8 @@
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',
),
),
@@ -74,17 +56,11 @@
group('AudioConstraints', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
- expect(
- const AudioConstraints(enabled: true).toMediaStreamConstraints(),
- true.toJS,
- );
+ expect(const AudioConstraints(enabled: true).toMediaStreamConstraints(), true.toJS);
});
testWidgets('supports value equality', (WidgetTester tester) async {
- expect(
- const AudioConstraints(enabled: true),
- equals(const AudioConstraints(enabled: true)),
- );
+ expect(const AudioConstraints(enabled: true), equals(const AudioConstraints(enabled: true)));
});
});
@@ -108,9 +84,7 @@
);
});
- testWidgets('serializes to true when no constraints are provided', (
- WidgetTester tester,
- ) async {
+ testWidgets('serializes to true when no constraints are provided', (WidgetTester tester) async {
const videoConstraints = VideoConstraints();
expect(videoConstraints.toMediaStreamConstraints().dartify(), isTrue);
});
@@ -119,31 +93,15 @@
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,
- ),
+ width: const VideoSizeConstraint(minimum: 90, ideal: 100, maximum: 100),
+ height: const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50),
deviceId: 'deviceId',
),
),
@@ -206,11 +164,7 @@
group('VideoSizeConstraint ', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
expect(
- const VideoSizeConstraint(
- minimum: 200,
- ideal: 400,
- maximum: 400,
- ).toJson(),
+ const VideoSizeConstraint(minimum: 200, ideal: 400, maximum: 400).toJson(),
equals(<String, Object>{'min': 200, 'ideal': 400, 'max': 400}),
);
});
@@ -218,9 +172,7 @@
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300),
- equals(
- const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300),
- ),
+ equals(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 2805ae0..26fe6a2 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
@@ -44,8 +44,7 @@
window = createJSInteropWrapper(mockWindow) as web.Window;
navigator = createJSInteropWrapper(mockNavigator) as web.Navigator;
- mediaDevices =
- createJSInteropWrapper(mockMediaDevices) as web.MediaDevices;
+ mediaDevices = createJSInteropWrapper(mockMediaDevices) as web.MediaDevices;
mockWindow.navigator = navigator;
mockNavigator.mediaDevices = mediaDevices;
@@ -54,10 +53,9 @@
// 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 invocation) => (invocation.positionalArguments[0] as JSObject).getProperty(
+ invocation.positionalArguments[1] as JSAny,
+ ),
);
cameraService = CameraService()..window = window;
@@ -67,12 +65,10 @@
testWidgets('calls MediaDevices.getUserMedia '
'with provided options', (WidgetTester tester) async {
late final web.MediaStreamConstraints? capturedConstraints;
- mockMediaDevices
- .getUserMedia = ([web.MediaStreamConstraints? constraints]) {
+ mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? constraints]) {
capturedConstraints = constraints;
final stream =
- createJSInteropWrapper(FakeMediaStream(<web.MediaStreamTrack>[]))
- as web.MediaStream;
+ createJSInteropWrapper(FakeMediaStream(<web.MediaStreamTrack>[])) as web.MediaStream;
return Future<web.MediaStream>.value(stream).toJS;
}.toJS;
@@ -106,22 +102,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -136,22 +121,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -165,22 +139,11 @@
return Future<web.MediaStream>.value(web.MediaStream()).toJS;
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -195,22 +158,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -225,17 +177,10 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- cameraId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -255,17 +200,10 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- cameraId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -285,17 +223,10 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- cameraId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -315,17 +246,10 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- cameraId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -345,22 +269,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -375,22 +288,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -405,22 +307,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -435,22 +326,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -466,22 +346,11 @@
}.toJS;
expect(
- () => cameraService.getMediaStreamForOptions(
- const CameraOptions(),
- cameraId: cameraId,
- ),
+ () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId),
throwsA(
isA<CameraWebException>()
- .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),
),
);
});
@@ -498,15 +367,13 @@
mockVideoTrack = MockMediaStreamTrack();
videoTracks = <web.MediaStreamTrack>[
createJSInteropWrapper(mockVideoTrack) as web.MediaStreamTrack,
- createJSInteropWrapper(MockMediaStreamTrack())
- as web.MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as web.MediaStreamTrack,
];
when(camera.textureId).thenReturn(0);
- when(camera.stream).thenReturn(
- createJSInteropWrapper(FakeMediaStream(videoTracks))
- as web.MediaStream,
- );
+ when(
+ camera.stream,
+ ).thenReturn(createJSInteropWrapper(FakeMediaStream(videoTracks)) as web.MediaStream);
cameraService.jsUtil = jsUtil;
});
@@ -549,11 +416,7 @@
() => cameraService.getZoomLevelCapabilityForCamera(camera),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- camera.textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', camera.textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -564,33 +427,22 @@
});
testWidgets('with notStarted error '
- 'when the camera stream has not been initialized', (
- WidgetTester tester,
- ) async {
+ '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(
- createJSInteropWrapper(FakeMediaStream(<web.MediaStreamTrack>[]))
- as web.MediaStream,
+ createJSInteropWrapper(FakeMediaStream(<web.MediaStreamTrack>[])) as web.MediaStream,
);
expect(
() => cameraService.getZoomLevelCapabilityForCamera(camera),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- camera.textureId,
- )
- .having(
- (CameraWebException e) => e.code,
- 'code',
- CameraErrorCode.notStarted,
- ),
+ .having((CameraWebException e) => e.cameraId, 'cameraId', camera.textureId)
+ .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notStarted),
),
);
});
@@ -609,8 +461,7 @@
}.toJS;
final String? facingMode = cameraService.getFacingModeForVideoTrack(
- createJSInteropWrapper(MockMediaStreamTrack())
- as web.MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as web.MediaStreamTrack,
);
expect(facingMode, isNull);
@@ -622,12 +473,9 @@
setUp(() {
mockVideoTrack = MockMediaStreamTrack();
- videoTrack =
- createJSInteropWrapper(mockVideoTrack) as web.MediaStreamTrack;
+ 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);
@@ -640,18 +488,14 @@
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 '
'based on the video track capabilities '
- 'when the facing mode setting is empty', (
- WidgetTester tester,
- ) async {
+ 'when the facing mode setting is empty', (WidgetTester tester) async {
mockVideoTrack.getSettings = () {
return web.MediaTrackSettings(facingMode: '');
}.toJS;
@@ -661,13 +505,9 @@
);
}.toJS;
- when(
- jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS),
- ).thenReturn(true);
+ when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(true);
- final String? facingMode = cameraService.getFacingModeForVideoTrack(
- videoTrack,
- );
+ final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, equals('environment'));
});
@@ -682,29 +522,21 @@
return web.MediaTrackCapabilities(facingMode: <JSString>[].toJS);
}.toJS;
- final String? facingMode = cameraService.getFacingModeForVideoTrack(
- videoTrack,
- );
+ final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, isNull);
});
testWidgets('returns null '
'when the facing mode setting is empty and '
- 'the video track capabilities are not supported', (
- WidgetTester tester,
- ) async {
+ '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);
+ when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(false);
- final String? facingMode = cameraService.getFacingModeForVideoTrack(
- videoTrack,
- );
+ final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, isNull);
});
@@ -713,21 +545,16 @@
'when the facing mode setting is empty and '
'the facingMode capability is null', (WidgetTester tester) async {
mockVideoTrack.getSettings = () {
- return createJSInteropWrapper(FakeMediaTrackSettings())
- as web.MediaTrackSettings;
+ return createJSInteropWrapper(FakeMediaTrackSettings()) as web.MediaTrackSettings;
}.toJS;
mockVideoTrack.getCapabilities = () {
return createJSInteropWrapper(FakeMediaTrackCapabilities())
as web.MediaTrackCapabilities;
}.toJS;
- when(
- jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS),
- ).thenReturn(true);
+ when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(true);
- final String? facingMode = cameraService.getFacingModeForVideoTrack(
- videoTrack,
- );
+ final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, isNull);
});
@@ -771,10 +598,7 @@
group('mapFacingModeToCameraType', () {
testWidgets('returns user '
'when the facing mode is user', (WidgetTester tester) async {
- expect(
- cameraService.mapFacingModeToCameraType('user'),
- equals(CameraType.user),
- );
+ expect(cameraService.mapFacingModeToCameraType('user'), equals(CameraType.user));
});
testWidgets('returns environment '
@@ -787,18 +611,12 @@
testWidgets('returns user '
'when the facing mode is left', (WidgetTester tester) async {
- expect(
- cameraService.mapFacingModeToCameraType('left'),
- equals(CameraType.user),
- );
+ expect(cameraService.mapFacingModeToCameraType('left'), equals(CameraType.user));
});
testWidgets('returns user '
'when the facing mode is right', (WidgetTester tester) async {
- expect(
- cameraService.mapFacingModeToCameraType('right'),
- equals(CameraType.user),
- );
+ expect(cameraService.mapFacingModeToCameraType('right'), equals(CameraType.user));
});
});
@@ -812,9 +630,7 @@
});
testWidgets('returns 4096x2160 '
- 'when the resolution preset is ultraHigh', (
- WidgetTester tester,
- ) async {
+ 'when the resolution preset is ultraHigh', (WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh),
equals(const Size(4096, 2160)),
@@ -822,9 +638,7 @@
});
testWidgets('returns 1920x1080 '
- 'when the resolution preset is veryHigh', (
- WidgetTester tester,
- ) async {
+ 'when the resolution preset is veryHigh', (WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.veryHigh),
equals(const Size(1920, 1080)),
@@ -858,49 +672,33 @@
group('mapDeviceOrientationToOrientationType', () {
testWidgets('returns portraitPrimary '
- 'when the device orientation is portraitUp', (
- WidgetTester tester,
- ) async {
+ 'when the device orientation is portraitUp', (WidgetTester tester) async {
expect(
- cameraService.mapDeviceOrientationToOrientationType(
- DeviceOrientation.portraitUp,
- ),
+ cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.portraitUp),
equals(OrientationType.portraitPrimary),
);
});
testWidgets('returns landscapePrimary '
- 'when the device orientation is landscapeLeft', (
- WidgetTester tester,
- ) async {
+ 'when the device orientation is landscapeLeft', (WidgetTester tester) async {
expect(
- cameraService.mapDeviceOrientationToOrientationType(
- DeviceOrientation.landscapeLeft,
- ),
+ cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeLeft),
equals(OrientationType.landscapePrimary),
);
});
testWidgets('returns portraitSecondary '
- 'when the device orientation is portraitDown', (
- WidgetTester tester,
- ) async {
+ 'when the device orientation is portraitDown', (WidgetTester tester) async {
expect(
- cameraService.mapDeviceOrientationToOrientationType(
- DeviceOrientation.portraitDown,
- ),
+ cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.portraitDown),
equals(OrientationType.portraitSecondary),
);
});
testWidgets('returns landscapeSecondary '
- 'when the device orientation is landscapeRight', (
- WidgetTester tester,
- ) async {
+ 'when the device orientation is landscapeRight', (WidgetTester tester) async {
expect(
- cameraService.mapDeviceOrientationToOrientationType(
- DeviceOrientation.landscapeRight,
- ),
+ cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeRight),
equals(OrientationType.landscapeSecondary),
);
});
@@ -908,61 +706,41 @@
group('mapOrientationTypeToDeviceOrientation', () {
testWidgets('returns portraitUp '
- 'when the orientation type is portraitPrimary', (
- WidgetTester tester,
- ) async {
+ 'when the orientation type is portraitPrimary', (WidgetTester tester) async {
expect(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.portraitPrimary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitPrimary),
equals(DeviceOrientation.portraitUp),
);
});
testWidgets('returns landscapeLeft '
- 'when the orientation type is landscapePrimary', (
- WidgetTester tester,
- ) async {
+ 'when the orientation type is landscapePrimary', (WidgetTester tester) async {
expect(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.landscapePrimary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.landscapePrimary),
equals(DeviceOrientation.landscapeLeft),
);
});
testWidgets('returns portraitDown '
- 'when the orientation type is portraitSecondary', (
- WidgetTester tester,
- ) async {
+ 'when the orientation type is portraitSecondary', (WidgetTester tester) async {
expect(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.portraitSecondary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitSecondary),
equals(DeviceOrientation.portraitDown),
);
});
testWidgets('returns portraitDown '
- 'when the orientation type is portraitSecondary', (
- WidgetTester tester,
- ) async {
+ 'when the orientation type is portraitSecondary', (WidgetTester tester) async {
expect(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.portraitSecondary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitSecondary),
equals(DeviceOrientation.portraitDown),
);
});
testWidgets('returns landscapeRight '
- 'when the orientation type is landscapeSecondary', (
- WidgetTester tester,
- ) async {
+ 'when the orientation type is landscapeSecondary', (WidgetTester tester) async {
expect(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.landscapeSecondary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.landscapeSecondary),
equals(DeviceOrientation.landscapeRight),
);
});
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 29af6ce..f03ba19 100644
--- a/packages/camera/camera_web/example/integration_test/camera_test.dart
+++ b/packages/camera/camera_web/example/integration_test/camera_test.dart
@@ -50,16 +50,11 @@
cameraService = MockCameraService();
- final HTMLVideoElement videoElement = getVideoElementWithBlankStream(
- const Size(10, 10),
- );
+ final HTMLVideoElement videoElement = getVideoElementWithBlankStream(const Size(10, 10));
mediaStream = videoElement.captureStream();
when(
- cameraService.getMediaStreamForOptions(
- any,
- cameraId: anyNamed('cameraId'),
- ),
+ cameraService.getMediaStreamForOptions(any, cameraId: anyNamed('cameraId')),
).thenAnswer((_) => Future<MediaStream>.value(mediaStream));
});
@@ -73,17 +68,11 @@
),
);
- final camera = Camera(
- textureId: textureId,
- options: options,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, options: options, cameraService: cameraService);
await camera.initialize();
- verify(
- cameraService.getMediaStreamForOptions(options, cameraId: textureId),
- ).called(1);
+ verify(cameraService.getMediaStreamForOptions(options, cameraId: textureId)).called(1);
});
testWidgets('creates a video element '
@@ -95,10 +84,7 @@
final camera = Camera(
textureId: textureId,
- options: CameraOptions(
- audio: audioConstraints,
- video: videoConstraints,
- ),
+ options: CameraOptions(audio: audioConstraints, video: videoConstraints),
cameraService: cameraService,
);
@@ -108,15 +94,9 @@
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'),
- );
+ expect(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%'));
@@ -142,10 +122,7 @@
testWidgets('creates a wrapping div element '
'with correct properties', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
@@ -161,10 +138,7 @@
});
testWidgets('initializes the camera stream', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
@@ -172,44 +146,30 @@
});
testWidgets('throws an exception '
- 'when CameraService.getMediaStreamForOptions throws', (
- WidgetTester tester,
- ) async {
+ 'when CameraService.getMediaStreamForOptions throws', (WidgetTester tester) async {
final exception = Exception('A media stream exception occured.');
when(
- cameraService.getMediaStreamForOptions(
- any,
- cameraId: anyNamed('cameraId'),
- ),
+ cameraService.getMediaStreamForOptions(any, cameraId: anyNamed('cameraId')),
).thenThrow(exception);
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
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 {
var startedPlaying = false;
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
- final StreamSubscription<Event> cameraPlaySubscription = camera
- .videoElement
- .onPlay
- .listen((Event event) => startedPlaying = true);
+ final StreamSubscription<Event> cameraPlaySubscription = camera.videoElement.onPlay.listen(
+ (Event event) => startedPlaying = true,
+ );
await camera.play();
@@ -225,11 +185,7 @@
video: VideoConstraints(width: VideoSizeConstraint(ideal: 100)),
);
- final camera = Camera(
- textureId: textureId,
- options: options,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, options: options, cameraService: cameraService);
await camera.initialize();
@@ -240,9 +196,7 @@
await camera.play();
// Should be called twice: for initialize and play.
- verify(
- cameraService.getMediaStreamForOptions(options, cameraId: textureId),
- ).called(2);
+ verify(cameraService.getMediaStreamForOptions(options, cameraId: textureId)).called(2);
expect(camera.videoElement.srcObject, mediaStream);
expect(camera.stream, mediaStream);
@@ -251,10 +205,7 @@
group('pause', () {
testWidgets('pauses the camera stream', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.play();
@@ -269,10 +220,7 @@
group('stop', () {
testWidgets('resets the camera stream', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.play();
@@ -286,10 +234,7 @@
group('takePicture', () {
testWidgets('returns a captured picture', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.play();
@@ -312,12 +257,9 @@
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;
+ videoElement = getVideoElementWithBlankStream(const Size(100, 100))..muted = true;
mockVideoTrack.getCapabilities = () {
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
@@ -325,23 +267,21 @@
});
testWidgets('if the flash mode is auto', (WidgetTester tester) async {
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream
- ..videoElement = videoElement
- ..flashMode = FlashMode.auto;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream
+ ..videoElement = videoElement
+ ..flashMode = FlashMode.auto;
await camera.play();
final capturedConstraints = <MediaTrackConstraints>[];
- mockVideoTrack.applyConstraints =
- ([MediaTrackConstraints? constraints]) {
- if (constraints != null) {
- capturedConstraints.add(constraints);
- }
- return Future<JSAny?>.value().toJS;
- }.toJS;
+ mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
+ if (constraints != null) {
+ capturedConstraints.add(constraints);
+ }
+ return Future<JSAny?>.value().toJS;
+ }.toJS;
final XFile _ = await camera.takePicture();
@@ -351,23 +291,21 @@
});
testWidgets('if the flash mode is always', (WidgetTester tester) async {
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream
- ..videoElement = videoElement
- ..flashMode = FlashMode.always;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream
+ ..videoElement = videoElement
+ ..flashMode = FlashMode.always;
await camera.play();
final capturedConstraints = <MediaTrackConstraints>[];
- mockVideoTrack.applyConstraints =
- ([MediaTrackConstraints? constraints]) {
- if (constraints != null) {
- capturedConstraints.add(constraints);
- }
- return Future<JSAny?>.value().toJS;
- }.toJS;
+ mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
+ if (constraints != null) {
+ capturedConstraints.add(constraints);
+ }
+ return Future<JSAny?>.value().toJS;
+ }.toJS;
final XFile _ = await camera.takePicture();
@@ -380,20 +318,13 @@
group('getVideoSize', () {
testWidgets('returns a size '
- 'based on the first video track settings', (
- WidgetTester tester,
- ) async {
+ 'based on the first video track settings', (WidgetTester tester) async {
const videoSize = Size(1280, 720);
- final HTMLVideoElement videoElement = getVideoElementWithBlankStream(
- videoSize,
- );
+ final HTMLVideoElement videoElement = getVideoElementWithBlankStream(videoSize);
mediaStream = videoElement.captureStream();
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
@@ -406,10 +337,7 @@
final videoElement = HTMLVideoElement();
mediaStream = videoElement.captureStream();
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
@@ -428,13 +356,11 @@
createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack,
createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
];
- videoStream =
- createJSInteropWrapper(FakeMediaStream(videoTracks)) as MediaStream;
+ videoStream = createJSInteropWrapper(FakeMediaStream(videoTracks)) as MediaStream;
- mockVideoTrack.applyConstraints =
- ([MediaTrackConstraints? constraints]) {
- return Future<JSAny?>.value().toJS;
- }.toJS;
+ mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
+ return Future<JSAny?>.value().toJS;
+ }.toJS;
mockVideoTrack.getCapabilities = () {
return MediaTrackCapabilities();
@@ -450,10 +376,9 @@
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
}.toJS;
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream;
const FlashMode flashMode = FlashMode.always;
@@ -472,19 +397,17 @@
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
}.toJS;
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream;
final capturedConstraints = <MediaTrackConstraints>[];
- mockVideoTrack.applyConstraints =
- ([MediaTrackConstraints? constraints]) {
- if (constraints != null) {
- capturedConstraints.add(constraints);
- }
- return Future<JSAny?>.value().toJS;
- }.toJS;
+ mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
+ if (constraints != null) {
+ capturedConstraints.add(constraints);
+ }
+ return Future<JSAny?>.value().toJS;
+ }.toJS;
camera.setFlashMode(FlashMode.torch);
@@ -502,19 +425,17 @@
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
}.toJS;
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream;
final capturedConstraints = <MediaTrackConstraints>[];
- mockVideoTrack.applyConstraints =
- ([MediaTrackConstraints? constraints]) {
- if (constraints != null) {
- capturedConstraints.add(constraints);
- }
- return Future<JSAny?>.value().toJS;
- }.toJS;
+ mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
+ if (constraints != null) {
+ capturedConstraints.add(constraints);
+ }
+ return Future<JSAny?>.value().toJS;
+ }.toJS;
camera.setFlashMode(FlashMode.auto);
@@ -534,20 +455,15 @@
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
}.toJS;
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -568,20 +484,15 @@
return MediaTrackCapabilities(torch: <JSBoolean>[false.toJS].toJS);
}.toJS;
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..window = window
- ..stream = videoStream;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window
+ ..stream = videoStream;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -592,9 +503,7 @@
});
testWidgets('with notStarted error '
- 'when the camera stream has not been initialized', (
- WidgetTester tester,
- ) async {
+ 'when the camera stream has not been initialized', (WidgetTester tester) async {
mockMediaDevices.getSupportedConstraints = () {
return MediaTrackSupportedConstraints(torch: true);
}.toJS;
@@ -603,25 +512,15 @@
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
}.toJS;
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- )..window = window;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..window = window;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
- .having(
- (CameraWebException e) => e.code,
- 'code',
- CameraErrorCode.notStarted,
- ),
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
+ .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notStarted),
),
);
});
@@ -631,20 +530,13 @@
group('zoomLevel', () {
group('getMaxZoomLevel', () {
testWidgets('returns maximum '
- 'from CameraService.getZoomLevelCapabilityForCamera', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ 'from CameraService.getZoomLevelCapabilityForCamera', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
- videoTrack:
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
);
when(
@@ -653,9 +545,7 @@
final double maximumZoomLevel = camera.getMaxZoomLevel();
- verify(
- cameraService.getZoomLevelCapabilityForCamera(camera),
- ).called(1);
+ verify(cameraService.getZoomLevelCapabilityForCamera(camera)).called(1);
expect(maximumZoomLevel, equals(zoomLevelCapability.maximum));
});
@@ -663,20 +553,13 @@
group('getMinZoomLevel', () {
testWidgets('returns minimum '
- 'from CameraService.getZoomLevelCapabilityForCamera', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ 'from CameraService.getZoomLevelCapabilityForCamera', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
- videoTrack:
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
);
when(
@@ -685,9 +568,7 @@
final double minimumZoomLevel = camera.getMinZoomLevel();
- verify(
- cameraService.getZoomLevelCapabilityForCamera(camera),
- ).called(1);
+ verify(cameraService.getZoomLevelCapabilityForCamera(camera)).called(1);
expect(minimumZoomLevel, equals(zoomLevelCapability.minimum));
});
@@ -695,17 +576,11 @@
group('setZoomLevel', () {
testWidgets('applies zoom on the video track '
- 'from CameraService.getZoomLevelCapabilityForCamera', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ 'from CameraService.getZoomLevelCapabilityForCamera', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final mockVideoTrack = MockMediaStreamTrack();
- final videoTrack =
- createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack;
+ final videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack;
final zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
@@ -714,13 +589,12 @@
);
final capturedConstraints = <MediaTrackConstraints>[];
- mockVideoTrack.applyConstraints =
- ([MediaTrackConstraints? constraints]) {
- if (constraints != null) {
- capturedConstraints.add(constraints);
- }
- return Future<JSAny?>.value().toJS;
- }.toJS;
+ mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
+ if (constraints != null) {
+ capturedConstraints.add(constraints);
+ }
+ return Future<JSAny?>.value().toJS;
+ }.toJS;
when(
cameraService.getZoomLevelCapabilityForCamera(camera),
@@ -736,20 +610,13 @@
group('throws a CameraWebException', () {
testWidgets('with zoomLevelInvalid error '
- 'when the provided zoom level is below minimum', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ 'when the provided zoom level is below minimum', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
- videoTrack:
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
);
when(
@@ -760,11 +627,7 @@
() => camera.setZoomLevel(45.0),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -775,20 +638,13 @@
});
testWidgets('with zoomLevelInvalid error '
- 'when the provided zoom level is below minimum', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ 'when the provided zoom level is below minimum', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
- videoTrack:
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
);
when(
@@ -799,11 +655,7 @@
() => camera.setZoomLevel(105.0),
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -818,17 +670,12 @@
group('getLensDirection', () {
testWidgets('returns a lens direction '
- 'based on the first video track settings', (
- WidgetTester tester,
- ) async {
+ 'based on the first video track settings', (WidgetTester tester) async {
final mockVideoElement = MockVideoElement();
- final videoElement =
- createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
+ final videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- )..videoElement = videoElement;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..videoElement = videoElement;
final firstVideoTrack = MockMediaStreamTrack();
@@ -836,8 +683,7 @@
createJSInteropWrapper(
FakeMediaStream(<MediaStreamTrack>[
createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack,
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
]),
)
as MediaStream;
@@ -854,17 +700,12 @@
});
testWidgets('returns null '
- 'if the first video track is missing the facing mode', (
- WidgetTester tester,
- ) async {
+ 'if the first video track is missing the facing mode', (WidgetTester tester) async {
final mockVideoElement = MockVideoElement();
- final videoElement =
- createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
+ final videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- )..videoElement = videoElement;
+ final camera = Camera(textureId: textureId, cameraService: cameraService)
+ ..videoElement = videoElement;
final firstVideoTrack = MockMediaStreamTrack();
@@ -872,8 +713,7 @@
createJSInteropWrapper(
FakeMediaStream(<MediaStreamTrack>[
createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack,
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
]),
)
as MediaStream;
@@ -891,10 +731,7 @@
final videoElement = HTMLVideoElement();
mediaStream = videoElement.captureStream();
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
@@ -904,17 +741,11 @@
group('getViewType', () {
testWidgets('returns a correct view type', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
- expect(
- camera.getViewType(),
- equals('plugins.flutter.io/camera_$textureId'),
- );
+ expect(camera.getViewType(), equals('plugins.flutter.io/camera_$textureId'));
});
});
@@ -928,8 +759,7 @@
setUp(() {
mockMediaRecorder = MockMediaRecorder();
- mediaRecorder =
- createJSInteropWrapper(mockMediaRecorder) as MediaRecorder;
+ mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder;
});
group('startVideoRecording', () {
@@ -950,9 +780,7 @@
expect(camera.mediaRecorder!.state, equals('recording'));
});
- testWidgets('listens to the media recorder data events', (
- WidgetTester tester,
- ) async {
+ testWidgets('listens to the media recorder data events', (WidgetTester tester) async {
final camera = Camera(textureId: 1, cameraService: cameraService)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
@@ -968,15 +796,10 @@
await camera.startVideoRecording();
- expect(
- capturedEvents.where((String e) => e == 'dataavailable').length,
- 1,
- );
+ expect(capturedEvents.where((String e) => e == 'dataavailable').length, 1);
});
- testWidgets('listens to the media recorder stop events', (
- WidgetTester tester,
- ) async {
+ testWidgets('listens to the media recorder stop events', (WidgetTester tester) async {
final camera = Camera(textureId: 1, cameraService: cameraService)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
@@ -1026,16 +849,8 @@
camera.startVideoRecording,
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
- .having(
- (CameraWebException e) => e.code,
- 'code',
- CameraErrorCode.notSupported,
- ),
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
+ .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notSupported),
),
);
});
@@ -1059,20 +874,14 @@
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(textureId: 1, cameraService: cameraService);
expect(
camera.pauseVideoRecording,
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -1100,20 +909,14 @@
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(textureId: 1, cameraService: cameraService);
expect(
camera.resumeVideoRecording,
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -1167,20 +970,15 @@
final capturedVideoPartOne = Blob(<JSAny>[].toJS);
final capturedVideoPartTwo = Blob(<JSAny>[].toJS);
- final capturedVideoParts = <Blob>[
- capturedVideoPartOne,
- capturedVideoPartTwo,
- ];
+ final capturedVideoParts = <Blob>[capturedVideoPartOne, capturedVideoPartTwo];
videoDataAvailableListener.callAsFunction(
null,
- createJSInteropWrapper(FakeBlobEvent(capturedVideoPartOne))
- as BlobEvent,
+ createJSInteropWrapper(FakeBlobEvent(capturedVideoPartOne)) as BlobEvent,
);
videoDataAvailableListener.callAsFunction(
null,
- createJSInteropWrapper(FakeBlobEvent(capturedVideoPartTwo))
- as BlobEvent,
+ createJSInteropWrapper(FakeBlobEvent(capturedVideoPartTwo)) as BlobEvent,
);
videoRecordingStoppedListener.callAsFunction(null, Event('stop'));
@@ -1200,20 +998,14 @@
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(textureId: 1, cameraService: cameraService);
expect(
camera.stopVideoRecording,
throwsA(
isA<CameraWebException>()
- .having(
- (CameraWebException e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
.having(
(CameraWebException e) => e.code,
'code',
@@ -1258,10 +1050,7 @@
await Future<void>.microtask(() {});
- expect(
- capturedEvents.where((String e) => e == 'dataavailable').length,
- 1,
- );
+ expect(capturedEvents.where((String e) => e == 'dataavailable').length, 1);
});
testWidgets('stops listening to the media recorder stop events', (
@@ -1289,9 +1078,7 @@
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 onErrorStreamController = StreamController<ErrorEvent>();
final provider = MockEventStreamProvider<Event>();
@@ -1300,9 +1087,7 @@
..isVideoTypeSupported = isVideoTypeSupported
..mediaRecorderOnErrorProvider = provider;
- when(
- provider.forTarget(mediaRecorder),
- ).thenAnswer((_) => onErrorStreamController.stream);
+ when(provider.forTarget(mediaRecorder)).thenAnswer((_) => onErrorStreamController.stream);
await camera.initialize();
await camera.play();
@@ -1319,13 +1104,8 @@
});
group('dispose', () {
- testWidgets("resets the video element's source", (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ testWidgets("resets the video element's source", (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.dispose();
@@ -1334,10 +1114,7 @@
});
testWidgets('closes the onEnded stream', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.dispose();
@@ -1345,13 +1122,8 @@
expect(camera.onEndedController.isClosed, isTrue);
});
- testWidgets('closes the onVideoRecordedEvent stream', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ testWidgets('closes the onVideoRecordedEvent stream', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.dispose();
@@ -1359,13 +1131,8 @@
expect(camera.videoRecorderController.isClosed, isTrue);
});
- testWidgets('closes the onVideoRecordingError stream', (
- WidgetTester tester,
- ) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ testWidgets('closes the onVideoRecordingError stream', (WidgetTester tester) async {
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
await camera.initialize();
await camera.dispose();
@@ -1381,8 +1148,7 @@
const supportedVideoType = 'video/webm';
final mockMediaRecorder = MockMediaRecorder();
- final mediaRecorder =
- createJSInteropWrapper(mockMediaRecorder) as MediaRecorder;
+ final mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder;
final camera = Camera(textureId: 1, cameraService: cameraService)
..mediaRecorder = mediaRecorder
@@ -1403,9 +1169,7 @@
}
}.toJS;
- final streamQueue = StreamQueue<VideoRecordedEvent>(
- camera.onVideoRecordedEvent,
- );
+ final streamQueue = StreamQueue<VideoRecordedEvent>(camera.onVideoRecordedEvent);
await camera.startVideoRecording();
@@ -1425,25 +1189,13 @@
await streamQueue.next,
equals(
isA<VideoRecordedEvent>()
- .having(
- (VideoRecordedEvent e) => e.cameraId,
- 'cameraId',
- textureId,
- )
+ .having((VideoRecordedEvent e) => e.cameraId, 'cameraId', textureId)
.having(
(VideoRecordedEvent e) => e.file,
'file',
isA<XFile>()
- .having(
- (XFile f) => f.mimeType,
- 'mimeType',
- supportedVideoType,
- )
- .having(
- (XFile f) => f.name,
- 'name',
- finalVideo.hashCode.toString(),
- ),
+ .having((XFile f) => f.mimeType, 'mimeType', supportedVideoType)
+ .having((XFile f) => f.name, 'name', finalVideo.hashCode.toString()),
),
),
);
@@ -1455,18 +1207,13 @@
group('onEnded', () {
testWidgets('emits the default video track '
'when it emits an ended event', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final streamQueue = StreamQueue<MediaStreamTrack>(camera.onEnded);
await camera.initialize();
- final List<MediaStreamTrack> videoTracks = camera.stream!
- .getVideoTracks()
- .toDart;
+ final List<MediaStreamTrack> videoTracks = camera.stream!.getVideoTracks().toDart;
final MediaStreamTrack defaultVideoTrack = videoTracks.first;
defaultVideoTrack.dispatchEvent(Event('ended'));
@@ -1478,18 +1225,13 @@
testWidgets('emits the default video track '
'when the camera is stopped', (WidgetTester tester) async {
- final camera = Camera(
- textureId: textureId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: textureId, cameraService: cameraService);
final streamQueue = StreamQueue<MediaStreamTrack>(camera.onEnded);
await camera.initialize();
- final List<MediaStreamTrack> videoTracks = camera.stream!
- .getVideoTracks()
- .toDart;
+ final List<MediaStreamTrack> videoTracks = camera.stream!.getVideoTracks().toDart;
final MediaStreamTrack defaultVideoTrack = videoTracks.first;
camera.stop();
@@ -1505,23 +1247,17 @@
'when the media recorder fails '
'when recording a video', (WidgetTester tester) async {
final mockMediaRecorder = MockMediaRecorder();
- final mediaRecorder =
- createJSInteropWrapper(mockMediaRecorder) as MediaRecorder;
+ final mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder;
final errorController = StreamController<ErrorEvent>();
final provider = MockEventStreamProvider<Event>();
- final camera =
- Camera(textureId: textureId, cameraService: cameraService)
- ..mediaRecorder = mediaRecorder
- ..mediaRecorderOnErrorProvider = provider;
+ final 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<ErrorEvent>(
- camera.onVideoRecordingError,
- );
+ final streamQueue = StreamQueue<ErrorEvent>(camera.onVideoRecordingError);
await camera.initialize();
await camera.play();
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 8bc9469..bf3f573 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
@@ -23,19 +23,14 @@
expect(exception.description, equals(description));
});
- testWidgets('toString includes all properties', (
- WidgetTester tester,
- ) async {
+ testWidgets('toString includes all properties', (WidgetTester tester) async {
const cameraId = 2;
const CameraErrorCode code = CameraErrorCode.notReadable;
const description = 'The camera is not readable.';
final exception = CameraWebException(cameraId, code, description);
- expect(
- exception.toString(),
- equals('CameraWebException($cameraId, $code, $description)'),
- );
+ expect(exception.toString(), equals('CameraWebException($cameraId, $code, $description)'));
});
});
}
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 5542bac..089b392 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
@@ -71,8 +71,7 @@
mockScreenOrientation = MockScreenOrientation();
screen = createJSInteropWrapper(mockScreen) as Screen;
- screenOrientation =
- createJSInteropWrapper(mockScreenOrientation) as ScreenOrientation;
+ screenOrientation = createJSInteropWrapper(mockScreenOrientation) as ScreenOrientation;
mockScreen.orientation = screenOrientation;
mockWindow.screen = screen;
@@ -89,19 +88,13 @@
cameraService = MockCameraService();
when(
- cameraService.getMediaStreamForOptions(
- any,
- cameraId: anyNamed('cameraId'),
- ),
+ cameraService.getMediaStreamForOptions(any, cameraId: anyNamed('cameraId')),
).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<CameraPlugin>());
});
@@ -110,45 +103,33 @@
when(cameraService.getFacingModeForVideoTrack(any)).thenReturn(null);
mockMediaDevices.enumerateDevices = () {
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[].toJS).toJS;
}.toJS;
});
testWidgets('requests video permissions', (WidgetTester tester) async {
- final List<CameraDescription> _ = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> _ = await CameraPlatform.instance.availableCameras();
- verify(
- cameraService.getMediaStreamForOptions(const CameraOptions()),
- ).called(1);
+ verify(cameraService.getMediaStreamForOptions(const CameraOptions())).called(1);
});
testWidgets('releases the camera stream '
'used to request video permissions', (WidgetTester tester) async {
final mockVideoTrack = MockMediaStreamTrack();
- final videoTrack =
- createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack;
+ final videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack;
var videoTrackStopped = false;
mockVideoTrack.stop = () {
videoTrackStopped = true;
}.toJS;
- when(
- cameraService.getMediaStreamForOptions(const CameraOptions()),
- ).thenAnswer(
+ when(cameraService.getMediaStreamForOptions(const CameraOptions())).thenAnswer(
(_) => Future<MediaStream>.value(
- createJSInteropWrapper(
- FakeMediaStream(<MediaStreamTrack>[videoTrack]),
- )
- as MediaStream,
+ createJSInteropWrapper(FakeMediaStream(<MediaStreamTrack>[videoTrack])) as MediaStream,
),
);
- final List<CameraDescription> _ = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> _ = await CameraPlatform.instance.availableCameras();
expect(videoTrackStopped, isTrue);
});
@@ -156,29 +137,18 @@
testWidgets('gets a video stream '
'for a video input device', (WidgetTester tester) async {
final videoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '1',
- 'Camera 1',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
mockMediaDevices.enumerateDevices = () {
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[videoDevice].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[videoDevice].toJS).toJS;
}.toJS;
- final List<CameraDescription> _ = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> _ = await CameraPlatform.instance.availableCameras();
verify(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: videoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)),
),
).called(1);
});
@@ -187,29 +157,18 @@
'for the video input device '
'with an empty device id', (WidgetTester tester) async {
final videoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '',
- 'Camera 1',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('', 'Camera 1', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
mockMediaDevices.enumerateDevices = () {
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[videoDevice].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[videoDevice].toJS).toJS;
}.toJS;
- final List<CameraDescription> _ = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> _ = await CameraPlatform.instance.availableCameras();
verifyNever(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: videoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)),
),
);
});
@@ -218,47 +177,32 @@
'from the first available video track '
'of the video input device', (WidgetTester tester) async {
final videoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '1',
- 'Camera 1',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
final videoStream =
createJSInteropWrapper(
FakeMediaStream(<MediaStreamTrack>[
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
]),
)
as MediaStream;
when(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: videoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)),
),
).thenAnswer((_) => Future<MediaStream>.value(videoStream));
mockMediaDevices.enumerateDevices = () {
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[videoDevice].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[videoDevice].toJS).toJS;
}.toJS;
- final List<CameraDescription> _ = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> _ = await CameraPlatform.instance.availableCameras();
verify(
- cameraService.getFacingModeForVideoTrack(
- videoStream.getVideoTracks().toDart.first,
- ),
+ cameraService.getFacingModeForVideoTrack(videoStream.getVideoTracks().toDart.first),
).called(1);
});
@@ -266,33 +210,19 @@
'for multiple video devices '
'based on video streams', (WidgetTester tester) async {
final firstVideoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '1',
- 'Camera 1',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
final secondVideoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '4',
- 'Camera 4',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('4', 'Camera 4', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
// Create a video stream for the first video device.
final firstVideoStream =
createJSInteropWrapper(
FakeMediaStream(<MediaStreamTrack>[
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
]),
)
as MediaStream;
@@ -301,8 +231,7 @@
final secondVideoStream =
createJSInteropWrapper(
FakeMediaStream(<MediaStreamTrack>[
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
]),
)
as MediaStream;
@@ -314,19 +243,11 @@
<MediaDeviceInfo>[
firstVideoDevice,
createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '2',
- 'Audio Input 2',
- MediaDeviceKind.audioInput,
- ),
+ FakeMediaDeviceInfo('2', 'Audio Input 2', MediaDeviceKind.audioInput),
)
as MediaDeviceInfo,
createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '3',
- 'Audio Output 3',
- MediaDeviceKind.audioOutput,
- ),
+ FakeMediaDeviceInfo('3', 'Audio Output 3', MediaDeviceKind.audioOutput),
)
as MediaDeviceInfo,
secondVideoDevice,
@@ -338,9 +259,7 @@
// for the first video device.
when(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: firstVideoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: firstVideoDevice.deviceId)),
),
).thenAnswer((_) => Future<MediaStream>.value(firstVideoStream));
@@ -348,18 +267,14 @@
// for the second video device.
when(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: secondVideoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: secondVideoDevice.deviceId)),
),
).thenAnswer((_) => Future<MediaStream>.value(secondVideoStream));
// Mock camera service to return a user facing mode
// for the first video stream.
when(
- cameraService.getFacingModeForVideoTrack(
- firstVideoStream.getVideoTracks().toDart.first,
- ),
+ cameraService.getFacingModeForVideoTrack(firstVideoStream.getVideoTracks().toDart.first),
).thenReturn('user');
when(
@@ -369,17 +284,14 @@
// Mock camera service to return an environment facing mode
// for the second video stream.
when(
- cameraService.getFacingModeForVideoTrack(
- secondVideoStream.getVideoTracks().toDart.first,
- ),
+ cameraService.getFacingModeForVideoTrack(secondVideoStream.getVideoTracks().toDart.first),
).thenReturn('environment');
when(
cameraService.mapFacingModeToLensDirection('environment'),
).thenReturn(CameraLensDirection.back);
- final List<CameraDescription> cameras = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
// Expect two cameras and ignore two audio devices.
expect(
@@ -402,60 +314,42 @@
testWidgets('sets camera metadata '
'for the camera description', (WidgetTester tester) async {
final videoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '1',
- 'Camera 1',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
final videoStream =
createJSInteropWrapper(
FakeMediaStream(<MediaStreamTrack>[
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
- createJSInteropWrapper(MockMediaStreamTrack())
- as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
+ createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
]),
)
as MediaStream;
mockMediaDevices.enumerateDevices = () {
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[videoDevice].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[videoDevice].toJS).toJS;
}.toJS;
when(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: videoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)),
),
).thenAnswer((_) => Future<MediaStream>.value(videoStream));
when(
- cameraService.getFacingModeForVideoTrack(
- videoStream.getVideoTracks().toDart.first,
- ),
+ cameraService.getFacingModeForVideoTrack(videoStream.getVideoTracks().toDart.first),
).thenReturn('left');
when(
cameraService.mapFacingModeToLensDirection('left'),
).thenReturn(CameraLensDirection.external);
- final CameraDescription camera =
- (await CameraPlatform.instance.availableCameras()).first;
+ final CameraDescription camera = (await CameraPlatform.instance.availableCameras()).first;
expect(
(CameraPlatform.instance as CameraPlugin).camerasMetadata,
equals(<CameraDescription, CameraMetadata>{
- camera: CameraMetadata(
- deviceId: videoDevice.deviceId,
- facingMode: 'left',
- ),
+ camera: CameraMetadata(deviceId: videoDevice.deviceId, facingMode: 'left'),
}),
);
});
@@ -463,13 +357,7 @@
testWidgets('releases the video stream '
'of a video input device', (WidgetTester tester) async {
final videoDevice =
- createJSInteropWrapper(
- FakeMediaDeviceInfo(
- '1',
- 'Camera 1',
- MediaDeviceKind.videoInput,
- ),
- )
+ createJSInteropWrapper(FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput))
as MediaDeviceInfo;
final tracks = <MediaStreamTrack>[];
@@ -482,25 +370,19 @@
tracks.add(createJSInteropWrapper(track) as MediaStreamTrack);
}
- final videoStream =
- createJSInteropWrapper(FakeMediaStream(tracks)) as MediaStream;
+ final videoStream = createJSInteropWrapper(FakeMediaStream(tracks)) as MediaStream;
mockMediaDevices.enumerateDevices = () {
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[videoDevice].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[videoDevice].toJS).toJS;
}.toJS;
when(
cameraService.getMediaStreamForOptions(
- CameraOptions(
- video: VideoConstraints(deviceId: videoDevice.deviceId),
- ),
+ CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)),
),
).thenAnswer((_) => Future<MediaStream>.value(videoStream));
- final List<CameraDescription> _ = await CameraPlatform.instance
- .availableCameras();
+ final List<CameraDescription> _ = await CameraPlatform.instance.availableCameras();
expect(stops.every((bool e) => e), isTrue);
});
@@ -514,34 +396,22 @@
mockMediaDevices.enumerateDevices = () {
throw exception;
// ignore: dead_code
- return Future<JSArray<MediaDeviceInfo>>.value(
- <MediaDeviceInfo>[].toJS,
- ).toJS;
+ return Future<JSArray<MediaDeviceInfo>>.value(<MediaDeviceInfo>[].toJS).toJS;
}.toJS;
expect(
() => CameraPlatform.instance.availableCameras(),
throwsA(
- isA<CameraException>().having(
- (CameraException e) => e.code,
- 'code',
- exception.name,
- ),
+ isA<CameraException>().having((CameraException e) => e.code, 'code', exception.name),
),
);
});
testWidgets('when CameraService.getMediaStreamForOptions '
'throws CameraWebException', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.security,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.security, 'description');
- when(
- cameraService.getMediaStreamForOptions(any),
- ).thenThrow(exception);
+ when(cameraService.getMediaStreamForOptions(any)).thenThrow(exception);
expect(
CameraPlatform.instance.availableCameras(),
@@ -562,18 +432,12 @@
message: 'message',
);
- when(
- cameraService.getMediaStreamForOptions(any),
- ).thenThrow(exception);
+ when(cameraService.getMediaStreamForOptions(any)).thenThrow(exception);
expect(
() => CameraPlatform.instance.availableCameras(),
throwsA(
- isA<CameraException>().having(
- (CameraException e) => e.code,
- 'code',
- exception.code,
- ),
+ isA<CameraException>().having((CameraException e) => e.code, 'code', exception.code),
),
);
});
@@ -591,20 +455,14 @@
sensorOrientation: 0,
);
- const cameraMetadata = CameraMetadata(
- deviceId: 'deviceId',
- facingMode: 'user',
- );
+ const cameraMetadata = CameraMetadata(deviceId: 'deviceId', facingMode: 'user');
setUp(() {
// Add metadata for the camera description.
- (CameraPlatform.instance as CameraPlugin)
- .camerasMetadata[cameraDescription] =
+ (CameraPlatform.instance as CameraPlugin).camerasMetadata[cameraDescription] =
cameraMetadata;
- when(
- cameraService.mapFacingModeToCameraType('user'),
- ).thenReturn(CameraType.user);
+ when(cameraService.mapFacingModeToCameraType('user')).thenReturn(CameraType.user);
});
testWidgets('with appropriate options', (WidgetTester tester) async {
@@ -618,24 +476,14 @@
enableAudio: true,
);
- final Camera? camera =
- (CameraPlatform.instance as CameraPlugin).cameras[cameraId];
+ final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId];
expect(camera, isA<Camera>());
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);
});
@@ -646,35 +494,24 @@
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];
+ final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId];
expect(camera, isA<Camera>());
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);
});
@@ -685,29 +522,16 @@
cameraService.mapResolutionPresetToSize(ResolutionPreset.max),
).thenReturn(maxResolutionSize);
- final int cameraId = await CameraPlatform.instance.createCamera(
- cameraDescription,
- null,
- );
+ final int cameraId = await CameraPlatform.instance.createCamera(cameraDescription, null);
- final Camera? camera =
- (CameraPlatform.instance as CameraPlugin).cameras[cameraId];
+ final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId];
expect(camera, isA<Camera>());
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);
});
@@ -719,29 +543,18 @@
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];
+ final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId];
expect(camera, isA<Camera>());
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);
});
});
@@ -811,8 +624,7 @@
setUp(() {
camera = MockCamera();
mockVideoElement = MockVideoElement();
- videoElement =
- createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
+ videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
errorStreamController = StreamController<Event>();
abortStreamController = StreamController<Event>();
@@ -827,24 +639,20 @@
final errorProvider = MockEventStreamProvider<Event>();
final abortProvider = MockEventStreamProvider<Event>();
- (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider =
- errorProvider;
- (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider =
- abortProvider;
+ (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider;
+ (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = abortProvider;
- when(errorProvider.forElement(videoElement)).thenAnswer(
- (_) => FakeElementStream<Event>(errorStreamController.stream),
- );
- when(abortProvider.forElement(videoElement)).thenAnswer(
- (_) => FakeElementStream<Event>(abortStreamController.stream),
- );
+ when(
+ errorProvider.forElement(videoElement),
+ ).thenAnswer((_) => FakeElementStream<Event>(errorStreamController.stream));
+ when(
+ abortProvider.forElement(videoElement),
+ ).thenAnswer((_) => FakeElementStream<Event>(abortStreamController.stream));
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;
@@ -854,28 +662,25 @@
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;
-
- expect(errorStreamController.hasListener, isFalse);
- expect(abortStreamController.hasListener, isFalse);
-
- await CameraPlatform.instance.initializeCamera(cameraId);
-
- expect(errorStreamController.hasListener, isTrue);
- expect(abortStreamController.hasListener, isTrue);
- },
- );
-
- testWidgets('starts listening to the camera ended events', (
+ 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);
+
+ await CameraPlatform.instance.initializeCamera(cameraId);
+
+ expect(errorStreamController.hasListener, isTrue);
+ expect(abortStreamController.hasListener, isTrue);
+ });
+
+ 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;
+
expect(endedStreamController.hasListener, isFalse);
await CameraPlatform.instance.initializeCamera(cameraId);
@@ -898,9 +703,7 @@
);
});
- testWidgets('when camera throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when camera throws CameraWebException', (WidgetTester tester) async {
final exception = CameraWebException(
cameraId,
CameraErrorCode.permissionDenied,
@@ -924,9 +727,7 @@
);
});
- testWidgets('when camera throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when camera throws DomException', (WidgetTester tester) async {
final exception = DOMException('NotAllowedError');
when(camera.initialize()).thenAnswer((_) => Future<void>.value());
@@ -975,9 +776,7 @@
testWidgets('locks the capture orientation '
'based on the given device orientation', (WidgetTester tester) async {
when(
- cameraService.mapDeviceOrientationToOrientationType(
- DeviceOrientation.landscapeRight,
- ),
+ cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeRight),
).thenReturn(OrientationType.landscapeSecondary);
final capturedTypes = <OrientationLockType>[];
@@ -992,9 +791,7 @@
);
verify(
- cameraService.mapDeviceOrientationToOrientationType(
- DeviceOrientation.landscapeRight,
- ),
+ cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeRight),
).called(1);
expect(capturedTypes.length, 1);
@@ -1003,9 +800,7 @@
group('throws PlatformException', () {
testWidgets('with orientationNotSupported error '
- 'when documentElement is not available', (
- WidgetTester tester,
- ) async {
+ 'when documentElement is not available', (WidgetTester tester) async {
mockDocument.documentElement = null;
expect(
@@ -1025,9 +820,7 @@
mockDocument.documentElement = documentElement;
});
- testWidgets('when lock throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when lock throws DomException', (WidgetTester tester) async {
final exception = DOMException('NotAllowedError');
mockScreenOrientation.lock = (OrientationLockType orientation) {
@@ -1060,9 +853,7 @@
).thenReturn(OrientationType.portraitPrimary);
});
- testWidgets('unlocks the capture orientation', (
- WidgetTester tester,
- ) async {
+ testWidgets('unlocks the capture orientation', (WidgetTester tester) async {
var unlocks = 0;
mockScreenOrientation.unlock = () {
unlocks++;
@@ -1075,9 +866,7 @@
group('throws PlatformException', () {
testWidgets('with orientationNotSupported error '
- 'when documentElement is not available', (
- WidgetTester tester,
- ) async {
+ 'when documentElement is not available', (WidgetTester tester) async {
mockDocument.documentElement = null;
expect(
@@ -1094,9 +883,7 @@
mockDocument.documentElement = documentElement;
});
- testWidgets('when unlock throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when unlock throws DomException', (WidgetTester tester) async {
final exception = DOMException('NotAllowedError');
mockScreenOrientation.unlock = () {
@@ -1129,9 +916,7 @@
// 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);
@@ -1153,9 +938,7 @@
);
});
- testWidgets('when takePicture throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when takePicture throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -1176,15 +959,9 @@
);
});
- testWidgets('when takePicture throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when takePicture throws CameraWebException', (WidgetTester tester) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.takePicture()).thenThrow(exception);
@@ -1213,9 +990,7 @@
when(camera.startVideoRecording()).thenAnswer((_) async {});
- when(
- camera.onVideoRecordingError,
- ).thenAnswer((_) => const Stream<ErrorEvent>.empty());
+ when(camera.onVideoRecordingError).thenAnswer((_) => const Stream<ErrorEvent>.empty());
});
testWidgets('starts a video recording', (WidgetTester tester) async {
@@ -1227,14 +1002,10 @@
verify(camera.startVideoRecording()).called(1);
});
- testWidgets('listens to the onVideoRecordingError stream', (
- WidgetTester tester,
- ) async {
+ testWidgets('listens to the onVideoRecordingError stream', (WidgetTester tester) async {
final videoRecordingErrorController = StreamController<ErrorEvent>();
- 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;
@@ -1259,9 +1030,7 @@
);
});
- testWidgets('when startVideoRecording throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when startVideoRecording throws DomException', (WidgetTester tester) async {
final exception = DOMException('InvalidStateError');
when(camera.startVideoRecording()).thenThrow(exception);
@@ -1284,11 +1053,7 @@
testWidgets('when startVideoRecording throws CameraWebException', (
WidgetTester tester,
) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.startVideoRecording()).thenThrow(exception);
@@ -1317,9 +1082,7 @@
when(camera.startVideoRecording()).thenAnswer((_) async {});
- when(
- camera.onVideoRecordingError,
- ).thenAnswer((_) => const Stream<ErrorEvent>.empty());
+ when(camera.onVideoRecordingError).thenAnswer((_) => const Stream<ErrorEvent>.empty());
});
testWidgets('fails if trying to stream', (WidgetTester tester) async {
@@ -1328,10 +1091,7 @@
expect(
() => CameraPlatform.instance.startVideoCapturing(
- VideoCaptureOptions(
- cameraId,
- streamCallback: (CameraImageData imageData) {},
- ),
+ VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}),
),
throwsA(isA<UnimplementedError>()),
);
@@ -1343,16 +1103,12 @@
final camera = MockCamera();
final 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);
@@ -1368,21 +1124,15 @@
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,
- );
+ final XFile _ = await CameraPlatform.instance.stopVideoRecording(cameraId);
expect(videoRecordingErrorController.hasListener, isFalse);
});
@@ -1402,9 +1152,7 @@
);
});
- testWidgets('when stopVideoRecording throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when stopVideoRecording throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('InvalidStateError');
@@ -1429,11 +1177,7 @@
WidgetTester tester,
) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.stopVideoRecording()).thenThrow(exception);
@@ -1483,9 +1227,7 @@
);
});
- testWidgets('when pauseVideoRecording throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when pauseVideoRecording throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('InvalidStateError');
@@ -1510,11 +1252,7 @@
WidgetTester tester,
) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.pauseVideoRecording()).thenThrow(exception);
@@ -1564,9 +1302,7 @@
);
});
- testWidgets('when resumeVideoRecording throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when resumeVideoRecording throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('InvalidStateError');
@@ -1591,11 +1327,7 @@
WidgetTester tester,
) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.resumeVideoRecording()).thenThrow(exception);
@@ -1617,9 +1349,7 @@
});
group('setFlashMode', () {
- testWidgets('calls setFlashMode on the camera', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls setFlashMode on the camera', (WidgetTester tester) async {
final camera = MockCamera();
const FlashMode flashMode = FlashMode.always;
@@ -1635,10 +1365,7 @@
testWidgets('with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
- () => CameraPlatform.instance.setFlashMode(
- cameraId,
- FlashMode.always,
- ),
+ () => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.always),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
@@ -1649,9 +1376,7 @@
);
});
- testWidgets('when setFlashMode throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when setFlashMode throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -1661,10 +1386,7 @@
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
- () => CameraPlatform.instance.setFlashMode(
- cameraId,
- FlashMode.always,
- ),
+ () => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.always),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
@@ -1675,15 +1397,9 @@
);
});
- testWidgets('when setFlashMode throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when setFlashMode throws CameraWebException', (WidgetTester tester) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.setFlashMode(any)).thenThrow(exception);
@@ -1691,8 +1407,7 @@
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
- () =>
- CameraPlatform.instance.setFlashMode(cameraId, FlashMode.torch),
+ () => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.torch),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
@@ -1705,91 +1420,64 @@
});
});
- testWidgets('setExposureMode throws UnimplementedError', (
- WidgetTester tester,
- ) async {
+ testWidgets('setExposureMode throws UnimplementedError', (WidgetTester tester) async {
expect(
- () => CameraPlatform.instance.setExposureMode(
- cameraId,
- ExposureMode.auto,
- ),
+ () => CameraPlatform.instance.setExposureMode(cameraId, ExposureMode.auto),
throwsUnimplementedError,
);
});
- testWidgets('setExposurePoint throws UnimplementedError', (
- WidgetTester tester,
- ) async {
+ testWidgets('setExposurePoint throws UnimplementedError', (WidgetTester tester) async {
expect(
- () => CameraPlatform.instance.setExposurePoint(
- cameraId,
- const Point<double>(0, 0),
- ),
+ () => CameraPlatform.instance.setExposurePoint(cameraId, const Point<double>(0, 0)),
throwsUnimplementedError,
);
});
- 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),
throwsUnimplementedError,
);
});
- testWidgets('setFocusMode throws UnimplementedError', (
- WidgetTester tester,
- ) async {
+ testWidgets('setFocusMode throws UnimplementedError', (WidgetTester tester) async {
expect(
() => 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,
- const Point<double>(0, 0),
- ),
+ () => CameraPlatform.instance.setFocusPoint(cameraId, const Point<double>(0, 0)),
throwsUnimplementedError,
);
});
group('getMaxZoomLevel', () {
- testWidgets('calls getMaxZoomLevel on the camera', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls getMaxZoomLevel on the camera', (WidgetTester tester) async {
final camera = MockCamera();
const maximumZoomLevel = 100.0;
@@ -1798,10 +1486,7 @@
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
- expect(
- await CameraPlatform.instance.getMaxZoomLevel(cameraId),
- equals(maximumZoomLevel),
- );
+ expect(await CameraPlatform.instance.getMaxZoomLevel(cameraId), equals(maximumZoomLevel));
verify(camera.getMaxZoomLevel()).called(1);
});
@@ -1821,9 +1506,7 @@
);
});
- testWidgets('when getMaxZoomLevel throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when getMaxZoomLevel throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -1844,15 +1527,9 @@
);
});
- testWidgets('when getMaxZoomLevel throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when getMaxZoomLevel throws CameraWebException', (WidgetTester tester) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.getMaxZoomLevel()).thenThrow(exception);
@@ -1874,9 +1551,7 @@
});
group('getMinZoomLevel', () {
- testWidgets('calls getMinZoomLevel on the camera', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls getMinZoomLevel on the camera', (WidgetTester tester) async {
final camera = MockCamera();
const minimumZoomLevel = 100.0;
@@ -1885,10 +1560,7 @@
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
- expect(
- await CameraPlatform.instance.getMinZoomLevel(cameraId),
- equals(minimumZoomLevel),
- );
+ expect(await CameraPlatform.instance.getMinZoomLevel(cameraId), equals(minimumZoomLevel));
verify(camera.getMinZoomLevel()).called(1);
});
@@ -1908,9 +1580,7 @@
);
});
- testWidgets('when getMinZoomLevel throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when getMinZoomLevel throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -1931,15 +1601,9 @@
);
});
- testWidgets('when getMinZoomLevel throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when getMinZoomLevel throws CameraWebException', (WidgetTester tester) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.getMinZoomLevel()).thenThrow(exception);
@@ -1961,9 +1625,7 @@
});
group('setZoomLevel', () {
- testWidgets('calls setZoomLevel on the camera', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls setZoomLevel on the camera', (WidgetTester tester) async {
final camera = MockCamera();
// Save the camera in the camera plugin.
@@ -1991,9 +1653,7 @@
);
});
- testWidgets('when setZoomLevel throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when setZoomLevel throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -2005,18 +1665,12 @@
expect(
() async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0),
throwsA(
- isA<CameraException>().having(
- (CameraException e) => e.code,
- 'code',
- exception.name,
- ),
+ isA<CameraException>().having((CameraException e) => e.code, 'code', exception.name),
),
);
});
- testWidgets('when setZoomLevel throws PlatformException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when setZoomLevel throws PlatformException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = PlatformException(
code: CameraErrorCode.notSupported.toString(),
@@ -2031,24 +1685,14 @@
expect(
() async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0),
throwsA(
- isA<CameraException>().having(
- (CameraException e) => e.code,
- 'code',
- exception.code,
- ),
+ isA<CameraException>().having((CameraException e) => e.code, 'code', exception.code),
),
);
});
- testWidgets('when setZoomLevel throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when setZoomLevel throws CameraWebException', (WidgetTester tester) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.setZoomLevel(any)).thenThrow(exception);
@@ -2096,9 +1740,7 @@
);
});
- testWidgets('when pause throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when pause throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -2150,9 +1792,7 @@
);
});
- testWidgets('when play throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when play throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('NotSupportedError');
@@ -2173,15 +1813,9 @@
);
});
- testWidgets('when play throws CameraWebException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when play throws CameraWebException', (WidgetTester tester) async {
final camera = MockCamera();
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.unknown,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.unknown, 'description');
when(camera.play()).thenThrow(exception);
@@ -2231,8 +1865,7 @@
setUp(() {
camera = MockCamera();
mockVideoElement = MockVideoElement();
- videoElement =
- createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
+ videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
errorStreamController = StreamController<Event>();
abortStreamController = StreamController<Event>();
@@ -2249,23 +1882,19 @@
final errorProvider = MockEventStreamProvider<Event>();
final abortProvider = MockEventStreamProvider<Event>();
- (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider =
- errorProvider;
- (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider =
- abortProvider;
+ (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider;
+ (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = abortProvider;
- when(errorProvider.forElement(videoElement)).thenAnswer(
- (_) => FakeElementStream<Event>(errorStreamController.stream),
- );
- when(abortProvider.forElement(videoElement)).thenAnswer(
- (_) => FakeElementStream<Event>(abortStreamController.stream),
- );
+ when(
+ errorProvider.forElement(videoElement),
+ ).thenAnswer((_) => FakeElementStream<Event>(errorStreamController.stream));
+ when(
+ abortProvider.forElement(videoElement),
+ ).thenAnswer((_) => FakeElementStream<Event>(abortStreamController.stream));
when(camera.onEnded).thenAnswer((_) => endedStreamController.stream);
- when(
- camera.onVideoRecordingError,
- ).thenAnswer((_) => videoRecordingErrorController.stream);
+ when(camera.onVideoRecordingError).thenAnswer((_) => videoRecordingErrorController.stream);
when(camera.startVideoRecording()).thenAnswer((_) async {});
});
@@ -2313,9 +1942,7 @@
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;
@@ -2353,9 +1980,7 @@
);
});
- testWidgets('when dispose throws DomException', (
- WidgetTester tester,
- ) async {
+ testWidgets('when dispose throws DomException', (WidgetTester tester) async {
final camera = MockCamera();
final exception = DOMException('InvalidAccessError');
@@ -2380,18 +2005,12 @@
group('getCamera', () {
testWidgets('returns the correct camera', (WidgetTester tester) async {
- final camera = Camera(
- textureId: cameraId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: cameraId, cameraService: cameraService);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
- expect(
- (CameraPlatform.instance as CameraPlugin).getCamera(cameraId),
- equals(camera),
- );
+ expect((CameraPlatform.instance as CameraPlugin).getCamera(cameraId), equals(camera));
});
testWidgets('throws PlatformException '
@@ -2422,8 +2041,7 @@
setUp(() {
camera = MockCamera();
mockVideoElement = MockVideoElement();
- videoElement =
- createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
+ videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement;
errorStreamController = StreamController<Event>();
abortStreamController = StreamController<Event>();
@@ -2439,23 +2057,19 @@
final errorProvider = MockEventStreamProvider<Event>();
final abortProvider = MockEventStreamProvider<Event>();
- (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider =
- errorProvider;
- (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider =
- abortProvider;
+ (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider;
+ (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = abortProvider;
- when(errorProvider.forElement(any)).thenAnswer(
- (_) => FakeElementStream<Event>(errorStreamController.stream),
- );
- when(abortProvider.forElement(any)).thenAnswer(
- (_) => FakeElementStream<Event>(abortStreamController.stream),
- );
+ when(
+ errorProvider.forElement(any),
+ ).thenAnswer((_) => FakeElementStream<Event>(errorStreamController.stream));
+ when(
+ abortProvider.forElement(any),
+ ).thenAnswer((_) => FakeElementStream<Event>(abortStreamController.stream));
when(camera.onEnded).thenAnswer((_) => endedStreamController.stream);
- when(
- camera.onVideoRecordingError,
- ).thenAnswer((_) => videoRecordingErrorController.stream);
+ when(camera.onVideoRecordingError).thenAnswer((_) => videoRecordingErrorController.stream);
when(camera.startVideoRecording()).thenAnswer((_) async {});
});
@@ -2471,16 +2085,12 @@
cameraService.getMediaStreamForOptions(any, cameraId: cameraId),
).thenAnswer((_) async => videoElement.captureStream());
- final camera = Camera(
- textureId: cameraId,
- cameraService: cameraService,
- );
+ final camera = Camera(textureId: cameraId, cameraService: cameraService);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
- final Stream<CameraInitializedEvent> eventStream = CameraPlatform
- .instance
+ final Stream<CameraInitializedEvent> eventStream = CameraPlatform.instance
.onCameraInitialized(cameraId);
final streamQueue = StreamQueue<CameraInitializedEvent>(eventStream);
@@ -2505,11 +2115,8 @@
await streamQueue.cancel();
});
- testWidgets('onCameraResolutionChanged emits an empty stream', (
- WidgetTester tester,
- ) async {
- final Stream<CameraResolutionChangedEvent> stream = CameraPlatform
- .instance
+ testWidgets('onCameraResolutionChanged emits an empty stream', (WidgetTester tester) async {
+ final Stream<CameraResolutionChangedEvent> stream = CameraPlatform.instance
.onCameraResolutionChanged(cameraId);
expect(await stream.isEmpty, isTrue);
});
@@ -2519,8 +2126,9 @@
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
- final Stream<CameraClosingEvent> eventStream = CameraPlatform.instance
- .onCameraClosing(cameraId);
+ final Stream<CameraClosingEvent> eventStream = CameraPlatform.instance.onCameraClosing(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraClosingEvent>(eventStream);
@@ -2530,10 +2138,7 @@
createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack,
);
- expect(
- await streamQueue.next,
- equals(const CameraClosingEvent(cameraId)),
- );
+ expect(await streamQueue.next, equals(const CameraClosingEvent(cameraId)));
await streamQueue.cancel();
});
@@ -2547,8 +2152,9 @@
testWidgets('emits a CameraErrorEvent '
'on the camera video error event '
'with a message', (WidgetTester tester) async {
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2556,16 +2162,11 @@
final error =
createJSInteropWrapper(
- FakeMediaError(
- MediaError.MEDIA_ERR_NETWORK,
- 'A network error occurred.',
- ),
+ 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'));
@@ -2573,10 +2174,7 @@
expect(
await streamQueue.next,
equals(
- CameraErrorEvent(
- cameraId,
- 'Error code: $errorCode, error message: ${error.message}',
- ),
+ CameraErrorEvent(cameraId, 'Error code: $errorCode, error message: ${error.message}'),
),
);
@@ -2586,21 +2184,17 @@
testWidgets('emits a CameraErrorEvent '
'on the camera video error event '
'with no message', (WidgetTester tester) async {
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
final error =
- createJSInteropWrapper(
- FakeMediaError(MediaError.MEDIA_ERR_NETWORK),
- )
- as MediaError;
- final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(
- error,
- );
+ createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_NETWORK)) as MediaError;
+ final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error);
mockVideoElement.error = error;
errorStreamController.add(Event('error'));
@@ -2620,8 +2214,9 @@
testWidgets('emits a CameraErrorEvent '
'on the camera video abort event', (WidgetTester tester) async {
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2644,16 +2239,13 @@
testWidgets('emits a CameraErrorEvent '
'on takePicture error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.takePicture()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2677,24 +2269,18 @@
testWidgets('emits a CameraErrorEvent '
'on setFlashMode error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.setFlashMode(any)).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
expect(
- () async => CameraPlatform.instance.setFlashMode(
- cameraId,
- FlashMode.always,
- ),
+ () async => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.always),
throwsA(isA<PlatformException>()),
);
@@ -2721,8 +2307,9 @@
when(camera.getMaxZoomLevel()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2754,8 +2341,9 @@
when(camera.getMinZoomLevel()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2787,8 +2375,9 @@
when(camera.setZoomLevel(any)).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2812,16 +2401,13 @@
testWidgets('emits a CameraErrorEvent '
'on resumePreview error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.unknown,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.unknown, 'description');
when(camera.play()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2845,20 +2431,15 @@
testWidgets('emits a CameraErrorEvent '
'on startVideoRecording error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
- when(
- camera.onVideoRecordingError,
- ).thenAnswer((_) => const Stream<ErrorEvent>.empty());
+ when(camera.onVideoRecordingError).thenAnswer((_) => const Stream<ErrorEvent>.empty());
when(camera.startVideoRecording()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2881,11 +2462,10 @@
});
testWidgets('emits a CameraErrorEvent '
- 'on the camera video recording error event', (
- WidgetTester tester,
- ) async {
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ 'on the camera video recording error event', (WidgetTester tester) async {
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2893,8 +2473,7 @@
await CameraPlatform.instance.startVideoRecording(cameraId);
final errorEvent =
- createJSInteropWrapper(FakeErrorEvent('type', 'message'))
- as ErrorEvent;
+ createJSInteropWrapper(FakeErrorEvent('type', 'message')) as ErrorEvent;
videoRecordingErrorController.add(errorEvent);
@@ -2913,16 +2492,13 @@
testWidgets('emits a CameraErrorEvent '
'on stopVideoRecording error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.stopVideoRecording()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2946,16 +2522,13 @@
testWidgets('emits a CameraErrorEvent '
'on pauseVideoRecording error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.pauseVideoRecording()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -2979,16 +2552,13 @@
testWidgets('emits a CameraErrorEvent '
'on resumeVideoRecording error', (WidgetTester tester) async {
- final exception = CameraWebException(
- cameraId,
- CameraErrorCode.notStarted,
- 'description',
- );
+ final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description');
when(camera.resumeVideoRecording()).thenThrow(exception);
- final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance
- .onCameraError(cameraId);
+ final Stream<CameraErrorEvent> eventStream = CameraPlatform.instance.onCameraError(
+ cameraId,
+ );
final streamQueue = StreamQueue<CameraErrorEvent>(eventStream);
@@ -3011,9 +2581,7 @@
});
});
- testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', (
- WidgetTester tester,
- ) async {
+ testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', (WidgetTester tester) async {
final camera = MockCamera();
final capturedVideo = XFile('/bogus/test');
final stream = Stream<VideoRecordedEvent>.value(
@@ -3039,65 +2607,45 @@
setUp(() {
final provider = MockEventStreamProvider<Event>();
- (CameraPlatform.instance as CameraPlugin)
- .orientationOnChangeProvider =
- provider;
- when(
- provider.forTarget(any),
- ).thenAnswer((_) => eventStreamController.stream);
+ (CameraPlatform.instance as CameraPlugin).orientationOnChangeProvider = provider;
+ 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,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitPrimary),
).thenReturn(DeviceOrientation.portraitUp);
// Set the initial screen orientation to portraitPrimary.
mockScreenOrientation.type = OrientationType.portraitPrimary;
- final Stream<DeviceOrientationChangedEvent> eventStream =
- CameraPlatform.instance.onDeviceOrientationChanged();
+ final Stream<DeviceOrientationChangedEvent> eventStream = CameraPlatform.instance
+ .onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
expect(
await streamQueue.next,
- equals(
- const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp),
- ),
+ equals(const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp)),
);
await streamQueue.cancel();
});
testWidgets('emits a DeviceOrientationChangedEvent '
- 'when the screen orientation is changed', (
- WidgetTester tester,
- ) async {
+ 'when the screen orientation is changed', (WidgetTester tester) async {
when(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.landscapePrimary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.landscapePrimary),
).thenReturn(DeviceOrientation.landscapeLeft);
when(
- cameraService.mapOrientationTypeToDeviceOrientation(
- OrientationType.portraitSecondary,
- ),
+ cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitSecondary),
).thenReturn(DeviceOrientation.portraitDown);
- final Stream<DeviceOrientationChangedEvent> eventStream =
- CameraPlatform.instance.onDeviceOrientationChanged();
+ final Stream<DeviceOrientationChangedEvent> eventStream = CameraPlatform.instance
+ .onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
// Change the screen orientation to landscapePrimary and
// emit an event on the screenOrientation.onChange stream.
@@ -3107,11 +2655,7 @@
expect(
await streamQueue.next,
- equals(
- const DeviceOrientationChangedEvent(
- DeviceOrientation.landscapeLeft,
- ),
- ),
+ equals(const DeviceOrientationChangedEvent(DeviceOrientation.landscapeLeft)),
);
// Change the screen orientation to portraitSecondary and
@@ -3122,11 +2666,7 @@
expect(
await streamQueue.next,
- equals(
- const DeviceOrientationChangedEvent(
- DeviceOrientation.portraitDown,
- ),
- ),
+ equals(const DeviceOrientationChangedEvent(DeviceOrientation.portraitDown)),
);
await streamQueue.cancel();
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 fa5c352..fe29edb 100644
--- a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart
+++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart
@@ -33,9 +33,7 @@
},
),
MockSpec<CameraOptions>(
- fallbackGenerators: <Symbol, Function>{
- #toMediaStreamConstraints: toMediaStreamConstraintsShim,
- },
+ fallbackGenerators: <Symbol, Function>{#toMediaStreamConstraints: toMediaStreamConstraintsShim},
),
])
export 'mocks.mocks.dart';
@@ -46,8 +44,7 @@
CameraOptions? options, {
int? cameraId = 0,
}) async {
- return createJSInteropWrapper(FakeMediaStream(<web.MediaStreamTrack>[]))
- as web.MediaStream;
+ return createJSInteropWrapper(FakeMediaStream(<web.MediaStreamTrack>[])) as web.MediaStream;
}
web.HTMLVideoElement videoElementShim() {
@@ -60,8 +57,7 @@
throw UnimplementedError();
}
-web.MediaStreamConstraints toMediaStreamConstraintsShim() =>
- throw UnimplementedError();
+web.MediaStreamConstraints toMediaStreamConstraintsShim() => throw UnimplementedError();
@JSExport()
class MockWindow {
@@ -195,8 +191,7 @@
}
/// A fake [web.ElementStream] that listens to the provided [_stream] on [listen].
-class FakeElementStream<T extends web.Event> extends Fake
- implements web.ElementStream<T> {
+class FakeElementStream<T extends web.Event> extends Fake implements web.ElementStream<T> {
FakeElementStream(this._stream);
final Stream<T> _stream;
@@ -208,12 +203,7 @@
void Function()? onDone,
bool? cancelOnError,
}) {
- return _stream.listen(
- onData,
- onError: onError,
- onDone: onDone,
- cancelOnError: cancelOnError,
- );
+ return _stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
}
@@ -247,8 +237,7 @@
..height = videoSize.height.toInt()
..context2D.fillRect(0, 0, videoSize.width, videoSize.height);
- final videoElement = web.HTMLVideoElement()
- ..srcObject = canvasElement.captureStream();
+ final videoElement = web.HTMLVideoElement()..srcObject = canvasElement.captureStream();
return videoElement;
}
@@ -258,11 +247,7 @@
@override
Stream<T> forTarget(web.EventTarget? e, {bool? useCapture = false}) {
return super.noSuchMethod(
- Invocation.method(
- #forTarget,
- <Object?>[e],
- <Symbol, Object?>{#useCapture: useCapture},
- ),
+ Invocation.method(#forTarget, <Object?>[e], <Symbol, Object?>{#useCapture: useCapture}),
returnValue: Stream<T>.empty(),
)
as Stream<T>;
@@ -271,11 +256,7 @@
@override
web.ElementStream<T> forElement(web.Element? e, {bool? useCapture = false}) {
return super.noSuchMethod(
- Invocation.method(
- #forElement,
- <Object?>[e],
- <Symbol, Object?>{#useCapture: useCapture},
- ),
+ Invocation.method(#forElement, <Object?>[e], <Symbol, Object?>{#useCapture: useCapture}),
returnValue: FakeElementStream<T>(Stream<T>.empty()),
)
as web.ElementStream<T>;
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 321507d..4ff53e1 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
@@ -7,8 +7,7 @@
import 'dart:js_interop' as _i13;
import 'dart:ui' as _i4;
-import 'package:camera_platform_interface/camera_platform_interface.dart'
- as _i7;
+import 'package:camera_platform_interface/camera_platform_interface.dart' as _i7;
import 'package:camera_web/src/camera.dart' as _i10;
import 'package:camera_web/src/camera_service.dart' as _i8;
import 'package:camera_web/src/shims/dart_js_util.dart' as _i2;
@@ -35,19 +34,16 @@
// ignore_for_file: subtype_of_sealed_class
class _FakeJsUtil_0 extends _i1.SmartFake implements _i2.JsUtil {
- _FakeJsUtil_0(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeJsUtil_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakeZoomLevelCapability_1 extends _i1.SmartFake
- implements _i3.ZoomLevelCapability {
+class _FakeZoomLevelCapability_1 extends _i1.SmartFake implements _i3.ZoomLevelCapability {
_FakeZoomLevelCapability_1(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeSize_2 extends _i1.SmartFake implements _i4.Size {
- _FakeSize_2(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeSize_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeCameraOptions_3 extends _i1.SmartFake implements _i3.CameraOptions {
@@ -55,8 +51,7 @@
: super(parent, parentInvocation);
}
-class _FakeStreamController_4<T> extends _i1.SmartFake
- implements _i5.StreamController<T> {
+class _FakeStreamController_4<T> extends _i1.SmartFake implements _i5.StreamController<T> {
_FakeStreamController_4(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -68,18 +63,15 @@
}
class _FakeXFile_6 extends _i1.SmartFake implements _i7.XFile {
- _FakeXFile_6(Object parent, Invocation parentInvocation)
- : super(parent, parentInvocation);
+ _FakeXFile_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
-class _FakeAudioConstraints_7 extends _i1.SmartFake
- implements _i3.AudioConstraints {
+class _FakeAudioConstraints_7 extends _i1.SmartFake implements _i3.AudioConstraints {
_FakeAudioConstraints_7(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
-class _FakeVideoConstraints_8 extends _i1.SmartFake
- implements _i3.VideoConstraints {
+class _FakeVideoConstraints_8 extends _i1.SmartFake implements _i3.VideoConstraints {
_FakeVideoConstraints_8(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -98,28 +90,21 @@
as _i6.Window);
@override
- set window(_i6.Window? _window) => super.noSuchMethod(
- Invocation.setter(#window, _window),
- returnValueForMissingStub: null,
- );
+ set window(_i6.Window? _window) =>
+ super.noSuchMethod(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),
- ),
+ returnValueForMissingStub: _FakeJsUtil_0(this, Invocation.getter(#jsUtil)),
)
as _i2.JsUtil);
@override
- set jsUtil(_i2.JsUtil? _jsUtil) => super.noSuchMethod(
- Invocation.setter(#jsUtil, _jsUtil),
- returnValueForMissingStub: null,
- );
+ set jsUtil(_i2.JsUtil? _jsUtil) =>
+ super.noSuchMethod(Invocation.setter(#jsUtil, _jsUtil), returnValueForMissingStub: null);
@override
_i5.Future<_i6.MediaStream> getMediaStreamForOptions(
@@ -127,15 +112,8 @@
int? cameraId = 0,
}) =>
(super.noSuchMethod(
- Invocation.method(
- #getMediaStreamForOptions,
- [options],
- {#cameraId: cameraId},
- ),
- returnValue: _i9.getMediaStreamForOptionsShim(
- options,
- cameraId: cameraId,
- ),
+ Invocation.method(#getMediaStreamForOptions, [options], {#cameraId: cameraId}),
+ returnValue: _i9.getMediaStreamForOptionsShim(options, cameraId: cameraId),
returnValueForMissingStub: _i9.getMediaStreamForOptionsShim(
options,
cameraId: cameraId,
@@ -144,9 +122,7 @@
as _i5.Future<_i6.MediaStream>);
@override
- _i3.ZoomLevelCapability getZoomLevelCapabilityForCamera(
- _i10.Camera? camera,
- ) =>
+ _i3.ZoomLevelCapability getZoomLevelCapabilityForCamera(_i10.Camera? camera) =>
(super.noSuchMethod(
Invocation.method(#getZoomLevelCapabilityForCamera, [camera]),
returnValue: _FakeZoomLevelCapability_1(
@@ -202,62 +178,42 @@
as _i4.Size);
@override
- int mapResolutionPresetToVideoBitrate(
- _i7.ResolutionPreset? resolutionPreset,
- ) =>
+ int mapResolutionPresetToVideoBitrate(_i7.ResolutionPreset? resolutionPreset) =>
(super.noSuchMethod(
- Invocation.method(#mapResolutionPresetToVideoBitrate, [
- resolutionPreset,
- ]),
+ Invocation.method(#mapResolutionPresetToVideoBitrate, [resolutionPreset]),
returnValue: 0,
returnValueForMissingStub: 0,
)
as int);
@override
- int mapResolutionPresetToAudioBitrate(
- _i7.ResolutionPreset? resolutionPreset,
- ) =>
+ int mapResolutionPresetToAudioBitrate(_i7.ResolutionPreset? resolutionPreset) =>
(super.noSuchMethod(
- Invocation.method(#mapResolutionPresetToAudioBitrate, [
- resolutionPreset,
- ]),
+ Invocation.method(#mapResolutionPresetToAudioBitrate, [resolutionPreset]),
returnValue: 0,
returnValueForMissingStub: 0,
)
as int);
@override
- String mapDeviceOrientationToOrientationType(
- _i11.DeviceOrientation? deviceOrientation,
- ) =>
+ String mapDeviceOrientationToOrientationType(_i11.DeviceOrientation? deviceOrientation) =>
(super.noSuchMethod(
- Invocation.method(#mapDeviceOrientationToOrientationType, [
- deviceOrientation,
- ]),
+ Invocation.method(#mapDeviceOrientationToOrientationType, [deviceOrientation]),
returnValue: _i12.dummyValue<String>(
this,
- Invocation.method(#mapDeviceOrientationToOrientationType, [
- deviceOrientation,
- ]),
+ Invocation.method(#mapDeviceOrientationToOrientationType, [deviceOrientation]),
),
returnValueForMissingStub: _i12.dummyValue<String>(
this,
- Invocation.method(#mapDeviceOrientationToOrientationType, [
- deviceOrientation,
- ]),
+ Invocation.method(#mapDeviceOrientationToOrientationType, [deviceOrientation]),
),
)
as String);
@override
- _i11.DeviceOrientation mapOrientationTypeToDeviceOrientation(
- String? orientationType,
- ) =>
+ _i11.DeviceOrientation mapOrientationTypeToDeviceOrientation(String? orientationType) =>
(super.noSuchMethod(
- Invocation.method(#mapOrientationTypeToDeviceOrientation, [
- orientationType,
- ]),
+ Invocation.method(#mapOrientationTypeToDeviceOrientation, [orientationType]),
returnValue: _i11.DeviceOrientation.portraitUp,
returnValueForMissingStub: _i11.DeviceOrientation.portraitUp,
)
@@ -303,14 +259,8 @@
_i3.CameraOptions get options =>
(super.noSuchMethod(
Invocation.getter(#options),
- returnValue: _FakeCameraOptions_3(
- this,
- Invocation.getter(#options),
- ),
- returnValueForMissingStub: _FakeCameraOptions_3(
- this,
- Invocation.getter(#options),
- ),
+ returnValue: _FakeCameraOptions_3(this, Invocation.getter(#options)),
+ returnValueForMissingStub: _FakeCameraOptions_3(this, Invocation.getter(#options)),
)
as _i3.CameraOptions);
@@ -354,10 +304,8 @@
);
@override
- set stream(_i6.MediaStream? _stream) => super.noSuchMethod(
- Invocation.setter(#stream, _stream),
- returnValueForMissingStub: null,
- );
+ set stream(_i6.MediaStream? _stream) =>
+ super.noSuchMethod(Invocation.setter(#stream, _stream), returnValueForMissingStub: null);
@override
_i5.StreamController<_i6.MediaStreamTrack> get onEndedController =>
@@ -367,11 +315,10 @@
this,
Invocation.getter(#onEndedController),
),
- returnValueForMissingStub:
- _FakeStreamController_4<_i6.MediaStreamTrack>(
- this,
- Invocation.getter(#onEndedController),
- ),
+ returnValueForMissingStub: _FakeStreamController_4<_i6.MediaStreamTrack>(
+ this,
+ Invocation.getter(#onEndedController),
+ ),
)
as _i5.StreamController<_i6.MediaStreamTrack>);
@@ -394,10 +341,7 @@
set mediaRecorderOnErrorProvider(
_i6.EventStreamProvider<_i6.Event>? _mediaRecorderOnErrorProvider,
) => super.noSuchMethod(
- Invocation.setter(
- #mediaRecorderOnErrorProvider,
- _mediaRecorderOnErrorProvider,
- ),
+ Invocation.setter(#mediaRecorderOnErrorProvider, _mediaRecorderOnErrorProvider),
returnValueForMissingStub: null,
);
@@ -432,10 +376,8 @@
as _i6.Window);
@override
- set window(_i6.Window? _window) => super.noSuchMethod(
- Invocation.setter(#window, _window),
- returnValueForMissingStub: null,
- );
+ set window(_i6.Window? _window) =>
+ super.noSuchMethod(Invocation.setter(#window, _window), returnValueForMissingStub: null);
@override
set mediaRecorder(_i6.MediaRecorder? _mediaRecorder) => super.noSuchMethod(
@@ -453,11 +395,10 @@
as bool Function(String));
@override
- set isVideoTypeSupported(bool Function(String)? _isVideoTypeSupported) =>
- super.noSuchMethod(
- Invocation.setter(#isVideoTypeSupported, _isVideoTypeSupported),
- returnValueForMissingStub: null,
- );
+ set isVideoTypeSupported(bool Function(String)? _isVideoTypeSupported) => super.noSuchMethod(
+ Invocation.setter(#isVideoTypeSupported, _isVideoTypeSupported),
+ returnValueForMissingStub: null,
+ );
@override
_i6.Blob Function(List<_i6.Blob>, String) get blobBuilder =>
@@ -469,11 +410,10 @@
as _i6.Blob Function(List<_i6.Blob>, String));
@override
- set blobBuilder(_i6.Blob Function(List<_i6.Blob>, String)? _blobBuilder) =>
- super.noSuchMethod(
- Invocation.setter(#blobBuilder, _blobBuilder),
- returnValueForMissingStub: null,
- );
+ set blobBuilder(_i6.Blob Function(List<_i6.Blob>, String)? _blobBuilder) => super.noSuchMethod(
+ Invocation.setter(#blobBuilder, _blobBuilder),
+ returnValueForMissingStub: null,
+ );
@override
_i5.StreamController<_i7.VideoRecordedEvent> get videoRecorderController =>
@@ -483,11 +423,10 @@
this,
Invocation.getter(#videoRecorderController),
),
- returnValueForMissingStub:
- _FakeStreamController_4<_i7.VideoRecordedEvent>(
- this,
- Invocation.getter(#videoRecorderController),
- ),
+ returnValueForMissingStub: _FakeStreamController_4<_i7.VideoRecordedEvent>(
+ this,
+ Invocation.getter(#videoRecorderController),
+ ),
)
as _i5.StreamController<_i7.VideoRecordedEvent>);
@@ -514,8 +453,7 @@
(super.noSuchMethod(
Invocation.getter(#onVideoRecordedEvent),
returnValue: _i5.Stream<_i7.VideoRecordedEvent>.empty(),
- returnValueForMissingStub:
- _i5.Stream<_i7.VideoRecordedEvent>.empty(),
+ returnValueForMissingStub: _i5.Stream<_i7.VideoRecordedEvent>.empty(),
)
as _i5.Stream<_i7.VideoRecordedEvent>);
@@ -538,16 +476,11 @@
as _i5.Future<void>);
@override
- void pause() => super.noSuchMethod(
- Invocation.method(#pause, []),
- returnValueForMissingStub: null,
- );
+ void pause() =>
+ super.noSuchMethod(Invocation.method(#pause, []), returnValueForMissingStub: null);
@override
- void stop() => super.noSuchMethod(
- Invocation.method(#stop, []),
- returnValueForMissingStub: null,
- );
+ void stop() => super.noSuchMethod(Invocation.method(#stop, []), returnValueForMissingStub: null);
@override
_i5.Future<_i7.XFile> takePicture() =>
@@ -566,22 +499,14 @@
_i4.Size getVideoSize() =>
(super.noSuchMethod(
Invocation.method(#getVideoSize, []),
- returnValue: _FakeSize_2(
- this,
- Invocation.method(#getVideoSize, []),
- ),
- returnValueForMissingStub: _FakeSize_2(
- this,
- 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,
- );
+ void setFlashMode(_i7.FlashMode? mode) =>
+ super.noSuchMethod(Invocation.method(#setFlashMode, [mode]), returnValueForMissingStub: null);
@override
double getMaxZoomLevel() =>
@@ -602,19 +527,14 @@
as double);
@override
- void setZoomLevel(double? zoom) => super.noSuchMethod(
- Invocation.method(#setZoomLevel, [zoom]),
- returnValueForMissingStub: null,
- );
+ void setZoomLevel(double? zoom) =>
+ super.noSuchMethod(Invocation.method(#setZoomLevel, [zoom]), returnValueForMissingStub: null);
@override
String getViewType() =>
(super.noSuchMethod(
Invocation.method(#getViewType, []),
- returnValue: _i12.dummyValue<String>(
- this,
- Invocation.method(#getViewType, []),
- ),
+ returnValue: _i12.dummyValue<String>(this, Invocation.method(#getViewType, [])),
returnValueForMissingStub: _i12.dummyValue<String>(
this,
Invocation.method(#getViewType, []),
@@ -681,14 +601,8 @@
_i3.AudioConstraints get audio =>
(super.noSuchMethod(
Invocation.getter(#audio),
- returnValue: _FakeAudioConstraints_7(
- this,
- Invocation.getter(#audio),
- ),
- returnValueForMissingStub: _FakeAudioConstraints_7(
- this,
- Invocation.getter(#audio),
- ),
+ returnValue: _FakeAudioConstraints_7(this, Invocation.getter(#audio)),
+ returnValueForMissingStub: _FakeAudioConstraints_7(this, Invocation.getter(#audio)),
)
as _i3.AudioConstraints);
@@ -696,14 +610,8 @@
_i3.VideoConstraints get video =>
(super.noSuchMethod(
Invocation.getter(#video),
- returnValue: _FakeVideoConstraints_8(
- this,
- Invocation.getter(#video),
- ),
- returnValueForMissingStub: _FakeVideoConstraints_8(
- this,
- Invocation.getter(#video),
- ),
+ returnValue: _FakeVideoConstraints_8(this, Invocation.getter(#video)),
+ returnValueForMissingStub: _FakeVideoConstraints_8(this, Invocation.getter(#video)),
)
as _i3.VideoConstraints);
diff --git a/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart b/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart
index dc938d4..12218d5 100644
--- a/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart
+++ b/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart
@@ -19,8 +19,7 @@
testWidgets('sets all properties', (WidgetTester tester) async {
const minimum = 100.0;
const maximum = 400.0;
- final videoTrack =
- createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack;
+ final videoTrack = createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack;
final capability = ZoomLevelCapability(
minimum: minimum,
@@ -34,22 +33,11 @@
});
testWidgets('supports value equality', (WidgetTester tester) async {
- final videoTrack =
- createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack;
+ final videoTrack = createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack;
expect(
- ZoomLevelCapability(
- minimum: 0.0,
- maximum: 100.0,
- videoTrack: videoTrack,
- ),
- equals(
- ZoomLevelCapability(
- minimum: 0.0,
- maximum: 100.0,
- videoTrack: videoTrack,
- ),
- ),
+ ZoomLevelCapability(minimum: 0.0, maximum: 100.0, videoTrack: videoTrack),
+ equals(ZoomLevelCapability(minimum: 0.0, maximum: 100.0, videoTrack: videoTrack)),
);
});
});
diff --git a/packages/camera/camera_web/lib/src/camera.dart b/packages/camera/camera_web/lib/src/camera.dart
index dd773d3..242a59d 100644
--- a/packages/camera/camera_web/lib/src/camera.dart
+++ b/packages/camera/camera_web/lib/src/camera.dart
@@ -97,8 +97,7 @@
///
/// MediaRecorder.error:
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/error_event
- Stream<web.ErrorEvent> get onVideoRecordingError =>
- videoRecordingErrorController.stream;
+ Stream<web.ErrorEvent> get onVideoRecordingError => videoRecordingErrorController.stream;
/// The stream provider for [MediaRecorder] error events.
@visibleForTesting
@@ -147,12 +146,10 @@
/// A builder to merge a list of blobs into a single blob.
@visibleForTesting
web.Blob Function(List<web.Blob> blobs, String type) blobBuilder =
- (List<web.Blob> blobs, String type) =>
- web.Blob(blobs.toJS, web.BlobPropertyBag(type: type));
+ (List<web.Blob> blobs, String type) => web.Blob(blobs.toJS, web.BlobPropertyBag(type: type));
/// The stream that emits a [VideoRecordedEvent] when a video recording is created.
- Stream<VideoRecordedEvent> get onVideoRecordedEvent =>
- videoRecorderController.stream;
+ Stream<VideoRecordedEvent> get onVideoRecordedEvent => videoRecorderController.stream;
/// The stream controller for the [onVideoRecordedEvent] stream.
@visibleForTesting
@@ -163,10 +160,7 @@
/// Registers the camera view with [textureId] under [_getViewType] type.
/// Emits the camera default video track on the [onEnded] stream when it ends.
Future<void> initialize() async {
- stream = await _cameraService.getMediaStreamForOptions(
- options,
- cameraId: textureId,
- );
+ stream = await _cameraService.getMediaStreamForOptions(options, cameraId: textureId);
videoElement = web.HTMLVideoElement();
@@ -176,10 +170,7 @@
..style.setProperty('width', '100%')
..append(videoElement);
- ui_web.platformViewRegistry.registerViewFactory(
- _getViewType(textureId),
- (_) => divElement,
- );
+ ui_web.platformViewRegistry.registerViewFactory(_getViewType(textureId), (_) => divElement);
videoElement
..autoplay = false
@@ -189,17 +180,15 @@
_applyDefaultVideoStyles(videoElement);
- final List<web.MediaStreamTrack> videoTracks = stream!
- .getVideoTracks()
- .toDart;
+ final List<web.MediaStreamTrack> videoTracks = stream!.getVideoTracks().toDart;
if (videoTracks.isNotEmpty) {
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
- _onEndedSubscription = EventStreamProviders.endedEvent
- .forTarget(defaultVideoTrack)
- .listen((web.Event _) {
- onEndedController.add(defaultVideoTrack);
- });
+ _onEndedSubscription = EventStreamProviders.endedEvent.forTarget(defaultVideoTrack).listen((
+ web.Event _,
+ ) {
+ onEndedController.add(defaultVideoTrack);
+ });
}
}
@@ -208,10 +197,7 @@
/// Initializes the camera source if the camera was previously stopped.
Future<void> play() async {
if (videoElement.srcObject == null) {
- stream = await _cameraService.getMediaStreamForOptions(
- options,
- cameraId: textureId,
- );
+ stream = await _cameraService.getMediaStreamForOptions(options, cameraId: textureId);
videoElement.srcObject = stream;
}
await videoElement.play().toDart;
@@ -224,9 +210,7 @@
/// Stops the camera stream and resets the camera source.
void stop() {
- final List<web.MediaStreamTrack> videoTracks = stream!
- .getVideoTracks()
- .toDart;
+ final List<web.MediaStreamTrack> videoTracks = stream!.getVideoTracks().toDart;
if (videoTracks.isNotEmpty) {
onEndedController.add(videoTracks.first);
}
@@ -246,8 +230,7 @@
/// Enables the camera flash (torch mode) for a period of taking a picture
/// if the flash mode is either [FlashMode.auto] or [FlashMode.always].
Future<XFile> takePicture() async {
- final bool shouldEnableTorchMode =
- flashMode == FlashMode.auto || flashMode == FlashMode.always;
+ final bool shouldEnableTorchMode = flashMode == FlashMode.auto || flashMode == FlashMode.always;
if (shouldEnableTorchMode) {
_setTorchMode(enabled: true);
@@ -267,13 +250,7 @@
..scale(-1, 1);
}
- canvas.context2D.drawImage(
- videoElement,
- 0,
- 0,
- videoWidth.toDouble(),
- videoHeight.toDouble(),
- );
+ canvas.context2D.drawImage(videoElement, 0, 0, videoWidth.toDouble(), videoHeight.toDouble());
final blobCompleter = Completer<web.Blob>();
canvas.toBlob(
@@ -306,8 +283,7 @@
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
- final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack
- .getSettings();
+ final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack.getSettings();
final int width = defaultVideoTrackSettings.width;
final int height = defaultVideoTrackSettings.height;
@@ -358,13 +334,7 @@
if (videoTracks.isNotEmpty) {
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final bool canEnableTorchMode =
- defaultVideoTrack
- .getCapabilities()
- .torchNullable
- ?.toDart
- .first
- .toDart ??
- false;
+ defaultVideoTrack.getCapabilities().torchNullable?.toDart.first.toDart ?? false;
if (canEnableTorchMode) {
defaultVideoTrack.applyWebTweakConstraints(
@@ -390,26 +360,24 @@
///
/// Throws a [CameraWebException] if the zoom level is not supported
/// or the camera has not been initialized or started.
- double getMaxZoomLevel() =>
- _cameraService.getZoomLevelCapabilityForCamera(this).maximum;
+ double getMaxZoomLevel() => _cameraService.getZoomLevelCapabilityForCamera(this).maximum;
/// Returns the camera minimum zoom level.
///
/// Throws a [CameraWebException] if the zoom level is not supported
/// or the camera has not been initialized or started.
- double getMinZoomLevel() =>
- _cameraService.getZoomLevelCapabilityForCamera(this).minimum;
+ double getMinZoomLevel() => _cameraService.getZoomLevelCapabilityForCamera(this).minimum;
/// Sets the camera zoom level to [zoom].
///
/// 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) {
+ if (zoom < zoomLevelCapability.minimum || zoom > zoomLevelCapability.maximum) {
throw CameraWebException(
textureId,
CameraErrorCode.zoomLevelInvalid,
@@ -436,8 +404,7 @@
}
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
- final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack
- .getSettings();
+ final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack.getSettings();
final String? facingMode = defaultVideoTrackSettings.facingModeNullable;
@@ -464,28 +431,17 @@
options.videoBitsPerSecond = recorderOptions.videoBitrate!;
}
- mediaRecorder ??= web.MediaRecorder(
- videoElement.srcObject! as web.MediaStream,
- options,
- );
+ mediaRecorder ??= web.MediaRecorder(videoElement.srcObject! as web.MediaStream, options);
_videoAvailableCompleter = Completer<XFile>();
- _videoDataAvailableListener = (web.BlobEvent event) =>
- _onVideoDataAvailable(event);
+ _videoDataAvailableListener = (web.BlobEvent event) => _onVideoDataAvailable(event);
- _videoRecordingStoppedListener = (web.Event event) =>
- _onVideoRecordingStopped(event);
+ _videoRecordingStoppedListener = (web.Event event) => _onVideoRecordingStopped(event);
- mediaRecorder!.addEventListener(
- 'dataavailable',
- _videoDataAvailableListener?.toJS,
- );
+ mediaRecorder!.addEventListener('dataavailable', _videoDataAvailableListener?.toJS);
- mediaRecorder!.addEventListener(
- 'stop',
- _videoRecordingStoppedListener?.toJS,
- );
+ mediaRecorder!.addEventListener('stop', _videoRecordingStoppedListener?.toJS);
_onVideoRecordingErrorSubscription = mediaRecorderOnErrorProvider
.forTarget(mediaRecorder)
@@ -522,15 +478,9 @@
}
// Clean up the media recorder with its event listeners and video data.
- mediaRecorder!.removeEventListener(
- 'dataavailable',
- _videoDataAvailableListener?.toJS,
- );
+ mediaRecorder!.removeEventListener('dataavailable', _videoDataAvailableListener?.toJS);
- mediaRecorder!.removeEventListener(
- 'stop',
- _videoDataAvailableListener?.toJS,
- );
+ mediaRecorder!.removeEventListener('stop', _videoDataAvailableListener?.toJS);
await _onVideoRecordingErrorSubscription?.cancel();
@@ -603,11 +553,7 @@
/// Throws a [CameraWebException] if the browser does not support
/// any of the available video mime types.
String get _videoMimeType {
- const types = <String>[
- 'video/webm;codecs="vp9,opus"',
- 'video/mp4',
- 'video/webm',
- ];
+ const types = <String>['video/webm;codecs="vp9,opus"', 'video/mp4', 'video/webm'];
return types.firstWhere(
(String type) => isVideoTypeSupported(type),
@@ -619,8 +565,7 @@
);
}
- CameraWebException
- get _videoRecordingNotStartedException => CameraWebException(
+ 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.',
diff --git a/packages/camera/camera_web/lib/src/camera_service.dart b/packages/camera/camera_web/lib/src/camera_service.dart
index 9bf588a..d620b4a 100644
--- a/packages/camera/camera_web/lib/src/camera_service.dart
+++ b/packages/camera/camera_web/lib/src/camera_service.dart
@@ -34,9 +34,7 @@
final web.MediaDevices mediaDevices = window.navigator.mediaDevices;
try {
- return await mediaDevices
- .getUserMedia(options.toMediaStreamConstraints())
- .toDart;
+ return await mediaDevices.getUserMedia(options.toMediaStreamConstraints()).toDart;
} on web.DOMException catch (e) {
switch (e.name) {
case 'NotFoundError':
@@ -195,8 +193,7 @@
return null;
}
- final web.MediaTrackCapabilities videoTrackCapabilities = videoTrack
- .getCapabilities();
+ final web.MediaTrackCapabilities videoTrackCapabilities = videoTrack.getCapabilities();
// A list of facing mode capabilities as
// the camera may support multiple facing modes.
@@ -329,9 +326,7 @@
}
/// Maps the given [deviceOrientation] to [OrientationType].
- String mapDeviceOrientationToOrientationType(
- DeviceOrientation deviceOrientation,
- ) {
+ String mapDeviceOrientationToOrientationType(DeviceOrientation deviceOrientation) {
switch (deviceOrientation) {
case DeviceOrientation.portraitUp:
return OrientationType.portraitPrimary;
@@ -345,9 +340,7 @@
}
/// Maps the given [orientationType] to [DeviceOrientation].
- DeviceOrientation mapOrientationTypeToDeviceOrientation(
- String orientationType,
- ) {
+ DeviceOrientation mapOrientationTypeToDeviceOrientation(String orientationType) {
switch (orientationType) {
case OrientationType.portraitPrimary:
return DeviceOrientation.portraitUp;
diff --git a/packages/camera/camera_web/lib/src/camera_web.dart b/packages/camera/camera_web/lib/src/camera_web.dart
index 9003368..ecb4da1 100644
--- a/packages/camera/camera_web/lib/src/camera_web.dart
+++ b/packages/camera/camera_web/lib/src/camera_web.dart
@@ -29,8 +29,7 @@
class CameraPlugin extends CameraPlatform {
/// Creates a new instance of [CameraPlugin]
/// with the given [cameraService].
- CameraPlugin({required CameraService cameraService})
- : _cameraService = cameraService;
+ CameraPlugin({required CameraService cameraService}) : _cameraService = cameraService;
/// Registers this class as the default instance of [CameraPlatform].
static void registerWith(Registrar registrar) {
@@ -74,17 +73,15 @@
final Map<int, StreamSubscription<web.Event>> _cameraVideoAbortSubscriptions =
<int, StreamSubscription<web.Event>>{};
- final Map<int, StreamSubscription<web.MediaStreamTrack>>
- _cameraEndedSubscriptions = <int, StreamSubscription<web.MediaStreamTrack>>{};
+ final Map<int, StreamSubscription<web.MediaStreamTrack>> _cameraEndedSubscriptions =
+ <int, StreamSubscription<web.MediaStreamTrack>>{};
- final Map<int, StreamSubscription<web.ErrorEvent>>
- _cameraVideoRecordingErrorSubscriptions =
+ final Map<int, StreamSubscription<web.ErrorEvent>> _cameraVideoRecordingErrorSubscriptions =
<int, StreamSubscription<web.ErrorEvent>>{};
/// Returns a stream of camera events for the given [cameraId].
- Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
- .stream
- .where((CameraEvent event) => event.cameraId == cameraId);
+ Stream<CameraEvent> _cameraEvents(int cameraId) =>
+ cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId);
/// The stream provider for [web.ScreenOrientation] change events.
@visibleForTesting
@@ -102,8 +99,9 @@
final cameras = <CameraDescription>[];
// 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(
@@ -116,10 +114,7 @@
// Filter video input devices.
final Iterable<web.MediaDeviceInfo> videoInputDevices = devices
- .where(
- (web.MediaDeviceInfo device) =>
- device.kind == MediaDeviceKind.videoInput,
- )
+ .where((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);
@@ -134,15 +129,11 @@
// Get all video tracks in the video stream
// to later extract the lens direction from the first track.
- final List<web.MediaStreamTrack> videoTracks = videoStream
- .getVideoTracks()
- .toDart;
+ final List<web.MediaStreamTrack> videoTracks = videoStream.getVideoTracks().toDart;
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
@@ -242,9 +233,7 @@
options: CameraOptions(
audio: AudioConstraints(enabled: mediaSettings?.enableAudio ?? true),
video: VideoConstraints(
- facingMode: cameraType != null
- ? FacingModeConstraint(cameraType)
- : null,
+ facingMode: cameraType != null ? FacingModeConstraint(cameraType) : null,
width: VideoSizeConstraint(ideal: videoSize.width.toInt()),
height: VideoSizeConstraint(ideal: videoSize.height.toInt()),
deviceId: cameraMetadata.deviceId,
@@ -284,18 +273,11 @@
// 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;
+ final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error);
+ final String errorMessage = error.message != '' ? error.message : _kDefaultErrorMessage;
cameraEventStreamController.add(
- CameraErrorEvent(
- cameraId,
- 'Error code: $errorCode, error message: $errorMessage',
- ),
+ CameraErrorEvent(cameraId, 'Error code: $errorCode, error message: $errorMessage'),
);
});
@@ -316,9 +298,7 @@
// 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 _,
- ) {
+ _cameraEndedSubscriptions[cameraId] = camera.onEnded.listen((web.MediaStreamTrack _) {
cameraEventStreamController.add(CameraClosingEvent(cameraId));
});
@@ -394,17 +374,15 @@
}
@override
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) async {
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async {
try {
final web.ScreenOrientation screenOrientation = window.screen.orientation;
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
@@ -478,17 +456,15 @@
// 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,
- ) {
- cameraEventStreamController.add(
- CameraErrorEvent(
- options.cameraId,
- 'Error code: ${errorEvent.type}, error message: ${errorEvent.message}.',
- ),
- );
- });
+ _cameraVideoRecordingErrorSubscriptions[options.cameraId] = camera.onVideoRecordingError
+ .listen((web.ErrorEvent errorEvent) {
+ cameraEventStreamController.add(
+ CameraErrorEvent(
+ options.cameraId,
+ 'Error code: ${errorEvent.type}, error message: ${errorEvent.message}.',
+ ),
+ );
+ });
return camera.startVideoRecording();
} on web.DOMException catch (e) {
@@ -502,9 +478,7 @@
@override
Future<XFile> stopVideoRecording(int cameraId) async {
try {
- final XFile videoRecording = await getCamera(
- cameraId,
- ).stopVideoRecording();
+ final XFile videoRecording = await getCamera(cameraId).stopVideoRecording();
await _cameraVideoRecordingErrorSubscriptions[cameraId]?.cancel();
return videoRecording;
} on web.DOMException catch (e) {
@@ -677,9 +651,7 @@
/// Returns a media video stream for the device with the given [deviceId].
Future<web.MediaStream> _getVideoStreamForDevice(String deviceId) {
// Create camera options with the desired device id.
- final cameraOptions = CameraOptions(
- video: VideoConstraints(deviceId: deviceId),
- );
+ final cameraOptions = CameraOptions(video: VideoConstraints(deviceId: deviceId));
return _cameraService.getMediaStreamForOptions(cameraOptions);
}
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 f5d54d7..ddfe93b 100644
--- a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart
+++ b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart
@@ -15,8 +15,7 @@
}
/// Adds missing fields to [MediaTrackSupportedConstraints].
-extension NonStandardFieldsOnMediaTrackSupportedConstraints
- on MediaTrackSupportedConstraints {
+extension NonStandardFieldsOnMediaTrackSupportedConstraints on MediaTrackSupportedConstraints {
@JS('zoom')
external bool? get zoomNullable;
@@ -58,17 +57,12 @@
/// Adds an applyConstraints method that accepts the WebTweakMediaTrackConstraints.
extension WebTweakMethodVersions on MediaStreamTrack {
@JS('applyConstraints')
- external JSPromise<JSAny?> applyWebTweakConstraints([
- WebTweakMediaTrackConstraints constraints,
- ]);
+ external JSPromise<JSAny?> applyWebTweakConstraints([WebTweakMediaTrackConstraints constraints]);
}
/// Allows creating the MediaTrackConstraints that are needed.
/// Brought over from package:web 1.0.0
extension type WebTweakMediaTrackConstraints._(JSObject _) implements JSObject {
@JS('MediaTrackConstraints')
- external factory WebTweakMediaTrackConstraints({
- JSAny zoom,
- ConstrainBoolean torch,
- });
+ external factory WebTweakMediaTrackConstraints({JSAny zoom, ConstrainBoolean torch});
}
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 81b3ab3..c10d58e 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,28 +15,20 @@
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.
@@ -49,9 +41,7 @@
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._(
@@ -59,24 +49,16 @@
);
/// 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._(
diff --git a/packages/camera/camera_web/lib/src/types/camera_metadata.dart b/packages/camera/camera_web/lib/src/types/camera_metadata.dart
index 5c9b3c5..26a95ca 100644
--- a/packages/camera/camera_web/lib/src/types/camera_metadata.dart
+++ b/packages/camera/camera_web/lib/src/types/camera_metadata.dart
@@ -30,9 +30,7 @@
return true;
}
- return other is CameraMetadata &&
- other.deviceId == deviceId &&
- other.facingMode == facingMode;
+ return other is CameraMetadata && other.deviceId == deviceId && other.facingMode == facingMode;
}
@override
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 fe3953f..f030af3 100644
--- a/packages/camera/camera_web/lib/src/types/camera_options.dart
+++ b/packages/camera/camera_web/lib/src/types/camera_options.dart
@@ -43,9 +43,7 @@
return true;
}
- return other is CameraOptions &&
- other.audio == audio &&
- other.video == video;
+ return other is CameraOptions && other.audio == audio && other.video == video;
}
@override
@@ -86,12 +84,7 @@
class VideoConstraints {
/// Creates a new instance of [VideoConstraints]
/// with the given constraints.
- const VideoConstraints({
- this.facingMode,
- this.width,
- this.height,
- this.deviceId,
- });
+ const VideoConstraints({this.facingMode, this.width, this.height, this.deviceId});
/// The facing mode of the video track.
final FacingModeConstraint? facingMode;
@@ -164,8 +157,7 @@
class FacingModeConstraint {
/// Creates a new instance of [FacingModeConstraint]
/// with [ideal] constraint set to [type].
- factory FacingModeConstraint(CameraType type) =>
- FacingModeConstraint._(ideal: type);
+ factory FacingModeConstraint(CameraType type) => FacingModeConstraint._(ideal: type);
/// Creates a new instance of [FacingModeConstraint]
/// with the given [ideal] and [exact] constraints.
@@ -173,8 +165,7 @@
/// Creates a new instance of [FacingModeConstraint]
/// with [exact] constraint set to [type].
- factory FacingModeConstraint.exact(CameraType type) =>
- FacingModeConstraint._(exact: type);
+ factory FacingModeConstraint.exact(CameraType type) => FacingModeConstraint._(exact: type);
/// The ideal facing mode constraint.
///
@@ -203,9 +194,7 @@
return true;
}
- return other is FacingModeConstraint &&
- other.ideal == ideal &&
- other.exact == exact;
+ return other is FacingModeConstraint && other.ideal == ideal && other.exact == exact;
}
@override
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 f26b7c6..bc835cb 100644
--- a/packages/camera/camera_windows/example/integration_test/camera_test.dart
+++ b/packages/camera/camera_windows/example/integration_test/camera_test.dart
@@ -19,100 +19,63 @@
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<CameraException>()),
- );
+ expect(() async => camera.initializeCamera(1234), throwsA(isA<CameraException>()));
});
});
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<PlatformException>()),
- );
+ expect(() async => camera.takePicture(1234), throwsA(isA<PlatformException>()));
});
});
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<PlatformException>()),
- );
+ expect(() async => camera.startVideoRecording(1234), throwsA(isA<PlatformException>()));
});
});
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<PlatformException>()),
- );
+ expect(() async => camera.stopVideoRecording(1234), throwsA(isA<PlatformException>()));
});
});
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<PlatformException>()),
- );
+ expect(() async => camera.pausePreview(1234), throwsA(isA<PlatformException>()));
});
});
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<PlatformException>()),
- );
+ expect(() async => camera.resumePreview(1234), throwsA(isA<PlatformException>()));
});
});
group('onDeviceOrientationChanged', () {
- testWidgets('emits the initial DeviceOrientationChangedEvent', (
- WidgetTester _,
- ) async {
- final Stream<DeviceOrientationChangedEvent> eventStream = CameraPlatform
- .instance
+ testWidgets('emits the initial DeviceOrientationChangedEvent', (WidgetTester _) async {
+ final Stream<DeviceOrientationChangedEvent> eventStream = CameraPlatform.instance
.onDeviceOrientationChanged();
- final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(
- eventStream,
- );
+ final streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream);
expect(
await streamQueue.next,
- equals(
- const DeviceOrientationChangedEvent(DeviceOrientation.landscapeRight),
- ),
+ equals(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 215ecb9..00dc930 100644
--- a/packages/camera/camera_windows/example/lib/main.dart
+++ b/packages/camera/camera_windows/example/lib/main.dart
@@ -97,10 +97,7 @@
final int cameraIndex = _cameraIndex % _cameras.length;
final CameraDescription camera = _cameras[cameraIndex];
- cameraId = await CameraPlatform.instance.createCameraWithSettings(
- camera,
- _mediaSettings,
- );
+ cameraId = await CameraPlatform.instance.createCameraWithSettings(camera, _mediaSettings);
unawaited(_errorStreamSubscription?.cancel());
_errorStreamSubscription = CameraPlatform.instance
@@ -146,8 +143,7 @@
_cameraIndex = 0;
_previewSize = null;
_recording = false;
- _cameraInfo =
- 'Failed to initialize camera: ${e.code}: ${e.description}';
+ _cameraInfo = 'Failed to initialize camera: ${e.code}: ${e.description}';
});
}
}
@@ -171,8 +167,7 @@
} on CameraException catch (e) {
if (mounted) {
setState(() {
- _cameraInfo =
- 'Failed to dispose camera: ${e.code}: ${e.description}';
+ _cameraInfo = 'Failed to dispose camera: ${e.code}: ${e.description}';
});
}
}
@@ -193,9 +188,7 @@
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}');
}
@@ -302,15 +295,11 @@
@override
Widget build(BuildContext context) {
- final List<DropdownMenuItem<ResolutionPreset>> resolutionItems =
- ResolutionPreset.values.map<DropdownMenuItem<ResolutionPreset>>((
- ResolutionPreset value,
- ) {
- return DropdownMenuItem<ResolutionPreset>(
- value: value,
- child: Text(value.toString()),
- );
- }).toList();
+ final List<DropdownMenuItem<ResolutionPreset>> resolutionItems = ResolutionPreset.values
+ .map<DropdownMenuItem<ResolutionPreset>>((ResolutionPreset value) {
+ return DropdownMenuItem<ResolutionPreset>(value: value, child: Text(value.toString()));
+ })
+ .toList();
return MaterialApp(
scaffoldMessengerKey: _scaffoldMessengerKey,
@@ -348,12 +337,8 @@
),
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(
@@ -363,9 +348,7 @@
const SizedBox(width: 5),
ElevatedButton(
onPressed: _initialized ? _togglePreview : null,
- child: Text(
- _previewPaused ? 'Resume preview' : 'Pause preview',
- ),
+ child: Text(_previewPaused ? 'Resume preview' : 'Pause preview'),
),
const SizedBox(width: 5),
ElevatedButton(
@@ -374,10 +357,7 @@
),
if (_cameras.length > 1) ...<Widget>[
const SizedBox(width: 5),
- ElevatedButton(
- onPressed: _switchCamera,
- child: const Text('Switch camera'),
- ),
+ ElevatedButton(onPressed: _switchCamera, child: const Text('Switch camera')),
],
],
),
diff --git a/packages/camera/camera_windows/lib/camera_windows.dart b/packages/camera/camera_windows/lib/camera_windows.dart
index 8000502..53b927b 100644
--- a/packages/camera/camera_windows/lib/camera_windows.dart
+++ b/packages/camera/camera_windows/lib/camera_windows.dart
@@ -15,8 +15,7 @@
/// An implementation of [CameraPlatform] for Windows.
class CameraWindows extends CameraPlatform {
/// Creates a new Windows [CameraPlatform] implementation instance.
- CameraWindows({@visibleForTesting CameraApi? api})
- : _hostApi = api ?? CameraApi();
+ CameraWindows({@visibleForTesting CameraApi? api}) : _hostApi = api ?? CameraApi();
/// Registers the Windows implementation of CameraPlatform.
static void registerWith() {
@@ -29,8 +28,7 @@
/// The per-camera handlers for messages that should be rebroadcast to
/// clients as [CameraEvent]s.
@visibleForTesting
- final Map<int, HostCameraMessageHandler> hostCameraHandlers =
- <int, HostCameraMessageHandler>{};
+ final Map<int, HostCameraMessageHandler> hostCameraHandlers = <int, HostCameraMessageHandler>{};
/// The controller that broadcasts events coming from handleCameraMethodCall
///
@@ -43,9 +41,8 @@
StreamController<CameraEvent>.broadcast();
/// Returns a stream of camera events for the given [cameraId].
- Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
- .stream
- .where((CameraEvent event) => event.cameraId == cameraId);
+ Stream<CameraEvent> _cameraEvents(int cameraId) =>
+ cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId);
@override
Future<List<CameraDescription>> availableCameras() async {
@@ -83,10 +80,7 @@
) async {
try {
// If resolutionPreset is not specified, plugin selects the highest resolution possible.
- return await _hostApi.create(
- cameraDescription.name,
- _pigeonMediaSettings(mediaSettings),
- );
+ return await _hostApi.create(cameraDescription.name, _pigeonMediaSettings(mediaSettings));
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
@@ -169,10 +163,7 @@
}
@override
- Future<void> lockCaptureOrientation(
- int cameraId,
- DeviceOrientation orientation,
- ) async {
+ Future<void> lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async {
// TODO(jokerttu): Implement lock capture orientation feature, https://github.com/flutter/flutter/issues/97540.
throw UnimplementedError('lockCaptureOrientation() is not implemented.');
}
@@ -196,10 +187,7 @@
}
@override
- Future<void> startVideoRecording(
- int cameraId, {
- Duration? maxVideoDuration,
- }) async {
+ Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async {
// Ignore maxVideoDuration, as it is unimplemented and deprecated.
return startVideoCapturing(VideoCaptureOptions(cameraId));
}
@@ -207,9 +195,7 @@
@override
Future<void> startVideoCapturing(VideoCaptureOptions options) async {
if (options.streamCallback != null || options.streamOptions != null) {
- throw UnimplementedError(
- 'Streaming is not currently supported on Windows',
- );
+ throw UnimplementedError('Streaming is not currently supported on Windows');
}
// Currently none of `options` is supported on Windows, so it's not passed.
@@ -225,16 +211,12 @@
@override
Future<void> pauseVideoRecording(int cameraId) async {
- throw UnsupportedError(
- 'pauseVideoRecording() is not supported due to Win32 API limitations.',
- );
+ throw UnsupportedError('pauseVideoRecording() is not supported due to Win32 API limitations.');
}
@override
Future<void> resumeVideoRecording(int cameraId) async {
- throw UnsupportedError(
- 'resumeVideoRecording() is not supported due to Win32 API limitations.',
- );
+ throw UnsupportedError('resumeVideoRecording() is not supported due to Win32 API limitations.');
}
@override
@@ -254,9 +236,7 @@
assert(point == null || point.x >= 0 && point.x <= 1);
assert(point == null || point.y >= 0 && point.y <= 1);
- throw UnsupportedError(
- 'setExposurePoint() is not supported due to Win32 API limitations.',
- );
+ throw UnsupportedError('setExposurePoint() is not supported due to Win32 API limitations.');
}
@override
@@ -297,9 +277,7 @@
assert(point == null || point.x >= 0 && point.x <= 1);
assert(point == null || point.y >= 0 && point.y <= 1);
- throw UnsupportedError(
- 'setFocusPoint() is not supported due to Win32 API limitations.',
- );
+ throw UnsupportedError('setFocusPoint() is not supported due to Win32 API limitations.');
}
@override
@@ -349,9 +327,7 @@
}
/// Returns a [ResolutionPreset]'s Pigeon representation.
- PlatformResolutionPreset _pigeonResolutionPreset(
- ResolutionPreset? resolutionPreset,
- ) {
+ PlatformResolutionPreset _pigeonResolutionPreset(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 79407a5..8081a18 100644
--- a/packages/camera/camera_windows/lib/src/messages.g.dart
+++ b/packages/camera/camera_windows/lib/src/messages.g.dart
@@ -18,11 +18,7 @@
);
}
-List<Object?> wrapResponse({
- Object? result,
- PlatformException? error,
- bool empty = false,
-}) {
+List<Object?> wrapResponse({Object? result, PlatformException? error, bool empty = false}) {
if (empty) {
return <Object?>[];
}
@@ -35,9 +31,7 @@
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 &&
@@ -74,13 +68,7 @@
bool enableAudio;
List<Object?> _toList() {
- return <Object?>[
- resolutionPreset,
- framesPerSecond,
- videoBitrate,
- audioBitrate,
- enableAudio,
- ];
+ return <Object?>[resolutionPreset, framesPerSecond, videoBitrate, audioBitrate, enableAudio];
}
Object encode() {
@@ -133,10 +121,7 @@
static PlatformSize decode(Object result) {
result as List<Object?>;
- return PlatformSize(
- width: result[0]! as double,
- height: result[1]! as double,
- );
+ return PlatformSize(width: result[0]! as double, height: result[1]! as double);
}
@override
@@ -197,13 +182,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -214,15 +197,13 @@
Future<List<String>> getAvailableCameras() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
+ );
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -245,17 +226,16 @@
Future<int> create(String cameraName, PlatformMediaSettings settings) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.create$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraName, settings],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ cameraName,
+ settings,
+ ]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -278,17 +258,13 @@
Future<PlatformSize> initialize(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.initialize$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -311,17 +287,13 @@
Future<void> dispose(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.dispose$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -340,17 +312,13 @@
Future<String> takePicture(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.takePicture$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -373,17 +341,13 @@
Future<void> startVideoRecording(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -402,17 +366,13 @@
Future<String> stopVideoRecording(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -435,17 +395,13 @@
Future<void> pausePreview(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.pausePreview$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -463,17 +419,13 @@
Future<void> resumePreview(int cameraId) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.camera_windows.CameraApi.resumePreview$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[cameraId],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[cameraId]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -502,12 +454,9 @@
BinaryMessenger? binaryMessenger,
String messageChannelSuffix = '',
}) {
- messageChannelSuffix = messageChannelSuffix.isNotEmpty
- ? '.$messageChannelSuffix'
- : '';
+ messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : '';
{
- final BasicMessageChannel<Object?>
- pigeonVar_channel = BasicMessageChannel<Object?>(
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_windows.CameraEventApi.cameraClosing$messageChannelSuffix',
pigeonChannelCodec,
binaryMessenger: binaryMessenger,
@@ -530,8 +479,7 @@
}
}
{
- final BasicMessageChannel<Object?>
- pigeonVar_channel = BasicMessageChannel<Object?>(
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.camera_windows.CameraEventApi.error$messageChannelSuffix',
pigeonChannelCodec,
binaryMessenger: binaryMessenger,
diff --git a/packages/camera/camera_windows/test/camera_windows_test.dart b/packages/camera/camera_windows/test/camera_windows_test.dart
index dcd35d3..e4351de 100644
--- a/packages/camera/camera_windows/test/camera_windows_test.dart
+++ b/packages/camera/camera_windows/test/camera_windows_test.dart
@@ -48,9 +48,7 @@
);
// Assert
- final VerificationResult verification = verify(
- mockApi.create(captureAny, captureAny),
- );
+ final VerificationResult verification = verify(mockApi.create(captureAny, captureAny));
expect(verification.captured[0], cameraName);
final settings = verification.captured[1] as PlatformMediaSettings?;
expect(settings, isNotNull);
@@ -58,78 +56,58 @@
expect(cameraId, 1);
});
- test(
- 'Should throw CameraException when create throws a PlatformException',
- () {
- // Arrange
- const exceptionCode = 'TESTING_ERROR_CODE';
- const exceptionMessage = 'Mock error message used during testing.';
- final mockApi = MockCameraApi();
- when(mockApi.create(any, any)).thenAnswer((_) async {
- throw PlatformException(
- code: exceptionCode,
- message: exceptionMessage,
- );
- });
- final camera = CameraWindows(api: mockApi);
+ test('Should throw CameraException when create throws a PlatformException', () {
+ // Arrange
+ const exceptionCode = 'TESTING_ERROR_CODE';
+ const exceptionMessage = 'Mock error message used during testing.';
+ final mockApi = MockCameraApi();
+ when(mockApi.create(any, any)).thenAnswer((_) async {
+ throw PlatformException(code: exceptionCode, message: exceptionMessage);
+ });
+ final camera = CameraWindows(api: mockApi);
- // Act
- expect(
- () => camera.createCamera(
- const CameraDescription(
- name: 'Test',
- lensDirection: CameraLensDirection.back,
- sensorOrientation: 0,
- ),
- ResolutionPreset.high,
+ // Act
+ expect(
+ () => camera.createCamera(
+ const CameraDescription(
+ name: 'Test',
+ lensDirection: CameraLensDirection.back,
+ sensorOrientation: 0,
),
- throwsA(
- isA<CameraException>()
- .having((CameraException e) => e.code, 'code', exceptionCode)
- .having(
- (CameraException e) => e.description,
- 'description',
- exceptionMessage,
- ),
- ),
- );
- },
- );
+ ResolutionPreset.high,
+ ),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', exceptionCode)
+ .having((CameraException e) => e.description, 'description', exceptionMessage),
+ ),
+ );
+ });
- test(
- 'Should throw CameraException when initialize throws a PlatformException',
- () {
- // Arrange
- const exceptionCode = 'TESTING_ERROR_CODE';
- const exceptionMessage = 'Mock error message used during testing.';
- final mockApi = MockCameraApi();
- when(mockApi.initialize(any)).thenAnswer((_) async {
- throw PlatformException(
- code: exceptionCode,
- message: exceptionMessage,
- );
- });
- final plugin = CameraWindows(api: mockApi);
+ test('Should throw CameraException when initialize throws a PlatformException', () {
+ // Arrange
+ const exceptionCode = 'TESTING_ERROR_CODE';
+ const exceptionMessage = 'Mock error message used during testing.';
+ final mockApi = MockCameraApi();
+ when(mockApi.initialize(any)).thenAnswer((_) async {
+ throw PlatformException(code: exceptionCode, message: exceptionMessage);
+ });
+ final plugin = CameraWindows(api: mockApi);
- // Act
- expect(
- () => plugin.initializeCamera(0),
- throwsA(
- isA<CameraException>()
- .having(
- (CameraException e) => e.code,
- 'code',
- 'TESTING_ERROR_CODE',
- )
- .having(
- (CameraException e) => e.description,
- 'description',
- 'Mock error message used during testing.',
- ),
- ),
- );
- },
- );
+ // Act
+ expect(
+ () => plugin.initializeCamera(0),
+ throwsA(
+ isA<CameraException>()
+ .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
+ .having(
+ (CameraException e) => e.description,
+ 'description',
+ 'Mock error message used during testing.',
+ ),
+ ),
+ );
+ });
test('Should send initialization data', () async {
// Arrange
@@ -157,9 +135,7 @@
await plugin.initializeCamera(cameraId);
// Assert
- final VerificationResult verification = verify(
- mockApi.initialize(captureAny),
- );
+ final VerificationResult verification = verify(mockApi.initialize(captureAny));
expect(verification.captured[0], cameraId);
});
@@ -190,9 +166,7 @@
await plugin.dispose(cameraId);
// Assert
- final VerificationResult verification = verify(
- mockApi.dispose(captureAny),
- );
+ final VerificationResult verification = verify(mockApi.dispose(captureAny));
expect(verification.captured[0], cameraId);
});
});
@@ -226,9 +200,7 @@
test('Should receive camera closing events', () async {
// Act
- final Stream<CameraClosingEvent> eventStream = plugin.onCameraClosing(
- cameraId,
- );
+ final Stream<CameraClosingEvent> eventStream = plugin.onCameraClosing(cameraId);
final streamQueue = StreamQueue<CameraClosingEvent>(eventStream);
// Emit test events
@@ -248,9 +220,7 @@
test('Should receive camera error events', () async {
// Act
- final Stream<CameraErrorEvent> errorStream = plugin.onCameraError(
- cameraId,
- );
+ final Stream<CameraErrorEvent> errorStream = plugin.onCameraError(cameraId);
final streamQueue = StreamQueue<CameraErrorEvent>(errorStream);
// Emit test events
@@ -300,60 +270,47 @@
clearInteractions(mockApi);
});
- test(
- 'Should fetch CameraDescription instances for available cameras',
- () async {
- // Arrange
- final returnData = <String>['Test 1', 'Test 2'];
- when(
- mockApi.getAvailableCameras(),
- ).thenAnswer((_) async => returnData);
+ test('Should fetch CameraDescription instances for available cameras', () async {
+ // Arrange
+ final returnData = <String>['Test 1', 'Test 2'];
+ when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData);
- // Act
- final List<CameraDescription> cameras = await plugin
- .availableCameras();
+ // Act
+ final List<CameraDescription> cameras = await plugin.availableCameras();
- // Assert
- expect(cameras.length, returnData.length);
- for (var 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);
- }
- },
- );
+ // Assert
+ expect(cameras.length, returnData.length);
+ for (var 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 code = 'TESTING_ERROR_CODE';
- const message = 'Mock error message used during testing.';
- when(mockApi.getAvailableCameras()).thenAnswer(
- (_) async => throw PlatformException(code: code, message: message),
- );
+ test('Should throw CameraException when availableCameras throws a PlatformException', () {
+ // Arrange
+ const code = 'TESTING_ERROR_CODE';
+ const message = 'Mock error message used during testing.';
+ when(
+ mockApi.getAvailableCameras(),
+ ).thenAnswer((_) async => throw PlatformException(code: code, message: message));
- // Act
- expect(
- plugin.availableCameras,
- throwsA(
- isA<CameraException>()
- .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<CameraException>()
+ .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
@@ -387,10 +344,7 @@
// Act and Assert
expect(
() => plugin.startVideoCapturing(
- VideoCaptureOptions(
- cameraId,
- streamCallback: (CameraImageData imageData) {},
- ),
+ VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}),
),
throwsA(isA<UnimplementedError>()),
);
@@ -408,27 +362,15 @@
expect(file.path, '/test/path.mp4');
});
- test(
- 'Should throw UnsupportedError when pause video recording is called',
- () async {
- // Act
- expect(
- () => plugin.pauseVideoRecording(cameraId),
- throwsA(isA<UnsupportedError>()),
- );
- },
- );
+ test('Should throw UnsupportedError when pause video recording is called', () async {
+ // Act
+ expect(() => plugin.pauseVideoRecording(cameraId), throwsA(isA<UnsupportedError>()));
+ });
- test(
- 'Should throw UnsupportedError when resume video recording is called',
- () async {
- // Act
- expect(
- () => plugin.resumeVideoRecording(cameraId),
- throwsA(isA<UnsupportedError>()),
- );
- },
- );
+ test('Should throw UnsupportedError when resume video recording is called', () async {
+ // Act
+ expect(() => plugin.resumeVideoRecording(cameraId), throwsA(isA<UnsupportedError>()));
+ });
test('Should throw UnimplementedError when flash mode is set', () async {
// Act
@@ -438,33 +380,22 @@
);
});
- test(
- 'Should throw UnimplementedError when exposure mode is set',
- () async {
- // Act
- expect(
- () => plugin.setExposureMode(cameraId, ExposureMode.auto),
- throwsA(isA<UnimplementedError>()),
- );
- },
- );
+ test('Should throw UnimplementedError when exposure mode is set', () async {
+ // Act
+ expect(
+ () => plugin.setExposureMode(cameraId, ExposureMode.auto),
+ throwsA(isA<UnimplementedError>()),
+ );
+ });
- test(
- 'Should throw UnsupportedError when exposure point is set',
- () async {
- // Act
- expect(
- () => plugin.setExposurePoint(cameraId, null),
- throwsA(isA<UnsupportedError>()),
- );
- },
- );
+ test('Should throw UnsupportedError when exposure point is set', () async {
+ // Act
+ expect(() => plugin.setExposurePoint(cameraId, null), throwsA(isA<UnsupportedError>()));
+ });
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);
@@ -472,9 +403,7 @@
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);
@@ -482,24 +411,16 @@
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<UnimplementedError>()),
- );
- },
- );
+ test('Should throw UnimplementedError when exposure offset is set', () async {
+ // Act
+ expect(() => plugin.setExposureOffset(cameraId, 0.5), throwsA(isA<UnimplementedError>()));
+ });
test('Should throw UnimplementedError when focus mode is set', () async {
// Act
@@ -509,16 +430,13 @@
);
});
- test(
- 'Should throw UnsupportedError when exposure point is set',
- () async {
- // Act
- expect(
- () => plugin.setFocusMode(cameraId, FocusMode.auto),
- throwsA(isA<UnsupportedError>()),
- );
- },
- );
+ test('Should throw UnsupportedError when exposure point is set', () async {
+ // Act
+ expect(
+ () => plugin.setFocusMode(cameraId, FocusMode.auto),
+ throwsA(isA<UnsupportedError>()),
+ );
+ });
test('Should build a texture widget as preview widget', () async {
// Act
@@ -547,42 +465,25 @@
test('Should throw UnimplementedError when zoom level is set', () async {
// Act
- expect(
- () => plugin.setZoomLevel(cameraId, 2.0),
- throwsA(isA<UnimplementedError>()),
- );
+ expect(() => plugin.setZoomLevel(cameraId, 2.0), throwsA(isA<UnimplementedError>()));
});
- test(
- 'Should throw UnimplementedError when lock capture orientation is called',
- () async {
- // Act
- expect(
- () => plugin.setZoomLevel(cameraId, 2.0),
- throwsA(isA<UnimplementedError>()),
- );
- },
- );
+ test('Should throw UnimplementedError when lock capture orientation is called', () async {
+ // Act
+ expect(() => plugin.setZoomLevel(cameraId, 2.0), throwsA(isA<UnimplementedError>()));
+ });
- test(
- 'Should throw UnimplementedError when unlock capture orientation is called',
- () async {
- // Act
- expect(
- () => plugin.unlockCaptureOrientation(cameraId),
- throwsA(isA<UnimplementedError>()),
- );
- },
- );
+ test('Should throw UnimplementedError when unlock capture orientation is called', () async {
+ // Act
+ expect(() => plugin.unlockCaptureOrientation(cameraId), throwsA(isA<UnimplementedError>()));
+ });
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);
});
@@ -591,9 +492,7 @@
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 c81dcec..80f8b03 100644
--- a/packages/camera/camera_windows/test/camera_windows_test.mocks.dart
+++ b/packages/camera/camera_windows/test/camera_windows_test.mocks.dart
@@ -23,8 +23,7 @@
// 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].
@@ -51,17 +50,12 @@
(super.noSuchMethod(
Invocation.method(#getAvailableCameras, []),
returnValue: _i4.Future<List<String>>.value(<String>[]),
- returnValueForMissingStub: _i4.Future<List<String>>.value(
- <String>[],
- ),
+ returnValueForMissingStub: _i4.Future<List<String>>.value(<String>[]),
)
as _i4.Future<List<String>>);
@override
- _i4.Future<int> create(
- String? cameraName,
- _i2.PlatformMediaSettings? settings,
- ) =>
+ _i4.Future<int> create(String? cameraName, _i2.PlatformMediaSettings? settings) =>
(super.noSuchMethod(
Invocation.method(#create, [cameraName, settings]),
returnValue: _i4.Future<int>.value(0),
@@ -74,16 +68,10 @@
(super.noSuchMethod(
Invocation.method(#initialize, [cameraId]),
returnValue: _i4.Future<_i2.PlatformSize>.value(
- _FakePlatformSize_0(
- this,
- Invocation.method(#initialize, [cameraId]),
- ),
+ _FakePlatformSize_0(this, Invocation.method(#initialize, [cameraId])),
),
returnValueForMissingStub: _i4.Future<_i2.PlatformSize>.value(
- _FakePlatformSize_0(
- this,
- Invocation.method(#initialize, [cameraId]),
- ),
+ _FakePlatformSize_0(this, Invocation.method(#initialize, [cameraId])),
),
)
as _i4.Future<_i2.PlatformSize>);
@@ -102,16 +90,10 @@
(super.noSuchMethod(
Invocation.method(#takePicture, [cameraId]),
returnValue: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#takePicture, [cameraId]),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#takePicture, [cameraId])),
),
returnValueForMissingStub: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#takePicture, [cameraId]),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#takePicture, [cameraId])),
),
)
as _i4.Future<String>);
@@ -130,16 +112,10 @@
(super.noSuchMethod(
Invocation.method(#stopVideoRecording, [cameraId]),
returnValue: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#stopVideoRecording, [cameraId]),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#stopVideoRecording, [cameraId])),
),
returnValueForMissingStub: _i4.Future<String>.value(
- _i3.dummyValue<String>(
- this,
- Invocation.method(#stopVideoRecording, [cameraId]),
- ),
+ _i3.dummyValue<String>(this, Invocation.method(#stopVideoRecording, [cameraId])),
),
)
as _i4.Future<String>);
diff --git a/packages/cross_file/lib/src/types/html.dart b/packages/cross_file/lib/src/types/html.dart
index 40703aa..1757051 100644
--- a/packages/cross_file/lib/src/types/html.dart
+++ b/packages/cross_file/lib/src/types/html.dart
@@ -67,10 +67,7 @@
Blob _createBlobFromBytes(Uint8List bytes, String? mimeType) {
return (mimeType == null)
? Blob(<JSUint8Array>[bytes.toJS].toJS)
- : Blob(
- <JSUint8Array>[bytes.toJS].toJS,
- BlobPropertyBag(type: mimeType),
- );
+ : Blob(<JSUint8Array>[bytes.toJS].toJS, BlobPropertyBag(type: mimeType));
}
// Overridable (meta) data that can be specified by the constructors.
@@ -126,10 +123,7 @@
..open('get', path, true)
..responseType = 'blob'
..onLoad.listen((ProgressEvent e) {
- assert(
- request.response != null,
- 'The Blob backing this XFile cannot be null!',
- );
+ assert(request.response != null, 'The Blob backing this XFile cannot be null!');
blobCompleter.complete(request.response! as Blob);
})
..onError.listen((ProgressEvent e) {
@@ -176,8 +170,7 @@
await reader.onLoadEnd.first;
- final Uint8List? result = (reader.result as JSArrayBuffer?)?.toDart
- .asUint8List();
+ final Uint8List? result = (reader.result as JSArrayBuffer?)?.toDart.asUint8List();
if (result == null) {
throw Exception('Cannot read bytes from Blob. Is it still available?');
diff --git a/packages/cross_file/lib/src/types/interface.dart b/packages/cross_file/lib/src/types/interface.dart
index d539b4e..6f18885 100644
--- a/packages/cross_file/lib/src/types/interface.dart
+++ b/packages/cross_file/lib/src/types/interface.dart
@@ -30,9 +30,7 @@
DateTime? lastModified,
@visibleForTesting CrossFileTestOverrides? overrides,
}) {
- throw UnimplementedError(
- 'CrossFile is not available in your current platform.',
- );
+ throw UnimplementedError('CrossFile is not available in your current platform.');
}
/// Construct a CrossFile object from its data.
@@ -48,9 +46,7 @@
String? path,
@visibleForTesting CrossFileTestOverrides? overrides,
}) : super(path) {
- throw UnimplementedError(
- 'CrossFile is not available in your current platform.',
- );
+ throw UnimplementedError('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 c1931a7..45a03b3 100644
--- a/packages/cross_file/lib/src/types/io.dart
+++ b/packages/cross_file/lib/src/types/io.dart
@@ -133,9 +133,7 @@
if (_bytes != null) {
return _getBytes(start, end);
} else {
- return _file
- .openRead(start ?? 0, end)
- .map((List<int> chunk) => Uint8List.fromList(chunk));
+ return _file.openRead(start ?? 0, end).map((List<int> chunk) => Uint8List.fromList(chunk));
}
}
}
diff --git a/packages/cross_file/lib/src/web_helpers/web_helpers.dart b/packages/cross_file/lib/src/web_helpers/web_helpers.dart
index 58231dd..76eb830 100644
--- a/packages/cross_file/lib/src/web_helpers/web_helpers.dart
+++ b/packages/cross_file/lib/src/web_helpers/web_helpers.dart
@@ -8,16 +8,13 @@
import '../types/html.dart';
/// Type definition for function that creates anchor elements
-typedef CreateAnchorElement =
- HTMLAnchorElement Function(String href, String? suggestedName);
+typedef CreateAnchorElement = HTMLAnchorElement Function(String href, String? suggestedName);
/// Create anchor element with download attribute
-HTMLAnchorElement _createAnchorElementImpl(
- String href,
- String? suggestedName,
-) => (document.createElement('a') as HTMLAnchorElement)
- ..href = href
- ..download = suggestedName ?? 'download';
+HTMLAnchorElement _createAnchorElementImpl(String href, String? suggestedName) =>
+ (document.createElement('a') as HTMLAnchorElement)
+ ..href = href
+ ..download = suggestedName ?? 'download';
/// Function for creating anchor elements. Can be overridden for testing.
@visibleForTesting
@@ -55,10 +52,7 @@
final Element target = ensureInitialized('__x_file_dom_element');
// Create <a> element.
- final HTMLAnchorElement element = createAnchorElementFunction(
- file.path,
- file.name,
- );
+ final HTMLAnchorElement element = createAnchorElementFunction(file.path, file.name);
// Clear existing children before appending new one.
while (target.children.length > 0) {
diff --git a/packages/cross_file/test/x_file_html_test.dart b/packages/cross_file/test/x_file_html_test.dart
index e57e36c..bea856d 100644
--- a/packages/cross_file/test/x_file_html_test.dart
+++ b/packages/cross_file/test/x_file_html_test.dart
@@ -16,10 +16,7 @@
const String expectedStringContents = 'Hello, world! I ❤ ñ! 空手';
final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents));
-final html.File textFile = html.File(
- <JSUint8Array>[bytes.toJS].toJS,
- 'hello.txt',
-);
+final html.File textFile = html.File(<JSUint8Array>[bytes.toJS].toJS, 'hello.txt');
final String textFileUrl =
// TODO(kevmoo): drop ignore when pkg:web constraint excludes v0.3
// ignore: unnecessary_cast
@@ -89,9 +86,7 @@
test('Stores data as a Blob', () async {
// Read the blob from its path 'natively'
- final html.Response response = await html.window
- .fetch(file.path.toJS)
- .toDart;
+ final html.Response response = await html.window.fetch(file.path.toJS).toDart;
final JSAny arrayBuffer = await response.arrayBuffer().toDart;
final ByteBuffer data = (arrayBuffer as JSArrayBuffer).toDart;
@@ -116,9 +111,7 @@
await file.saveTo('');
- final html.Element? container = html.document.querySelector(
- '#$crossFileDomElementId',
- );
+ final html.Element? container = html.document.querySelector('#$crossFileDomElementId');
expect(container, isNotNull);
});
@@ -128,9 +121,7 @@
await file.saveTo('path');
- final html.Element container = html.document.querySelector(
- '#$crossFileDomElementId',
- )!;
+ final html.Element container = html.document.querySelector('#$crossFileDomElementId')!;
late html.HTMLAnchorElement element;
for (var i = 0; i < container.childNodes.length; i++) {
@@ -147,12 +138,10 @@
});
test('anchor element is clicked', () async {
- final mockAnchor =
- html.document.createElement('a') as html.HTMLAnchorElement;
+ final mockAnchor = html.document.createElement('a') as html.HTMLAnchorElement;
// Save original function so we can restore it
- final helpers.CreateAnchorElement original =
- helpers.createAnchorElementFunction;
+ final helpers.CreateAnchorElement original = helpers.createAnchorElementFunction;
addTearDown(() {
helpers.createAnchorElementFunction = original;
diff --git a/packages/cross_file/test/x_file_io_test.dart b/packages/cross_file/test/x_file_io_test.dart
index 904a5c0..8ca6768 100644
--- a/packages/cross_file/test/x_file_io_test.dart
+++ b/packages/cross_file/test/x_file_io_test.dart
@@ -12,9 +12,7 @@
import 'package:cross_file/cross_file.dart';
import 'package:test/test.dart';
-final String pathPrefix = Directory.current.path.endsWith('test')
- ? './assets/'
- : './test/assets/';
+final String pathPrefix = Directory.current.path.endsWith('test') ? './assets/' : './test/assets/';
final String path = '${pathPrefix}hello.txt';
const String expectedStringContents = 'Hello, world!';
final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents));
diff --git a/packages/cupertino_ui/test/flutter_test_config.dart b/packages/cupertino_ui/test/flutter_test_config.dart
index 89496e1..decec13 100644
--- a/packages/cupertino_ui/test/flutter_test_config.dart
+++ b/packages/cupertino_ui/test/flutter_test_config.dart
@@ -4,9 +4,7 @@
import 'dart:async';
-import 'goldens_io.dart'
- if (dart.library.js_interop) 'goldens_web.dart'
- as flutter_goldens;
+import 'goldens_io.dart' if (dart.library.js_interop) 'goldens_web.dart' as flutter_goldens;
Future<void> testExecutable(FutureOr<void> Function() testMain) {
// Enable golden file testing using Skia Gold.
diff --git a/packages/cupertino_ui/test/goldens/goldens_test.dart b/packages/cupertino_ui/test/goldens/goldens_test.dart
index d099e7a..955d4a3 100644
--- a/packages/cupertino_ui/test/goldens/goldens_test.dart
+++ b/packages/cupertino_ui/test/goldens/goldens_test.dart
@@ -10,9 +10,7 @@
testWidgets('Inconsequential golden test', (WidgetTester tester) async {
// The test validates the Flutter Gold integration. Any changes to the
// golden file can be approved at any time.
- await tester.pumpWidget(
- const CupertinoApp(home: Center(child: Text('Cupertino Goldens'))),
- );
+ await tester.pumpWidget(const CupertinoApp(home: Center(child: Text('Cupertino Goldens'))));
await tester.pumpAndSettle();
await expectLater(
diff --git a/packages/cupertino_ui/test/goldens_web.dart b/packages/cupertino_ui/test/goldens_web.dart
index 80945b7..fd3ea2d 100644
--- a/packages/cupertino_ui/test/goldens_web.dart
+++ b/packages/cupertino_ui/test/goldens_web.dart
@@ -5,7 +5,5 @@
import 'dart:async';
// package:flutter_goldens is not used as part of the test process for web.
-Future<void> testExecutable(
- FutureOr<void> Function() testMain, {
- String? namePrefix,
-}) async => testMain();
+Future<void> testExecutable(FutureOr<void> Function() testMain, {String? namePrefix}) async =>
+ testMain();
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 ec28a2d..8a2bf11 100644
--- a/packages/extension_google_sign_in_as_googleapis_auth/README.md
+++ b/packages/extension_google_sign_in_as_googleapis_auth/README.md
@@ -28,8 +28,10 @@
// Prepare a People Service authenticated client.
final 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 79e1a24..79018cf 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,9 +19,7 @@
const List<String> scopes = <String>[PeopleServiceApi.contactsReadonlyScope];
void main() {
- runApp(
- const MaterialApp(title: 'Google Sign In + googleapis', home: SignInDemo()),
- );
+ runApp(const MaterialApp(title: 'Google Sign In + googleapis', home: SignInDemo()));
}
/// The main widget of this demo.
@@ -90,9 +88,7 @@
}
Future<void> _checkAuthorization() async {
- _updateAuthorization(
- await _currentUser?.authorizationClient.authorizationForScopes(scopes),
- );
+ _updateAuthorization(await _currentUser?.authorizationClient.authorizationForScopes(scopes));
}
Future<void> _requestAuthorization() async {
@@ -103,9 +99,7 @@
);
}
- Future<void> _handleGetContact(
- GoogleSignInClientAuthorization authorization,
- ) async {
+ Future<void> _handleGetContact(GoogleSignInClientAuthorization authorization) async {
if (!mounted) {
return;
}
@@ -120,13 +114,13 @@
// Prepare a People Service authenticated client.
final 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(() {
@@ -188,26 +182,17 @@
child: const Text('LOAD CONTACTS'),
),
],
- ElevatedButton(
- onPressed: _handleSignOut,
- child: const Text('SIGN OUT'),
- ),
+ ElevatedButton(onPressed: _handleSignOut, child: const Text('SIGN OUT')),
] else ...<Widget>[
const Text('You are not currently signed in.'),
- ElevatedButton(
- onPressed: _handleSignIn,
- child: const Text('SIGN IN'),
- ),
+ ElevatedButton(onPressed: _handleSignIn, child: const Text('SIGN IN')),
],
];
} else {
children = <Widget>[const CircularProgressIndicator()];
}
- return Column(
- mainAxisAlignment: MainAxisAlignment.spaceAround,
- children: children,
- );
+ return Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: children);
},
);
}
@@ -216,10 +201,7 @@
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Google Sign In + googleapis')),
- body: ConstrainedBox(
- constraints: const BoxConstraints.expand(),
- child: _buildBody(),
- ),
+ body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()),
);
}
}
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 334941f..3c259ee 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
@@ -9,24 +9,17 @@
const String SOME_FAKE_ACCESS_TOKEN = 'this-is-something-not-null';
-class FakeGoogleSignInClientAuthorization extends Fake
- implements GoogleSignInClientAuthorization {
+class FakeGoogleSignInClientAuthorization extends Fake implements GoogleSignInClientAuthorization {
@override
final String accessToken = SOME_FAKE_ACCESS_TOKEN;
}
void main() {
- test(
- 'authClient returned client contains the expected information',
- () async {
- const scopes = <String>['some-scope', 'another-scope'];
- final 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 scopes = <String>['some-scope', 'another-scope'];
+ final 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/README.md b/packages/file_selector/file_selector/README.md
index b6a8cde..c59aa68 100644
--- a/packages/file_selector/file_selector/README.md
+++ b/packages/file_selector/file_selector/README.md
@@ -40,9 +40,7 @@
extensions: <String>['jpg', 'png'],
uniformTypeIdentifiers: <String>['public.jpeg', 'public.png'],
);
-final XFile? file = await openFile(
- acceptedTypeGroups: <XTypeGroup>[typeGroup],
-);
+final XFile? file = await openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
```
#### Open multiple files at once
@@ -69,9 +67,7 @@
<?code-excerpt "readme_standalone_excerpts.dart (Save)"?>
```dart
const 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;
@@ -79,11 +75,7 @@
final fileData = Uint8List.fromList('Hello World!'.codeUnits);
const mimeType = 'text/plain';
-final textFile = XFile.fromData(
- fileData,
- mimeType: mimeType,
- name: fileName,
-);
+final 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 9f8b6fd..3e24bbb 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
@@ -15,9 +15,7 @@
Future<void> _getDirectoryPath(BuildContext context) async {
const confirmButtonText = 'Choose';
- final String? directoryPath = await getDirectoryPath(
- confirmButtonText: confirmButtonText,
- );
+ final String? directoryPath = await getDirectoryPath(confirmButtonText: confirmButtonText);
if (directoryPath == null) {
// Operation was canceled by the user.
return;
@@ -65,14 +63,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directory'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoryPath)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 aa51955..e81afac 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
@@ -45,9 +45,7 @@
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
- child: const Text(
- 'Press to ask user to choose multiple directories',
- ),
+ child: const Text('Press to ask user to choose multiple directories'),
onPressed: () => _getDirectoryPaths(context),
),
],
@@ -69,14 +67,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directories'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoriesPaths)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoriesPaths))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 76801d5..d895a50 100644
--- a/packages/file_selector/file_selector/example/lib/home_page.dart
+++ b/packages/file_selector/file_selector/example/lib/home_page.dart
@@ -64,8 +64,7 @@
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 da38163..db70eb5 100644
--- a/packages/file_selector/file_selector/example/lib/main.dart
+++ b/packages/file_selector/file_selector/example/lib/main.dart
@@ -32,13 +32,11 @@
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/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 e2260c9..0d3d01d 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
@@ -20,9 +20,7 @@
extensions: <String>['jpg', 'png'],
uniformTypeIdentifiers: <String>['public.jpeg', 'public.png'],
);
- final XFile? file = await openFile(
- acceptedTypeGroups: <XTypeGroup>[typeGroup],
- );
+ final XFile? file = await openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
// #enddocregion SingleOpen
if (file == null) {
// Operation was canceled by the user.
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 eb6b0e9..523cca0 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
@@ -82,11 +82,8 @@
child: Row(
children: <Widget>[
...files.map(
- (XFile file) => Flexible(
- child: kIsWeb
- ? Image.network(file.path)
- : Image.file(File(file.path)),
- ),
+ (XFile file) =>
+ Flexible(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 ab6dd5a..167f9d1 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
@@ -81,14 +81,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(fileContent)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 cbfc728..fb71f53 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
@@ -37,9 +37,7 @@
Future<void> saveFile() async {
// #docregion Save
const 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;
@@ -47,11 +45,7 @@
final fileData = Uint8List.fromList('Hello World!'.codeUnits);
const mimeType = 'text/plain';
- final textFile = XFile.fromData(
- fileData,
- mimeType: mimeType,
- name: fileName,
- );
+ final 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 809c7f4..59b71e2 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
@@ -38,11 +38,7 @@
final String text = _contentController.text;
final fileData = Uint8List.fromList(text.codeUnits);
const fileMimeType = 'text/plain';
- final textFile = XFile.fromData(
- fileData,
- mimeType: fileMimeType,
- name: fileName,
- );
+ final textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName);
await textFile.saveTo(result.path);
}
@@ -61,9 +57,7 @@
minLines: 1,
maxLines: 12,
controller: _nameController,
- decoration: const InputDecoration(
- hintText: '(Optional) Suggest File Name',
- ),
+ decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'),
),
),
SizedBox(
@@ -72,9 +66,7 @@
minLines: 1,
maxLines: 12,
controller: _contentController,
- decoration: const InputDecoration(
- hintText: 'Enter File Contents',
- ),
+ decoration: const InputDecoration(hintText: 'Enter File Contents'),
),
),
const SizedBox(height: 10),
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 9b4b952..374a9a8 100644
--- a/packages/file_selector/file_selector/test/file_selector_test.dart
+++ b/packages/file_selector/file_selector/test/file_selector_test.dart
@@ -81,9 +81,7 @@
..setExpectations(acceptedTypeGroups: acceptedTypeGroups)
..setFileResponse(<XFile>[expectedFile]);
- final XFile? file = await openFile(
- acceptedTypeGroups: acceptedTypeGroups,
- );
+ final XFile? file = await openFile(acceptedTypeGroups: acceptedTypeGroups);
expect(file, expectedFile);
});
});
@@ -122,9 +120,7 @@
..setExpectations(initialDirectory: initialDirectory)
..setFileResponse(expectedFiles);
- final List<XFile> files = await openFiles(
- initialDirectory: initialDirectory,
- );
+ final List<XFile> files = await openFiles(initialDirectory: initialDirectory);
expect(files, expectedFiles);
});
@@ -133,9 +129,7 @@
..setExpectations(confirmButtonText: confirmButtonText)
..setFileResponse(expectedFiles);
- final List<XFile> files = await openFiles(
- confirmButtonText: confirmButtonText,
- );
+ final List<XFile> files = await openFiles(confirmButtonText: confirmButtonText);
expect(files, expectedFiles);
});
@@ -144,9 +138,7 @@
..setExpectations(acceptedTypeGroups: acceptedTypeGroups)
..setFileResponse(expectedFiles);
- final List<XFile> files = await openFiles(
- acceptedTypeGroups: acceptedTypeGroups,
- );
+ final List<XFile> files = await openFiles(acceptedTypeGroups: acceptedTypeGroups);
expect(files, expectedFiles);
});
});
@@ -163,9 +155,7 @@
acceptedTypeGroups: acceptedTypeGroups,
suggestedName: suggestedName,
)
- ..setPathsResponse(<String>[
- expectedSavePath,
- ], activeFilter: expectedActiveFilter);
+ ..setPathsResponse(<String>[expectedSavePath], activeFilter: expectedActiveFilter);
final FileSaveLocation? location = await getSaveLocation(
initialDirectory: initialDirectory,
@@ -190,9 +180,7 @@
..setExpectations(initialDirectory: initialDirectory)
..setPathsResponse(<String>[expectedSavePath]);
- final FileSaveLocation? location = await getSaveLocation(
- initialDirectory: initialDirectory,
- );
+ final FileSaveLocation? location = await getSaveLocation(initialDirectory: initialDirectory);
expect(location?.path, expectedSavePath);
});
@@ -223,9 +211,7 @@
..setExpectations(suggestedName: suggestedName)
..setPathsResponse(<String>[expectedSavePath]);
- final FileSaveLocation? location = await getSaveLocation(
- suggestedName: suggestedName,
- );
+ final FileSaveLocation? location = await getSaveLocation(suggestedName: suggestedName);
expect(location?.path, expectedSavePath);
});
@@ -247,10 +233,7 @@
test('works', () async {
fakePlatformImplementation
- ..setExpectations(
- initialDirectory: initialDirectory,
- confirmButtonText: confirmButtonText,
- )
+ ..setExpectations(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText)
..setPathsResponse(<String>[expectedDirectoryPath]);
final String? directoryPath = await getDirectoryPath(
@@ -262,9 +245,7 @@
});
test('works with no arguments', () async {
- fakePlatformImplementation.setPathsResponse(<String>[
- expectedDirectoryPath,
- ]);
+ fakePlatformImplementation.setPathsResponse(<String>[expectedDirectoryPath]);
final String? directoryPath = await getDirectoryPath();
expect(directoryPath, expectedDirectoryPath);
@@ -275,9 +256,7 @@
..setExpectations(initialDirectory: initialDirectory)
..setPathsResponse(<String>[expectedDirectoryPath]);
- final String? directoryPath = await getDirectoryPath(
- initialDirectory: initialDirectory,
- );
+ final String? directoryPath = await getDirectoryPath(initialDirectory: initialDirectory);
expect(directoryPath, expectedDirectoryPath);
});
@@ -286,9 +265,7 @@
..setExpectations(confirmButtonText: confirmButtonText)
..setPathsResponse(<String>[expectedDirectoryPath]);
- final String? directoryPath = await getDirectoryPath(
- confirmButtonText: confirmButtonText,
- );
+ final String? directoryPath = await getDirectoryPath(confirmButtonText: confirmButtonText);
expect(directoryPath, expectedDirectoryPath);
});
@@ -310,10 +287,7 @@
test('works', () async {
fakePlatformImplementation
- ..setExpectations(
- initialDirectory: initialDirectory,
- confirmButtonText: confirmButtonText,
- )
+ ..setExpectations(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText)
..setPathsResponse(expectedDirectoryPaths);
final List<String?> directoryPaths = await getDirectoryPaths(
@@ -461,9 +435,7 @@
? null
: FileSaveLocation(
path,
- activeFilter: activeFilterIndex == null
- ? null
- : acceptedTypeGroups?[activeFilterIndex],
+ activeFilter: activeFilterIndex == null ? null : acceptedTypeGroups?[activeFilterIndex],
);
}
@@ -500,9 +472,7 @@
}
@override
- Future<List<String>> getDirectoryPathsWithOptions(
- FileDialogOptions options,
- ) async {
+ Future<List<String>> getDirectoryPathsWithOptions(FileDialogOptions options) async {
expect(options.initialDirectory, initialDirectory);
expect(options.confirmButtonText, confirmButtonText);
expect(options.canCreateDirectories, canCreateDirectories);
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 b69b4c1..f0da879 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,7 @@
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/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_multiple_images_page.dart b/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart
index 9bc2cfa..88208db 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
@@ -84,10 +84,7 @@
child: Row(
children: <Widget>[
for (int i = 0; i < fileBytes.length; i++)
- Flexible(
- key: Key('result_image_name$i'),
- child: Image.memory(fileBytes[i]),
- ),
+ 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 5469e58..815c723 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
@@ -73,14 +73,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(fileContent)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 461ede2..fe8b080 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
@@ -12,8 +12,7 @@
/// An implementation of [FileSelectorPlatform] for Android.
class FileSelectorAndroid extends FileSelectorPlatform {
- FileSelectorAndroid({@visibleForTesting FileSelectorApi? api})
- : _api = api ?? FileSelectorApi();
+ FileSelectorAndroid({@visibleForTesting FileSelectorApi? api}) : _api = api ?? FileSelectorApi();
final FileSelectorApi _api;
@@ -49,10 +48,7 @@
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async {
return _api.getDirectoryPath(initialDirectory);
}
@@ -80,9 +76,7 @@
final extensions = <String>{};
for (final XTypeGroup group in typeGroups) {
- if (!group.allowsAny &&
- group.mimeTypes == null &&
- group.extensions == null) {
+ if (!group.allowsAny && group.mimeTypes == null && group.extensions == null) {
throw ArgumentError(
'Provided type group $group does not allow all files, but does not '
'set any of the Android supported filter categories. At least one of '
@@ -94,22 +88,15 @@
extensions.addAll(group.extensions ?? <String>{});
}
- return FileTypes(
- mimeTypes: mimeTypes.toList(),
- extensions: extensions.toList(),
- );
+ return FileTypes(mimeTypes: mimeTypes.toList(), extensions: extensions.toList());
}
/// Translates a [FileSelectorExceptionCode] to its corresponding error and
/// handles throwing.
- void _resolveErrorCodeAndMaybeThrow(
- FileSelectorNativeException fileSelectorNativeException,
- ) {
+ void _resolveErrorCodeAndMaybeThrow(FileSelectorNativeException fileSelectorNativeException) {
switch (fileSelectorNativeException.fileSelectorExceptionCode) {
case FileSelectorExceptionCode.illegalArgumentException:
- throw NativeIllegalArgumentException(
- fileSelectorNativeException.message,
- );
+ throw NativeIllegalArgumentException(fileSelectorNativeException.message);
case (FileSelectorExceptionCode.illegalStateException ||
FileSelectorExceptionCode.ioException ||
FileSelectorExceptionCode.securityException):
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 2d76187..5a2094e 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
@@ -49,9 +49,7 @@
}
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) {
if (a.length != b.length) {
@@ -108,10 +106,7 @@
}
class FileSelectorNativeException {
- FileSelectorNativeException({
- required this.fileSelectorExceptionCode,
- required this.message,
- });
+ FileSelectorNativeException({required this.fileSelectorExceptionCode, required this.message});
FileSelectorExceptionCode fileSelectorExceptionCode;
@@ -136,17 +131,13 @@
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
- if (other is! FileSelectorNativeException ||
- other.runtimeType != runtimeType) {
+ if (other is! FileSelectorNativeException || other.runtimeType != runtimeType) {
return false;
}
if (identical(this, other)) {
return true;
}
- return _deepEquals(
- fileSelectorExceptionCode,
- other.fileSelectorExceptionCode,
- ) &&
+ return _deepEquals(fileSelectorExceptionCode, other.fileSelectorExceptionCode) &&
_deepEquals(message, other.message);
}
@@ -178,14 +169,7 @@
FileSelectorNativeException? fileSelectorNativeException;
List<Object?> _toList() {
- return <Object?>[
- path,
- mimeType,
- name,
- size,
- bytes,
- fileSelectorNativeException,
- ];
+ return <Object?>[path, mimeType, name, size, bytes, fileSelectorNativeException];
}
Object encode() {
@@ -218,10 +202,7 @@
_deepEquals(name, other.name) &&
_deepEquals(size, other.size) &&
_deepEquals(bytes, other.bytes) &&
- _deepEquals(
- fileSelectorNativeException,
- other.fileSelectorNativeException,
- );
+ _deepEquals(fileSelectorNativeException, other.fileSelectorNativeException);
}
@override
@@ -261,8 +242,7 @@
if (identical(this, other)) {
return true;
}
- return _deepEquals(mimeTypes, other.mimeTypes) &&
- _deepEquals(extensions, other.extensions);
+ return _deepEquals(mimeTypes, other.mimeTypes) && _deepEquals(extensions, other.extensions);
}
@override
@@ -317,13 +297,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -333,10 +311,7 @@
/// Opens a file dialog for loading files and returns a file path.
///
/// Returns `null` if user cancels the operation.
- Future<FileResponse?> openFile(
- String? initialDirectory,
- FileTypes allowedTypes,
- ) async {
+ Future<FileResponse?> openFile(String? initialDirectory, FileTypes allowedTypes) async {
final pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_android.FileSelectorApi.openFile$pigeonVar_messageChannelSuffix';
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -344,9 +319,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[initialDirectory, allowedTypes],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ initialDirectory,
+ allowedTypes,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
final Object? pigeonVar_replyValue = _extractReplyValueOrThrow(
@@ -359,10 +335,7 @@
/// Opens a file dialog for loading files and returns a list of file responses
/// chosen by the user.
- Future<List<FileResponse>> openFiles(
- String? initialDirectory,
- FileTypes allowedTypes,
- ) async {
+ Future<List<FileResponse>> openFiles(String? initialDirectory, FileTypes allowedTypes) async {
final pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_android.FileSelectorApi.openFiles$pigeonVar_messageChannelSuffix';
final pigeonVar_channel = BasicMessageChannel<Object?>(
@@ -370,9 +343,10 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[initialDirectory, allowedTypes],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ initialDirectory,
+ allowedTypes,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
final Object? pigeonVar_replyValue = _extractReplyValueOrThrow(
@@ -394,9 +368,9 @@
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[initialDirectory],
- );
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ initialDirectory,
+ ]);
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
final Object? pigeonVar_replyValue = _extractReplyValueOrThrow(
diff --git a/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart b/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart
index 6390022..9dc72fb 100644
--- a/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart
+++ b/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart
@@ -9,9 +9,7 @@
dartOut: 'lib/src/file_selector_api.g.dart',
kotlinOut:
'android/src/main/kotlin/dev/flutter/packages/file_selector_android/GeneratedFileSelectorApi.kt',
- kotlinOptions: KotlinOptions(
- package: 'dev.flutter.packages.file_selector_android',
- ),
+ kotlinOptions: KotlinOptions(package: 'dev.flutter.packages.file_selector_android'),
copyrightHeader: 'pigeons/copyright.txt',
),
)
@@ -53,10 +51,7 @@
/// Opens a file dialog for loading files and returns a list of file responses
/// chosen by the user.
@async
- List<FileResponse> openFiles(
- String? initialDirectory,
- FileTypes allowedTypes,
- );
+ List<FileResponse> openFiles(String? initialDirectory, FileTypes allowedTypes);
/// Opens a file dialog for loading directories and returns a directory path.
///
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 b4f7ece..2bd5bd2 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
@@ -37,16 +37,14 @@
'some/path/',
argThat(
isA<FileTypes>()
- .having(
- (FileTypes types) => types.mimeTypes,
- 'mimeTypes',
- <String>['text/plain', 'image/jpg'],
- )
- .having(
- (FileTypes types) => types.extensions,
- 'extensions',
- <String>['txt', 'jpg'],
- ),
+ .having((FileTypes types) => types.mimeTypes, 'mimeTypes', <String>[
+ 'text/plain',
+ 'image/jpg',
+ ])
+ .having((FileTypes types) => types.extensions, 'extensions', <String>[
+ 'txt',
+ 'jpg',
+ ]),
),
),
).thenAnswer(
@@ -61,15 +59,9 @@
),
);
- const group = XTypeGroup(
- extensions: <String>['txt'],
- mimeTypes: <String>['text/plain'],
- );
+ const group = XTypeGroup(extensions: <String>['txt'], mimeTypes: <String>['text/plain']);
- const group2 = XTypeGroup(
- extensions: <String>['jpg'],
- mimeTypes: <String>['image/jpg'],
- );
+ const group2 = XTypeGroup(extensions: <String>['jpg'], mimeTypes: <String>['image/jpg']);
final XFile? file = await plugin.openFile(
acceptedTypeGroups: <XTypeGroup>[group, group2],
@@ -90,16 +82,14 @@
'some/path/',
argThat(
isA<FileTypes>()
- .having(
- (FileTypes types) => types.mimeTypes,
- 'mimeTypes',
- <String>['text/plain', 'image/jpg'],
- )
- .having(
- (FileTypes types) => types.extensions,
- 'extensions',
- <String>['txt', 'jpg'],
- ),
+ .having((FileTypes types) => types.mimeTypes, 'mimeTypes', <String>[
+ 'text/plain',
+ 'image/jpg',
+ ])
+ .having((FileTypes types) => types.extensions, 'extensions', <String>[
+ 'txt',
+ 'jpg',
+ ]),
),
),
).thenAnswer(
@@ -111,24 +101,13 @@
name: 'name',
mimeType: 'text/plain',
),
- FileResponse(
- path: 'other/dir.jpg',
- size: 40,
- bytes: Uint8List(0),
- mimeType: 'image/jpg',
- ),
+ FileResponse(path: 'other/dir.jpg', size: 40, bytes: Uint8List(0), mimeType: 'image/jpg'),
]),
);
- const group = XTypeGroup(
- extensions: <String>['txt'],
- mimeTypes: <String>['text/plain'],
- );
+ const group = XTypeGroup(extensions: <String>['txt'], mimeTypes: <String>['text/plain']);
- const group2 = XTypeGroup(
- extensions: <String>['jpg'],
- mimeTypes: <String>['image/jpg'],
- );
+ const group2 = XTypeGroup(extensions: <String>['jpg'], mimeTypes: <String>['image/jpg']);
final List<XFile> files = await plugin.openFiles(
acceptedTypeGroups: <XTypeGroup>[group, group2],
@@ -152,9 +131,7 @@
mockApi.getDirectoryPath('some/path'),
).thenAnswer((_) => Future<String?>.value('some/path/chosen/'));
- final String? path = await plugin.getDirectoryPath(
- initialDirectory: 'some/path',
- );
+ final String? path = await plugin.getDirectoryPath(initialDirectory: 'some/path');
expect(path, 'some/path/chosen/');
});
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 45cfa75..33556a4 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
@@ -42,10 +42,7 @@
as String);
@override
- _i4.Future<_i2.FileResponse?> openFile(
- String? initialDirectory,
- _i2.FileTypes? allowedTypes,
- ) =>
+ _i4.Future<_i2.FileResponse?> openFile(String? initialDirectory, _i2.FileTypes? allowedTypes) =>
(super.noSuchMethod(
Invocation.method(#openFile, [initialDirectory, allowedTypes]),
returnValue: _i4.Future<_i2.FileResponse?>.value(),
@@ -59,9 +56,7 @@
) =>
(super.noSuchMethod(
Invocation.method(#openFiles, [initialDirectory, allowedTypes]),
- returnValue: _i4.Future<List<_i2.FileResponse>>.value(
- <_i2.FileResponse>[],
- ),
+ returnValue: _i4.Future<List<_i2.FileResponse>>.value(<_i2.FileResponse>[]),
)
as _i4.Future<List<_i2.FileResponse>>);
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 556f420..28b56d3 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,7 @@
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/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 9996174..cef0fc6 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
@@ -66,10 +66,7 @@
title: Text(fileName),
content: Text(filePath),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 9585ac8..2b5f2c8 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
@@ -81,11 +81,8 @@
child: Row(
children: <Widget>[
...files.map(
- (XFile file) => Flexible(
- child: kIsWeb
- ? Image.network(file.path)
- : Image.file(File(file.path)),
- ),
+ (XFile file) =>
+ Flexible(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 9a9b361..0e12eb7 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
@@ -73,14 +73,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(fileContent)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 2f6f241..4fc9d3d 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
@@ -10,8 +10,7 @@
/// An implementation of [FileSelectorPlatform] for iOS.
class FileSelectorIOS extends FileSelectorPlatform {
/// Creates a new plugin implementation instance.
- FileSelectorIOS({@visibleForTesting FileSelectorApi? api})
- : _hostApi = api ?? FileSelectorApi();
+ FileSelectorIOS({@visibleForTesting FileSelectorApi? api}) : _hostApi = api ?? FileSelectorApi();
final FileSelectorApi _hostApi;
@@ -27,9 +26,7 @@
String? confirmButtonText,
}) async {
final List<String> path = await _hostApi.openFile(
- FileSelectorConfig(
- utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups),
- ),
+ FileSelectorConfig(utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups)),
);
return path.isEmpty ? null : XFile(path.first);
}
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 6e37952..6679ba8 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
@@ -21,9 +21,7 @@
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 &&
@@ -37,10 +35,7 @@
}
class FileSelectorConfig {
- FileSelectorConfig({
- this.utis = const <String>[],
- this.allowMultiSelection = false,
- });
+ FileSelectorConfig({this.utis = const <String>[], this.allowMultiSelection = false});
List<String> utis;
@@ -109,13 +104,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -125,17 +118,13 @@
Future<List<String>> openFile(FileSelectorConfig config) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[config],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[config]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
diff --git a/packages/file_selector/file_selector_ios/pigeons/messages.dart b/packages/file_selector/file_selector_ios/pigeons/messages.dart
index 857e888..815e7b2 100644
--- a/packages/file_selector/file_selector_ios/pigeons/messages.dart
+++ b/packages/file_selector/file_selector_ios/pigeons/messages.dart
@@ -7,16 +7,12 @@
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
- swiftOut:
- 'ios/file_selector_ios/Sources/file_selector_ios/messages.g.swift',
+ swiftOut: 'ios/file_selector_ios/Sources/file_selector_ios/messages.g.swift',
copyrightHeader: 'pigeons/copyright.txt',
),
)
class FileSelectorConfig {
- FileSelectorConfig({
- this.utis = const <String>[],
- this.allowMultiSelection = false,
- });
+ FileSelectorConfig({this.utis = const <String>[], this.allowMultiSelection = false});
List<String> utis;
bool allowMultiSelection;
}
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 ef6bad4..0e41429 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
@@ -49,20 +49,11 @@
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
// iOS only accepts uniformTypeIdentifiers.
- expect(
- listEquals(api.passedConfig?.utis, <String>[
- 'public.text',
- 'public.image',
- ]),
- isTrue,
- );
+ expect(listEquals(api.passedConfig?.utis, <String>['public.text', 'public.image']), isTrue);
expect(api.passedConfig?.allowMultiSelection, isFalse);
});
test('throws for a type group that does not support iOS', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -72,23 +63,14 @@
test('correctly handles no type groups', () async {
await expectLater(plugin.openFile(), completes);
- expect(
- listEquals(api.passedConfig?.utis, <String>['public.data']),
- isTrue,
- );
+ expect(listEquals(api.passedConfig?.utis, <String>['public.data']), isTrue);
});
test('correctly handles a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
- expect(
- listEquals(api.passedConfig?.utis, <String>['public.data']),
- isTrue,
- );
+ await expectLater(plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), completes);
+ expect(listEquals(api.passedConfig?.utis, <String>['public.data']), isTrue);
});
});
@@ -115,21 +97,12 @@
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
- expect(
- listEquals(api.passedConfig?.utis, <String>[
- 'public.text',
- 'public.image',
- ]),
- isTrue,
- );
+ expect(listEquals(api.passedConfig?.utis, <String>['public.text', 'public.image']), isTrue);
expect(api.passedConfig?.allowMultiSelection, isTrue);
});
test('throws for a type group that does not support iOS', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -139,23 +112,14 @@
test('correctly handles no type groups', () async {
await expectLater(plugin.openFiles(), completes);
- expect(
- listEquals(api.passedConfig?.utis, <String>['public.data']),
- isTrue,
- );
+ expect(listEquals(api.passedConfig?.utis, <String>['public.data']), isTrue);
});
test('correctly handles a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
- expect(
- listEquals(api.passedConfig?.utis, <String>['public.data']),
- isTrue,
- );
+ await expectLater(plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), completes);
+ expect(listEquals(api.passedConfig?.utis, <String>['public.data']), isTrue);
});
});
}
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 4e3fa86..718f67d 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,9 @@
Future<void> _getDirectoryPath(BuildContext context) async {
const confirmButtonText = 'Choose';
- final String? directoryPath = await FileSelectorPlatform.instance
- .getDirectoryPathWithOptions(
- const FileDialogOptions(confirmButtonText: confirmButtonText),
- );
+ final String? directoryPath = await FileSelectorPlatform.instance.getDirectoryPathWithOptions(
+ const FileDialogOptions(confirmButtonText: confirmButtonText),
+ );
if (directoryPath == null) {
// Operation was canceled by the user.
return;
@@ -64,14 +63,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directory'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoryPath)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 9e2d2cc..07263ac 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
@@ -24,8 +24,7 @@
if (context.mounted) {
await showDialog<void>(
context: context,
- builder: (BuildContext context) =>
- TextDisplay(directoryPaths.join('\n')),
+ builder: (BuildContext context) => TextDisplay(directoryPaths.join('\n')),
);
}
}
@@ -43,9 +42,7 @@
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
- child: const Text(
- 'Press to ask user to choose multiple directories',
- ),
+ child: const Text('Press to ask user to choose multiple directories'),
onPressed: () => _getDirectoryPaths(context),
),
],
@@ -67,14 +64,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directories'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoriesPaths)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoriesPaths))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 b498848..f90d366 100644
--- a/packages/file_selector/file_selector_linux/example/lib/home_page.dart
+++ b/packages/file_selector/file_selector_linux/example/lib/home_page.dart
@@ -54,8 +54,7 @@
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 28a3420..4fefa8b 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,11 @@
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/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 6554cbf..5983fa5 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
@@ -15,10 +15,7 @@
const OpenImagePage({super.key});
Future<void> _openImageFile(BuildContext context) async {
- const typeGroup = XTypeGroup(
- label: 'images',
- extensions: <String>['jpg', 'png'],
- );
+ const typeGroup = XTypeGroup(label: 'images', extensions: <String>['jpg', 'png']);
final XFile? file = await FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
);
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 da7e307..da35dc5 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
@@ -15,10 +15,7 @@
const OpenMultipleImagesPage({super.key});
Future<void> _openImageFile(BuildContext context) async {
- const jpgsTypeGroup = XTypeGroup(
- label: 'JPEGs',
- extensions: <String>['jpg', 'jpeg'],
- );
+ const jpgsTypeGroup = XTypeGroup(label: 'JPEGs', extensions: <String>['jpg', 'jpeg']);
const pngTypeGroup = XTypeGroup(label: 'PNGs', extensions: <String>['png']);
final List<XFile> files = await FileSelectorPlatform.instance.openFiles(
acceptedTypeGroups: <XTypeGroup>[jpgsTypeGroup, pngTypeGroup],
@@ -76,11 +73,8 @@
child: Row(
children: <Widget>[
...files.map(
- (XFile file) => Flexible(
- child: kIsWeb
- ? Image.network(file.path)
- : Image.file(File(file.path)),
- ),
+ (XFile file) =>
+ Flexible(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 023cd8c..5b5abbc 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
@@ -12,10 +12,7 @@
const OpenTextPage({super.key});
Future<void> _openTextFile(BuildContext context) async {
- const typeGroup = XTypeGroup(
- label: 'text',
- extensions: <String>['txt', 'json'],
- );
+ const typeGroup = XTypeGroup(label: 'text', extensions: <String>['txt', 'json']);
final XFile? file = await FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
);
@@ -72,14 +69,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(fileContent)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 988176f..156f095 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,8 +17,9 @@
Future<void> _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;
@@ -26,11 +27,7 @@
final String text = _contentController.text;
final fileData = Uint8List.fromList(text.codeUnits);
const fileMimeType = 'text/plain';
- final textFile = XFile.fromData(
- fileData,
- mimeType: fileMimeType,
- name: fileName,
- );
+ final textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName);
await textFile.saveTo(result.path);
}
@@ -48,9 +45,7 @@
minLines: 1,
maxLines: 12,
controller: _nameController,
- decoration: const InputDecoration(
- hintText: '(Optional) Suggest File Name',
- ),
+ decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'),
),
),
SizedBox(
@@ -59,9 +54,7 @@
minLines: 1,
maxLines: 12,
controller: _contentController,
- decoration: const InputDecoration(
- hintText: 'Enter File Contents',
- ),
+ decoration: const InputDecoration(hintText: 'Enter File Contents'),
),
),
const SizedBox(height: 10),
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 f80c9f6..e8d7fe4 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
@@ -29,9 +29,7 @@
final List<String> paths = await _hostApi.showFileChooser(
PlatformFileChooserActionType.open,
PlatformFileChooserOptions(
- allowedFileTypes: _platformTypeGroupsFromXTypeGroups(
- acceptedTypeGroups,
- ),
+ allowedFileTypes: _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups),
currentFolderPath: initialDirectory,
acceptButtonLabel: confirmButtonText,
selectMultiple: false,
@@ -49,9 +47,7 @@
final List<String> paths = await _hostApi.showFileChooser(
PlatformFileChooserActionType.open,
PlatformFileChooserOptions(
- allowedFileTypes: _platformTypeGroupsFromXTypeGroups(
- acceptedTypeGroups,
- ),
+ allowedFileTypes: _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups),
currentFolderPath: initialDirectory,
acceptButtonLabel: confirmButtonText,
selectMultiple: true,
@@ -88,9 +84,7 @@
final List<String> paths = await _hostApi.showFileChooser(
PlatformFileChooserActionType.save,
PlatformFileChooserOptions(
- allowedFileTypes: _platformTypeGroupsFromXTypeGroups(
- acceptedTypeGroups,
- ),
+ allowedFileTypes: _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups),
currentFolderPath: options.initialDirectory,
currentName: options.suggestedName,
acceptButtonLabel: options.confirmButtonText,
@@ -101,15 +95,9 @@
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async {
return getDirectoryPathWithOptions(
- FileDialogOptions(
- initialDirectory: initialDirectory,
- confirmButtonText: confirmButtonText,
- ),
+ FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText),
);
}
@@ -133,17 +121,12 @@
String? confirmButtonText,
}) async {
return getDirectoryPathsWithOptions(
- FileDialogOptions(
- initialDirectory: initialDirectory,
- confirmButtonText: confirmButtonText,
- ),
+ FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText),
);
}
@override
- Future<List<String>> getDirectoryPathsWithOptions(
- FileDialogOptions options,
- ) async {
+ Future<List<String>> getDirectoryPathsWithOptions(FileDialogOptions options) async {
return _hostApi.showFileChooser(
PlatformFileChooserActionType.chooseDirectory,
PlatformFileChooserOptions(
@@ -156,9 +139,7 @@
}
}
-List<PlatformTypeGroup>? _platformTypeGroupsFromXTypeGroups(
- List<XTypeGroup>? groups,
-) {
+List<PlatformTypeGroup>? _platformTypeGroupsFromXTypeGroups(List<XTypeGroup>? groups) {
return groups?.map(_platformTypeGroupFromXTypeGroup).toList();
}
@@ -167,8 +148,7 @@
if (group.allowsAny) {
return PlatformTypeGroup(label: label, extensions: <String>['*']);
}
- if ((group.extensions?.isEmpty ?? true) &&
- (group.mimeTypes?.isEmpty ?? true)) {
+ 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 '
@@ -179,9 +159,7 @@
return PlatformTypeGroup(
label: label,
// Covert to GtkFileFilter's *.<extension> format.
- extensions:
- group.extensions?.map((String extension) => '*.$extension').toList() ??
- <String>[],
+ extensions: group.extensions?.map((String extension) => '*.$extension').toList() ?? <String>[],
mimeTypes: group.mimeTypes ?? <String>[],
);
}
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 592db03..464fe87 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
@@ -21,9 +21,7 @@
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 &&
@@ -136,8 +134,7 @@
static PlatformFileChooserOptions decode(Object result) {
result as List<Object?>;
return PlatformFileChooserOptions(
- allowedFileTypes: (result[0] as List<Object?>?)
- ?.cast<PlatformTypeGroup>(),
+ allowedFileTypes: (result[0] as List<Object?>?)?.cast<PlatformTypeGroup>(),
currentFolderPath: result[1] as String?,
currentName: result[2] as String?,
acceptButtonLabel: result[3] as String?,
@@ -149,8 +146,7 @@
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
- if (other is! PlatformFileChooserOptions ||
- other.runtimeType != runtimeType) {
+ if (other is! PlatformFileChooserOptions || other.runtimeType != runtimeType) {
return false;
}
if (identical(this, other)) {
@@ -190,9 +186,7 @@
switch (type) {
case 129:
final int? value = readValue(buffer) as int?;
- return value == null
- ? null
- : PlatformFileChooserActionType.values[value];
+ return value == null ? null : PlatformFileChooserActionType.values[value];
case 130:
return PlatformTypeGroup.decode(readValue(buffer)!);
case 131:
@@ -207,13 +201,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -230,17 +222,13 @@
) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_linux.FileSelectorApi.showFileChooser$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[type, options],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[type, options]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
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 01c068d..b5fc165 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,21 +58,11 @@
expect(api.passedOptions?.allowedFileTypes?[0].label, group.label);
// Extensions should be converted to *.<extension> format.
- expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>[
- '*.txt',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[0].mimeTypes,
- group.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>['*.txt']);
+ expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes);
expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label);
- expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>[
- '*.jpg',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[1].mimeTypes,
- groupTwo.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>['*.jpg']);
+ expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes);
});
test('passes initialDirectory correctly', () async {
@@ -90,10 +80,7 @@
});
test('throws for a type group that does not support Linux', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -141,21 +128,11 @@
expect(api.passedOptions?.allowedFileTypes?[0].label, group.label);
// Extensions should be converted to *.<extension> format.
- expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>[
- '*.txt',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[0].mimeTypes,
- group.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>['*.txt']);
+ expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes);
expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label);
- expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>[
- '*.jpg',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[1].mimeTypes,
- groupTwo.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>['*.jpg']);
+ expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes);
});
test('passes initialDirectory correctly', () async {
@@ -173,10 +150,7 @@
});
test('throws for a type group that does not support Linux', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -216,52 +190,33 @@
mimeTypes: <String>['image/jpg'],
);
- await plugin.getSaveLocation(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expect(api.passedOptions?.allowedFileTypes?[0].label, group.label);
// Extensions should be converted to *.<extension> format.
- expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>[
- '*.txt',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[0].mimeTypes,
- group.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>['*.txt']);
+ expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes);
expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label);
- expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>[
- '*.jpg',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[1].mimeTypes,
- groupTwo.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>['*.jpg']);
+ expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes);
});
test('passes initialDirectory correctly', () async {
const path = '/example/directory';
- await plugin.getSaveLocation(
- options: const SaveDialogOptions(initialDirectory: path),
- );
+ await plugin.getSaveLocation(options: const SaveDialogOptions(initialDirectory: path));
expect(api.passedOptions?.currentFolderPath, path);
});
test('passes confirmButtonText correctly', () async {
const button = 'Open File';
- await plugin.getSaveLocation(
- options: const SaveDialogOptions(confirmButtonText: button),
- );
+ await plugin.getSaveLocation(options: const SaveDialogOptions(confirmButtonText: button));
expect(api.passedOptions?.acceptButtonLabel, button);
});
test('throws for a type group that does not support Linux', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -301,27 +256,15 @@
mimeTypes: <String>['image/jpg'],
);
- await plugin.getSavePath(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expect(api.passedOptions?.allowedFileTypes?[0].label, group.label);
// Extensions should be converted to *.<extension> format.
- expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>[
- '*.txt',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[0].mimeTypes,
- group.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[0].extensions, <String>['*.txt']);
+ expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes);
expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label);
- expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>[
- '*.jpg',
- ]);
- expect(
- api.passedOptions?.allowedFileTypes?[1].mimeTypes,
- groupTwo.mimeTypes,
- );
+ expect(api.passedOptions?.allowedFileTypes?[1].extensions, <String>['*.jpg']);
+ expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes);
});
test('passes initialDirectory correctly', () async {
@@ -339,10 +282,7 @@
});
test('throws for a type group that does not support Linux', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -390,10 +330,7 @@
const path = '/foo/bar';
api.result = <String>[path];
- expect(
- await plugin.getDirectoryPathWithOptions(const FileDialogOptions()),
- path,
- );
+ expect(await plugin.getDirectoryPathWithOptions(const FileDialogOptions()), path);
expect(api.passedType, PlatformFileChooserActionType.chooseDirectory);
expect(api.passedOptions?.selectMultiple, false);
@@ -401,25 +338,19 @@
test('passes initialDirectory correctly', () async {
const path = '/example/directory';
- await plugin.getDirectoryPathWithOptions(
- const FileDialogOptions(initialDirectory: path),
- );
+ await plugin.getDirectoryPathWithOptions(const FileDialogOptions(initialDirectory: path));
expect(api.passedOptions?.currentFolderPath, path);
});
test('passes confirmButtonText correctly', () async {
const button = 'Select Folder';
- await plugin.getDirectoryPathWithOptions(
- const FileDialogOptions(confirmButtonText: button),
- );
+ await plugin.getDirectoryPathWithOptions(const FileDialogOptions(confirmButtonText: button));
expect(api.passedOptions?.acceptButtonLabel, button);
});
test('passes canCreateDirectories correctly', () async {
- await plugin.getDirectoryPathWithOptions(
- const FileDialogOptions(canCreateDirectories: true),
- );
+ await plugin.getDirectoryPathWithOptions(const FileDialogOptions(canCreateDirectories: true));
expect(api.passedOptions?.createFolders, true);
});
});
@@ -459,10 +390,7 @@
test('passes the core flags correctly', () async {
api.result = <String>['/foo/bar', 'baz'];
- expect(
- await plugin.getDirectoryPathsWithOptions(const FileDialogOptions()),
- api.result,
- );
+ expect(await plugin.getDirectoryPathsWithOptions(const FileDialogOptions()), api.result);
expect(api.passedType, PlatformFileChooserActionType.chooseDirectory);
expect(api.passedOptions?.selectMultiple, true);
@@ -470,18 +398,14 @@
test('passes initialDirectory correctly', () async {
const path = '/example/directory';
- await plugin.getDirectoryPathsWithOptions(
- const FileDialogOptions(initialDirectory: path),
- );
+ await plugin.getDirectoryPathsWithOptions(const FileDialogOptions(initialDirectory: path));
expect(api.passedOptions?.currentFolderPath, path);
});
test('passes confirmButtonText correctly', () async {
const button = 'Select one or mode folders';
- await plugin.getDirectoryPathsWithOptions(
- const FileDialogOptions(confirmButtonText: button),
- );
+ await plugin.getDirectoryPathsWithOptions(const FileDialogOptions(confirmButtonText: button));
expect(api.passedOptions?.acceptButtonLabel, button);
});
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 065f5c0..b3150be 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,13 +13,9 @@
Future<void> _getDirectoryPath(BuildContext context) async {
const confirmButtonText = 'Choose';
- final String? directoryPath = await FileSelectorPlatform.instance
- .getDirectoryPathWithOptions(
- const FileDialogOptions(
- confirmButtonText: confirmButtonText,
- canCreateDirectories: true,
- ),
- );
+ final String? directoryPath = await FileSelectorPlatform.instance.getDirectoryPathWithOptions(
+ const FileDialogOptions(confirmButtonText: confirmButtonText, canCreateDirectories: true),
+ );
if (directoryPath == null) {
// Operation was canceled by the user.
return;
@@ -67,14 +63,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directory'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoryPath)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 18ae7f5..a2c5df7 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
@@ -15,10 +15,7 @@
const confirmButtonText = 'Choose';
final List<String?> directoriesPaths = await FileSelectorPlatform.instance
.getDirectoryPathsWithOptions(
- const FileDialogOptions(
- confirmButtonText: confirmButtonText,
- canCreateDirectories: true,
- ),
+ const FileDialogOptions(confirmButtonText: confirmButtonText, canCreateDirectories: true),
);
if (directoriesPaths.isEmpty) {
// Operation was canceled by the user.
@@ -27,8 +24,7 @@
if (context.mounted) {
await showDialog<void>(
context: context,
- builder: (BuildContext context) =>
- TextDisplay(directoriesPaths.join('\n')),
+ builder: (BuildContext context) => TextDisplay(directoriesPaths.join('\n')),
);
}
}
@@ -46,9 +42,7 @@
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
- child: const Text(
- 'Press to ask user to choose multiple directories',
- ),
+ child: const Text('Press to ask user to choose multiple directories'),
onPressed: () => _getDirectoryPaths(context),
),
],
@@ -70,14 +64,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directories'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoryPaths)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPaths))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 b498848..f90d366 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
@@ -54,8 +54,7 @@
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 28a3420..4fefa8b 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,11 @@
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/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 6554cbf..5983fa5 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
@@ -15,10 +15,7 @@
const OpenImagePage({super.key});
Future<void> _openImageFile(BuildContext context) async {
- const typeGroup = XTypeGroup(
- label: 'images',
- extensions: <String>['jpg', 'png'],
- );
+ const typeGroup = XTypeGroup(label: 'images', extensions: <String>['jpg', 'png']);
final XFile? file = await FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
);
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 da7e307..da35dc5 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
@@ -15,10 +15,7 @@
const OpenMultipleImagesPage({super.key});
Future<void> _openImageFile(BuildContext context) async {
- const jpgsTypeGroup = XTypeGroup(
- label: 'JPEGs',
- extensions: <String>['jpg', 'jpeg'],
- );
+ const jpgsTypeGroup = XTypeGroup(label: 'JPEGs', extensions: <String>['jpg', 'jpeg']);
const pngTypeGroup = XTypeGroup(label: 'PNGs', extensions: <String>['png']);
final List<XFile> files = await FileSelectorPlatform.instance.openFiles(
acceptedTypeGroups: <XTypeGroup>[jpgsTypeGroup, pngTypeGroup],
@@ -76,11 +73,8 @@
child: Row(
children: <Widget>[
...files.map(
- (XFile file) => Flexible(
- child: kIsWeb
- ? Image.network(file.path)
- : Image.file(File(file.path)),
- ),
+ (XFile file) =>
+ Flexible(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 023cd8c..5b5abbc 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
@@ -12,10 +12,7 @@
const OpenTextPage({super.key});
Future<void> _openTextFile(BuildContext context) async {
- const typeGroup = XTypeGroup(
- label: 'text',
- extensions: <String>['txt', 'json'],
- );
+ const typeGroup = XTypeGroup(label: 'text', extensions: <String>['txt', 'json']);
final XFile? file = await FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
);
@@ -72,14 +69,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(fileContent)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 b7847bd..f86e1bb 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,8 +17,9 @@
Future<void> _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;
@@ -26,11 +27,7 @@
final String text = _contentController.text;
final fileData = Uint8List.fromList(text.codeUnits);
const fileMimeType = 'text/plain';
- final textFile = XFile.fromData(
- fileData,
- mimeType: fileMimeType,
- name: fileName,
- );
+ final textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName);
await textFile.saveTo(result.path);
}
@@ -48,9 +45,7 @@
minLines: 1,
maxLines: 12,
controller: _nameController,
- decoration: const InputDecoration(
- hintText: '(Optional) Suggest File Name',
- ),
+ decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'),
),
),
SizedBox(
@@ -59,9 +54,7 @@
minLines: 1,
maxLines: 12,
controller: _contentController,
- decoration: const InputDecoration(
- hintText: 'Enter File Contents',
- ),
+ decoration: const InputDecoration(hintText: 'Enter File Contents'),
),
),
const SizedBox(height: 10),
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 c534e43..761f466 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
@@ -98,15 +98,9 @@
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async {
return getDirectoryPathWithOptions(
- FileDialogOptions(
- initialDirectory: initialDirectory,
- confirmButtonText: confirmButtonText,
- ),
+ FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText),
);
}
@@ -133,17 +127,12 @@
String? confirmButtonText,
}) async {
return getDirectoryPathsWithOptions(
- FileDialogOptions(
- initialDirectory: initialDirectory,
- confirmButtonText: confirmButtonText,
- ),
+ FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText),
);
}
@override
- Future<List<String>> getDirectoryPathsWithOptions(
- FileDialogOptions options,
- ) async {
+ Future<List<String>> getDirectoryPathsWithOptions(FileDialogOptions options) async {
final List<String?> paths = await _hostApi.displayOpenPanel(
OpenPanelOptions(
allowsMultipleSelection: true,
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 f91bc53..8e62534 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
@@ -21,9 +21,7 @@
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 &&
@@ -169,12 +167,7 @@
SavePanelOptions baseOptions;
List<Object?> _toList() {
- return <Object?>[
- allowsMultipleSelection,
- canChooseDirectories,
- canChooseFiles,
- baseOptions,
- ];
+ return <Object?>[allowsMultipleSelection, canChooseDirectories, canChooseFiles, baseOptions];
}
Object encode() {
@@ -248,13 +241,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -268,17 +259,13 @@
Future<List<String>> displayOpenPanel(OpenPanelOptions options) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[options],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[options]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -303,17 +290,13 @@
Future<String?> displaySavePanel(SavePanelOptions options) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[options],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[options]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
diff --git a/packages/file_selector/file_selector_macos/pigeons/messages.dart b/packages/file_selector/file_selector_macos/pigeons/messages.dart
index e65780f..eda934e 100644
--- a/packages/file_selector/file_selector_macos/pigeons/messages.dart
+++ b/packages/file_selector/file_selector_macos/pigeons/messages.dart
@@ -6,8 +6,7 @@
@ConfigurePigeon(
PigeonOptions(
input: 'pigeons/messages.dart',
- swiftOut:
- 'macos/file_selector_macos/Sources/file_selector_macos/messages.g.swift',
+ swiftOut: 'macos/file_selector_macos/Sources/file_selector_macos/messages.g.swift',
dartOut: 'lib/src/messages.g.dart',
copyrightHeader: 'pigeons/copyright.txt',
),
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 58563dd..9797350 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
@@ -68,18 +68,9 @@
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final OpenPanelOptions options = api.passedOpenPanelOptions!;
- expect(options.baseOptions.allowedFileTypes!.extensions, <String>[
- 'txt',
- 'jpg',
- ]);
- expect(options.baseOptions.allowedFileTypes!.mimeTypes, <String>[
- 'text/plain',
- 'image/jpg',
- ]);
- expect(options.baseOptions.allowedFileTypes!.utis, <String>[
- 'public.text',
- 'public.image',
- ]);
+ expect(options.baseOptions.allowedFileTypes!.extensions, <String>['txt', 'jpg']);
+ expect(options.baseOptions.allowedFileTypes!.mimeTypes, <String>['text/plain', 'image/jpg']);
+ expect(options.baseOptions.allowedFileTypes!.utis, <String>['public.text', 'public.image']);
});
test('passes initialDirectory correctly', () async {
@@ -97,10 +88,7 @@
});
test('throws for a type group that does not support macOS', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -111,10 +99,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
@@ -163,18 +148,9 @@
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final OpenPanelOptions options = api.passedOpenPanelOptions!;
- expect(options.baseOptions.allowedFileTypes!.extensions, <String>[
- 'txt',
- 'jpg',
- ]);
- expect(options.baseOptions.allowedFileTypes!.mimeTypes, <String>[
- 'text/plain',
- 'image/jpg',
- ]);
- expect(options.baseOptions.allowedFileTypes!.utis, <String>[
- 'public.text',
- 'public.image',
- ]);
+ expect(options.baseOptions.allowedFileTypes!.extensions, <String>['txt', 'jpg']);
+ expect(options.baseOptions.allowedFileTypes!.mimeTypes, <String>['text/plain', 'image/jpg']);
+ expect(options.baseOptions.allowedFileTypes!.utis, <String>['public.text', 'public.image']);
});
test('passes initialDirectory correctly', () async {
@@ -192,10 +168,7 @@
});
test('throws for a type group that does not support macOS', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -206,10 +179,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
@@ -251,20 +221,12 @@
webWildCards: <String>['image/*'],
);
- await plugin.getSavePath(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final SavePanelOptions options = api.passedSavePanelOptions!;
expect(options.allowedFileTypes!.extensions, <String>['txt', 'jpg']);
- expect(options.allowedFileTypes!.mimeTypes, <String>[
- 'text/plain',
- 'image/jpg',
- ]);
- expect(options.allowedFileTypes!.utis, <String>[
- 'public.text',
- 'public.image',
- ]);
+ expect(options.allowedFileTypes!.mimeTypes, <String>['text/plain', 'image/jpg']);
+ expect(options.allowedFileTypes!.utis, <String>['public.text', 'public.image']);
});
test('passes initialDirectory correctly', () async {
@@ -282,10 +244,7 @@
});
test('throws for a type group that does not support macOS', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -296,10 +255,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
test('ignores all type groups if any of them is a wildcard', () async {
@@ -364,27 +320,17 @@
webWildCards: <String>['image/*'],
);
- await plugin.getSaveLocation(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final SavePanelOptions options = api.passedSavePanelOptions!;
expect(options.allowedFileTypes!.extensions, <String>['txt', 'jpg']);
- expect(options.allowedFileTypes!.mimeTypes, <String>[
- 'text/plain',
- 'image/jpg',
- ]);
- expect(options.allowedFileTypes!.utis, <String>[
- 'public.text',
- 'public.image',
- ]);
+ expect(options.allowedFileTypes!.mimeTypes, <String>['text/plain', 'image/jpg']);
+ expect(options.allowedFileTypes!.utis, <String>['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 SavePanelOptions options = api.passedSavePanelOptions!;
@@ -401,10 +347,7 @@
});
test('throws for a type group that does not support macOS', () async {
- const group = XTypeGroup(
- label: 'images',
- webWildCards: <String>['images/*'],
- );
+ const group = XTypeGroup(label: 'images', webWildCards: <String>['images/*']);
await expectLater(
plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -415,10 +358,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
test('ignores all type groups if any of them is a wildcard', () async {
@@ -489,9 +429,7 @@
test('works as expected with no arguments', () async {
api.result = <String>['foo'];
- final String? path = await plugin.getDirectoryPathWithOptions(
- const FileDialogOptions(),
- );
+ final String? path = await plugin.getDirectoryPathWithOptions(const FileDialogOptions());
expect(path, 'foo');
final OpenPanelOptions options = api.passedOpenPanelOptions!;
@@ -543,19 +481,11 @@
group('getDirectoryPaths', () {
test('works as expected with no arguments', () async {
- api.result = <String>[
- 'firstDirectory',
- 'secondDirectory',
- 'thirdDirectory',
- ];
+ api.result = <String>['firstDirectory', 'secondDirectory', 'thirdDirectory'];
final List<String> path = await plugin.getDirectoryPaths();
- expect(path, <String>[
- 'firstDirectory',
- 'secondDirectory',
- 'thirdDirectory',
- ]);
+ expect(path, <String>['firstDirectory', 'secondDirectory', 'thirdDirectory']);
final OpenPanelOptions options = api.passedOpenPanelOptions!;
expect(options.allowsMultipleSelection, true);
expect(options.canChooseFiles, false);
@@ -591,21 +521,13 @@
group('getDirectoryPathsWithOptions', () {
test('works as expected with no arguments', () async {
- api.result = <String>[
- 'firstDirectory',
- 'secondDirectory',
- 'thirdDirectory',
- ];
+ api.result = <String>['firstDirectory', 'secondDirectory', 'thirdDirectory'];
final List<String> path = await plugin.getDirectoryPathsWithOptions(
const FileDialogOptions(),
);
- expect(path, <String>[
- 'firstDirectory',
- 'secondDirectory',
- 'thirdDirectory',
- ]);
+ expect(path, <String>['firstDirectory', 'secondDirectory', 'thirdDirectory']);
final OpenPanelOptions options = api.passedOpenPanelOptions!;
expect(options.allowsMultipleSelection, true);
expect(options.canChooseFiles, false);
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 a39a189..29961b3 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,9 +7,7 @@
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 {
@@ -61,9 +59,7 @@
String? confirmButtonText,
}) async {
return _channel.invokeMethod<String>('getSavePath', <String, dynamic>{
- 'acceptedTypeGroups': acceptedTypeGroups
- ?.map((XTypeGroup group) => group.toJSON())
- .toList(),
+ 'acceptedTypeGroups': acceptedTypeGroups?.map((XTypeGroup group) => group.toJSON()).toList(),
'initialDirectory': initialDirectory,
'suggestedName': suggestedName,
'confirmButtonText': confirmButtonText,
@@ -71,10 +67,7 @@
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async {
return _channel.invokeMethod<String>('getDirectoryPath', <String, dynamic>{
'initialDirectory': initialDirectory,
'confirmButtonText': confirmButtonText,
diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart b/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart
index 97c5968..c32ecef 100644
--- a/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart
+++ b/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart
@@ -97,10 +97,7 @@
///
/// Returns `null` if the user cancels the operation.
@Deprecated('Use getDirectoryPathWithOptions instead')
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) {
throw UnimplementedError('getDirectoryPath() has not been implemented.');
}
@@ -122,10 +119,7 @@
///
/// Returns an empty list if the user cancels the operation.
@Deprecated('Use getDirectoryPathsWithOptions instead')
- Future<List<String>> getDirectoryPaths({
- String? initialDirectory,
- String? confirmButtonText,
- }) {
+ Future<List<String>> getDirectoryPaths({String? initialDirectory, String? confirmButtonText}) {
throw UnimplementedError('getDirectoryPaths() has not been implemented.');
}
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 12761e9..fffba3c 100644
--- a/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart
+++ b/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart
@@ -70,7 +70,6 @@
@Deprecated('Use uniformTypeIdentifiers instead')
List<String>? get macUTIs => uniformTypeIdentifiers;
- static List<String>? _removeLeadingDots(List<String>? exts) => exts
- ?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext)
- .toList();
+ static List<String>? _removeLeadingDots(List<String>? exts) =>
+ exts?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext).toList();
}
diff --git a/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart b/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart
index 541897b..90bdce1 100644
--- a/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart
+++ b/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart
@@ -32,8 +32,7 @@
group('getDirectoryPathWithOptions', () {
test('Should fall back to getDirectoryPath by default', () async {
- final FileSelectorPlatform fileSelector =
- OldFileSelectorPlatformImplementation();
+ final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation();
final String? result = await fileSelector.getDirectoryPathWithOptions(
const FileDialogOptions(),
@@ -56,22 +55,19 @@
group('getDirectoryPathsWithOptions', () {
test('Should fall back to getDirectoryPaths by default', () async {
- final FileSelectorPlatform fileSelector =
- OldFileSelectorPlatformImplementation();
+ final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation();
- final List<String> result = await fileSelector
- .getDirectoryPathsWithOptions(const FileDialogOptions());
+ final List<String> result = await fileSelector.getDirectoryPathsWithOptions(
+ const FileDialogOptions(),
+ );
// Should call the old method and return its result
- expect(result, <String>[
- OldFileSelectorPlatformImplementation.directoryPath,
- ]);
+ expect(result, <String>[OldFileSelectorPlatformImplementation.directoryPath]);
});
});
test('getSaveLocation falls back to getSavePath by default', () async {
- final FileSelectorPlatform fileSelector =
- OldFileSelectorPlatformImplementation();
+ final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation();
final FileSaveLocation? result = await fileSelector.getSaveLocation();
@@ -97,10 +93,7 @@
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async {
return directoryPath;
}
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 12b3839..77b0010 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
@@ -16,13 +16,13 @@
final log = <MethodCall>[];
setUp(() {
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(plugin.channel, (
- MethodCall methodCall,
- ) async {
- log.add(methodCall);
- return null;
- });
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ plugin.channel,
+ (MethodCall methodCall) async {
+ log.add(methodCall);
+ return null;
+ },
+ );
log.clear();
});
@@ -44,18 +44,13 @@
webWildCards: <String>['image/*'],
);
- await plugin.openFile(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
- 'acceptedTypeGroups': <Map<String, dynamic>>[
- group.toJSON(),
- groupTwo.toJSON(),
- ],
+ 'acceptedTypeGroups': <Map<String, dynamic>>[group.toJSON(), groupTwo.toJSON()],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
@@ -108,18 +103,13 @@
webWildCards: <String>['image/*'],
);
- await plugin.openFiles(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
- 'acceptedTypeGroups': <Map<String, dynamic>>[
- group.toJSON(),
- groupTwo.toJSON(),
- ],
+ 'acceptedTypeGroups': <Map<String, dynamic>>[group.toJSON(), groupTwo.toJSON()],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
@@ -173,18 +163,13 @@
webWildCards: <String>['image/*'],
);
- await plugin.getSavePath(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
- 'acceptedTypeGroups': <Map<String, dynamic>>[
- group.toJSON(),
- groupTwo.toJSON(),
- ],
+ 'acceptedTypeGroups': <Map<String, dynamic>>[group.toJSON(), groupTwo.toJSON()],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
@@ -260,9 +245,7 @@
);
});
test('passes confirmButtonText correctly', () async {
- await plugin.getDirectoryPaths(
- confirmButtonText: 'Select one or more Folders',
- );
+ await plugin.getDirectoryPaths(confirmButtonText: 'Select one or more Folders');
expectMethodCall(
log,
@@ -277,10 +260,6 @@
});
}
-void expectMethodCall(
- List<MethodCall> log,
- String methodName, {
- Map<String, dynamic>? arguments,
-}) {
+void expectMethodCall(List<MethodCall> log, String methodName, {Map<String, dynamic>? arguments}) {
expect(log, <Matcher>[isMethodCall(methodName, arguments: arguments)]);
}
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 795fe33..5bac916 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
@@ -55,18 +55,9 @@
});
test('allowsAny returns false if anything is set', () {
- const extensionOnly = XTypeGroup(
- label: 'extensions',
- extensions: <String>['txt'],
- );
- const mimeOnly = XTypeGroup(
- label: 'mime',
- mimeTypes: <String>['text/plain'],
- );
- const utiOnly = XTypeGroup(
- label: 'utis',
- uniformTypeIdentifiers: <String>['public.text'],
- );
+ const extensionOnly = XTypeGroup(label: 'extensions', extensions: <String>['txt']);
+ const mimeOnly = XTypeGroup(label: 'mime', mimeTypes: <String>['text/plain']);
+ const utiOnly = XTypeGroup(label: 'utis', uniformTypeIdentifiers: <String>['public.text']);
const webOnly = XTypeGroup(label: 'web', webWildCards: <String>['.txt']);
expect(extensionOnly.allowsAny, false);
@@ -83,17 +74,12 @@
expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers);
});
- test(
- 'passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers',
- () {
- const uniformTypeIdentifiers = <String>['public.plain-text'];
- const group = XTypeGroup(
- uniformTypeIdentifiers: uniformTypeIdentifiers,
- );
+ test('passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers', () {
+ const uniformTypeIdentifiers = <String>['public.plain-text'];
+ const group = XTypeGroup(uniformTypeIdentifiers: uniformTypeIdentifiers);
- expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers);
- },
- );
+ expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers);
+ });
test('macUTIs getter return macUTIs value passed in constructor', () {
const uniformTypeIdentifiers = <String>['public.plain-text'];
@@ -102,17 +88,12 @@
expect(group.macUTIs, uniformTypeIdentifiers);
});
- test(
- 'macUTIs getter returns uniformTypeIdentifiers value passed in constructor',
- () {
- const uniformTypeIdentifiers = <String>['public.plain-text'];
- const group = XTypeGroup(
- uniformTypeIdentifiers: uniformTypeIdentifiers,
- );
+ test('macUTIs getter returns uniformTypeIdentifiers value passed in constructor', () {
+ const uniformTypeIdentifiers = <String>['public.plain-text'];
+ const group = XTypeGroup(uniformTypeIdentifiers: uniformTypeIdentifiers);
- expect(group.macUTIs, uniformTypeIdentifiers);
- },
- );
+ expect(group.macUTIs, uniformTypeIdentifiers);
+ });
test('passing both uniformTypeIdentifiers and macUTIs should throw', () {
expect(
@@ -124,8 +105,7 @@
predicate(
(Object? e) =>
e is AssertionError &&
- e.message ==
- 'Only one of uniformTypeIdentifiers or macUTIs can be non-null',
+ e.message == 'Only one of uniformTypeIdentifiers or macUTIs can be non-null',
),
),
);
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 c04102e..234affc 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,7 @@
setUp(() {
domHelper = DomHelper();
- input = (document.createElement('input') as HTMLInputElement)
- ..type = 'file';
+ input = (document.createElement('input') as HTMLInputElement)..type = 'file';
});
group('getFiles', () {
@@ -51,16 +50,10 @@
'file1.txt',
FilePropertyBag(type: 'text/plain'),
);
- final mockFile2 = File(
- <JSAny>[].toJS,
- 'file2.txt',
- FilePropertyBag(type: 'text/plain'),
- );
+ final mockFile2 = File(<JSAny>[].toJS, 'file2.txt', FilePropertyBag(type: 'text/plain'));
testWidgets('works', (_) async {
- final Future<List<XFile>> futureFiles = domHelper.getFiles(
- input: input,
- );
+ final Future<List<XFile>> futureFiles = domHelper.getFiles(input: input);
setFilesAndTriggerChange(<File>[mockFile1, mockFile2]);
@@ -82,9 +75,7 @@
});
testWidgets('"cancel" returns an empty selection', (_) async {
- final Future<List<XFile>> futureFiles = domHelper.getFiles(
- input: input,
- );
+ final Future<List<XFile>> futureFiles = domHelper.getFiles(input: input);
setFilesAndTriggerCancel(<File>[mockFile1, mockFile2]);
@@ -127,18 +118,13 @@
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 <input /> should be clicked otherwise no dialog will be shown',
+ reason: 'The <input /> should be clicked otherwise no dialog will be shown',
);
setFilesAndTriggerChange(<File>[]);
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 e36b79d..2096009 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
@@ -17,11 +17,7 @@
group('openFile', () {
testWidgets('works', (WidgetTester _) async {
- final XFile mockFile = createXFile(
- '1001',
- 'identity.png',
- mimeType: 'image/png',
- );
+ final XFile mockFile = createXFile('1001', 'identity.png', mimeType: 'image/png');
final mockDomHelper = MockDomHelper(
files: <XFile>[mockFile],
@@ -37,9 +33,7 @@
webWildCards: <String>['image/*'],
);
- final XFile? file = await plugin.openFile(
- acceptedTypeGroups: <XTypeGroup>[typeGroup],
- );
+ final XFile? file = await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
expect(file, isNotNull);
expect(file!.name, mockFile.name);
@@ -49,9 +43,7 @@
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(files: <XFile>[]);
@@ -76,10 +68,7 @@
final plugin = FileSelectorWeb(domHelper: mockDomHelper);
- const typeGroup = XTypeGroup(
- label: 'files',
- extensions: <String>['.txt'],
- );
+ const typeGroup = XTypeGroup(label: 'files', extensions: <String>['.txt']);
final List<XFile> files = await plugin.openFiles(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
@@ -128,30 +117,13 @@
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<List<XFile>>.value(_files);
}
}
-XFile createXFile(
- String content,
- String name, {
- String mimeType = 'text/plain',
-}) {
+XFile createXFile(String content, String name, {String mimeType = 'text/plain'}) {
final data = Uint8List.fromList(content.codeUnits);
- return XFile.fromData(
- data,
- name: name,
- lastModified: DateTime.now(),
- mimeType: mimeType,
- );
+ return XFile.fromData(data, name: name, lastModified: DateTime.now(), mimeType: mimeType);
}
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 381cd6c..baf0507 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
@@ -34,9 +34,7 @@
String? initialDirectory,
String? confirmButtonText,
}) async {
- final List<XFile> files = await _openFiles(
- acceptedTypeGroups: acceptedTypeGroups,
- );
+ final List<XFile> files = await _openFiles(acceptedTypeGroups: acceptedTypeGroups);
return files.isNotEmpty ? files.first : null;
}
@@ -71,10 +69,8 @@
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async => null;
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async =>
+ null;
Future<List<XFile>> _openFiles({
List<XTypeGroup>? acceptedTypeGroups,
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 f043116..e6a79ac 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
@@ -48,10 +48,7 @@
inputElement.onError.first.then((Event event) {
final error = event as ErrorEvent;
- final platformException = PlatformException(
- code: error.type,
- message: error.message,
- );
+ final platformException = PlatformException(code: error.type, message: error.message);
inputElement.remove();
completer.completeError(platformException);
});
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 33d76d4..afc509a 100644
--- a/packages/file_selector/file_selector_web/test/utils_test.dart
+++ b/packages/file_selector/file_selector_web/test/utils_test.dart
@@ -39,10 +39,7 @@
test('works with mime types', () {
const acceptedTypes = <XTypeGroup>[
- XTypeGroup(
- label: 'jpgs',
- mimeTypes: <String>['image/jpeg', 'image/jpg'],
- ),
+ XTypeGroup(label: 'jpgs', mimeTypes: <String>['image/jpeg', 'image/jpg']),
XTypeGroup(label: 'pngs', mimeTypes: <String>['image/png']),
];
final String accepts = acceptedTypesToString(acceptedTypes);
@@ -61,10 +58,7 @@
test('throws for a type group that does not support web', () {
const acceptedTypes = <XTypeGroup>[
- XTypeGroup(
- label: 'text',
- uniformTypeIdentifiers: <String>['public.text'],
- ),
+ XTypeGroup(label: 'text', uniformTypeIdentifiers: <String>['public.text']),
];
expect(() => acceptedTypesToString(acceptedTypes), throwsArgumentError);
});
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 4e3fa86..718f67d 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,9 @@
Future<void> _getDirectoryPath(BuildContext context) async {
const confirmButtonText = 'Choose';
- final String? directoryPath = await FileSelectorPlatform.instance
- .getDirectoryPathWithOptions(
- const FileDialogOptions(confirmButtonText: confirmButtonText),
- );
+ final String? directoryPath = await FileSelectorPlatform.instance.getDirectoryPathWithOptions(
+ const FileDialogOptions(confirmButtonText: confirmButtonText),
+ );
if (directoryPath == null) {
// Operation was canceled by the user.
return;
@@ -64,14 +63,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directory'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoryPath)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 a4d751e..5abe62a 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
@@ -24,8 +24,7 @@
if (context.mounted) {
await showDialog<void>(
context: context,
- builder: (BuildContext context) =>
- TextDisplay(directoriesPaths.join('\n')),
+ builder: (BuildContext context) => TextDisplay(directoriesPaths.join('\n')),
);
}
}
@@ -43,9 +42,7 @@
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
- child: const Text(
- 'Press to ask user to choose multiple directories',
- ),
+ child: const Text('Press to ask user to choose multiple directories'),
onPressed: () => _getDirectoryPaths(context),
),
],
@@ -67,14 +64,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directories'),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(directoryPaths)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPaths))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 b498848..f90d366 100644
--- a/packages/file_selector/file_selector_windows/example/lib/home_page.dart
+++ b/packages/file_selector/file_selector_windows/example/lib/home_page.dart
@@ -54,8 +54,7 @@
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 28a3420..4fefa8b 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,11 @@
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/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 6554cbf..5983fa5 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
@@ -15,10 +15,7 @@
const OpenImagePage({super.key});
Future<void> _openImageFile(BuildContext context) async {
- const typeGroup = XTypeGroup(
- label: 'images',
- extensions: <String>['jpg', 'png'],
- );
+ const typeGroup = XTypeGroup(label: 'images', extensions: <String>['jpg', 'png']);
final XFile? file = await FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
);
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 da7e307..da35dc5 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
@@ -15,10 +15,7 @@
const OpenMultipleImagesPage({super.key});
Future<void> _openImageFile(BuildContext context) async {
- const jpgsTypeGroup = XTypeGroup(
- label: 'JPEGs',
- extensions: <String>['jpg', 'jpeg'],
- );
+ const jpgsTypeGroup = XTypeGroup(label: 'JPEGs', extensions: <String>['jpg', 'jpeg']);
const pngTypeGroup = XTypeGroup(label: 'PNGs', extensions: <String>['png']);
final List<XFile> files = await FileSelectorPlatform.instance.openFiles(
acceptedTypeGroups: <XTypeGroup>[jpgsTypeGroup, pngTypeGroup],
@@ -76,11 +73,8 @@
child: Row(
children: <Widget>[
...files.map(
- (XFile file) => Flexible(
- child: kIsWeb
- ? Image.network(file.path)
- : Image.file(File(file.path)),
- ),
+ (XFile file) =>
+ Flexible(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 023cd8c..5b5abbc 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
@@ -12,10 +12,7 @@
const OpenTextPage({super.key});
Future<void> _openTextFile(BuildContext context) async {
- const typeGroup = XTypeGroup(
- label: 'text',
- extensions: <String>['txt', 'json'],
- );
+ const typeGroup = XTypeGroup(label: 'text', extensions: <String>['txt', 'json']);
final XFile? file = await FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
);
@@ -72,14 +69,9 @@
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
- content: Scrollbar(
- child: SingleChildScrollView(child: Text(fileContent)),
- ),
+ content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))),
actions: <Widget>[
- TextButton(
- child: const Text('Close'),
- onPressed: () => Navigator.pop(context),
- ),
+ TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)),
],
);
}
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 ff45a7c..0d467b8 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,14 +18,13 @@
Future<void> _saveFile() async {
final String fileName = _nameController.text;
- final FileSaveLocation? result = await FileSelectorPlatform.instance
- .getSaveLocation(
- options: SaveDialogOptions(suggestedName: fileName),
- acceptedTypeGroups: const <XTypeGroup>[
- XTypeGroup(label: 'Plain text', extensions: <String>['txt']),
- XTypeGroup(label: 'JSON', extensions: <String>['json']),
- ],
- );
+ final FileSaveLocation? result = await FileSelectorPlatform.instance.getSaveLocation(
+ options: SaveDialogOptions(suggestedName: fileName),
+ acceptedTypeGroups: const <XTypeGroup>[
+ XTypeGroup(label: 'Plain text', extensions: <String>['txt']),
+ XTypeGroup(label: 'JSON', extensions: <String>['json']),
+ ],
+ );
// Operation was canceled by the user.
if (result == null) {
return;
@@ -61,9 +60,7 @@
minLines: 1,
maxLines: 12,
controller: _nameController,
- decoration: const InputDecoration(
- hintText: '(Optional) Suggest File Name',
- ),
+ decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'),
),
),
SizedBox(
@@ -72,9 +69,7 @@
minLines: 1,
maxLines: 12,
controller: _contentController,
- decoration: const InputDecoration(
- hintText: 'Enter File Contents',
- ),
+ decoration: const InputDecoration(hintText: 'Enter File Contents'),
),
),
const SizedBox(height: 10),
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 fe5b7a9..444d0fe 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
@@ -27,9 +27,7 @@
String? confirmButtonText,
}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
- SelectionOptions(
- allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
- ),
+ SelectionOptions(allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups)),
initialDirectory,
confirmButtonText,
);
@@ -77,9 +75,7 @@
SaveDialogOptions options = const SaveDialogOptions(),
}) async {
final FileDialogResult result = await _hostApi.showSaveDialog(
- SelectionOptions(
- allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
- ),
+ SelectionOptions(allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups)),
options.initialDirectory,
options.suggestedName,
options.confirmButtonText,
@@ -89,17 +85,12 @@
? null
: FileSaveLocation(
result.paths.first,
- activeFilter: groupIndex == null
- ? null
- : acceptedTypeGroups?[groupIndex],
+ activeFilter: groupIndex == null ? null : acceptedTypeGroups?[groupIndex],
);
}
@override
- Future<String?> getDirectoryPath({
- String? initialDirectory,
- String? confirmButtonText,
- }) async {
+ Future<String?> getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
SelectionOptions(selectFolders: true, allowedTypes: <TypeGroup>[]),
initialDirectory,
@@ -114,11 +105,7 @@
String? confirmButtonText,
}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
- SelectionOptions(
- allowMultiple: true,
- selectFolders: true,
- allowedTypes: <TypeGroup>[],
- ),
+ SelectionOptions(allowMultiple: true, selectFolders: true, allowedTypes: <TypeGroup>[]),
initialDirectory,
confirmButtonText,
);
@@ -136,9 +123,6 @@
'anything is non-empty.',
);
}
- return TypeGroup(
- label: xtype.label ?? '',
- extensions: xtype.extensions ?? <String>[],
- );
+ return TypeGroup(label: xtype.label ?? '', extensions: xtype.extensions ?? <String>[]);
}).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 7e2ec3e..633c2a1 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
@@ -21,9 +21,7 @@
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 &&
@@ -211,13 +209,11 @@
/// 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<Object?> pigeonChannelCodec = _PigeonCodec();
@@ -231,17 +227,17 @@
) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[options, initialDirectory, confirmButtonText],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ options,
+ initialDirectory,
+ confirmButtonText,
+ ]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
@@ -268,17 +264,18 @@
) async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog$pigeonVar_messageChannelSuffix';
- final BasicMessageChannel<Object?> pigeonVar_channel =
- BasicMessageChannel<Object?>(
- pigeonVar_channelName,
- pigeonChannelCodec,
- binaryMessenger: pigeonVar_binaryMessenger,
- );
- final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(
- <Object?>[options, initialDirectory, suggestedName, confirmButtonText],
+ final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
+ pigeonVar_channelName,
+ pigeonChannelCodec,
+ binaryMessenger: pigeonVar_binaryMessenger,
);
- final List<Object?>? pigeonVar_replyList =
- await pigeonVar_sendFuture as List<Object?>?;
+ final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
+ options,
+ initialDirectory,
+ suggestedName,
+ confirmButtonText,
+ ]);
+ final List<Object?>? pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
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 30349f9..ed31ed6 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
@@ -75,10 +75,7 @@
});
test('throws for a type group that does not support Windows', () async {
- const group = XTypeGroup(
- label: 'text',
- mimeTypes: <String>['text/plain'],
- );
+ const group = XTypeGroup(label: 'text', mimeTypes: <String>['text/plain']);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -89,10 +86,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
@@ -147,10 +141,7 @@
});
test('throws for a type group that does not support Windows', () async {
- const group = XTypeGroup(
- label: 'text',
- mimeTypes: <String>['text/plain'],
- );
+ const group = XTypeGroup(label: 'text', mimeTypes: <String>['text/plain']);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -161,10 +152,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
@@ -248,9 +236,7 @@
mimeTypes: <String>['image/jpg'],
);
- await plugin.getSaveLocation(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expect(
_typeGroupListsMatch(api.passedOptions!.allowedTypes, <TypeGroup>[
@@ -285,18 +271,14 @@
test('passes initialDirectory correctly', () async {
await plugin.getSaveLocation(
- options: const SaveDialogOptions(
- initialDirectory: '/example/directory',
- ),
+ options: const SaveDialogOptions(initialDirectory: '/example/directory'),
);
expect(api.passedInitialDirectory, '/example/directory');
});
test('passes suggestedName correctly', () async {
- await plugin.getSaveLocation(
- options: const SaveDialogOptions(suggestedName: 'baz.txt'),
- );
+ await plugin.getSaveLocation(options: const SaveDialogOptions(suggestedName: 'baz.txt'));
expect(api.passedSuggestedName, 'baz.txt');
});
@@ -310,10 +292,7 @@
});
test('throws for a type group that does not support Windows', () async {
- const group = XTypeGroup(
- label: 'text',
- mimeTypes: <String>['text/plain'],
- );
+ const group = XTypeGroup(label: 'text', mimeTypes: <String>['text/plain']);
await expectLater(
plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -324,10 +303,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
@@ -357,9 +333,7 @@
mimeTypes: <String>['image/jpg'],
);
- await plugin.getSavePath(
- acceptedTypeGroups: <XTypeGroup>[group, groupTwo],
- );
+ await plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expect(
_typeGroupListsMatch(api.passedOptions!.allowedTypes, <TypeGroup>[
@@ -389,10 +363,7 @@
});
test('throws for a type group that does not support Windows', () async {
- const group = XTypeGroup(
- label: 'text',
- mimeTypes: <String>['text/plain'],
- );
+ const group = XTypeGroup(label: 'text', mimeTypes: <String>['text/plain']);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
@@ -403,10 +374,7 @@
test('allows a wildcard group', () async {
const group = XTypeGroup(label: 'text');
- await expectLater(
- plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
- completes,
- );
+ await expectLater(plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
}
@@ -453,10 +421,7 @@
passedInitialDirectory = initialDirectory;
passedConfirmButtonText = confirmButtonText;
passedOptions = options;
- return FileDialogResult(
- paths: result,
- typeGroupIndex: resultTypeGroupIndex,
- );
+ return FileDialogResult(paths: result, typeGroupIndex: resultTypeGroupIndex);
}
@override
@@ -470,10 +435,7 @@
passedConfirmButtonText = confirmButtonText;
passedSuggestedName = suggestedName;
passedOptions = options;
- return FileDialogResult(
- paths: result,
- typeGroupIndex: resultTypeGroupIndex,
- );
+ return FileDialogResult(paths: result, typeGroupIndex: resultTypeGroupIndex);
}
@override
diff --git a/packages/flutter_plugin_android_lifecycle/example/lib/main.dart b/packages/flutter_plugin_android_lifecycle/example/lib/main.dart
index 0a0361b..f3c4510 100644
--- a/packages/flutter_plugin_android_lifecycle/example/lib/main.dart
+++ b/packages/flutter_plugin_android_lifecycle/example/lib/main.dart
@@ -15,9 +15,7 @@
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
- appBar: AppBar(
- title: const Text('Sample flutter_plugin_android_lifecycle usage'),
- ),
+ appBar: AppBar(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.',
diff --git a/packages/go_router/doc/configuration.md b/packages/go_router/doc/configuration.md
index 085cd90..5f53104 100644
--- a/packages/go_router/doc/configuration.md
+++ b/packages/go_router/doc/configuration.md
@@ -206,11 +206,7 @@
```dart
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (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 b36de3b..bf59ead 100644
--- a/packages/go_router/example/lib/async_redirection.dart
+++ b/packages/go_router/example/lib/async_redirection.dart
@@ -29,23 +29,18 @@
// 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,
- );
+ Widget build(BuildContext context) =>
+ MaterialApp.router(routerConfig: _router, title: title, debugShowCheckedModeBanner: false);
late final GoRouter _router = GoRouter(
routes: <GoRoute>[
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(),
),
],
@@ -81,19 +76,17 @@
State<LoginScreen> createState() => _LoginScreenState();
}
-class _LoginScreenState extends State<LoginScreen>
- with TickerProviderStateMixin {
+class _LoginScreenState extends State<LoginScreen> with TickerProviderStateMixin {
bool loggingIn = false;
late final AnimationController controller;
@override
void initState() {
super.initState();
- controller =
- AnimationController(vsync: this, duration: const Duration(seconds: 1))
- ..addListener(() {
- setState(() {});
- });
+ controller = AnimationController(vsync: this, duration: const Duration(seconds: 1))
+ ..addListener(() {
+ setState(() {});
+ });
controller.repeat();
}
@@ -155,15 +148,11 @@
/// A scope that provides [StreamAuth] for the subtree.
class StreamAuthScope extends InheritedNotifier<StreamAuthNotifier> {
/// 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) {
- return context
- .dependOnInheritedWidgetOfExactType<StreamAuthScope>()!
- .notifier!
- .streamAuth;
+ return context.dependOnInheritedWidgetOfExactType<StreamAuthScope>()!.notifier!.streamAuth;
}
}
diff --git a/packages/go_router/example/lib/books/main.dart b/packages/go_router/example/lib/books/main.dart
index 083ce37..392da9f 100644
--- a/packages/go_router/example/lib/books/main.dart
+++ b/packages/go_router/example/lib/books/main.dart
@@ -40,17 +40,14 @@
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);
- },
- ),
- ),
+ 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(
@@ -60,21 +57,21 @@
),
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>[
GoRoute(
path: ':bookId',
builder: (BuildContext context, GoRouterState state) {
final String bookId = state.pathParameters['bookId']!;
- final Book? selectedBook = libraryInstance.allBooks
- .firstWhereOrNull((Book b) => b.id.toString() == bookId);
+ final Book? selectedBook = libraryInstance.allBooks.firstWhereOrNull(
+ (Book b) => b.id.toString() == bookId,
+ );
return BookDetailsScreen(book: selectedBook);
},
@@ -88,21 +85,18 @@
),
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>[
GoRoute(
path: ':authorId',
builder: (BuildContext context, GoRouterState state) {
final int authorId = int.parse(state.pathParameters['authorId']!);
- final Author? selectedAuthor = libraryInstance.allAuthors
- .firstWhereOrNull((Author a) => a.id == authorId);
+ final Author? selectedAuthor = libraryInstance.allAuthors.firstWhereOrNull(
+ (Author a) => a.id == authorId,
+ );
return AuthorDetailsScreen(author: selectedAuthor);
},
@@ -111,14 +105,13 @@
),
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,
@@ -155,10 +148,7 @@
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
- ) => FadeTransition(
- opacity: animation.drive(_curveTween),
- child: 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 65a9a47..0e3e154 100644
--- a/packages/go_router/example/lib/books/src/auth.dart
+++ b/packages/go_router/example/lib/books/src/auth.dart
@@ -40,7 +40,6 @@
});
/// Gets the [BookstoreAuth] above the context.
- static BookstoreAuth of(BuildContext context) => context
- .dependOnInheritedWidgetOfExactType<BookstoreAuthScope>()!
- .notifier!;
+ static BookstoreAuth of(BuildContext context) =>
+ context.dependOnInheritedWidgetOfExactType<BookstoreAuthScope>()!.notifier!;
}
diff --git a/packages/go_router/example/lib/books/src/data/library.dart b/packages/go_router/example/lib/books/src/data/library.dart
index 769b078..ef03d2c 100644
--- a/packages/go_router/example/lib/books/src/data/library.dart
+++ b/packages/go_router/example/lib/books/src/data/library.dart
@@ -19,12 +19,7 @@
isPopular: false,
isNew: true,
)
- ..addBook(
- title: 'Kindred',
- authorName: 'Octavia E. Butler',
- isPopular: true,
- isNew: false,
- )
+ ..addBook(title: 'Kindred', authorName: 'Octavia E. Butler', isPopular: true, isNew: false)
..addBook(
title: 'The Lathe of Heaven',
authorName: 'Ursula K. Le Guin',
@@ -69,12 +64,8 @@
}
/// The list of popular books in the library.
- List<Book> get popularBooks => <Book>[
- ...allBooks.where((Book book) => book.isPopular),
- ];
+ List<Book> get popularBooks => <Book>[...allBooks.where((Book book) => book.isPopular)];
/// The list of new books in the library.
- List<Book> get newBooks => <Book>[
- ...allBooks.where((Book book) => book.isNew),
- ];
+ List<Book> get newBooks => <Book>[...allBooks.where((Book book) => book.isNew)];
}
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 8362682..de781ae 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
@@ -27,20 +27,13 @@
body: Center(
child: Column(
children: <Widget>[
- Text(
- book!.title,
- style: Theme.of(context).textTheme.headlineMedium,
- ),
- Text(
- book!.author.name,
- style: Theme.of(context).textTheme.titleMedium,
- ),
+ Text(book!.title, style: Theme.of(context).textTheme.headlineMedium),
+ Text(book!.author.name, style: Theme.of(context).textTheme.titleMedium),
TextButton(
onPressed: () {
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
- builder: (BuildContext context) =>
- AuthorDetailsScreen(author: book!.author),
+ builder: (BuildContext context) => AuthorDetailsScreen(author: book!.author),
),
);
},
@@ -49,10 +42,7 @@
Link(
uri: Uri.parse('/author/${book!.author.id}'),
builder: (BuildContext context, FollowLink? followLink) =>
- TextButton(
- onPressed: followLink,
- child: const Text('View author (Link)'),
- ),
+ 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 56e1e2b..3bee36a 100644
--- a/packages/go_router/example/lib/books/src/screens/books.dart
+++ b/packages/go_router/example/lib/books/src/screens/books.dart
@@ -20,8 +20,7 @@
State<BooksScreen> createState() => _BooksScreenState();
}
-class _BooksScreenState extends State<BooksScreen>
- with SingleTickerProviderStateMixin {
+class _BooksScreenState extends State<BooksScreen> with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
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 e32963c..633fea0 100644
--- a/packages/go_router/example/lib/books/src/screens/scaffold.dart
+++ b/packages/go_router/example/lib/books/src/screens/scaffold.dart
@@ -22,11 +22,7 @@
/// The scaffold for the book store.
class BookstoreScaffold extends StatelessWidget {
/// Creates a [BookstoreScaffold].
- const BookstoreScaffold({
- required this.selectedTab,
- required this.child,
- super.key,
- });
+ const BookstoreScaffold({required this.selectedTab, required this.child, super.key});
/// Which tab of the scaffold to display.
final ScaffoldTab selectedTab;
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 4b0a386..7b20c60 100644
--- a/packages/go_router/example/lib/books/src/screens/settings.dart
+++ b/packages/go_router/example/lib/books/src/screens/settings.dart
@@ -57,10 +57,8 @@
),
Link(
uri: Uri.parse('/book/0'),
- builder: (BuildContext context, FollowLink? followLink) => TextButton(
- onPressed: followLink,
- child: const Text('Go directly to /book/0 (Link)'),
- ),
+ builder: (BuildContext context, FollowLink? followLink) =>
+ TextButton(onPressed: followLink, child: const Text('Go directly to /book/0 (Link)')),
),
TextButton(
onPressed: () {
@@ -68,9 +66,7 @@
},
child: const Text('Go directly to /book/0 (GoRouter)'),
),
- ].map<Widget>(
- (Widget w) => Padding(padding: const EdgeInsets.all(8), child: w),
- ),
+ ].map<Widget>((Widget w) => Padding(padding: const EdgeInsets.all(8), child: w)),
TextButton(
onPressed: () => showDialog<String>(
context: context,
@@ -82,10 +78,7 @@
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')),
],
),
),
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 9d2c209..07c0110 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
@@ -43,10 +43,7 @@
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
- Text(
- 'Sign in',
- style: Theme.of(context).textTheme.headlineMedium,
- ),
+ Text('Sign in', style: Theme.of(context).textTheme.headlineMedium),
TextField(
decoration: const InputDecoration(labelText: 'Username'),
controller: _usernameController,
@@ -61,10 +58,7 @@
child: TextButton(
onPressed: () async {
widget.onSignIn(
- Credentials(
- _usernameController.value.text,
- _passwordController.value.text,
- ),
+ Credentials(_usernameController.value.text, _passwordController.value.text),
);
},
child: const Text('Sign in'),
diff --git a/packages/go_router/example/lib/extra_codec.dart b/packages/go_router/example/lib/extra_codec.dart
index a273b8c..a8e53f0 100644
--- a/packages/go_router/example/lib/extra_codec.dart
+++ b/packages/go_router/example/lib/extra_codec.dart
@@ -13,11 +13,7 @@
/// The router configuration.
final GoRouter _router = GoRouter(
routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
- ),
+ GoRoute(path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen()),
],
extraCodec: const MyExtraCodec(),
);
@@ -49,9 +45,7 @@
const Text(
"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}',
- ),
+ Text('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/named_routes.dart b/packages/go_router/example/lib/named_routes.dart
index 4223486..abfe959 100644
--- a/packages/go_router/example/lib/named_routes.dart
+++ b/packages/go_router/example/lib/named_routes.dart
@@ -65,11 +65,8 @@
static const String title = 'GoRouter Example: Named Routes';
@override
- Widget build(BuildContext context) => MaterialApp.router(
- routerConfig: _router,
- title: title,
- debugShowCheckedModeBanner: false,
- );
+ Widget build(BuildContext context) =>
+ MaterialApp.router(routerConfig: _router, title: title, debugShowCheckedModeBanner: false);
late final GoRouter _router = GoRouter(
debugLogDiagnostics: true,
@@ -77,8 +74,7 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
@@ -119,10 +115,7 @@
ListTile(
title: Text(entry.value.name),
onTap: () => context.go(
- context.namedLocation(
- 'family',
- pathParameters: <String, String>{'fid': entry.key},
- ),
+ context.namedLocation('family', pathParameters: <String, String>{'fid': entry.key}),
),
),
],
@@ -152,10 +145,7 @@
onTap: () => context.go(
context.namedLocation(
'person',
- pathParameters: <String, String>{
- 'fid': fid,
- 'pid': entry.key,
- },
+ pathParameters: <String, String>{'fid': fid, 'pid': entry.key},
queryParameters: <String, String>{'qid': 'quid'},
),
),
diff --git a/packages/go_router/example/lib/others/custom_stateful_shell_route.dart b/packages/go_router/example/lib/others/custom_stateful_shell_route.dart
index 0755d2b..3364b8c 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,9 +7,7 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
-final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(
- debugLabel: 'root',
-);
+final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _tabANavigatorKey = GlobalKey<NavigatorState>(
debugLabel: 'tabANav',
);
@@ -25,8 +23,9 @@
@visibleForTesting
// ignore: public_member_api_docs
-final GlobalKey<TabbedRootScreenState> tabbedRootScreenKey =
- GlobalKey<TabbedRootScreenState>(debugLabel: 'TabbedRootScreen');
+final GlobalKey<TabbedRootScreenState> tabbedRootScreenKey = GlobalKey<TabbedRootScreenState>(
+ debugLabel: 'TabbedRootScreen',
+);
// This example demonstrates how to setup nested navigation using a
// BottomNavigationBar, where each bar item uses its own persistent navigator,
@@ -51,11 +50,7 @@
routes: <RouteBase>[
StatefulShellRoute(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (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
@@ -65,20 +60,13 @@
return navigationShell;
},
navigatorContainerBuilder:
- (
- BuildContext context,
- StatefulNavigationShell navigationShell,
- List<Widget> children,
- ) {
+ (BuildContext context, StatefulNavigationShell navigationShell, List<Widget> children) {
// Returning a customized container for the branch
// Navigators (i.e. the `List<Widget> children` argument).
//
// See ScaffoldWithNavBar for more details on how the children
// are managed (using AnimatedBranchContainer).
- return ScaffoldWithNavBar(
- navigationShell: navigationShell,
- children: children,
- );
+ return ScaffoldWithNavBar(navigationShell: navigationShell, children: children);
// NOTE: To use a Cupertino version of ScaffoldWithNavBar, replace
// ScaffoldWithNavBar above with CupertinoScaffoldWithNavBar.
},
@@ -91,8 +79,7 @@
// 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: <RouteBase>[
// The details screen to display stacked on navigator of the
// first tab. This will cover screen A but not the application
@@ -158,19 +145,12 @@
GoRoute(
path: '/b1',
builder: (BuildContext context, GoRouterState state) =>
- const TabScreen(
- label: 'B1',
- detailsPath: '/b1/details',
- ),
+ const TabScreen(label: 'B1', detailsPath: '/b1/details'),
routes: <RouteBase>[
GoRoute(
path: 'details',
- builder:
- (BuildContext context, GoRouterState state) =>
- const DetailsScreen(
- label: 'B1',
- withScaffold: false,
- ),
+ builder: (BuildContext context, GoRouterState state) =>
+ const DetailsScreen(label: 'B1', withScaffold: false),
),
],
),
@@ -185,19 +165,12 @@
GoRoute(
path: '/b2',
builder: (BuildContext context, GoRouterState state) =>
- const TabScreen(
- label: 'B2',
- detailsPath: '/b2/details',
- ),
+ const TabScreen(label: 'B2', detailsPath: '/b2/details'),
routes: <RouteBase>[
GoRoute(
path: 'details',
- builder:
- (BuildContext context, GoRouterState state) =>
- const DetailsScreen(
- label: 'B2',
- withScaffold: false,
- ),
+ builder: (BuildContext context, GoRouterState state) =>
+ const DetailsScreen(label: 'B2', withScaffold: false),
),
],
),
@@ -226,11 +199,8 @@
/// BottomNavigationBar, where [child] is placed in the body of the Scaffold.
class ScaffoldWithNavBar extends StatelessWidget {
/// Constructs an [ScaffoldWithNavBar].
- const ScaffoldWithNavBar({
- required this.navigationShell,
- required this.children,
- Key? key,
- }) : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar'));
+ const ScaffoldWithNavBar({required this.navigationShell, required this.children, Key? key})
+ : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar'));
/// The navigation shell and container for the branch Navigators.
final StatefulNavigationShell navigationShell;
@@ -242,10 +212,7 @@
@override
Widget build(BuildContext context) {
return Scaffold(
- body: AnimatedBranchContainer(
- currentIndex: navigationShell.currentIndex,
- children: children,
- ),
+ body: AnimatedBranchContainer(currentIndex: navigationShell.currentIndex, children: children),
bottomNavigationBar: BottomNavigationBar(
// Here, the items of BottomNavigationBar are hard coded. In a real
// world scenario, the items would most likely be generated from the
@@ -302,8 +269,7 @@
State<StatefulWidget> createState() => _CupertinoScaffoldWithNavBarState();
}
-class _CupertinoScaffoldWithNavBarState
- extends State<CupertinoScaffoldWithNavBar> {
+class _CupertinoScaffoldWithNavBarState extends State<CupertinoScaffoldWithNavBar> {
late final CupertinoTabController tabController = CupertinoTabController(
initialIndex: widget.navigationShell.currentIndex,
);
@@ -347,11 +313,7 @@
/// 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;
@@ -413,12 +375,7 @@
/// The details screen for either the A or B screen.
class DetailsScreen extends StatefulWidget {
/// Constructs a [DetailsScreen].
- const DetailsScreen({
- required this.label,
- this.param,
- this.withScaffold = true,
- super.key,
- });
+ const DetailsScreen({required this.label, this.param, this.withScaffold = true, super.key});
/// The label to display in the center of the screen.
final String label;
@@ -445,10 +402,7 @@
body: _build(context),
);
} else {
- return ColoredBox(
- color: Theme.of(context).scaffoldBackgroundColor,
- child: _build(context),
- );
+ return ColoredBox(color: Theme.of(context).scaffoldBackgroundColor, child: _build(context));
}
}
@@ -472,10 +426,7 @@
),
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) ...<Widget>[
const Padding(padding: EdgeInsets.all(16)),
@@ -498,11 +449,7 @@
/// 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;
@@ -516,8 +463,7 @@
@visibleForTesting
// ignore: public_member_api_docs
-class TabbedRootScreenState extends State<TabbedRootScreen>
- with SingleTickerProviderStateMixin {
+class TabbedRootScreenState extends State<TabbedRootScreen> with SingleTickerProviderStateMixin {
@visibleForTesting
// ignore: public_member_api_docs
late final TabController tabController = TabController(
@@ -559,9 +505,7 @@
return Scaffold(
appBar: AppBar(
- title: Text(
- 'Section B root (tab: ${widget.navigationShell.currentIndex + 1})',
- ),
+ title: Text('Section B root (tab: ${widget.navigationShell.currentIndex + 1})'),
bottom: TabBar(
controller: tabController,
tabs: tabs,
@@ -583,11 +527,7 @@
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
@@ -618,23 +558,15 @@
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
- title: Text(
- 'Section B root (tab ${widget.navigationShell.currentIndex + 1})',
- ),
+ title: Text('Section B root (tab ${widget.navigationShell.currentIndex + 1})'),
),
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
- ElevatedButton(
- onPressed: () => _animateToPage(0),
- child: const Text('Tab 1'),
- ),
- ElevatedButton(
- onPressed: () => _animateToPage(1),
- child: const Text('Tab 2'),
- ),
+ ElevatedButton(onPressed: () => _animateToPage(0), child: const Text('Tab 1')),
+ ElevatedButton(onPressed: () => _animateToPage(1), child: const Text('Tab 2')),
],
),
Expanded(
diff --git a/packages/go_router/example/lib/others/error_screen.dart b/packages/go_router/example/lib/others/error_screen.dart
index 27b30a9..b6ee48b 100644
--- a/packages/go_router/example/lib/others/error_screen.dart
+++ b/packages/go_router/example/lib/others/error_screen.dart
@@ -16,24 +16,20 @@
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>[
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!),
);
}
@@ -49,10 +45,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/page2'),
- child: const Text('Go to page 2'),
- ),
+ ElevatedButton(onPressed: () => context.go('/page2'), child: const Text('Go to page 2')),
],
),
),
@@ -71,10 +64,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/'),
- child: const Text('Go to home page'),
- ),
+ ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')),
],
),
),
@@ -97,10 +87,7 @@
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText(error.toString()),
- TextButton(
- onPressed: () => context.go('/'),
- child: const Text('Home'),
- ),
+ 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 0b0b2d5..d190f97 100644
--- a/packages/go_router/example/lib/others/extra_param.dart
+++ b/packages/go_router/example/lib/others/extra_param.dart
@@ -54,23 +54,20 @@
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>[
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family',
builder: (BuildContext context, GoRouterState state) {
- final Map<String, Object> params =
- state.extra! as Map<String, String>;
+ final Map<String, Object> params = state.extra! as Map<String, String>;
final fid = params['fid']! as String;
return FamilyScreen(fid: fid);
},
@@ -94,10 +91,7 @@
for (final MapEntry<String, Family> entry in _families.entries)
ListTile(
title: Text(entry.value.name),
- onTap: () => context.goNamed(
- 'family',
- extra: <String, String>{'fid': entry.key},
- ),
+ onTap: () => context.goNamed('family', extra: <String, String>{'fid': entry.key}),
),
],
),
@@ -118,9 +112,7 @@
return Scaffold(
appBar: AppBar(title: Text(_families[fid]!.name)),
body: ListView(
- children: <Widget>[
- for (final Person p in people.values) ListTile(title: Text(p.name)),
- ],
+ children: <Widget>[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 a980b8d..7c98b8c 100644
--- a/packages/go_router/example/lib/others/init_loc.dart
+++ b/packages/go_router/example/lib/others/init_loc.dart
@@ -16,26 +16,22 @@
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>[
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(),
),
],
);
@@ -53,10 +49,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/page2'),
- child: const Text('Go to page 2'),
- ),
+ ElevatedButton(onPressed: () => context.go('/page2'), child: const Text('Go to page 2')),
],
),
),
@@ -75,10 +68,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/'),
- child: const Text('Go to home page'),
- ),
+ ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')),
],
),
),
@@ -97,10 +87,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/page2'),
- child: const Text('Go to page 2'),
- ),
+ 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 fea069f..4375fa8 100644
--- a/packages/go_router/example/lib/others/nav_observer.dart
+++ b/packages/go_router/example/lib/others/nav_observer.dart
@@ -17,8 +17,7 @@
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: <NavigatorObserver>[MyNavObserver()],
@@ -26,20 +25,17 @@
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>[
GoRoute(
name: 'page2',
path: 'page2/:p1',
- builder: (BuildContext context, GoRouterState state) =>
- const Page2Screen(),
+ builder: (BuildContext context, GoRouterState state) => const Page2Screen(),
routes: <GoRoute>[
GoRoute(
name: 'page3',
path: 'page3',
- builder: (BuildContext context, GoRouterState state) =>
- const Page3Screen(),
+ builder: (BuildContext context, GoRouterState state) => const Page3Screen(),
),
],
),
@@ -76,10 +72,7 @@
log.info('didReplace: new= ${newRoute?.str}, old= ${oldRoute?.str}');
@override
- void didStartUserGesture(
- Route<dynamic> route,
- Route<dynamic>? previousRoute,
- ) => log.info(
+ void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) => log.info(
'didStartUserGesture: ${route.str}, '
'previousRoute= ${previousRoute?.str}',
);
@@ -131,10 +124,8 @@
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
- onPressed: () => context.goNamed(
- 'page3',
- pathParameters: <String, String>{'p1': 'pv2'},
- ),
+ onPressed: () =>
+ context.goNamed('page3', pathParameters: <String, String>{'p1': 'pv2'}),
child: const Text('Go to page 3'),
),
],
@@ -155,10 +146,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/'),
- child: const Text('Go to home page'),
- ),
+ 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 f915bae..7c58c12 100644
--- a/packages/go_router/example/lib/others/push.dart
+++ b/packages/go_router/example/lib/others/push.dart
@@ -16,22 +16,18 @@
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>[
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']!),
- ),
+ Page2ScreenWithPush(int.parse(state.uri.queryParameters['push-count']!)),
),
],
);
@@ -69,9 +65,7 @@
@override
Widget build(BuildContext context) => Scaffold(
- appBar: AppBar(
- title: Text('${App.title}: page 2 w/ push count $pushCount'),
- ),
+ appBar: AppBar(title: Text('${App.title}: page 2 w/ push count $pushCount')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
@@ -86,8 +80,7 @@
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
- onPressed: () =>
- context.push('/page2?push-count=${pushCount + 1}'),
+ onPressed: () => context.push('/page2?push-count=${pushCount + 1}'),
child: const Text('Push page 2 (again)'),
),
),
diff --git a/packages/go_router/example/lib/others/router_neglect.dart b/packages/go_router/example/lib/others/router_neglect.dart
index 3c1e4bc..21bb7c9 100644
--- a/packages/go_router/example/lib/others/router_neglect.dart
+++ b/packages/go_router/example/lib/others/router_neglect.dart
@@ -16,8 +16,7 @@
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,
@@ -26,13 +25,11 @@
routes: <GoRoute>[
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(),
),
],
);
@@ -50,17 +47,13 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/page2'),
- child: const Text('Go to page 2'),
- ),
+ 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')),
+ onPressed: () => Router.neglect(context, () => context.push('/page2')),
child: const Text('Push page 2'),
),
],
@@ -81,10 +74,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- ElevatedButton(
- onPressed: () => context.go('/'),
- child: const Text('Go to home page'),
- ),
+ ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')),
],
),
),
diff --git a/packages/go_router/example/lib/others/transitions.dart b/packages/go_router/example/lib/others/transitions.dart
index d95862b..1833b69 100644
--- a/packages/go_router/example/lib/others/transitions.dart
+++ b/packages/go_router/example/lib/others/transitions.dart
@@ -16,102 +16,81 @@
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>[
GoRoute(path: '/', redirect: (_, __) => '/none'),
GoRoute(
path: '/fade',
- pageBuilder: (BuildContext context, GoRouterState state) =>
- CustomTransitionPage<void>(
- key: state.pageKey,
- child: const ExampleTransitionsScreen(
- kind: 'fade',
- color: Colors.red,
- ),
- transitionsBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Animation<double> secondaryAnimation,
- Widget child,
- ) => FadeTransition(opacity: animation, child: child),
- ),
+ pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>(
+ key: state.pageKey,
+ child: const ExampleTransitionsScreen(kind: 'fade', color: Colors.red),
+ transitionsBuilder:
+ (
+ BuildContext context,
+ Animation<double> animation,
+ Animation<double> secondaryAnimation,
+ Widget child,
+ ) => FadeTransition(opacity: animation, child: child),
+ ),
),
GoRoute(
path: '/scale',
- pageBuilder: (BuildContext context, GoRouterState state) =>
- CustomTransitionPage<void>(
- key: state.pageKey,
- child: const ExampleTransitionsScreen(
- kind: 'scale',
- color: Colors.green,
- ),
- transitionsBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Animation<double> secondaryAnimation,
- Widget child,
- ) => ScaleTransition(scale: animation, child: child),
- ),
+ pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>(
+ key: state.pageKey,
+ child: const ExampleTransitionsScreen(kind: 'scale', color: Colors.green),
+ transitionsBuilder:
+ (
+ BuildContext context,
+ Animation<double> animation,
+ Animation<double> secondaryAnimation,
+ Widget child,
+ ) => ScaleTransition(scale: animation, child: child),
+ ),
),
GoRoute(
path: '/slide',
- pageBuilder: (BuildContext context, GoRouterState state) =>
- CustomTransitionPage<void>(
- key: state.pageKey,
- child: const ExampleTransitionsScreen(
- kind: 'slide',
- color: Colors.yellow,
+ pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>(
+ key: state.pageKey,
+ child: const ExampleTransitionsScreen(kind: 'slide', color: Colors.yellow),
+ transitionsBuilder:
+ (
+ BuildContext context,
+ Animation<double> animation,
+ Animation<double> secondaryAnimation,
+ Widget child,
+ ) => SlideTransition(
+ position: animation.drive(
+ Tween<Offset>(
+ begin: const Offset(0.25, 0.25),
+ end: Offset.zero,
+ ).chain(CurveTween(curve: Curves.easeIn)),
+ ),
+ child: child,
),
- transitionsBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Animation<double> secondaryAnimation,
- Widget child,
- ) => SlideTransition(
- position: animation.drive(
- Tween<Offset>(
- 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<void>(
- key: state.pageKey,
- child: const ExampleTransitionsScreen(
- kind: 'rotation',
- color: Colors.purple,
- ),
- transitionsBuilder:
- (
- BuildContext context,
- Animation<double> animation,
- Animation<double> secondaryAnimation,
- Widget child,
- ) => RotationTransition(turns: animation, child: child),
- ),
+ pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>(
+ key: state.pageKey,
+ child: const ExampleTransitionsScreen(kind: 'rotation', color: Colors.purple),
+ transitionsBuilder:
+ (
+ BuildContext context,
+ Animation<double> animation,
+ Animation<double> secondaryAnimation,
+ Widget child,
+ ) => RotationTransition(turns: animation, child: child),
+ ),
),
GoRoute(
path: '/none',
- pageBuilder: (BuildContext context, GoRouterState state) =>
- NoTransitionPage<void>(
- key: state.pageKey,
- child: const ExampleTransitionsScreen(
- kind: 'none',
- color: Colors.white,
- ),
- ),
+ pageBuilder: (BuildContext context, GoRouterState state) => NoTransitionPage<void>(
+ key: state.pageKey,
+ child: const ExampleTransitionsScreen(kind: 'none', color: Colors.white),
+ ),
),
],
);
@@ -120,20 +99,10 @@
/// An Example transitions screen.
class ExampleTransitionsScreen extends StatelessWidget {
/// Creates an [ExampleTransitionsScreen].
- const ExampleTransitionsScreen({
- required this.color,
- required this.kind,
- super.key,
- });
+ const ExampleTransitionsScreen({required this.color, required this.kind, super.key});
/// The available transition kinds.
- static final List<String> kinds = <String>[
- 'fade',
- 'scale',
- 'slide',
- 'rotation',
- 'none',
- ];
+ static final List<String> kinds = <String>['fade', 'scale', 'slide', 'rotation', 'none'];
/// The color of the container.
final Color color;
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 6cd8a4b..5de9d4a 100755
--- a/packages/go_router/example/lib/path_and_query_parameters.dart
+++ b/packages/go_router/example/lib/path_and_query_parameters.dart
@@ -63,18 +63,14 @@
// 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,
- );
+ Widget build(BuildContext context) =>
+ MaterialApp.router(routerConfig: _router, title: title, debugShowCheckedModeBanner: false);
late final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
@@ -154,8 +150,7 @@
),
body: ListView(
children: <Widget>[
- for (final String name in asc ? names : names.reversed)
- ListTile(title: Text(name)),
+ for (final String name in asc ? names : names.reversed) 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 95d04c5..2f02646 100644
--- a/packages/go_router/example/lib/push_with_shell_route.dart
+++ b/packages/go_router/example/lib/push_with_shell_route.dart
@@ -38,9 +38,8 @@
),
GoRoute(
path: '/shell1',
- pageBuilder: (_, __) => const NoTransitionPage<void>(
- child: Center(child: Text('shell1 body')),
- ),
+ pageBuilder: (_, __) =>
+ const NoTransitionPage<void>(child: Center(child: Text('shell1 body'))),
),
],
),
diff --git a/packages/go_router/example/lib/redirection.dart b/packages/go_router/example/lib/redirection.dart
index 35232b6..2ce0013 100644
--- a/packages/go_router/example/lib/redirection.dart
+++ b/packages/go_router/example/lib/redirection.dart
@@ -36,19 +36,13 @@
/// Provides login information to its descendants.
class LoginInfoProvider extends InheritedNotifier<LoginInfo> {
/// Creates a [LoginInfoProvider].
- const LoginInfoProvider({
- super.key,
- required super.notifier,
- required super.child,
- });
+ const LoginInfoProvider({super.key, required super.notifier, required super.child});
/// Returns the [LoginInfo] from the closest [LoginInfoProvider] ancestor.
static LoginInfo of(BuildContext context, {bool listen = true}) {
final LoginInfoProvider? result = listen
? context.dependOnInheritedWidgetOfExactType<LoginInfoProvider>()
- : context
- .getElementForInheritedWidgetOfExactType<LoginInfoProvider>()
- ?.widget
+ : context.getElementForInheritedWidgetOfExactType<LoginInfoProvider>()?.widget
as LoginInfoProvider?;
assert(result != null, 'No LoginInfoProvider found in context');
return result!.notifier!;
@@ -82,13 +76,11 @@
routes: <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
diff --git a/packages/go_router/example/lib/routing_config.dart b/packages/go_router/example/lib/routing_config.dart
index 209e117..34e78b0 100644
--- a/packages/go_router/example/lib/routing_config.dart
+++ b/packages/go_router/example/lib/routing_config.dart
@@ -20,8 +20,9 @@
class _MyAppState extends State<MyApp> {
bool isNewRouteAdded = false;
- late final ValueNotifier<RoutingConfig> myConfig =
- ValueNotifier<RoutingConfig>(_generateRoutingConfig());
+ late final ValueNotifier<RoutingConfig> myConfig = ValueNotifier<RoutingConfig>(
+ _generateRoutingConfig(),
+ );
late final GoRouter router = GoRouter.routingConfig(
routingConfig: myConfig,
@@ -32,10 +33,7 @@
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('${state.uri} does not exist'),
- ElevatedButton(
- onPressed: () => router.go('/'),
- child: const Text('Go to home'),
- ),
+ ElevatedButton(onPressed: () => router.go('/'), child: const Text('Go to home')),
],
),
),
diff --git a/packages/go_router/example/lib/shell_route.dart b/packages/go_router/example/lib/shell_route.dart
index aa8e36c..69b533a 100644
--- a/packages/go_router/example/lib/shell_route.dart
+++ b/packages/go_router/example/lib/shell_route.dart
@@ -5,12 +5,8 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
-final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(
- debugLabel: 'root',
-);
-final GlobalKey<NavigatorState> _shellNavigatorKey = GlobalKey<NavigatorState>(
- debugLabel: 'shell',
-);
+final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
+final GlobalKey<NavigatorState> _shellNavigatorKey = GlobalKey<NavigatorState>(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
@@ -130,10 +126,7 @@
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'A Screen'),
- BottomNavigationBarItem(
- icon: Icon(Icons.business),
- label: 'B Screen',
- ),
+ BottomNavigationBarItem(icon: Icon(Icons.business), label: 'B Screen'),
BottomNavigationBarItem(
icon: Icon(Icons.notification_important_rounded),
label: 'C Screen',
@@ -265,10 +258,7 @@
return Scaffold(
appBar: AppBar(title: const Text('Details Screen')),
body: Center(
- child: Text(
- 'Details for $label',
- style: Theme.of(context).textTheme.headlineMedium,
- ),
+ child: Text('Details for $label', style: Theme.of(context).textTheme.headlineMedium),
),
);
}
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 9fa2df1..6156517 100644
--- a/packages/go_router/example/lib/shell_route_top_route.dart
+++ b/packages/go_router/example/lib/shell_route_top_route.dart
@@ -5,12 +5,8 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
-final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(
- debugLabel: 'root',
-);
-final GlobalKey<NavigatorState> _shellNavigatorKey = GlobalKey<NavigatorState>(
- debugLabel: 'shell',
-);
+final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
+final GlobalKey<NavigatorState> _shellNavigatorKey = GlobalKey<NavigatorState>(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
@@ -137,11 +133,7 @@
/// BottomNavigationBar, where [child] is placed in the body of the Scaffold.
class ScaffoldWithNavBar extends StatelessWidget {
/// Constructs an [ScaffoldWithNavBar].
- const ScaffoldWithNavBar({
- super.key,
- required this.title,
- required this.child,
- });
+ const ScaffoldWithNavBar({super.key, required this.title, required this.child});
/// The title to display in the AppBar.
final String title;
@@ -158,10 +150,7 @@
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'A Screen'),
- BottomNavigationBarItem(
- icon: Icon(Icons.business),
- label: 'B Screen',
- ),
+ BottomNavigationBarItem(icon: Icon(Icons.business), label: 'B Screen'),
BottomNavigationBarItem(
icon: Icon(Icons.notification_important_rounded),
label: 'C Screen',
@@ -287,10 +276,7 @@
Widget build(BuildContext context) {
return Scaffold(
body: Center(
- child: Text(
- 'Details for $label',
- style: Theme.of(context).textTheme.headlineMedium,
- ),
+ child: Text('Details for $label', style: Theme.of(context).textTheme.headlineMedium),
),
);
}
diff --git a/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart
index 3df568e..bcffd41 100644
--- a/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart
+++ b/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart
@@ -48,10 +48,7 @@
@override
Widget build(BuildContext context) {
- return MaterialApp.router(
- restorationScopeId: 'mainApp',
- routerConfig: _router,
- );
+ return MaterialApp.router(restorationScopeId: 'mainApp', routerConfig: _router);
}
}
diff --git a/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart
index e3ee30b..7283694 100644
--- a/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart
+++ b/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart
@@ -29,13 +29,12 @@
routes: <RouteBase>[
ShellRoute(
restorationScopeId: 'onboardingShell',
- pageBuilder:
- (BuildContext context, GoRouterState state, Widget child) {
- return MaterialPage<void>(
- restorationId: 'onboardingPage',
- child: OnboardingScaffold(child: child),
- );
- },
+ pageBuilder: (BuildContext context, GoRouterState state, Widget child) {
+ return MaterialPage<void>(
+ restorationId: 'onboardingPage',
+ child: OnboardingScaffold(child: child),
+ );
+ },
routes: <GoRoute>[
GoRoute(
path: 'welcome',
@@ -97,10 +96,7 @@
@override
Widget build(BuildContext context) {
return Scaffold(
- appBar: AppBar(
- title: const Text('Onboarding'),
- automaticallyImplyLeading: false,
- ),
+ appBar: AppBar(title: const Text('Onboarding'), automaticallyImplyLeading: false),
body: child,
);
}
diff --git a/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart
index a81a103..bf79d0d 100644
--- a/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart
+++ b/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart
@@ -24,11 +24,7 @@
StatefulShellRoute.indexedStack(
restorationScopeId: 'appShell',
pageBuilder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
return MaterialPage<void>(
restorationId: 'appShellPage',
child: AppShell(navigationShell: navigationShell),
@@ -89,10 +85,7 @@
},
destinations: const <NavigationDestination>[
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
- NavigationDestination(
- icon: Icon(Icons.account_circle),
- label: 'Profile',
- ),
+ NavigationDestination(icon: Icon(Icons.account_circle), label: 'Profile'),
],
),
);
diff --git a/packages/go_router/example/lib/stateful_shell_route.dart b/packages/go_router/example/lib/stateful_shell_route.dart
index 455d6f4..1d485fa 100644
--- a/packages/go_router/example/lib/stateful_shell_route.dart
+++ b/packages/go_router/example/lib/stateful_shell_route.dart
@@ -5,11 +5,10 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
-final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(
- debugLabel: 'root',
+final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
+final GlobalKey<NavigatorState> _sectionANavigatorKey = GlobalKey<NavigatorState>(
+ debugLabel: 'sectionANav',
);
-final GlobalKey<NavigatorState> _sectionANavigatorKey =
- GlobalKey<NavigatorState>(debugLabel: 'sectionANav');
// This example demonstrates how to setup nested navigation using a
// BottomNavigationBar, where each bar item uses its own persistent navigator,
@@ -32,11 +31,7 @@
// #docregion configuration-builder
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (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
@@ -82,20 +77,16 @@
// 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: <RouteBase>[
GoRoute(
path: 'details/:param',
builder: (BuildContext context, GoRouterState state) =>
- DetailsScreen(
- label: 'B',
- param: state.pathParameters['param'],
- ),
+ DetailsScreen(label: 'B', param: state.pathParameters['param']),
),
],
),
@@ -219,10 +210,7 @@
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
- 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,10 +272,7 @@
body: _build(context),
);
} else {
- return ColoredBox(
- color: Theme.of(context).scaffoldBackgroundColor,
- child: _build(context),
- );
+ return ColoredBox(color: Theme.of(context).scaffoldBackgroundColor, child: _build(context));
}
}
@@ -311,16 +296,10 @@
),
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) ...<Widget>[
const Padding(padding: EdgeInsets.all(16)),
TextButton(
diff --git a/packages/go_router/example/lib/top_level_on_enter.dart b/packages/go_router/example/lib/top_level_on_enter.dart
index 58b63c8..3b17ddb 100644
--- a/packages/go_router/example/lib/top_level_on_enter.dart
+++ b/packages/go_router/example/lib/top_level_on_enter.dart
@@ -35,10 +35,7 @@
Widget build(BuildContext context) {
final key = GlobalKey<NavigatorState>();
- return MaterialApp.router(
- routerConfig: _router(key),
- title: 'Top-level onEnter',
- );
+ return MaterialApp.router(routerConfig: _router(key), title: 'Top-level onEnter');
}
/// Configures the router with navigation handling and deep link support.
@@ -50,30 +47,26 @@
// If anything goes sideways during parsing/guards/redirects,
// surface a friendly message and offer a one-tap “Go Home”.
- onException:
- (BuildContext context, GoRouterState state, GoRouter router) {
- // Show a user-friendly error message
- if (context.mounted) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('Navigation error: ${state.error}'),
- backgroundColor: Colors.red,
- duration: const Duration(seconds: 5),
- action: SnackBarAction(
- label: 'Go Home',
- onPressed: () => router.go('/home'),
- ),
- ),
- );
- }
- // Log the error for debugging
- debugPrint('Router exception: ${state.error}');
+ onException: (BuildContext context, GoRouterState state, GoRouter router) {
+ // Show a user-friendly error message
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text('Navigation error: ${state.error}'),
+ backgroundColor: Colors.red,
+ duration: const Duration(seconds: 5),
+ action: SnackBarAction(label: 'Go Home', onPressed: () => router.go('/home')),
+ ),
+ );
+ }
+ // Log the error for debugging
+ debugPrint('Router exception: ${state.error}');
- // Navigate to error screen if needed
- if (state.uri.path == '/crash-test') {
- router.go('/error');
- }
- },
+ // Navigate to error screen if needed
+ if (state.uri.path == '/crash-test') {
+ router.go('/error');
+ }
+ },
/// Top-level guard runs BEFORE legacy top-level redirects and route-level redirects.
/// Return:
@@ -81,12 +74,7 @@
/// - `Block.stop()` to cancel navigation immediately
/// - `Block.then(() => ...)` to cancel navigation and run follow-up work
onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter router,
- ) async {
+ (BuildContext context, GoRouterState current, GoRouterState next, GoRouter router) async {
// Example: fire-and-forget analytics for deep links; never block the nav
if (next.uri.hasQuery || next.uri.hasFragment) {
// Don't await: keep the guard non-blocking for best UX.
@@ -136,9 +124,7 @@
if (!isLoggedIn) {
// Chaining block: cancel the original nav, then redirect to /login.
// This preserves redirection history to detect loops.
- final String from = Uri.encodeComponent(
- next.uri.toString(),
- );
+ final String from = Uri.encodeComponent(next.uri.toString());
return Block.then(() => router.go('/login?from=$from'));
}
// ignore: dead_code
@@ -152,10 +138,7 @@
routes: <RouteBase>[
// Simple “root → home”
- GoRoute(
- path: '/',
- redirect: (BuildContext _, GoRouterState __) => '/home',
- ),
+ GoRoute(path: '/', redirect: (BuildContext _, GoRouterState __) => '/home'),
// Auth + simple pages
GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
@@ -166,10 +149,7 @@
// but they exist so deep-links resolve safely.
GoRoute(path: '/referral', builder: (_, __) => const SizedBox.shrink()),
GoRoute(path: '/auth', builder: (_, __) => const SizedBox.shrink()),
- GoRoute(
- path: '/crash-test',
- builder: (_, __) => const SizedBox.shrink(),
- ),
+ GoRoute(path: '/crash-test', builder: (_, __) => const SizedBox.shrink()),
// Route-level redirect happens AFTER top-level onEnter allows.
GoRoute(
@@ -186,9 +166,7 @@
return Scaffold(
appBar: AppBar(title: const Text('Article')),
body: Center(
- child: Text(
- 'id=${state.pathParameters['id']}; fragment=${state.uri.fragment}',
- ),
+ child: Text('id=${state.pathParameters['id']}; fragment=${state.uri.fragment}'),
),
);
},
@@ -200,10 +178,7 @@
}
/// Processes referral code in the background without blocking navigation
- Future<void> _processReferralCodeInBackground(
- BuildContext context,
- String code,
- ) async {
+ Future<void> _processReferralCodeInBackground(BuildContext context, String code) async {
final bool ok = await ReferralService.processReferralCode(code);
if (!context.mounted) {
return;
@@ -213,9 +188,7 @@
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
- ok
- ? 'Referral code $code applied successfully!'
- : 'Failed to apply referral code',
+ ok ? 'Referral code $code applied successfully!' : 'Failed to apply referral code',
),
),
);
@@ -268,10 +241,7 @@
appBar: AppBar(
title: const Text('Top-level onEnter'),
actions: <Widget>[
- IconButton(
- icon: const Icon(Icons.settings),
- onPressed: () => context.go('/settings'),
- ),
+ IconButton(icon: const Icon(Icons.settings), onPressed: () => context.go('/settings')),
],
),
body: ListView(
@@ -285,10 +255,7 @@
),
const SizedBox(height: 16),
- Text(
- 'Deep Link Tests',
- style: Theme.of(context).textTheme.titleMedium,
- ),
+ Text('Deep Link Tests', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
const _DeepLinkButton(
label: 'Process Referral',
@@ -303,10 +270,7 @@
),
const SizedBox(height: 24),
- Text(
- 'Guards & Redirects',
- style: Theme.of(context).textTheme.titleMedium,
- ),
+ Text('Guards & Redirects', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
const _DeepLinkButton(
label: 'Protected Route (redirects to login)',
@@ -321,10 +285,7 @@
),
const SizedBox(height: 24),
- Text(
- 'Fragments (hash)',
- style: Theme.of(context).textTheme.titleMedium,
- ),
+ Text('Fragments (hash)', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
OutlinedButton(
onPressed: goArticleWithFragment,
@@ -343,11 +304,7 @@
/// A button that demonstrates a deep link scenario.
class _DeepLinkButton extends StatelessWidget {
- const _DeepLinkButton({
- required this.label,
- required this.path,
- required this.description,
- });
+ const _DeepLinkButton({required this.label, required this.path, required this.description});
final String label;
final String path;
@@ -435,10 +392,7 @@
children: <Widget>[
const Icon(Icons.error_outline, color: Colors.red, size: 60),
const SizedBox(height: 16),
- const Text(
- 'An error occurred during navigation',
- style: TextStyle(fontSize: 18),
- ),
+ const Text('An error occurred during navigation', style: TextStyle(fontSize: 18)),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: () => context.go('/home'),
diff --git a/packages/go_router/example/lib/transition_animations.dart b/packages/go_router/example/lib/transition_animations.dart
index 96f93f1..178b40d 100644
--- a/packages/go_router/example/lib/transition_animations.dart
+++ b/packages/go_router/example/lib/transition_animations.dart
@@ -39,9 +39,7 @@
// 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,
);
},
@@ -125,11 +123,8 @@
),
const SizedBox(height: 48),
ElevatedButton(
- onPressed: () =>
- context.go('/custom-reverse-transition-duration'),
- child: const Text(
- 'Go to the Custom Reverse Transition Duration Screen',
- ),
+ 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/test/custom_stateful_shell_route_test.dart b/packages/go_router/example/test/custom_stateful_shell_route_test.dart
index d88c3bc..b770a84 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
@@ -7,27 +7,25 @@
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);
+ 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);
- // 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 69ed829..cf4abc2 100644
--- a/packages/go_router/example/test/exception_handling_test.dart
+++ b/packages/go_router/example/test/exception_handling_test.dart
@@ -12,9 +12,6 @@
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 345698e..c182987 100644
--- a/packages/go_router/example/test/extra_codec_test.dart
+++ b/packages/go_router/example/test/extra_codec_test.dart
@@ -12,17 +12,11 @@
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 19ec52d..d35da34 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
@@ -12,9 +12,7 @@
expect(find.text(example.App.title), findsOneWidget);
// Directly set the url through platform message.
- var testRouteInformation = <String, dynamic>{
- 'location': '/family/f1?sort=asc',
- };
+ var testRouteInformation = <String, dynamic>{'location': '/family/f1?sort=asc'};
ByteData message = const JSONMethodCodec().encodeMethodCall(
MethodCall('pushRouteInformation', testRouteInformation),
);
@@ -26,15 +24,9 @@
await tester.pumpAndSettle();
// 'Chris' should be higher than 'Tom'.
- expect(
- tester.getCenter(find.text('Jane')).dy <
- tester.getCenter(find.text('John')).dy,
- isTrue,
- );
+ expect(tester.getCenter(find.text('Jane')).dy < tester.getCenter(find.text('John')).dy, isTrue);
- testRouteInformation = <String, dynamic>{
- 'location': '/family/f1?privacy=false',
- };
+ testRouteInformation = <String, dynamic>{'location': '/family/f1?privacy=false'};
message = const JSONMethodCodec().encodeMethodCall(
MethodCall('pushRouteInformation', testRouteInformation),
);
@@ -46,10 +38,6 @@
await tester.pumpAndSettle();
// 'Chris' should be lower than 'Tom'.
- expect(
- tester.getCenter(find.text('Jane')).dy >
- tester.getCenter(find.text('John')).dy,
- isTrue,
- );
+ expect(tester.getCenter(find.text('Jane')).dy > tester.getCenter(find.text('John')).dy, isTrue);
});
}
diff --git a/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart b/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart
index e471c0a..bac4fe9 100644
--- a/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart
+++ b/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart
@@ -8,9 +8,7 @@
void main() {
testWidgets('GoRoute navigation location and route state '
- 'is restored when restorationIds are provided', (
- WidgetTester tester,
- ) async {
+ 'is restored when restorationIds are provided', (WidgetTester tester) async {
const homeTitle = 'Home';
const loginTitle = 'Login';
diff --git a/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart b/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart
index 98b3dd0..80977cf 100644
--- a/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart
+++ b/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart
@@ -8,9 +8,7 @@
void main() {
testWidgets('ShellRoute navigation location and route state '
- 'is restored when restorationIds are provided', (
- WidgetTester tester,
- ) async {
+ 'is restored when restorationIds are provided', (WidgetTester tester) async {
const homeTitle = 'Home';
const welcomeTitle = 'Welcome';
const setupTitle = 'Setup';
diff --git a/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart b/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart
index 2f4cd10..4ad7e6c 100644
--- a/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart
+++ b/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart
@@ -8,9 +8,7 @@
void main() {
testWidgets('StatefulShellRoute navigation location and route state '
- 'is restored when restorationIds are provided', (
- WidgetTester tester,
- ) async {
+ 'is restored when restorationIds are provided', (WidgetTester tester) async {
const homeLabel = 'Home';
const profileLabel = 'Profile';
diff --git a/packages/go_router/lib/go_router.dart b/packages/go_router/lib/go_router.dart
index 8ec3fb2..0decf2e 100644
--- a/packages/go_router/lib/go_router.dart
+++ b/packages/go_router/lib/go_router.dart
@@ -15,12 +15,10 @@
export 'src/misc/errors.dart';
export 'src/misc/extensions.dart';
export 'src/misc/inherited_router.dart';
-export 'src/on_enter.dart'
- show Allow, Block, OnEnterResult, OnEnterThenCallback;
+export 'src/on_enter.dart' show Allow, Block, OnEnterResult, OnEnterThenCallback;
export 'src/pages/custom_transition_page.dart';
export 'src/parser.dart';
export 'src/route.dart';
export 'src/route_data.dart' hide NoOpPage;
-export 'src/router.dart'
- show GoExceptionHandler, GoRouter, OnEnter, RoutingConfig;
+export 'src/router.dart' show GoExceptionHandler, GoRouter, OnEnter, RoutingConfig;
export 'src/state.dart' hide GoRouterStateRegistry, GoRouterStateRegistryScope;
diff --git a/packages/go_router/lib/src/builder.dart b/packages/go_router/lib/src/builder.dart
index 4eb036e..7594513 100644
--- a/packages/go_router/lib/src/builder.dart
+++ b/packages/go_router/lib/src/builder.dart
@@ -17,8 +17,7 @@
import 'state.dart';
/// Signature of a go router builder function with navigator.
-typedef GoRouterBuilderWithNav =
- Widget Function(BuildContext context, Widget child);
+typedef GoRouterBuilderWithNav = Widget Function(BuildContext context, Widget child);
typedef _PageBuilderForAppType =
Page<void> Function({
@@ -29,8 +28,7 @@
required Widget child,
});
-typedef _ErrorBuilderForAppType =
- Widget Function(BuildContext context, GoRouterState state);
+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
@@ -214,10 +212,7 @@
}
pages.add(page);
pageToRouteMatchBase[page] = match;
- registry[page] = match.buildState(
- widget.configuration,
- widget.matchList,
- );
+ registry[page] = match.buildState(widget.configuration, widget.matchList);
}
}
_pages = pages;
@@ -241,10 +236,7 @@
/// Builds a [Page] for a [RouteMatch]
Page<Object?>? _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<Object?> page = pageBuilder(context, state);
if (page is! NoOpPage) {
@@ -269,14 +261,8 @@
}
/// Builds a [Page] for a [ShellRouteMatch]
- Page<Object?> _buildPageForShellRoute(
- BuildContext context,
- ShellRouteMatch match,
- ) {
- final GoRouterState state = match.buildState(
- widget.configuration,
- widget.matchList,
- );
+ Page<Object?> _buildPageForShellRoute(BuildContext context, ShellRouteMatch match) {
+ final GoRouterState state = match.buildState(widget.configuration, widget.matchList);
final GlobalKey<NavigatorState> navigatorKey = match.navigatorKey;
final shellRouteContext = ShellRouteContext(
route: match.route,
@@ -316,11 +302,7 @@
);
},
);
- final Page<Object?>? page = match.route.buildPage(
- context,
- state,
- shellRouteContext,
- );
+ final Page<Object?>? page = match.route.buildPage(context, state, shellRouteContext);
if (page != null && page is! NoOpPage) {
return page;
}
@@ -352,8 +334,7 @@
if (elem != null && isMaterialApp(elem)) {
log('Using MaterialApp configuration');
_pageBuilderForAppType = pageBuilderForMaterialApp;
- _errorBuilderForAppType = (BuildContext c, GoRouterState s) =>
- MaterialErrorScreen(s.error);
+ _errorBuilderForAppType = (BuildContext c, GoRouterState s) => MaterialErrorScreen(s.error);
} else if (elem != null && isCupertinoApp(elem)) {
log('Using CupertinoApp configuration');
_pageBuilderForAppType = pageBuilderForCupertinoApp;
@@ -375,8 +356,7 @@
restorationId: restorationId,
child: child,
);
- _errorBuilderForAppType = (BuildContext c, GoRouterState s) =>
- ErrorScreen(s.error);
+ _errorBuilderForAppType = (BuildContext c, GoRouterState s) => ErrorScreen(s.error);
}
}
@@ -385,20 +365,13 @@
}
/// builds the page based on app type, i.e. MaterialApp vs. CupertinoApp
- Page<Object?> _buildPlatformAdapterPage(
- BuildContext context,
- GoRouterState state,
- Widget child,
- ) {
+ Page<Object?> _buildPlatformAdapterPage(BuildContext context, GoRouterState state, Widget child) {
// build the page based on app type
_cacheAppType(context);
return _pageBuilderForAppType!(
key: state.pageKey,
name: state.name ?? state.path,
- arguments: <String, String>{
- ...state.pathParameters,
- ...state.uri.queryParameters,
- },
+ arguments: <String, String>{...state.pathParameters, ...state.uri.queryParameters},
restorationId: state.pageKey.value,
child: child,
);
diff --git a/packages/go_router/lib/src/configuration.dart b/packages/go_router/lib/src/configuration.dart
index 15c159a..189d8b7 100644
--- a/packages/go_router/lib/src/configuration.dart
+++ b/packages/go_router/lib/src/configuration.dart
@@ -18,8 +18,7 @@
import 'state.dart';
/// The signature of the redirect callback.
-typedef GoRouterRedirect =
- FutureOr<String?> Function(BuildContext context, GoRouterState state);
+typedef GoRouterRedirect = FutureOr<String?> Function(BuildContext context, GoRouterState state);
typedef _NamedPath = ({String path, bool caseSensitive});
@@ -74,25 +73,19 @@
' navigatorKey',
);
- _debugCheckParentNavigatorKeys(
- route.routes,
- <GlobalKey<NavigatorState>>[
- // Once a parentNavigatorKey is used, only that navigator key
- // or keys above it can be used.
- ...allowedKeys.sublist(0, allowedKeys.indexOf(parentKey) + 1),
- ],
- );
+ _debugCheckParentNavigatorKeys(route.routes, <GlobalKey<NavigatorState>>[
+ // Once a parentNavigatorKey is used, only that navigator key
+ // or keys above it can be used.
+ ...allowedKeys.sublist(0, allowedKeys.indexOf(parentKey) + 1),
+ ]);
} else {
- _debugCheckParentNavigatorKeys(
- route.routes,
- <GlobalKey<NavigatorState>>[...allowedKeys],
- );
+ _debugCheckParentNavigatorKeys(route.routes, <GlobalKey<NavigatorState>>[...allowedKeys]);
}
} else if (route is ShellRoute) {
- _debugCheckParentNavigatorKeys(
- route.routes,
- <GlobalKey<NavigatorState>>[...allowedKeys, route.navigatorKey],
- );
+ _debugCheckParentNavigatorKeys(route.routes, <GlobalKey<NavigatorState>>[
+ ...allowedKeys,
+ route.navigatorKey,
+ ]);
} else if (route is StatefulShellRoute) {
for (final StatefulShellBranch branch in route.branches) {
assert(
@@ -101,10 +94,10 @@
'(${branch.navigatorKey})',
);
- _debugCheckParentNavigatorKeys(
- branch.routes,
- <GlobalKey<NavigatorState>>[...allowedKeys, branch.navigatorKey],
- );
+ _debugCheckParentNavigatorKeys(branch.routes, <GlobalKey<NavigatorState>>[
+ ...allowedKeys,
+ branch.navigatorKey,
+ ]);
}
}
}
@@ -158,9 +151,7 @@
'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 '
@@ -188,11 +179,7 @@
}
/// The match used when there is an error during parsing.
- static RouteMatchList _errorRouteMatchList(
- Uri uri,
- GoException exception, {
- Object? extra,
- }) {
+ static RouteMatchList _errorRouteMatchList(Uri uri, GoException exception, {Object? extra}) {
return RouteMatchList(
matches: const <RouteMatch>[],
extra: extra,
@@ -205,17 +192,11 @@
void _onRoutingTableChanged() {
final RoutingConfig routingTable = _routingConfig.value;
assert(_debugCheckPath(routingTable.routes, true));
+ assert(_debugVerifyNoDuplicatePathParameter(routingTable.routes, <String, GoRoute>{}));
assert(
- _debugVerifyNoDuplicatePathParameter(
- routingTable.routes,
- <String, GoRoute>{},
- ),
- );
- assert(
- _debugCheckParentNavigatorKeys(
- routingTable.routes,
- <GlobalKey<NavigatorState>>[navigatorKey],
- ),
+ _debugCheckParentNavigatorKeys(routingTable.routes, <GlobalKey<NavigatorState>>[
+ navigatorKey,
+ ]),
);
assert(_debugCheckStatefulShellBranchDefaultLocations(routingTable.routes));
_nameToPath.clear();
@@ -322,10 +303,7 @@
final paramNames = <String>[];
patternToRegExp(path.path, paramNames, caseSensitive: path.caseSensitive);
for (final 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
@@ -349,24 +327,12 @@
/// Finds the routes that matched the given URL.
RouteMatchList findMatch(Uri uri, {Object? extra}) {
final pathParameters = <String, String>{};
- final List<RouteMatchBase> matches = _getLocRouteMatches(
- uri,
- pathParameters,
- );
+ final List<RouteMatchBase> matches = _getLocRouteMatches(uri, pathParameters);
if (matches.isEmpty) {
- return _errorRouteMatchList(
- uri,
- GoException('no routes for location: $uri'),
- extra: extra,
- );
+ return _errorRouteMatchList(uri, GoException('no routes for location: $uri'), extra: extra);
}
- return RouteMatchList(
- matches: matches,
- uri: uri,
- pathParameters: pathParameters,
- extra: extra,
- );
+ return RouteMatchList(matches: matches, uri: uri, pathParameters: pathParameters, extra: extra);
}
/// Reparse the input RouteMatchList
@@ -377,10 +343,7 @@
in matchList.matches.whereType<ImperativeRouteMatch>()) {
final match = ImperativeRouteMatch(
pageKey: imperativeMatch.pageKey,
- matches: findMatch(
- imperativeMatch.matches.uri,
- extra: imperativeMatch.matches.extra,
- ),
+ matches: findMatch(imperativeMatch.matches.uri, extra: imperativeMatch.matches.extra),
completer: imperativeMatch.completer,
);
result = result.push(match);
@@ -388,10 +351,7 @@
return result;
}
- List<RouteMatchBase> _getLocRouteMatches(
- Uri uri,
- Map<String, String> pathParameters,
- ) {
+ List<RouteMatchBase> _getLocRouteMatches(Uri uri, Map<String, String> pathParameters) {
for (final RouteBase route in _routingConfig.value.routes) {
final List<RouteMatchBase> result = RouteMatchBase.match(
rootNavigatorKey: navigatorKey,
@@ -428,11 +388,7 @@
// Step 2: Then apply route-level redirects on the post-top-level result.
if (afterTopLevel is RouteMatchList) {
- return _processRouteLevelRedirects(
- context,
- afterTopLevel,
- redirectHistory,
- );
+ return _processRouteLevelRedirects(context, afterTopLevel, redirectHistory);
}
return afterTopLevel.then<RouteMatchList>((RouteMatchList ml) {
if (!context.mounted) {
@@ -459,11 +415,8 @@
) {
final prevLocation = matchList.uri.toString();
- FutureOr<RouteMatchList> processRouteLevelRedirect(
- String? routeRedirectLocation,
- ) {
- if (routeRedirectLocation != null &&
- routeRedirectLocation != prevLocation) {
+ FutureOr<RouteMatchList> processRouteLevelRedirect(String? routeRedirectLocation) {
+ if (routeRedirectLocation != null && routeRedirectLocation != prevLocation) {
final RouteMatchList newMatch = _getNewMatches(
routeRedirectLocation,
matchList.uri,
@@ -499,27 +452,19 @@
if (routeLevelRedirectResult is String?) {
return processRouteLevelRedirect(routeLevelRedirectResult);
}
- return routeLevelRedirectResult
- .then<RouteMatchList>(processRouteLevelRedirect)
- .catchError((Object error) {
- final GoException goException = error is GoException
- ? error
- : GoException('Exception during route redirect: $error');
- return _errorRouteMatchList(
- matchList.uri,
- goException,
- extra: matchList.extra,
- );
- });
+ return routeLevelRedirectResult.then<RouteMatchList>(processRouteLevelRedirect).catchError((
+ Object error,
+ ) {
+ final GoException goException = error is GoException
+ ? error
+ : GoException('Exception during route redirect: $error');
+ return _errorRouteMatchList(matchList.uri, goException, extra: matchList.extra);
+ });
} catch (exception) {
final GoException goException = exception is GoException
? exception
: GoException('Exception during route redirect: $exception');
- return _errorRouteMatchList(
- matchList.uri,
- goException,
- extra: matchList.extra,
- );
+ return _errorRouteMatchList(matchList.uri, goException, extra: matchList.extra);
}
}
@@ -551,21 +496,14 @@
return newMatch;
}
// Recursively re-evaluate the top-level redirect on the new location.
- return applyTopLegacyRedirect(
- context,
- newMatch,
- redirectHistory: redirectHistory,
- );
+ return applyTopLegacyRedirect(context, newMatch, redirectHistory: redirectHistory);
}
return prevMatchList;
}
try {
final FutureOr<String?> res = _runInRouterZone(() {
- return _routingConfig.value.redirect(
- context,
- buildTopLevelGoRouterState(prevMatchList),
- );
+ return _routingConfig.value.redirect(context, buildTopLevelGoRouterState(prevMatchList));
});
if (res is String?) {
return done(res);
@@ -574,21 +512,13 @@
final GoException goException = error is GoException
? error
: GoException('Exception during redirect: $error');
- return _errorRouteMatchList(
- prevMatchList.uri,
- goException,
- extra: prevMatchList.extra,
- );
+ return _errorRouteMatchList(prevMatchList.uri, goException, extra: prevMatchList.extra);
});
} catch (exception) {
final GoException goException = exception is GoException
? exception
: GoException('Exception during redirect: $exception');
- return _errorRouteMatchList(
- prevMatchList.uri,
- goException,
- extra: prevMatchList.extra,
- );
+ return _errorRouteMatchList(prevMatchList.uri, goException, extra: prevMatchList.extra);
}
}
@@ -604,12 +534,7 @@
final RouteMatchBase match = routeMatches[currentCheckIndex];
FutureOr<String?> processRouteRedirect(String? newLocation) =>
newLocation ??
- _getRouteLevelRedirect(
- context,
- matchList,
- routeMatches,
- currentCheckIndex + 1,
- );
+ _getRouteLevelRedirect(context, matchList, routeMatches, currentCheckIndex + 1);
final RouteBase route = match.route;
try {
final FutureOr<String?> routeRedirectResult = _runInRouterZone(() {
@@ -618,16 +543,14 @@
if (routeRedirectResult is String?) {
return processRouteRedirect(routeRedirectResult);
}
- return routeRedirectResult.then<String?>(processRouteRedirect).catchError(
- (Object error) {
- // Convert any exception during async route redirect to a GoException
- final GoException goException = error is GoException
- ? error
- : GoException('Exception during route redirect: $error');
- // Throw the GoException to be caught by the redirect handling chain
- throw goException;
- },
- );
+ return routeRedirectResult.then<String?>(processRouteRedirect).catchError((Object error) {
+ // Convert any exception during async route redirect to a GoException
+ final GoException goException = error is GoException
+ ? error
+ : GoException('Exception during route redirect: $error');
+ // Throw the GoException to be caught by the redirect handling chain
+ throw goException;
+ });
} catch (exception) {
// Convert any exception during route redirect to a GoException
final GoException goException = exception is GoException
@@ -685,9 +608,7 @@
String _formatRedirectionHistory(List<RouteMatchList> redirections) {
return redirections
- .map<String>(
- (RouteMatchList routeMatches) => routeMatches.uri.toString(),
- )
+ .map<String>((RouteMatchList routeMatches) => routeMatches.uri.toString())
.join(' => ');
}
@@ -743,12 +664,7 @@
String debugKnownRoutes() {
final sb = StringBuffer();
sb.writeln('Full paths for routes:');
- _debugFullPathsFor(
- _routingConfig.value.routes,
- '',
- const <_DecorationType>[],
- sb,
- );
+ _debugFullPathsFor(_routingConfig.value.routes, '', const <_DecorationType>[], sb);
if (_nameToPath.isNotEmpty) {
sb.writeln('known full paths for route names:');
@@ -774,16 +690,11 @@
index,
routes.length,
);
- final String decorationString = decoration
- .map((_DecorationType e) => e.toString())
- .join();
+ final String decorationString = decoration.map((_DecorationType e) => e.toString()).join();
var path = parentFullpath;
if (route is GoRoute) {
path = concatenatePaths(parentFullpath, route.path);
- final String? screenName = route.builder?.runtimeType
- .toString()
- .split('=> ')
- .last;
+ final String? screenName = route.builder?.runtimeType.toString().split('=> ').last;
sb.writeln(
'$decorationString$path '
'${screenName == null ? '' : '($screenName)'}',
@@ -800,9 +711,7 @@
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:
@@ -835,10 +744,7 @@
'duplication fullpaths for name '
'"$name":${_nameToPath[name]!.path}, $fullPath',
);
- _nameToPath[name] = (
- path: fullPath,
- caseSensitive: route.caseSensitive,
- );
+ _nameToPath[name] = (path: fullPath, caseSensitive: route.caseSensitive);
}
if (route.routes.isNotEmpty) {
diff --git a/packages/go_router/lib/src/delegate.dart b/packages/go_router/lib/src/delegate.dart
index 37e5698..1459d2f 100644
--- a/packages/go_router/lib/src/delegate.dart
+++ b/packages/go_router/lib/src/delegate.dart
@@ -16,8 +16,7 @@
import 'state.dart';
/// GoRouter implementation of [RouterDelegate].
-class GoRouterDelegate extends RouterDelegate<RouteMatchList>
- with ChangeNotifier {
+class GoRouterDelegate extends RouterDelegate<RouteMatchList> with ChangeNotifier {
/// Constructor for GoRouter's implementation of the RouterDelegate base
/// class.
GoRouterDelegate({
@@ -68,10 +67,7 @@
if (lastRoute.onExit != null && navigatorKey.currentContext != null) {
return !(await lastRoute.onExit!(
navigatorKey.currentContext!,
- currentConfiguration.last.buildState(
- _configuration,
- currentConfiguration,
- ),
+ currentConfiguration.last.buildState(_configuration, currentConfiguration),
));
}
@@ -122,12 +118,9 @@
RouteMatchBase walker = currentConfiguration.matches.last;
while (walker is ShellRouteMatch) {
- final NavigatorState potentialCandidate =
- walker.navigatorKey.currentState!;
+ final NavigatorState potentialCandidate = walker.navigatorKey.currentState!;
- final ModalRoute<dynamic>? modalRoute = ModalRoute.of(
- potentialCandidate.context,
- );
+ final ModalRoute<dynamic>? modalRoute = ModalRoute.of(potentialCandidate.context);
if (modalRoute == null || !modalRoute.isCurrent) {
// Stop if there is a pageless route on top of the shell route.
break;
@@ -138,11 +131,7 @@
return states.reversed;
}
- bool _handlePopPageWithRouteMatch(
- Route<Object?> route,
- Object? result,
- RouteMatchBase match,
- ) {
+ bool _handlePopPageWithRouteMatch(Route<Object?> route, Object? result, RouteMatchBase match) {
if (route.willHandlePopInternally) {
final bool popped = route.didPop(result);
assert(!popped);
@@ -198,10 +187,8 @@
/// 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<NavigatorState> get navigatorKey => _configuration.navigatorKey;
@@ -245,14 +232,10 @@
return true;
});
- final int compareUntil = math.min(
- currentGoRouteMatches.length,
- newGoRouteMatches.length,
- );
+ final int compareUntil = math.min(currentGoRouteMatches.length, newGoRouteMatches.length);
var indexOfFirstDiff = 0;
for (; indexOfFirstDiff < compareUntil; indexOfFirstDiff++) {
- if (currentGoRouteMatches[indexOfFirstDiff] !=
- newGoRouteMatches[indexOfFirstDiff]) {
+ if (currentGoRouteMatches[indexOfFirstDiff] != newGoRouteMatches[indexOfFirstDiff]) {
break;
}
}
@@ -297,11 +280,7 @@
Future<bool> handleOnExitResult(bool exit) {
if (exit) {
- return _callOnExitStartsAt(
- index - 1,
- context: context,
- matches: matches,
- );
+ return _callOnExitStartsAt(index - 1, context: context, matches: matches);
}
return SynchronousFuture<bool>(false);
}
diff --git a/packages/go_router/lib/src/information_provider.dart b/packages/go_router/lib/src/information_provider.dart
index 5c0e1f1..2674c97 100644
--- a/packages/go_router/lib/src/information_provider.dart
+++ b/packages/go_router/lib/src/information_provider.dart
@@ -44,16 +44,9 @@
class RouteInformationState<T> {
/// Creates an InternalRouteInformationState.
@visibleForTesting
- RouteInformationState({
- this.extra,
- this.completer,
- this.baseRouteMatchList,
- required this.type,
- }) : assert(
- (type == NavigatingType.go || type == NavigatingType.restore) ==
- (completer == null),
- ),
- assert((type != NavigatingType.go) == (baseRouteMatchList != null));
+ RouteInformationState({this.extra, this.completer, this.baseRouteMatchList, required this.type})
+ : 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;
@@ -78,14 +71,12 @@
RouteInformationState<void>(extra: extra, type: NavigatingType.go);
/// Factory constructor for 'restore' navigation type.
- static RouteInformationState<void> restore({
- required RouteMatchList base,
- Object? extra,
- }) => RouteInformationState<void>(
- extra: extra ?? base.extra,
- baseRouteMatchList: base,
- type: NavigatingType.restore,
- );
+ static RouteInformationState<void> restore({required RouteMatchList base, Object? extra}) =>
+ RouteInformationState<void>(
+ extra: extra ?? base.extra,
+ baseRouteMatchList: base,
+ type: NavigatingType.restore,
+ );
}
/// The [RouteInformationProvider] created by go_router.
@@ -100,10 +91,7 @@
}) : _refreshListenable = refreshListenable,
_value = RouteInformation(
uri: Uri.parse(initialLocation),
- state: RouteInformationState<void>(
- extra: initialExtra,
- type: NavigatingType.go,
- ),
+ state: RouteInformationState<void>(extra: initialExtra, type: NavigatingType.go),
),
_valueInEngine = _kEmptyRouteInformation,
_routerNeglect = routerNeglect {
@@ -115,9 +103,7 @@
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(
@@ -168,10 +154,7 @@
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();
@@ -179,11 +162,7 @@
}
/// Pushes the `location` as a new route on top of `base`.
- Future<T?> push<T>(
- String location, {
- required RouteMatchList base,
- Object? extra,
- }) {
+ Future<T?> push<T>(String location, {required RouteMatchList base, Object? extra}) {
final completer = Completer<T?>();
_setValue(
location,
@@ -199,10 +178,7 @@
/// Replace the current route matches with the `location`.
void go(String location, {Object? extra}) {
- _setValue(
- location,
- RouteInformationState<void>(extra: extra, type: NavigatingType.go),
- );
+ _setValue(location, RouteInformationState<void>(extra: extra, type: NavigatingType.go));
}
/// Restores the current route matches with the `matchList`.
@@ -219,11 +195,7 @@
/// Removes the top-most route match from `base` and pushes the `location` as a
/// new route on top.
- Future<T?> pushReplacement<T>(
- String location, {
- required RouteMatchList base,
- Object? extra,
- }) {
+ Future<T?> pushReplacement<T>(String location, {required RouteMatchList base, Object? extra}) {
final completer = Completer<T?>();
_setValue(
location,
@@ -238,11 +210,7 @@
}
/// Replaces the top-most route match from `base` with the `location`.
- Future<T?> replace<T>(
- String location, {
- required RouteMatchList base,
- Object? extra,
- }) {
+ Future<T?> replace<T>(String location, {required RouteMatchList base, Object? extra}) {
final completer = Completer<T?>();
_setValue(
location,
@@ -265,32 +233,20 @@
if (routeInformation.state != null) {
_value = _valueInEngine = routeInformation;
} else {
- _value = RouteInformation(
- uri: routeInformation.uri,
- state: RouteInformationState.go(),
- );
+ _value = RouteInformation(uri: routeInformation.uri, state: RouteInformationState.go());
_valueInEngine = _kEmptyRouteInformation;
}
notifyListeners();
}
- bool _valueHasChanged({
- required Uri newLocationUri,
- required Object? newState,
- }) {
+ bool _valueHasChanged({required Uri newLocationUri, required Object? newState}) {
const deepCollectionEquality = DeepCollectionEquality();
- return !deepCollectionEquality.equals(
- _value.uri.path,
- newLocationUri.path,
- ) ||
+ return !deepCollectionEquality.equals(_value.uri.path, newLocationUri.path) ||
!deepCollectionEquality.equals(
_value.uri.queryParameters,
newLocationUri.queryParameters,
) ||
- !deepCollectionEquality.equals(
- _value.uri.fragment,
- newLocationUri.fragment,
- ) ||
+ !deepCollectionEquality.equals(_value.uri.fragment, newLocationUri.fragment) ||
!deepCollectionEquality.equals(_value.state, newState);
}
diff --git a/packages/go_router/lib/src/logging.dart b/packages/go_router/lib/src/logging.dart
index f25d211..d4f1cb0 100644
--- a/packages/go_router/lib/src/logging.dart
+++ b/packages/go_router/lib/src/logging.dart
@@ -70,5 +70,4 @@
void Function(LogRecord)? testDeveloperLog;
/// The function used to log messages.
-void Function(LogRecord) get _developerLogFunction =>
- testDeveloperLog ?? _developerLog;
+void Function(LogRecord) get _developerLogFunction => testDeveloperLog ?? _developerLog;
diff --git a/packages/go_router/lib/src/match.dart b/packages/go_router/lib/src/match.dart
index 87f588a..10f0432 100644
--- a/packages/go_router/lib/src/match.dart
+++ b/packages/go_router/lib/src/match.dart
@@ -47,10 +47,7 @@
String get matchedLocation;
/// Gets the state that represent this route match.
- GoRouterState buildState(
- RouteConfiguration configuration,
- RouteMatchList matches,
- );
+ GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches);
/// Generates a list of [RouteMatchBase] objects by matching the `route` and
/// its sub-routes with `uri`.
@@ -89,8 +86,7 @@
/// The null key corresponds to the route matches of `scopedNavigatorKey`.
/// The scopedNavigatorKey must not be part of the returned map; otherwise,
/// it is impossible to order the matches.
- static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>>
- _matchByNavigatorKey({
+ static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _matchByNavigatorKey({
required RouteBase route,
required String matchedPath, // e.g. /family/:fid
required String remainingLocation, // e.g. person/p1
@@ -127,19 +123,14 @@
// Grab the route matches for the scope navigator key and put it into the
// matches for `null`.
if (result.containsKey(scopedNavigatorKey)) {
- final List<RouteMatchBase> matchesForScopedNavigator = result.remove(
- scopedNavigatorKey,
- )!;
+ final List<RouteMatchBase> matchesForScopedNavigator = result.remove(scopedNavigatorKey)!;
assert(matchesForScopedNavigator.isNotEmpty);
- result
- .putIfAbsent(null, () => <RouteMatchBase>[])
- .addAll(matchesForScopedNavigator);
+ result.putIfAbsent(null, () => <RouteMatchBase>[]).addAll(matchesForScopedNavigator);
}
return result;
}
- static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>>
- _matchByNavigatorKeyForShellRoute({
+ static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _matchByNavigatorKeyForShellRoute({
required ShellRouteBase route,
required String matchedPath, // e.g. /family/:fid
required String remainingLocation, // e.g. person/p1
@@ -148,8 +139,7 @@
required GlobalKey<NavigatorState> scopedNavigatorKey,
required Uri uri,
}) {
- final GlobalKey<NavigatorState>? parentKey =
- route.parentNavigatorKey == scopedNavigatorKey
+ final GlobalKey<NavigatorState>? parentKey = route.parentNavigatorKey == scopedNavigatorKey
? null
: route.parentNavigatorKey;
Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>>? subRouteMatches;
@@ -165,9 +155,7 @@
uri: uri,
scopedNavigatorKey: navigatorKeyUsed,
);
- assert(
- !subRouteMatches.containsKey(route.navigatorKeyForSubRoute(subRoute)),
- );
+ assert(!subRouteMatches.containsKey(route.navigatorKeyForSubRoute(subRoute)));
if (subRouteMatches.isNotEmpty) {
break;
}
@@ -184,15 +172,12 @@
pageKey: ValueKey<String>(route.hashCode.toString()),
navigatorKey: navigatorKeyUsed,
);
- subRouteMatches
- .putIfAbsent(parentKey, () => <RouteMatchBase>[])
- .insert(0, result);
+ subRouteMatches.putIfAbsent(parentKey, () => <RouteMatchBase>[]).insert(0, result);
return subRouteMatches;
}
- static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>>
- _matchByNavigatorKeyForGoRoute({
+ static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _matchByNavigatorKeyForGoRoute({
required GoRoute route,
required String matchedPath, // e.g. /family/:fid
required String remainingLocation, // e.g. person/p1
@@ -201,33 +186,23 @@
required GlobalKey<NavigatorState> scopedNavigatorKey,
required Uri uri,
}) {
- final GlobalKey<NavigatorState>? parentKey =
- route.parentNavigatorKey == scopedNavigatorKey
+ final GlobalKey<NavigatorState>? parentKey = route.parentNavigatorKey == scopedNavigatorKey
? null
: route.parentNavigatorKey;
- final RegExpMatch? regExpMatch = route.matchPatternAsPrefix(
- remainingLocation,
- );
+ final RegExpMatch? regExpMatch = route.matchPatternAsPrefix(remainingLocation);
if (regExpMatch == null) {
return _empty;
}
- final Map<String, String> encodedParams = route.extractPathParams(
- regExpMatch,
- );
+ final Map<String, String> 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<String, String> currentPathParameter = encodedParams
- .map<String, String>(
- (String key, String value) =>
- MapEntry<String, String>(key, Uri.decodeComponent(value)),
- );
- final String pathLoc = patternToPath(route.path, encodedParams);
- final String newMatchedLocation = concatenatePaths(
- matchedLocation,
- pathLoc,
+ final Map<String, String> currentPathParameter = encodedParams.map<String, String>(
+ (String key, String value) => MapEntry<String, String>(key, Uri.decodeComponent(value)),
);
+ final String pathLoc = patternToPath(route.path, encodedParams);
+ final String newMatchedLocation = concatenatePaths(matchedLocation, pathLoc);
final String newMatchedPath = concatenatePaths(matchedPath, route.path);
final String newMatchedLocationToCompare;
@@ -308,11 +283,7 @@
@immutable
class RouteMatch extends RouteMatchBase {
/// Constructor for [RouteMatch].
- const RouteMatch({
- required this.route,
- required this.matchedLocation,
- required this.pageKey,
- });
+ const RouteMatch({required this.route, required this.matchedLocation, required this.pageKey});
/// The matched route.
@override
@@ -339,10 +310,7 @@
int get hashCode => Object.hash(route, matchedLocation, pageKey);
@override
- GoRouterState buildState(
- RouteConfiguration configuration,
- RouteMatchList matches,
- ) {
+ GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches) {
return GoRouterState(
configuration,
uri: matches.uri,
@@ -396,10 +364,7 @@
final ValueKey<String> pageKey;
@override
- GoRouterState buildState(
- RouteConfiguration configuration,
- RouteMatchList matches,
- ) {
+ GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches) {
// The route related data is stored in the leaf route match.
final RouteMatch leafMatch = _lastLeaf;
if (leafMatch is ImperativeRouteMatch) {
@@ -444,28 +409,21 @@
}
@override
- int get hashCode =>
- Object.hash(route, matchedLocation, Object.hashAll(matches), pageKey);
+ int get hashCode => Object.hash(route, matchedLocation, Object.hashAll(matches), pageKey);
}
/// 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(),
- );
+ return GoRoute(path: 'error', builder: (_, __) => throw UnimplementedError());
}
return matchList.last.route;
}
@@ -490,10 +448,7 @@
}
@override
- GoRouterState buildState(
- RouteConfiguration configuration,
- RouteMatchList matches,
- ) {
+ GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches) {
return super.buildState(configuration, this.matches);
}
@@ -623,11 +578,7 @@
return copyWith(matches: <RouteMatchBase>[...matches, match]);
}
return copyWith(
- matches: _createNewMatchUntilIncompatible(
- matches,
- match.matches.matches,
- match,
- ),
+ matches: _createNewMatchUntilIncompatible(matches, match.matches.matches, match),
);
}
@@ -654,9 +605,7 @@
);
return newMatches;
}
- newMatches.add(
- _cloneBranchAndInsertImperativeMatch(otherMatches.last, match),
- );
+ newMatches.add(_cloneBranchAndInsertImperativeMatch(otherMatches.last, match));
return newMatches;
}
@@ -666,9 +615,7 @@
) {
if (branch is ShellRouteMatch) {
return branch.copyWith(
- matches: <RouteMatchBase>[
- _cloneBranchAndInsertImperativeMatch(branch.matches.last, match),
- ],
+ matches: <RouteMatchBase>[_cloneBranchAndInsertImperativeMatch(branch.matches.last, match)],
);
}
// Add the input `match` instead of the incompatibleMatch since it contains
@@ -680,10 +627,7 @@
/// Returns a new instance of RouteMatchList with the input `match` removed
/// from the current instance.
RouteMatchList remove(RouteMatchBase match) {
- final List<RouteMatchBase> newMatches = _removeRouteMatchFromList(
- matches,
- match,
- );
+ final List<RouteMatchBase> newMatches = _removeRouteMatchFromList(matches, match);
if (newMatches == matches) {
return this;
}
@@ -704,25 +648,15 @@
newRoute as GoRoute;
// Need to remove path parameters that are no longer in the fullPath.
final newParameters = <String>[];
- patternToRegExp(
- fullPath,
- newParameters,
- caseSensitive: newRoute.caseSensitive,
- );
+ patternToRegExp(fullPath, newParameters, caseSensitive: newRoute.caseSensitive);
final Set<String> validParameters = newParameters.toSet();
final newPathParameters = Map<String, String>.fromEntries(
pathParameters.entries.where(
(MapEntry<String, String> value) => validParameters.contains(value.key),
),
);
- final Uri newUri = uri.replace(
- path: patternToPath(fullPath, newPathParameters),
- );
- return copyWith(
- matches: newMatches,
- uri: newUri,
- pathParameters: newPathParameters,
- );
+ final Uri newUri = uri.replace(path: patternToPath(fullPath, newPathParameters));
+ return copyWith(matches: newMatches, uri: newUri, pathParameters: newPathParameters);
}
/// Returns a new List from the input matches with target removed.
@@ -755,10 +689,7 @@
return matches.sublist(0, index);
}
if (match is ShellRouteMatch) {
- final List<RouteMatchBase> newSubMatches = _removeRouteMatchFromList(
- match.matches,
- target,
- );
+ final List<RouteMatchBase> newSubMatches = _removeRouteMatchFromList(match.matches, target);
if (newSubMatches == match.matches) {
// Didn't find target in the newSubMatches.
continue;
@@ -824,16 +755,12 @@
_visitRouteMatches(matches, visitor);
}
- static bool _visitRouteMatches(
- List<RouteMatchBase> matches,
- RouteMatchVisitor visitor,
- ) {
+ static bool _visitRouteMatches(List<RouteMatchBase> matches, RouteMatchVisitor visitor) {
for (final routeMatch in matches) {
if (!visitor(routeMatch)) {
return false;
}
- if (routeMatch is ShellRouteMatch &&
- !_visitRouteMatches(routeMatch.matches, visitor)) {
+ if (routeMatch is ShellRouteMatch && !_visitRouteMatches(routeMatch.matches, visitor)) {
return false;
}
}
@@ -868,10 +795,7 @@
extra == other.extra &&
error == other.error &&
const ListEquality<RouteMatchBase>().equals(matches, other.matches) &&
- const MapEquality<String, String>().equals(
- pathParameters,
- other.pathParameters,
- );
+ const MapEquality<String, String>().equals(pathParameters, other.pathParameters);
}
@override
@@ -883,8 +807,7 @@
error,
Object.hashAllUnordered(
pathParameters.entries.map<int>(
- (MapEntry<String, String> entry) =>
- Object.hash(entry.key, entry.value),
+ (MapEntry<String, String> entry) => Object.hash(entry.key, entry.value),
),
),
);
@@ -894,9 +817,7 @@
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Uri>('uri', uri));
- properties.add(
- DiagnosticsProperty<List<RouteMatchBase>>('matches', matches),
- );
+ properties.add(DiagnosticsProperty<List<RouteMatchBase>>('matches', matches));
}
}
@@ -929,8 +850,7 @@
final Converter<Map<Object?, Object?>, RouteMatchList> decoder;
}
-class _RouteMatchListEncoder
- extends Converter<RouteMatchList, Map<Object?, Object?>> {
+class _RouteMatchListEncoder extends Converter<RouteMatchList, Map<Object?, Object?>> {
const _RouteMatchListEncoder(this.configuration);
final RouteConfiguration configuration;
@@ -943,16 +863,12 @@
}
return true;
});
- final List<Map<Object?, Object?>> encodedImperativeMatches =
- imperativeMatches
- .map(
- (ImperativeRouteMatch e) => _toPrimitives(
- e.matches.uri.toString(),
- e.matches.extra,
- pageKey: e.pageKey.value,
- ),
- )
- .toList();
+ final List<Map<Object?, Object?>> encodedImperativeMatches = imperativeMatches
+ .map(
+ (ImperativeRouteMatch e) =>
+ _toPrimitives(e.matches.uri.toString(), e.matches.extra, pageKey: e.pageKey.value),
+ )
+ .toList();
return _toPrimitives(
input.uri.toString(),
@@ -971,9 +887,7 @@
if (configuration.extraCodec != null) {
encodedExtra = <String, Object?>{
RouteMatchListCodec._codecKey: RouteMatchListCodec._customCodecName,
- RouteMatchListCodec._encodedKey: configuration.extraCodec?.encode(
- extra,
- ),
+ RouteMatchListCodec._encodedKey: configuration.extraCodec?.encode(extra),
};
} else {
String jsonEncodedExtra;
@@ -997,15 +911,13 @@
return <Object?, Object?>{
RouteMatchListCodec._locationKey: location,
RouteMatchListCodec._extraKey: encodedExtra,
- if (imperativeMatches != null)
- RouteMatchListCodec._imperativeMatchesKey: imperativeMatches,
+ if (imperativeMatches != null) RouteMatchListCodec._imperativeMatchesKey: imperativeMatches,
if (pageKey != null) RouteMatchListCodec._pageKey: pageKey,
};
}
}
-class _RouteMatchListDecoder
- extends Converter<Map<Object?, Object?>, RouteMatchList> {
+class _RouteMatchListDecoder extends Converter<Map<Object?, Object?>, RouteMatchList> {
_RouteMatchListDecoder(this.configuration);
final RouteConfiguration configuration;
@@ -1013,33 +925,21 @@
@override
RouteMatchList convert(Map<Object?, Object?> input) {
final rootLocation = input[RouteMatchListCodec._locationKey]! as String;
- final encodedExtra =
- input[RouteMatchListCodec._extraKey]! as Map<Object?, Object?>;
+ final encodedExtra = input[RouteMatchListCodec._extraKey]! as Map<Object?, Object?>;
final Object? extra;
- if (encodedExtra[RouteMatchListCodec._codecKey] ==
- RouteMatchListCodec._jsonCodecName) {
- extra = json.decoder.convert(
- encodedExtra[RouteMatchListCodec._encodedKey]! as String,
- );
+ if (encodedExtra[RouteMatchListCodec._codecKey] == RouteMatchListCodec._jsonCodecName) {
+ 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 imperativeMatches =
- input[RouteMatchListCodec._imperativeMatchesKey] as List<Object?>?;
+ final imperativeMatches = input[RouteMatchListCodec._imperativeMatchesKey] as List<Object?>?;
if (imperativeMatches != null) {
for (final Map<Object?, Object?> encodedImperativeMatch
in imperativeMatches.whereType<Map<Object?, Object?>>()) {
- final RouteMatchList imperativeMatchList = convert(
- encodedImperativeMatch,
- );
+ final RouteMatchList imperativeMatchList = convert(encodedImperativeMatch);
final pageKey = ValueKey<String>(
encodedImperativeMatch[RouteMatchListCodec._pageKey]! as String,
);
diff --git a/packages/go_router/lib/src/misc/error_screen.dart b/packages/go_router/lib/src/misc/error_screen.dart
index 2556944..55a76a4 100644
--- a/packages/go_router/lib/src/misc/error_screen.dart
+++ b/packages/go_router/lib/src/misc/error_screen.dart
@@ -22,19 +22,13 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- const Text(
- 'Page Not Found',
- style: TextStyle(fontWeight: FontWeight.bold),
- ),
+ 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: const Text('Go to home page', style: TextStyle(color: _kWhite)),
),
],
),
@@ -61,19 +55,13 @@
void didChangeDependencies() {
super.didChangeDependencies();
_color =
- (context as Element)
- .findAncestorWidgetOfExactType<WidgetsApp>()
- ?.color ??
+ (context as Element).findAncestorWidgetOfExactType<WidgetsApp>()?.color ??
const Color(0xFF2196F3); // blue
}
@override
Widget build(BuildContext context) => GestureDetector(
onTap: widget.onPressed,
- child: Container(
- padding: const EdgeInsets.all(8),
- color: _color,
- child: widget.child,
- ),
+ 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 4c06c6d..36cb7e3 100644
--- a/packages/go_router/lib/src/misc/extensions.dart
+++ b/packages/go_router/lib/src/misc/extensions.dart
@@ -23,8 +23,7 @@
);
/// Navigate to a location.
- void go(String location, {Object? extra}) =>
- GoRouter.of(this).go(location, extra: extra);
+ void go(String location, {Object? extra}) => GoRouter.of(this).go(location, extra: extra);
/// Navigate to a named route.
void goNamed(
diff --git a/packages/go_router/lib/src/misc/inherited_router.dart b/packages/go_router/lib/src/misc/inherited_router.dart
index f5fd5e0..39e2d7c 100644
--- a/packages/go_router/lib/src/misc/inherited_router.dart
+++ b/packages/go_router/lib/src/misc/inherited_router.dart
@@ -13,11 +13,7 @@
/// when routing from anywhere in your app.
class InheritedGoRouter extends InheritedWidget {
/// Default constructor for the inherited go router.
- const InheritedGoRouter({
- required super.child,
- required this.goRouter,
- super.key,
- });
+ const InheritedGoRouter({required super.child, required this.goRouter, super.key});
/// The [GoRouter] that is made available to the widget tree.
final GoRouter goRouter;
diff --git a/packages/go_router/lib/src/pages/cupertino.dart b/packages/go_router/lib/src/pages/cupertino.dart
index 152eae6..3061059 100644
--- a/packages/go_router/lib/src/pages/cupertino.dart
+++ b/packages/go_router/lib/src/pages/cupertino.dart
@@ -12,8 +12,7 @@
context.findAncestorWidgetOfExactType<CupertinoApp>() != null;
/// Creates a Cupertino HeroController.
-HeroController createCupertinoHeroController() =>
- CupertinoApp.createCupertinoHeroController();
+HeroController createCupertinoHeroController() => CupertinoApp.createCupertinoHeroController();
/// Builds a Cupertino page.
CupertinoPage<void> pageBuilderForCupertinoApp({
@@ -46,10 +45,7 @@
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(error?.toString() ?? 'page not found'),
- CupertinoButton(
- onPressed: () => context.go('/'),
- child: const Text('Home'),
- ),
+ 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 8164e7a..606db68 100644
--- a/packages/go_router/lib/src/pages/custom_transition_page.dart
+++ b/packages/go_router/lib/src/pages/custom_transition_page.dart
@@ -108,13 +108,11 @@
transitionsBuilder;
@override
- Route<T> createRoute(BuildContext context) =>
- _CustomTransitionPageRoute<T>(this);
+ Route<T> createRoute(BuildContext context) => _CustomTransitionPageRoute<T>(this);
}
class _CustomTransitionPageRoute<T> extends PageRoute<T> {
- _CustomTransitionPageRoute(CustomTransitionPage<T> page)
- : super(settings: page);
+ _CustomTransitionPageRoute(CustomTransitionPage<T> page) : super(settings: page);
CustomTransitionPage<T> get _page => settings as CustomTransitionPage<T>;
@@ -147,11 +145,7 @@
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
- ) => Semantics(
- scopesRoute: true,
- explicitChildNodes: true,
- child: _page.child,
- );
+ ) => Semantics(scopesRoute: true, explicitChildNodes: true, child: _page.child);
@override
Widget buildTransitions(
diff --git a/packages/go_router/lib/src/pages/material.dart b/packages/go_router/lib/src/pages/material.dart
index 953cc0d..299bfbf 100644
--- a/packages/go_router/lib/src/pages/material.dart
+++ b/packages/go_router/lib/src/pages/material.dart
@@ -13,8 +13,7 @@
context.findAncestorWidgetOfExactType<MaterialApp>() != null;
/// Creates a Material HeroController.
-HeroController createMaterialHeroController() =>
- MaterialApp.createMaterialHeroController();
+HeroController createMaterialHeroController() => MaterialApp.createMaterialHeroController();
/// Builds a Material page.
MaterialPage<void> pageBuilderForMaterialApp({
@@ -47,10 +46,7 @@
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText(error?.toString() ?? 'page not found'),
- TextButton(
- onPressed: () => context.go('/'),
- child: const Text('Home'),
- ),
+ 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 5b91b0e..7ed750b 100644
--- a/packages/go_router/lib/src/parser.dart
+++ b/packages/go_router/lib/src/parser.dart
@@ -24,10 +24,7 @@
/// The returned [RouteMatchList] is used as parsed result for the
/// [GoRouterDelegate].
typedef ParserExceptionHandler =
- RouteMatchList Function(
- BuildContext context,
- RouteMatchList routeMatchList,
- );
+ RouteMatchList Function(BuildContext context, RouteMatchList routeMatchList);
/// The function signature for navigation callbacks in [_OnEnterHandler].
typedef NavigationCallback = Future<RouteMatchList> Function();
@@ -94,9 +91,7 @@
incomingUri = routeInformation.uri;
} else if (raw is! RouteInformationState) {
// Restoration/back-forward: decode the stored match list and treat as restore.
- final RouteMatchList decoded = _routeMatchListCodec.decode(
- raw as Map<Object?, Object?>,
- );
+ final RouteMatchList decoded = _routeMatchListCodec.decode(raw as Map<Object?, Object?>);
infoState = RouteInformationState.restore(base: decoded);
incomingUri = decoded.uri;
} else {
@@ -121,19 +116,12 @@
effectiveRoute.uri,
extra: infoState.extra,
);
- return _navigate(
- effectiveRoute,
- context,
- infoState,
- startingMatches: initialMatches,
- );
+ return _navigate(effectiveRoute, context, infoState, startingMatches: initialMatches);
},
onCanNotEnter: () {
// If blocked, stay on the current route by restoring the last known good configuration.
if (router.routerDelegate.currentConfiguration.isNotEmpty) {
- return SynchronousFuture<RouteMatchList>(
- router.routerDelegate.currentConfiguration,
- );
+ return SynchronousFuture<RouteMatchList>(router.routerDelegate.currentConfiguration);
}
if (_lastMatchList != null) {
@@ -170,47 +158,34 @@
// If we weren't given matches, compute them here. The URI has already been
// normalized at the parser entry point.
final FutureOr<RouteMatchList> baseMatches =
- startingMatches ??
- configuration.findMatch(routeInformation.uri, extra: infoState.extra);
+ startingMatches ?? configuration.findMatch(routeInformation.uri, extra: infoState.extra);
final redirectHistory = <RouteMatchList>[];
// redirect() handles both top-level and route-level redirects.
FutureOr<RouteMatchList> applyRedirects(FutureOr<RouteMatchList> base) {
if (base is RouteMatchList) {
- return configuration.redirect(
- context,
- base,
- redirectHistory: redirectHistory,
- );
+ return configuration.redirect(context, base, redirectHistory: redirectHistory);
}
return base.then<RouteMatchList>((RouteMatchList ml) {
if (!context.mounted) {
return ml;
}
- return configuration.redirect(
- context,
- ml,
- redirectHistory: redirectHistory,
- );
+ return configuration.redirect(context, ml, redirectHistory: redirectHistory);
});
}
final FutureOr<RouteMatchList> redirected = applyRedirects(baseMatches);
return debugParserFuture =
- (redirected is RouteMatchList
- ? SynchronousFuture<RouteMatchList>(redirected)
- : redirected)
+ (redirected is RouteMatchList ? SynchronousFuture<RouteMatchList>(redirected) : redirected)
.then((RouteMatchList matchList) {
// Guard against context disposal during async redirects.
if (!context.mounted) {
return _lastMatchList ??
_OnEnterHandler._errorRouteMatchList(
routeInformation.uri,
- GoException(
- 'Navigation aborted because the router context was disposed.',
- ),
+ GoException('Navigation aborted because the router context was disposed.'),
extra: infoState.extra,
);
}
@@ -244,13 +219,9 @@
}
@override
- Future<RouteMatchList> parseRouteInformation(
- RouteInformation routeInformation,
- ) {
+ Future<RouteMatchList> parseRouteInformation(RouteInformation routeInformation) {
// Not used in go_router; instruct users to use parseRouteInformationWithDependencies.
- throw UnimplementedError(
- 'Use parseRouteInformationWithDependencies instead',
- );
+ throw UnimplementedError('Use parseRouteInformationWithDependencies instead');
}
@override
@@ -338,9 +309,7 @@
/// Returns a unique [ValueKey<String>] for a new route.
ValueKey<String> _getUniqueValueKey() {
return ValueKey<String>(
- String.fromCharCodes(
- List<int>.generate(32, (_) => _random.nextInt(33) + 89),
- ),
+ String.fromCharCodes(List<int>.generate(32, (_) => _random.nextInt(33) + 89)),
);
}
}
@@ -418,8 +387,11 @@
// Check if the redirection history exceeds the configured limit.
// `routeInformation` has already been normalized by the parser entrypoint.
- final RouteMatchList? redirectionErrorMatchList =
- _redirectionErrorMatchList(context, routeInformation.uri, infoState);
+ final RouteMatchList? redirectionErrorMatchList = _redirectionErrorMatchList(
+ context,
+ routeInformation.uri,
+ infoState,
+ );
if (redirectionErrorMatchList != null) {
// Return immediately if the redirection limit is exceeded.
@@ -433,13 +405,10 @@
);
// Build the next navigation state.
- final GoRouterState nextState = _buildTopLevelGoRouterState(
- incomingMatches,
- );
+ final GoRouterState nextState = _buildTopLevelGoRouterState(incomingMatches);
// Get the current state from the router delegate.
- final RouteMatchList currentMatchList =
- _router.routerDelegate.currentConfiguration;
+ final RouteMatchList currentMatchList = _router.routerDelegate.currentConfiguration;
final GoRouterState currentState = currentMatchList.isNotEmpty
? _buildTopLevelGoRouterState(currentMatchList)
: nextState;
@@ -447,12 +416,7 @@
// Execute the onEnter callback in a try-catch to capture synchronous exceptions.
Future<OnEnterResult> onEnterResultFuture;
try {
- final FutureOr<OnEnterResult> result = topOnEnter(
- context,
- currentState,
- nextState,
- _router,
- );
+ final FutureOr<OnEnterResult> result = topOnEnter(context, currentState, nextState, _router);
// Convert FutureOr to Future
onEnterResultFuture = result is OnEnterResult
? SynchronousFuture<OnEnterResult>(result)
@@ -466,8 +430,7 @@
_resetRedirectionHistory();
- final bool canHandleException =
- _onParserException != null && context.mounted;
+ final bool canHandleException = _onParserException != null && context.mounted;
final RouteMatchList handledMatchList = canHandleException
? _onParserException(context, errorMatchList)
: errorMatchList;
@@ -486,9 +449,7 @@
_resetRedirectionHistory(); // reset after committed navigation
} else {
// Block: check if this is a hard stop or chaining block
- log(
- 'onEnter blocked navigation from ${currentState.uri} to ${nextState.uri}',
- );
+ log('onEnter blocked navigation from ${currentState.uri} to ${nextState.uri}');
matchList = await onCanNotEnter();
// Treat `Block.stop()` as the explicit hard stop.
@@ -609,9 +570,7 @@
) {
_redirectionHistory.add(redirectedUri);
if (_redirectionHistory.length > _configuration.redirectLimit) {
- final String formattedHistory = _formatOnEnterRedirectionHistory(
- _redirectionHistory,
- );
+ final String formattedHistory = _formatOnEnterRedirectionHistory(_redirectionHistory);
final RouteMatchList errorMatchList = _errorRouteMatchList(
redirectedUri,
GoException('Too many onEnter calls detected: $formattedHistory'),
@@ -639,11 +598,7 @@
/// Creates an error [RouteMatchList] for the given [uri] and [exception].
///
/// This is used to encapsulate errors encountered during redirection or parsing.
- static RouteMatchList _errorRouteMatchList(
- Uri uri,
- GoException exception, {
- Object? extra,
- }) {
+ static RouteMatchList _errorRouteMatchList(Uri uri, GoException exception, {Object? extra}) {
return RouteMatchList(
matches: const <RouteMatch>[],
extra: extra,
diff --git a/packages/go_router/lib/src/path_utils.dart b/packages/go_router/lib/src/path_utils.dart
index ed1ce7c..de8dafc 100644
--- a/packages/go_router/lib/src/path_utils.dart
+++ b/packages/go_router/lib/src/path_utils.dart
@@ -23,11 +23,7 @@
/// 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<String> parameters, {
- required bool caseSensitive,
-}) {
+RegExp patternToRegExp(String pattern, List<String> parameters, {required bool caseSensitive}) {
final buffer = StringBuffer('^');
var start = 0;
for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) {
@@ -99,13 +95,9 @@
///
/// The [parameters] should originate from the call to [patternToRegExp] that
/// creates the [RegExp].
-Map<String, String> extractPathParameters(
- List<String> parameters,
- RegExpMatch match,
-) {
+Map<String, String> extractPathParameters(List<String> parameters, RegExpMatch match) {
return <String, String>{
- for (int i = 0; i < parameters.length; ++i)
- parameters[i]: match.namedGroup(parameters[i])!,
+ for (int i = 0; i < parameters.length; ++i) parameters[i]: match.namedGroup(parameters[i])!,
};
}
@@ -125,9 +117,7 @@
///
/// e.g: pathA = /a?fid=f1, pathB = c/d?pid=p2, concatenatePaths(pathA, pathB) = /a/c/d?pid=2.
Uri concatenateUris(Uri parentUri, Uri childUri) {
- Uri newUri = childUri.replace(
- path: concatenatePaths(parentUri.path, childUri.path),
- );
+ Uri newUri = childUri.replace(path: concatenatePaths(parentUri.path, childUri.path));
// Parse the new normalized uri to remove unnecessary parts, like the trailing '?'.
newUri = Uri.parse(canonicalUri(newUri.toString()));
@@ -147,11 +137,7 @@
// /profile/ => /profile
// / => /
// /login?from=/ => /login?from=/
- canon =
- uri.path.endsWith('/') &&
- uri.path != '/' &&
- !uri.hasQuery &&
- !uri.hasFragment
+ canon = uri.path.endsWith('/') && uri.path != '/' && !uri.hasQuery && !uri.hasFragment
? canon.substring(0, canon.length - 1)
: canon;
@@ -171,11 +157,7 @@
}
/// Builds an absolute path for the provided route.
-String? fullPathForRoute(
- RouteBase targetRoute,
- String parentFullpath,
- List<RouteBase> routes,
-) {
+String? fullPathForRoute(RouteBase targetRoute, String parentFullpath, List<RouteBase> routes) {
for (final route in routes) {
final String fullPath = (route is GoRoute)
? concatenatePaths(parentFullpath, route.path)
@@ -184,11 +166,7 @@
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 cf1a7e2..6d75560 100644
--- a/packages/go_router/lib/src/route.dart
+++ b/packages/go_router/lib/src/route.dart
@@ -18,12 +18,10 @@
import 'state.dart';
/// The page builder for [GoRoute].
-typedef GoRouterPageBuilder =
- Page<dynamic> Function(BuildContext context, GoRouterState state);
+typedef GoRouterPageBuilder = Page<dynamic> 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 =
@@ -31,11 +29,7 @@
/// The page builder for [ShellRoute].
typedef ShellRoutePageBuilder =
- Page<dynamic> Function(
- BuildContext context,
- GoRouterState state,
- Widget child,
- );
+ Page<dynamic> Function(BuildContext context, GoRouterState state, Widget child);
/// The widget builder for [StatefulShellRoute].
typedef StatefulShellRouteBuilder =
@@ -67,8 +61,7 @@
///
/// 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<bool> Function(BuildContext context, GoRouterState state);
+typedef ExitCallback = FutureOr<bool> Function(BuildContext context, GoRouterState state);
/// The base class for [GoRoute] and [ShellRoute].
///
@@ -158,11 +151,7 @@
/// See [main.dart](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/main.dart)
@immutable
abstract class RouteBase with Diagnosticable {
- const RouteBase._({
- this.redirect,
- required this.routes,
- required this.parentNavigatorKey,
- });
+ const RouteBase._({this.redirect, required this.routes, required this.parentNavigatorKey});
/// An optional redirect function for this route.
///
@@ -233,9 +222,7 @@
/// Builds a lists containing the provided routes along with all their
/// descendant [routes].
static Iterable<RouteBase> routesRecursively(Iterable<RouteBase> routes) {
- return routes.expand(
- (RouteBase e) => <RouteBase>[e, ...routesRecursively(e.routes)],
- );
+ return routes.expand((RouteBase e) => <RouteBase>[e, ...routesRecursively(e.routes)]);
}
@override
@@ -243,10 +230,7 @@
super.debugFillProperties(properties);
if (parentNavigatorKey != null) {
properties.add(
- DiagnosticsProperty<GlobalKey<NavigatorState>>(
- 'parentNavKey',
- parentNavigatorKey,
- ),
+ DiagnosticsProperty<GlobalKey<NavigatorState>>('parentNavKey', parentNavigatorKey),
);
}
}
@@ -294,11 +278,7 @@
),
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.
@@ -482,9 +462,7 @@
super.debugFillProperties(properties);
properties.add(StringProperty('name', name));
properties.add(StringProperty('path', path));
- properties.add(
- FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only'),
- );
+ properties.add(FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only'));
}
late final RegExp _pathRE;
@@ -515,8 +493,7 @@
) {
for (final route in subRoutes) {
assert(
- route.parentNavigatorKey == null ||
- route.parentNavigatorKey == navigatorKey,
+ 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) {
@@ -594,9 +571,7 @@
final effectiveObservers = <NavigatorObserver>[...?observers];
if (notifyRootObserver) {
- final List<NavigatorObserver>? rootObservers = GoRouter.maybeOf(
- context,
- )?.observers;
+ final List<NavigatorObserver>? rootObservers = GoRouter.maybeOf(context)?.observers;
if (rootObservers != null) {
effectiveObservers.add(_MergedNavigatorObserver(rootObservers));
}
@@ -723,10 +698,7 @@
navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>(),
super._() {
assert(() {
- ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(
- routes,
- this.navigatorKey,
- );
+ ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(routes, this.navigatorKey);
return true;
}());
}
@@ -807,12 +779,7 @@
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
- properties.add(
- DiagnosticsProperty<GlobalKey<NavigatorState>>(
- 'navigatorKey',
- navigatorKey,
- ),
- );
+ properties.add(DiagnosticsProperty<GlobalKey<NavigatorState>>('navigatorKey', navigatorKey));
}
}
@@ -1021,11 +988,7 @@
ShellRouteContext shellRouteContext,
) {
if (pageBuilder != null) {
- return pageBuilder!(
- context,
- state,
- _createShell(context, shellRouteContext),
- );
+ return pageBuilder!(context, state, _createShell(context, shellRouteContext));
}
return null;
}
@@ -1042,14 +1005,12 @@
Iterable<GlobalKey<NavigatorState>> get _navigatorKeys =>
branches.map((StatefulShellBranch b) => b.navigatorKey);
- StatefulNavigationShell _createShell(
- BuildContext context,
- ShellRouteContext shellRouteContext,
- ) => StatefulNavigationShell(
- shellRouteContext: shellRouteContext,
- router: GoRouter.of(context),
- containerBuilder: navigatorContainerBuilder,
- );
+ StatefulNavigationShell _createShell(BuildContext context, ShellRouteContext shellRouteContext) =>
+ StatefulNavigationShell(
+ shellRouteContext: shellRouteContext,
+ router: GoRouter.of(context),
+ containerBuilder: navigatorContainerBuilder,
+ );
static Widget _indexedStackContainerBuilder(
BuildContext context,
@@ -1067,19 +1028,14 @@
static Set<GlobalKey<NavigatorState>> _debugUniqueNavigatorKeys(
List<StatefulShellBranch> branches,
- ) => Set<GlobalKey<NavigatorState>>.from(
- branches.map((StatefulShellBranch e) => e.navigatorKey),
- );
+ ) => Set<GlobalKey<NavigatorState>>.from(branches.map((StatefulShellBranch e) => e.navigatorKey));
- static bool _debugValidateParentNavigatorKeys(
- List<StatefulShellBranch> branches,
- ) {
+ static bool _debugValidateParentNavigatorKeys(List<StatefulShellBranch> branches) {
for (final branch in branches) {
for (final RouteBase route in branch.routes) {
if (route is GoRoute) {
assert(
- route.parentNavigatorKey == null ||
- route.parentNavigatorKey == branch.navigatorKey,
+ route.parentNavigatorKey == null || route.parentNavigatorKey == branch.navigatorKey,
);
}
}
@@ -1091,10 +1047,7 @@
String? restorationScopeId,
List<StatefulShellBranch> branches,
) {
- if (branches
- .map((StatefulShellBranch e) => e.restorationScopeId)
- .nonNulls
- .isNotEmpty) {
+ if (branches.map((StatefulShellBranch e) => e.restorationScopeId).nonNulls.isNotEmpty) {
assert(
restorationScopeId != null,
'A restorationScopeId must be set for '
@@ -1109,10 +1062,7 @@
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
- DiagnosticsProperty<Iterable<GlobalKey<NavigatorState>>>(
- 'navigatorKeys',
- _navigatorKeys,
- ),
+ DiagnosticsProperty<Iterable<GlobalKey<NavigatorState>>>('navigatorKeys', _navigatorKeys),
);
}
}
@@ -1144,10 +1094,7 @@
this.preload = false,
}) : navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>() {
assert(() {
- ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(
- routes,
- this.navigatorKey,
- );
+ ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(routes, this.navigatorKey);
return true;
}());
}
@@ -1199,8 +1146,7 @@
///
/// This route will be used when loading the branch for the first time, if
/// an [initialLocation] has not been provided.
- GoRoute? get defaultRoute =>
- RouteBase.routesRecursively(routes).whereType<GoRoute>().firstOrNull;
+ GoRoute? get defaultRoute => RouteBase.routesRecursively(routes).whereType<GoRoute>().firstOrNull;
}
/// Builder for a custom container for the branch Navigators of a
@@ -1243,9 +1189,7 @@
shellRouteContext.route as StatefulShellRoute,
shellRouteContext.navigatorKey,
),
- super(
- key: (shellRouteContext.route as StatefulShellRoute)._shellStateKey,
- );
+ super(key: (shellRouteContext.route as StatefulShellRoute)._shellStateKey);
/// The ShellRouteContext responsible for building the Navigator for the
/// current [StatefulShellBranch].
@@ -1275,8 +1219,7 @@
// class.
void goBranch(int index, {bool initialLocation = false}) {
final route = shellRouteContext.route as StatefulShellRoute;
- final StatefulNavigationShellState? shellState =
- route._shellStateKey.currentState;
+ final StatefulNavigationShellState? shellState = route._shellStateKey.currentState;
if (shellState != null) {
shellState.goBranch(index, initialLocation: initialLocation);
} else {
@@ -1288,8 +1231,7 @@
/// associated with it).
@visibleForTesting
List<StatefulShellBranch> get debugLoadedBranches =>
- route._shellStateKey.currentState?._loadedBranches ??
- <StatefulShellBranch>[];
+ route._shellStateKey.currentState?._loadedBranches ?? <StatefulShellBranch>[];
/// Gets the effective initial location for the branch at the provided index
/// in the associated [StatefulShellRoute].
@@ -1308,17 +1250,10 @@
/// find the first GoRoute, from which a full path will be derived.
final GoRoute route = branch.defaultRoute!;
final parameters = <String>[];
- 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,
- );
+ return patternToPath(fullPath, shellRouteContext.routerState.pathParameters);
}
}
@@ -1355,8 +1290,7 @@
}
/// State for StatefulNavigationShell.
-class StatefulNavigationShellState extends State<StatefulNavigationShell>
- with RestorationMixin {
+class StatefulNavigationShellState extends State<StatefulNavigationShell> with RestorationMixin {
final Map<StatefulShellBranch, _StatefulShellBranchState> _branchState =
<StatefulShellBranch, _StatefulShellBranchState>{};
@@ -1365,8 +1299,7 @@
GoRouter get _router => widget._router;
- bool _isBranchLoaded(StatefulShellBranch branch) =>
- _branchState[branch] != null;
+ bool _isBranchLoaded(StatefulShellBranch branch) => _branchState[branch] != null;
List<StatefulShellBranch> get _loadedBranches => _branchState.keys.toList();
@@ -1382,19 +1315,13 @@
: identityHashCode(branch).toString();
}
- _StatefulShellBranchState _branchStateFor(
- StatefulShellBranch branch, [
- bool register = true,
- ]) {
+ _StatefulShellBranchState _branchStateFor(StatefulShellBranch branch, [bool register = true]) {
return _branchState.putIfAbsent(branch, () {
final branchState = _StatefulShellBranchState(
location: _RestorableRouteMatchList(_router.configuration),
);
if (register) {
- registerForRestoration(
- branchState.location,
- _branchLocationRestorationScopeId(branch),
- );
+ registerForRestoration(branchState.location, _branchLocationRestorationScopeId(branch));
}
return branchState;
});
@@ -1433,14 +1360,9 @@
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 hasExistingNavigator = branchState.navigator != null;
@@ -1484,10 +1406,7 @@
branch.restorationScopeId,
);
- final _StatefulShellBranchState branchState = _branchStateFor(
- branch,
- false,
- );
+ final _StatefulShellBranchState branchState = _branchStateFor(branch, false);
branchState.location.value = matchList;
branchState.navigator = navigator;
}
@@ -1495,10 +1414,7 @@
}
void _cleanUpObsoleteBranches() {
- _branchState.removeWhere((
- StatefulShellBranch branch,
- _StatefulShellBranchState branchState,
- ) {
+ _branchState.removeWhere((StatefulShellBranch branch, _StatefulShellBranchState branchState) {
if (!route.branches.contains(branch)) {
branchState.dispose();
return true;
@@ -1521,9 +1437,7 @@
/// the branch (see [StatefulShellBranch.initialLocation]).
void goBranch(int index, {bool initialLocation = false}) {
assert(index >= 0 && index < route.branches.length);
- final RouteMatchList? matchList = initialLocation
- ? null
- : _matchListForBranch(index);
+ final RouteMatchList? matchList = initialLocation ? null : _matchListForBranch(index);
if (matchList != null && matchList.isNotEmpty) {
_router.restore(matchList);
} else {
@@ -1563,8 +1477,7 @@
(StatefulShellBranch branch) => _BranchNavigatorProxy(
key: ObjectKey(branch),
branch: branch,
- navigatorForBranch: (StatefulShellBranch branch) =>
- _branchState[branch]?.navigator,
+ navigatorForBranch: (StatefulShellBranch branch) => _branchState[branch]?.navigator,
),
)
.toList();
@@ -1635,11 +1548,7 @@
/// important for container implementations that cache child widgets,
/// such as [TabBarView].
class _BranchNavigatorProxy extends StatefulWidget {
- const _BranchNavigatorProxy({
- super.key,
- required this.branch,
- required this.navigatorForBranch,
- });
+ const _BranchNavigatorProxy({super.key, required this.branch, required this.navigatorForBranch});
final StatefulShellBranch branch;
final _NavigatorForBranch navigatorForBranch;
@@ -1666,10 +1575,7 @@
/// 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;
@@ -1687,11 +1593,7 @@
return IndexedStack(index: currentIndex, children: stackItems);
}
- Widget _buildRouteBranchContainer(
- BuildContext context,
- bool isActive,
- Widget child,
- ) {
+ Widget _buildRouteBranchContainer(BuildContext context, bool isActive, Widget child) {
return Offstage(
offstage: !isActive,
child: TickerMode(enabled: isActive, child: child),
@@ -1746,10 +1648,7 @@
}
@override
- void didStartUserGesture(
- Route<dynamic> route,
- Route<dynamic>? previousRoute,
- ) {
+ void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) {
for (final NavigatorObserver observer in observers) {
observer.didStartUserGesture(route, previousRoute);
}
diff --git a/packages/go_router/lib/src/route_data.dart b/packages/go_router/lib/src/route_data.dart
index 4a832d1..6cca5b1 100644
--- a/packages/go_router/lib/src/route_data.dart
+++ b/packages/go_router/lib/src/route_data.dart
@@ -31,9 +31,7 @@
///
/// Corresponds to [GoRoute.builder].
Widget build(BuildContext context, GoRouterState state) =>
- throw UnimplementedError(
- 'One of `build` or `buildPage` must be implemented.',
- );
+ throw UnimplementedError('One of `build` or `buildPage` must be implemented.');
/// A page builder for this route.
///
@@ -46,8 +44,7 @@
///
/// By default, returns a [Page] instance that is ignored, causing a default
/// [Page] implementation to be used with the results of [build].
- Page<void> buildPage(BuildContext context, GoRouterState state) =>
- const NoOpPage();
+ Page<void> buildPage(BuildContext context, GoRouterState state) => const NoOpPage();
/// An optional redirect function for this route.
///
@@ -70,19 +67,19 @@
/// Used to cache [_GoRouteDataBase] that corresponds to a given [GoRouterState]
/// to minimize the number of times it has to be deserialized.
- static final Expando<_GoRouteDataBase> stateObjectExpando =
- Expando<_GoRouteDataBase>('GoRouteState to _GoRouteDataBase expando');
+ static final Expando<_GoRouteDataBase> stateObjectExpando = Expando<_GoRouteDataBase>(
+ 'GoRouteState to _GoRouteDataBase expando',
+ );
}
/// Helper to build a location string from a path and query parameters.
-String _buildLocation(String path, {Map<String, dynamic>? queryParams}) =>
- Uri.parse(path)
- .replace(
- queryParameters:
- // Avoid `?` in generated location if `queryParams` is empty
- queryParams?.isNotEmpty ?? false ? queryParams : null,
- )
- .toString();
+String _buildLocation(String path, {Map<String, dynamic>? queryParams}) => Uri.parse(path)
+ .replace(
+ queryParameters:
+ // Avoid `?` in generated location if `queryParams` is empty
+ queryParams?.isNotEmpty ?? false ? queryParams : null,
+ )
+ .toString();
/// Holds the parameters for constructing a [GoRoute].
class _GoRouteParameters {
@@ -127,8 +124,7 @@
redirect: (BuildContext context, GoRouterState state) =>
factoryImpl(state).redirect(context, state),
onExit: hasOverriddenOnExit == null || hasOverriddenOnExit
- ? (BuildContext context, GoRouterState state) =>
- factoryImpl(state).onExit(context, state)
+ ? (BuildContext context, GoRouterState state) => factoryImpl(state).onExit(context, state)
: null,
);
}
@@ -186,16 +182,13 @@
String get location => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Navigate to the route.
- void go(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ void go(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Push the route onto the page stack.
- Future<T?> push<T>(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ Future<T?> push<T>(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Replaces the top-most page of the page stack with the route.
- void pushReplacement(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ void pushReplacement(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Replaces the top-most page of the page stack with the route but treats
/// it as the same page.
@@ -203,8 +196,7 @@
/// The page key will be reused. This will preserve the state and not run any
/// page animation.
///
- void replace(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ void replace(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
}
/// A class to represent a relative [GoRoute] in
@@ -261,12 +253,10 @@
String get relativeLocation => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Navigate to the route.
- void goRelative(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ void goRelative(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Push the route onto the page stack.
- Future<T?> pushRelative<T>(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ Future<T?> pushRelative<T>(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
/// Replaces the top-most page of the page stack with the route.
void pushReplacementRelative(BuildContext context) =>
@@ -278,8 +268,7 @@
/// The page key will be reused. This will preserve the state and not run any
/// page animation.
///
- void replaceRelative(BuildContext context) =>
- throw _GoRouteDataBase.shouldBeGeneratedError;
+ void replaceRelative(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError;
}
/// A class to represent a [ShellRoute] in
@@ -291,17 +280,12 @@
const ShellRouteData();
/// [pageBuilder] is used to build the page
- Page<void> pageBuilder(
- BuildContext context,
- GoRouterState state,
- Widget navigator,
- ) => const NoOpPage();
+ Page<void> pageBuilder(BuildContext context, GoRouterState state, Widget navigator) =>
+ const NoOpPage();
/// [builder] is used to build the widget
Widget builder(BuildContext context, GoRouterState state, Widget navigator) =>
- throw UnimplementedError(
- 'One of `builder` or `pageBuilder` must be implemented.',
- );
+ throw UnimplementedError('One of `builder` or `pageBuilder` must be implemented.');
/// An optional redirect function for this route.
///
@@ -330,17 +314,11 @@
FutureOr<String?> redirect(BuildContext context, GoRouterState state) =>
factoryImpl(state).redirect(context, state);
- Widget builder(
- BuildContext context,
- GoRouterState state,
- Widget navigator,
- ) => factoryImpl(state).builder(context, state, navigator);
+ Widget builder(BuildContext context, GoRouterState state, Widget navigator) =>
+ factoryImpl(state).builder(context, state, navigator);
- Page<void> pageBuilder(
- BuildContext context,
- GoRouterState state,
- Widget navigator,
- ) => factoryImpl(state).pageBuilder(context, state, navigator);
+ Page<void> pageBuilder(BuildContext context, GoRouterState state, Widget navigator) =>
+ factoryImpl(state).pageBuilder(context, state, navigator);
return ShellRoute(
builder: builder,
@@ -357,8 +335,9 @@
/// Used to cache [ShellRouteData] that corresponds to a given [GoRouterState]
/// to minimize the number of times it has to be deserialized.
- static final Expando<ShellRouteData> _stateObjectExpando =
- Expando<ShellRouteData>('GoRouteState to ShellRouteData expando');
+ static final Expando<ShellRouteData> _stateObjectExpando = Expando<ShellRouteData>(
+ 'GoRouteState to ShellRouteData expando',
+ );
}
/// Base class for supporting
@@ -387,9 +366,7 @@
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
- ) => throw UnimplementedError(
- 'One of `builder` or `pageBuilder` must be implemented.',
- );
+ ) => throw UnimplementedError('One of `builder` or `pageBuilder` must be implemented.');
/// A helper function used by generated code.
///
@@ -444,9 +421,7 @@
/// Used to cache [StatefulShellRouteData] that corresponds to a given [GoRouterState]
/// to minimize the number of times it has to be deserialized.
static final Expando<StatefulShellRouteData> _stateObjectExpando =
- Expando<StatefulShellRouteData>(
- 'GoRouteState to StatefulShellRouteData expando',
- );
+ Expando<StatefulShellRouteData>('GoRouteState to StatefulShellRouteData expando');
}
/// Base class for supporting
@@ -528,8 +503,7 @@
/// A superclass for each typed relative go route descendant
@Target(<TargetKind>{TargetKind.library, TargetKind.classType})
-class TypedRelativeGoRoute<T extends RelativeGoRouteData>
- extends TypedRoute<T> {
+class TypedRelativeGoRoute<T extends RelativeGoRouteData> extends TypedRoute<T> {
/// Default const constructor
const TypedRelativeGoRoute({
required this.path,
@@ -584,8 +558,7 @@
/// A superclass for each typed shell route descendant
@Target(<TargetKind>{TargetKind.library, TargetKind.classType})
-class TypedStatefulShellRoute<T extends StatefulShellRouteData>
- extends TypedRoute<T> {
+class TypedStatefulShellRoute<T extends StatefulShellRouteData> extends TypedRoute<T> {
/// Default const constructor
const TypedStatefulShellRoute({
this.notifyRootObserver = true,
@@ -608,9 +581,7 @@
@Target(<TargetKind>{TargetKind.library, TargetKind.classType})
class TypedStatefulShellBranch<T extends StatefulShellBranchData> {
/// Default const constructor
- const TypedStatefulShellBranch({
- this.routes = const <TypedRoute<RouteData>>[],
- });
+ const TypedStatefulShellBranch({this.routes = const <TypedRoute<RouteData>>[]});
/// Child route definitions.
///
@@ -625,8 +596,7 @@
const NoOpPage();
@override
- Route<void> createRoute(BuildContext context) =>
- throw UnsupportedError('Should never be called');
+ Route<void> createRoute(BuildContext context) => throw UnsupportedError('Should never be called');
}
/// Signature of custom query parameter encoding.
@@ -652,19 +622,15 @@
@Target({TargetKind.parameter})
class TypedQueryParameter<T> {
/// Annotation to override the URI name for a route parameter.
- const TypedQueryParameter({
- this.name,
- this.encoder,
- this.decoder,
- this.compare,
- }) : assert(
- (encoder == null) == (decoder == null),
- 'encoder and decoder must both be provided together',
- ),
- assert(
- compare == null || encoder != null,
- 'compare function requires an encoder to be provided',
- );
+ const TypedQueryParameter({this.name, this.encoder, this.decoder, this.compare})
+ : assert(
+ (encoder == null) == (decoder == null),
+ 'encoder and decoder must both be provided together',
+ ),
+ assert(
+ compare == null || encoder != null,
+ 'compare function requires an encoder to be provided',
+ );
/// The name of the parameter in the URI.
///
diff --git a/packages/go_router/lib/src/router.dart b/packages/go_router/lib/src/router.dart
index de8bdf1..5f1ff5d 100644
--- a/packages/go_router/lib/src/router.dart
+++ b/packages/go_router/lib/src/router.dart
@@ -59,10 +59,7 @@
this.redirectLimit = 5,
});
- static FutureOr<String?> _defaultRedirect(
- BuildContext context,
- GoRouterState state,
- ) => null;
+ static FutureOr<String?> _defaultRedirect(BuildContext context, GoRouterState state) => null;
/// The supported routes.
///
@@ -272,16 +269,11 @@
final ParserExceptionHandler? parserExceptionHandler;
if (onException != null) {
- parserExceptionHandler =
- (BuildContext context, RouteMatchList routeMatchList) {
- onException(
- context,
- configuration.buildTopLevelGoRouterState(routeMatchList),
- this,
- );
- // Avoid updating GoRouterDelegate if onException is provided.
- return routerDelegate.currentConfiguration;
- };
+ parserExceptionHandler = (BuildContext context, RouteMatchList routeMatchList) {
+ onException(context, configuration.buildTopLevelGoRouterState(routeMatchList), this);
+ // Avoid updating GoRouterDelegate if onException is provided.
+ return routerDelegate.currentConfiguration;
+ };
} else {
parserExceptionHandler = null;
}
@@ -420,10 +412,7 @@
/// Restore the RouteMatchList
void restore(RouteMatchList matchList) {
log('restoring ${matchList.uri}');
- routeInformationProvider.restore(
- matchList.uri.toString(),
- matchList: matchList,
- );
+ routeInformationProvider.restore(matchList.uri.toString(), matchList: matchList);
}
/// Navigate to a named route w/ optional parameters, e.g.
@@ -473,11 +462,7 @@
Map<String, dynamic> queryParameters = const <String, dynamic>{},
Object? extra,
}) => push<T>(
- namedLocation(
- name,
- pathParameters: pathParameters,
- queryParameters: queryParameters,
- ),
+ namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters),
extra: extra,
);
@@ -490,10 +475,7 @@
/// * [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<T?> pushReplacement<T extends Object?>(
- String location, {
- Object? extra,
- }) {
+ Future<T?> pushReplacement<T extends Object?>(String location, {Object? extra}) {
log('pushReplacement $location');
return routeInformationProvider.pushReplacement<T>(
location,
@@ -516,11 +498,7 @@
Object? extra,
}) {
return pushReplacement<T>(
- namedLocation(
- name,
- pathParameters: pathParameters,
- queryParameters: queryParameters,
- ),
+ namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters),
extra: extra,
);
}
@@ -562,11 +540,7 @@
Object? extra,
}) {
return replace(
- namedLocation(
- name,
- pathParameters: pathParameters,
- queryParameters: queryParameters,
- ),
+ namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters),
extra: extra,
);
}
@@ -613,9 +587,7 @@
/// The current GoRouter in the widget tree, if any.
static GoRouter? maybeOf(BuildContext context) {
final inherited =
- context
- .getElementForInheritedWidgetOfExactType<InheritedGoRouter>()
- ?.widget
+ context.getElementForInheritedWidgetOfExactType<InheritedGoRouter>()?.widget
as InheritedGoRouter?;
if (inherited != null) {
return inherited.goRouter;
@@ -638,9 +610,7 @@
// verified by assert() during the initialization.
return initialLocation!;
}
- Uri platformDefaultUri = Uri.parse(
- WidgetsBinding.instance.platformDispatcher.defaultRouteName,
- );
+ Uri platformDefaultUri = Uri.parse(WidgetsBinding.instance.platformDispatcher.defaultRouteName);
if (platformDefaultUri.hasEmptyPath) {
platformDefaultUri = platformDefaultUri.replace(path: '/');
}
diff --git a/packages/go_router/lib/src/state.dart b/packages/go_router/lib/src/state.dart
index 8055463..bd57559 100644
--- a/packages/go_router/lib/src/state.dart
+++ b/packages/go_router/lib/src/state.dart
@@ -125,16 +125,14 @@
}
final RouteSettings settings = route.settings;
if (settings is Page<Object?>) {
- scope = context
- .dependOnInheritedWidgetOfExactType<GoRouterStateRegistryScope>();
+ scope = context.dependOnInheritedWidgetOfExactType<GoRouterStateRegistryScope>();
if (scope == null) {
throw _noGoRouterStateError;
}
- final GoRouterState? state = scope.notifier!
- ._createPageRouteAssociation(
- route.settings as Page<Object?>,
- route,
- );
+ final GoRouterState? state = scope.notifier!._createPageRouteAssociation(
+ route.settings as Page<Object?>,
+ route,
+ );
if (state != null) {
return state;
}
@@ -204,8 +202,7 @@
/// Should not be used directly, consider using [GoRouterState.of] to access
/// [GoRouterState] from the context.
@internal
-class GoRouterStateRegistryScope
- extends InheritedNotifier<GoRouterStateRegistry> {
+class GoRouterStateRegistryScope extends InheritedNotifier<GoRouterStateRegistry> {
/// Creates a GoRouterStateRegistryScope.
const GoRouterStateRegistryScope({
super.key,
@@ -225,16 +222,12 @@
/// A [Map] that maps a [Page] to a [GoRouterState].
@visibleForTesting
- final Map<Page<Object?>, GoRouterState> registry =
- <Page<Object?>, GoRouterState>{};
+ final Map<Page<Object?>, GoRouterState> registry = <Page<Object?>, GoRouterState>{};
final Map<Route<Object?>, Page<Object?>> _routePageAssociation =
<ModalRoute<Object?>, Page<Object?>>{};
- GoRouterState? _createPageRouteAssociation(
- Page<Object?> page,
- ModalRoute<Object?> route,
- ) {
+ GoRouterState? _createPageRouteAssociation(Page<Object?> page, ModalRoute<Object?> route) {
assert(route.settings == page);
if (!registry.containsKey(page)) {
return null;
@@ -249,9 +242,7 @@
route.completed.then<void>((Object? result) {
// Can't use `page` directly because Route.settings may have changed during
// the lifetime of this route.
- final Page<Object?> associatedPage = _routePageAssociation.remove(
- route,
- )!;
+ final Page<Object?> associatedPage = _routePageAssociation.remove(route)!;
assert(registry.containsKey(associatedPage));
registry.remove(associatedPage);
});
@@ -268,15 +259,12 @@
/// Updates this registry with new records.
void updateRegistry(Map<Page<Object?>, GoRouterState> newRegistry) {
var shouldNotify = false;
- final Set<Page<Object?>> pagesWithAssociation = _routePageAssociation.values
- .toSet();
- for (final MapEntry<Page<Object?>, GoRouterState> entry
- in newRegistry.entries) {
+ final Set<Page<Object?>> pagesWithAssociation = _routePageAssociation.values.toSet();
+ for (final MapEntry<Page<Object?>, GoRouterState> entry in newRegistry.entries) {
final GoRouterState? existingState = registry[entry.key];
if (existingState != null) {
if (existingState != entry.value) {
- shouldNotify =
- shouldNotify || pagesWithAssociation.contains(entry.key);
+ shouldNotify = shouldNotify || pagesWithAssociation.contains(entry.key);
registry[entry.key] = entry.value;
}
continue;
diff --git a/packages/go_router/test/builder_test.dart b/packages/go_router/test/builder_test.dart
index 46292b6..ebdc75e 100644
--- a/packages/go_router/test/builder_test.dart
+++ b/packages/go_router/test/builder_test.dart
@@ -39,9 +39,7 @@
pathParameters: const <String, String>{},
);
- await tester.pumpWidget(
- _BuilderTestWidget(routeConfiguration: config, matches: matches),
- );
+ await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches));
expect(find.byType(_DetailsScreen), findsOneWidget);
});
@@ -92,9 +90,7 @@
pathParameters: const <String, String>{},
);
- await tester.pumpWidget(
- _BuilderTestWidget(routeConfiguration: config, matches: matches),
- );
+ await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches));
expect(find.byType(_DetailsScreen), findsOneWidget);
});
@@ -129,16 +125,12 @@
pathParameters: const <String, String>{},
);
- await tester.pumpWidget(
- _BuilderTestWidget(routeConfiguration: config, matches: matches),
- );
+ await tester.pumpWidget(_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 rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
final shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell');
final RouteConfiguration config = createRouteConfiguration(
@@ -185,9 +177,7 @@
pathParameters: const <String, String>{},
);
- await tester.pumpWidget(
- _BuilderTestWidget(routeConfiguration: config, matches: matches),
- );
+ await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches));
expect(find.byType(_HomeScreen, skipOffstage: false), findsOneWidget);
expect(find.byType(_DetailsScreen), findsOneWidget);
@@ -246,9 +236,7 @@
pathParameters: const <String, String>{},
);
- await tester.pumpWidget(
- _BuilderTestWidget(routeConfiguration: config, matches: matches),
- );
+ await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches));
// The Details screen should be visible, but the HomeScreen should be
// offstage (underneath) the DetailsScreen.
@@ -256,9 +244,7 @@
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 rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
final shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell');
final RouteConfiguration config = createRouteConfiguration(
@@ -306,16 +292,11 @@
pathParameters: const <String, String>{},
);
- await tester.pumpWidget(
- _BuilderTestWidget(routeConfiguration: config, matches: matches),
- );
+ await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches));
expect(find.byKey(rootNavigatorKey), findsOneWidget);
expect(find.byKey(shellNavigatorKey), findsOneWidget);
- expect(
- (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId,
- 'scope1',
- );
+ expect((shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, 'scope1');
});
testWidgets('Uses the correct restorationScopeId for StatefulShellRoute', (
@@ -358,15 +339,10 @@
expect(find.byKey(rootNavigatorKey), findsOneWidget);
expect(find.byKey(shellNavigatorKey), findsOneWidget);
- expect(
- (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId,
- 'scope1',
- );
+ expect((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 router = GoRouter(
routes: <RouteBase>[
GoRoute(
@@ -381,15 +357,11 @@
addTearDown(() => router.dispose());
- final Navigator navigator = tester.widget<Navigator>(
- find.byType(Navigator),
- );
+ final Navigator navigator = tester.widget<Navigator>(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 router = GoRouter(
routes: <RouteBase>[
GoRoute(
@@ -405,9 +377,7 @@
addTearDown(() => router.dispose());
- final Navigator navigator = tester.widget<Navigator>(
- find.byType(Navigator),
- );
+ final Navigator navigator = tester.widget<Navigator>(find.byType(Navigator));
expect(navigator.requestFocus, isFalse);
});
});
diff --git a/packages/go_router/test/configuration_test.dart b/packages/go_router/test/configuration_test.dart
index 2e6e9cc..3960c73 100644
--- a/packages/go_router/test/configuration_test.dart
+++ b/packages/go_router/test/configuration_test.dart
@@ -26,19 +26,13 @@
ShellRoute(
navigatorKey: a,
builder: _mockShellBuilder,
- routes: <RouteBase>[
- GoRoute(path: 'b', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: 'b', builder: _mockScreenBuilder)],
),
ShellRoute(
navigatorKey: b,
builder: _mockShellBuilder,
routes: <RouteBase>[
- GoRoute(
- path: 'c',
- parentNavigatorKey: a,
- builder: _mockScreenBuilder,
- ),
+ GoRoute(path: 'c', parentNavigatorKey: a, builder: _mockScreenBuilder),
],
),
],
@@ -67,54 +61,12 @@
}, throwsAssertionError);
});
- test(
- 'throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final keyA = GlobalKey<NavigatorState>(debugLabel: 'A');
- final keyB = GlobalKey<NavigatorState>(debugLabel: 'B');
+ test('throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final keyA = GlobalKey<NavigatorState>(debugLabel: 'A');
+ final keyB = GlobalKey<NavigatorState>(debugLabel: 'B');
- expect(() {
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- StatefulShellRoute.indexedStack(
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- navigatorKey: keyA,
- routes: <RouteBase>[
- GoRoute(
- path: '/a',
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'details',
- builder: _mockScreenBuilder,
- parentNavigatorKey: keyB,
- ),
- ],
- ),
- ],
- ),
- ],
- builder: mockStackedShellBuilder,
- ),
- ],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- );
- }, throwsA(isA<AssertionError>()));
- },
- );
-
- test(
- 'does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final keyA = GlobalKey<NavigatorState>(debugLabel: 'A');
-
+ expect(() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
@@ -130,7 +82,7 @@
GoRoute(
path: 'details',
builder: _mockScreenBuilder,
- parentNavigatorKey: keyA,
+ parentNavigatorKey: keyB,
),
],
),
@@ -145,79 +97,78 @@
return null;
},
);
- },
- );
+ }, throwsA(isA<AssertionError>()));
+ });
- test(
- 'throws when a sub-route of StatefulShellRoute has a parentNavigatorKey',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final someNavigatorKey = GlobalKey<NavigatorState>();
- expect(() {
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- StatefulShellRoute.indexedStack(
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
+ test('does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final keyA = GlobalKey<NavigatorState>(debugLabel: 'A');
+
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ navigatorKey: keyA,
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/a',
+ builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
- path: '/a',
+ path: 'details',
builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'details',
- builder: _mockScreenBuilder,
- parentNavigatorKey: someNavigatorKey,
- ),
- ],
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(
- path: '/b',
- builder: _mockScreenBuilder,
- parentNavigatorKey: someNavigatorKey,
+ parentNavigatorKey: keyA,
),
],
),
],
- builder: mockStackedShellBuilder,
),
],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- );
- }, throwsAssertionError);
- },
- );
+ builder: mockStackedShellBuilder,
+ ),
+ ],
+ redirectLimit: 10,
+ topRedirect: (BuildContext context, GoRouterState state) {
+ return null;
+ },
+ );
+ });
- test('throws when StatefulShellRoute has duplicate navigator keys', () {
+ test('throws when a sub-route of StatefulShellRoute has a parentNavigatorKey', () {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final keyA = GlobalKey<NavigatorState>(debugLabel: 'A');
- final shellRouteChildren = <GoRoute>[
- GoRoute(
- path: '/a',
- builder: _mockScreenBuilder,
- parentNavigatorKey: keyA,
- ),
- GoRoute(
- path: '/b',
- builder: _mockScreenBuilder,
- parentNavigatorKey: keyA,
- ),
- ];
+ final someNavigatorKey = GlobalKey<NavigatorState>();
expect(() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
branches: <StatefulShellBranch>[
- StatefulShellBranch(routes: shellRouteChildren),
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/a',
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'details',
+ builder: _mockScreenBuilder,
+ parentNavigatorKey: someNavigatorKey,
+ ),
+ ],
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/b',
+ builder: _mockScreenBuilder,
+ parentNavigatorKey: someNavigatorKey,
+ ),
+ ],
+ ),
],
builder: mockStackedShellBuilder,
),
@@ -230,6 +181,30 @@
}, throwsAssertionError);
});
+ test('throws when StatefulShellRoute has duplicate navigator keys', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final keyA = GlobalKey<NavigatorState>(debugLabel: 'A');
+ final shellRouteChildren = <GoRoute>[
+ GoRoute(path: '/a', builder: _mockScreenBuilder, parentNavigatorKey: keyA),
+ GoRoute(path: '/b', builder: _mockScreenBuilder, parentNavigatorKey: keyA),
+ ];
+ expect(() {
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ branches: <StatefulShellBranch>[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 '
'parentNavigatorKey', () {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
@@ -285,15 +260,11 @@
StatefulShellBranch(
initialLocation: '/x',
navigatorKey: sectionANavigatorKey,
- routes: <RouteBase>[
- GoRoute(path: '/a', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: '/a', builder: _mockScreenBuilder)],
),
StatefulShellBranch(
navigatorKey: sectionBNavigatorKey,
- routes: <RouteBase>[
- GoRoute(path: '/b', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: '/b', builder: _mockScreenBuilder)],
),
],
builder: mockStackedShellBuilder,
@@ -321,9 +292,7 @@
StatefulShellBranch(
initialLocation: '/b',
navigatorKey: sectionANavigatorKey,
- routes: <RouteBase>[
- GoRoute(path: '/a', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: '/a', builder: _mockScreenBuilder)],
),
StatefulShellBranch(
initialLocation: '/b',
@@ -332,9 +301,7 @@
StatefulShellRoute.indexedStack(
branches: <StatefulShellBranch>[
StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(path: '/b', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: '/b', builder: _mockScreenBuilder)],
),
],
builder: mockStackedShellBuilder,
@@ -367,9 +334,7 @@
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(path: 'detail', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: 'detail', builder: _mockScreenBuilder)],
),
],
),
@@ -379,9 +344,7 @@
GoRoute(
path: '/b',
builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(path: 'detail', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: 'detail', builder: _mockScreenBuilder)],
),
],
),
@@ -396,10 +359,7 @@
path: '/c',
builder: _mockScreenBuilder,
routes: <RouteBase>[
- GoRoute(
- path: 'detail',
- builder: _mockScreenBuilder,
- ),
+ GoRoute(path: 'detail', builder: _mockScreenBuilder),
],
),
],
@@ -411,10 +371,7 @@
path: '/d',
builder: _mockScreenBuilder,
routes: <RouteBase>[
- GoRoute(
- path: 'detail',
- builder: _mockScreenBuilder,
- ),
+ GoRoute(path: 'detail', builder: _mockScreenBuilder),
],
),
],
@@ -431,9 +388,7 @@
routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
- routes: <RouteBase>[
- GoRoute(path: '/e', builder: _mockScreenBuilder),
- ],
+ routes: <RouteBase>[GoRoute(path: '/e', builder: _mockScreenBuilder)],
),
],
),
@@ -479,14 +434,8 @@
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
- GoRoute(
- path: 'y1',
- builder: _mockScreenBuilder,
- ),
- GoRoute(
- path: 'y2',
- builder: _mockScreenBuilder,
- ),
+ GoRoute(path: 'y1', builder: _mockScreenBuilder),
+ GoRoute(path: 'y2', builder: _mockScreenBuilder),
],
),
],
@@ -534,41 +483,34 @@
expect('/b1', initialLocation(branchB));
});
- test(
- 'throws when there is a GoRoute ancestor with a different parentNavigatorKey',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
- expect(() {
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- ShellRoute(
- navigatorKey: shell,
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: _mockScreenBuilder,
- parentNavigatorKey: root,
- routes: <RouteBase>[
- GoRoute(
- path: 'a',
- builder: _mockScreenBuilder,
- parentNavigatorKey: shell,
- ),
- ],
- ),
- ],
- ),
- ],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- );
- }, throwsAssertionError);
- },
- );
+ test('throws when there is a GoRoute ancestor with a different parentNavigatorKey', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
+ expect(() {
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ ShellRoute(
+ navigatorKey: shell,
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: _mockScreenBuilder,
+ parentNavigatorKey: root,
+ routes: <RouteBase>[
+ GoRoute(path: 'a', builder: _mockScreenBuilder, parentNavigatorKey: shell),
+ ],
+ ),
+ ],
+ ),
+ ],
+ redirectLimit: 10,
+ topRedirect: (BuildContext context, GoRouterState state) {
+ return null;
+ },
+ );
+ }, throwsAssertionError);
+ });
test('Does not throw with valid parentNavigatorKey configuration', () {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
@@ -619,52 +561,45 @@
);
});
- test(
- 'Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- ShellRoute(
- navigatorKey: shell,
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'a',
- builder: _mockScreenBuilder,
- parentNavigatorKey: root,
- routes: <RouteBase>[
- GoRoute(
- path: 'b',
- builder: _mockScreenBuilder,
- parentNavigatorKey: root,
- routes: <RouteBase>[
- GoRoute(
- path: 'c',
- builder: _mockScreenBuilder,
- parentNavigatorKey: root,
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- );
- },
- );
+ test('Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ ShellRoute(
+ navigatorKey: shell,
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'a',
+ builder: _mockScreenBuilder,
+ parentNavigatorKey: root,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'b',
+ builder: _mockScreenBuilder,
+ parentNavigatorKey: root,
+ routes: <RouteBase>[
+ GoRoute(path: 'c', builder: _mockScreenBuilder, parentNavigatorKey: root),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ redirectLimit: 10,
+ topRedirect: (BuildContext context, GoRouterState state) {
+ return null;
+ },
+ );
+ });
test('Throws when parentNavigatorKeys are overlapping', () {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
@@ -712,51 +647,44 @@
);
});
- test(
- 'Does not throw when parentNavigatorKeys are overlapping correctly',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- ShellRoute(
- navigatorKey: shell,
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'a',
- builder: _mockScreenBuilder,
- parentNavigatorKey: shell,
- routes: <RouteBase>[
- GoRoute(
- path: 'b',
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'b',
- builder: _mockScreenBuilder,
- parentNavigatorKey: root,
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- );
- },
- );
+ test('Does not throw when parentNavigatorKeys are overlapping correctly', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ ShellRoute(
+ navigatorKey: shell,
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'a',
+ builder: _mockScreenBuilder,
+ parentNavigatorKey: shell,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'b',
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ GoRoute(path: 'b', builder: _mockScreenBuilder, parentNavigatorKey: root),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ redirectLimit: 10,
+ topRedirect: (BuildContext context, GoRouterState state) {
+ return null;
+ },
+ );
+ });
test('throws when a GoRoute with a different parentNavigatorKey '
'exists between a GoRoute with a parentNavigatorKey and '
@@ -811,34 +739,29 @@
throwsA(isA<AssertionError>()),
);
});
- test(
- 'does not throw when ShellRoute is the child of another ShellRoute',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- createRouteConfiguration(
- routes: <RouteBase>[
- ShellRoute(
- builder: _mockShellBuilder,
- routes: <RouteBase>[
- ShellRoute(
- builder: _mockShellBuilder,
- routes: <GoRoute>[
- 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('does not throw when ShellRoute is the child of another ShellRoute', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ createRouteConfiguration(
+ routes: <RouteBase>[
+ ShellRoute(
+ builder: _mockShellBuilder,
+ routes: <RouteBase>[
+ ShellRoute(
+ builder: _mockShellBuilder,
+ routes: <GoRoute>[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('Does not throw with valid parentNavigatorKey configuration', () {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
@@ -889,127 +812,101 @@
);
});
- test(
- 'throws when ShellRoute contains a GoRoute with a parentNavigatorKey',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- expect(() {
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- ShellRoute(
- routes: <RouteBase>[
- GoRoute(
- path: '/a',
- builder: _mockScreenBuilder,
- parentNavigatorKey: root,
- ),
- ],
- ),
- ],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- );
- }, throwsAssertionError);
- },
- );
-
- test(
- 'All known route strings returned by debugKnownRoutes are correct',
- () {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
-
- expect(
- createRouteConfiguration(
- navigatorKey: root,
- routes: <RouteBase>[
- GoRoute(
- path: '/a',
- parentNavigatorKey: root,
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- ShellRoute(
- navigatorKey: shell,
- builder: _mockShellBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'b',
- parentNavigatorKey: shell,
- builder: _mockScreenBuilder,
- ),
- GoRoute(
- path: 'c',
- parentNavigatorKey: shell,
- builder: _mockScreenBuilder,
- ),
- ],
- ),
- ],
- ),
- GoRoute(
- path: '/d',
- parentNavigatorKey: root,
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'e',
- parentNavigatorKey: root,
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- GoRoute(
- path: 'f',
- parentNavigatorKey: root,
- builder: _mockScreenBuilder,
- ),
- ],
- ),
- ],
- ),
- GoRoute(
- path: '/g',
- builder: _mockScreenBuilder,
- routes: <RouteBase>[
- StatefulShellRoute.indexedStack(
- builder: _mockIndexedStackShellBuilder,
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(path: 'h', builder: _mockScreenBuilder),
- ],
- ),
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(path: 'i', builder: _mockScreenBuilder),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- redirectLimit: 10,
- topRedirect: (BuildContext context, GoRouterState state) {
- return null;
- },
- ).debugKnownRoutes(),
- 'Full paths for routes:\n'
- '├─/a (Widget)\n'
- '│ └─ (ShellRoute)\n'
- '│ ├─/a/b (Widget)\n'
- '│ └─/a/c (Widget)\n'
- '├─/d (Widget)\n'
- '│ └─/d/e (Widget)\n'
- '│ └─/d/e/f (Widget)\n'
- '└─/g (Widget)\n'
- ' └─ (ShellRoute)\n'
- ' ├─/g/h (Widget)\n'
- ' └─/g/i (Widget)\n',
+ test('throws when ShellRoute contains a GoRoute with a parentNavigatorKey', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ expect(() {
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ ShellRoute(
+ routes: <RouteBase>[
+ GoRoute(path: '/a', builder: _mockScreenBuilder, parentNavigatorKey: root),
+ ],
+ ),
+ ],
+ redirectLimit: 10,
+ topRedirect: (BuildContext context, GoRouterState state) {
+ return null;
+ },
);
- },
- );
+ }, throwsAssertionError);
+ });
+
+ test('All known route strings returned by debugKnownRoutes are correct', () {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
+
+ expect(
+ createRouteConfiguration(
+ navigatorKey: root,
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/a',
+ parentNavigatorKey: root,
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ ShellRoute(
+ navigatorKey: shell,
+ builder: _mockShellBuilder,
+ routes: <RouteBase>[
+ GoRoute(path: 'b', parentNavigatorKey: shell, builder: _mockScreenBuilder),
+ GoRoute(path: 'c', parentNavigatorKey: shell, builder: _mockScreenBuilder),
+ ],
+ ),
+ ],
+ ),
+ GoRoute(
+ path: '/d',
+ parentNavigatorKey: root,
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'e',
+ parentNavigatorKey: root,
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ GoRoute(path: 'f', parentNavigatorKey: root, builder: _mockScreenBuilder),
+ ],
+ ),
+ ],
+ ),
+ GoRoute(
+ path: '/g',
+ builder: _mockScreenBuilder,
+ routes: <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ builder: _mockIndexedStackShellBuilder,
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <RouteBase>[GoRoute(path: 'h', builder: _mockScreenBuilder)],
+ ),
+ StatefulShellBranch(
+ routes: <RouteBase>[GoRoute(path: 'i', builder: _mockScreenBuilder)],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ redirectLimit: 10,
+ topRedirect: (BuildContext context, GoRouterState state) {
+ return null;
+ },
+ ).debugKnownRoutes(),
+ 'Full paths for routes:\n'
+ '├─/a (Widget)\n'
+ '│ └─ (ShellRoute)\n'
+ '│ ├─/a/b (Widget)\n'
+ '│ └─/a/c (Widget)\n'
+ '├─/d (Widget)\n'
+ '│ └─/d/e (Widget)\n'
+ '│ └─/d/e/f (Widget)\n'
+ '└─/g (Widget)\n'
+ ' └─ (ShellRoute)\n'
+ ' ├─/g/h (Widget)\n'
+ ' └─/g/i (Widget)\n',
+ );
+ });
group('normalizeUri', () {
test('adds leading slash if missing', () {
@@ -1021,10 +918,7 @@
});
test('removes trailing slash if length > 1', () {
- expect(
- RouteConfiguration.normalizeUri(Uri.parse('/foo/')).path,
- '/foo',
- );
+ expect(RouteConfiguration.normalizeUri(Uri.parse('/foo/')).path, '/foo');
});
test('does not remove slash for root root', () {
@@ -1039,9 +933,7 @@
});
test('handles hash fragments with authority', () {
- final Uri uri = RouteConfiguration.normalizeUri(
- Uri.parse('http://localhost:3000/#foo'),
- );
+ final Uri uri = RouteConfiguration.normalizeUri(Uri.parse('http://localhost:3000/#foo'));
expect(uri.path, '/');
expect(uri.fragment, 'foo');
});
@@ -1071,11 +963,7 @@
Widget _mockScreenBuilder(BuildContext context, GoRouterState state) =>
_MockScreen(key: state.pageKey);
-Widget _mockShellBuilder(
- BuildContext context,
- GoRouterState state,
- Widget child,
-) => child;
+Widget _mockShellBuilder(BuildContext context, GoRouterState state, Widget child) => child;
Widget _mockIndexedStackShellBuilder(
BuildContext context,
diff --git a/packages/go_router/test/cupertino_test.dart b/packages/go_router/test/cupertino_test.dart
index 12fa0ee..d6de929 100644
--- a/packages/go_router/test/cupertino_test.dart
+++ b/packages/go_router/test/cupertino_test.dart
@@ -11,20 +11,14 @@
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 key = GlobalKey<_DummyStatefulWidgetState>();
- await tester.pumpWidget(
- CupertinoApp(home: DummyStatefulWidget(key: key)),
- );
+ await tester.pumpWidget(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 key = GlobalKey<_DummyStatefulWidgetState>();
await tester.pumpWidget(MaterialApp(home: DummyStatefulWidget(key: key)));
final bool isCupertino = isCupertinoApp(key.currentContext! as Element);
@@ -55,9 +49,7 @@
group('GoRouterCupertinoErrorScreen', () {
testWidgets(
'shows "page not found" by default',
- testPageNotFound(
- widget: const CupertinoApp(home: CupertinoErrorScreen(null)),
- ),
+ testPageNotFound(widget: const CupertinoApp(home: CupertinoErrorScreen(null))),
);
final exception = Exception('Something went wrong!');
diff --git a/packages/go_router/test/custom_transition_page_test.dart b/packages/go_router/test/custom_transition_page_test.dart
index 0fae9d9..d1d43da 100644
--- a/packages/go_router/test/custom_transition_page_test.dart
+++ b/packages/go_router/test/custom_transition_page_test.dart
@@ -7,30 +7,23 @@
import 'package:go_router/go_router.dart';
void main() {
- testWidgets(
- 'CustomTransitionPage builds its child using transitionsBuilder',
- (WidgetTester tester) async {
- const child = HomeScreen();
- final transition = CustomTransitionPage<void>(
- transitionsBuilder: expectAsync4((_, __, ___, Widget child) => child),
- child: child,
- );
- final router = GoRouter(
- routes: <GoRoute>[
- 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', (
+ testWidgets('CustomTransitionPage builds its child using transitionsBuilder', (
WidgetTester tester,
) async {
+ const child = HomeScreen();
+ final transition = CustomTransitionPage<void>(
+ transitionsBuilder: expectAsync4((_, __, ___, Widget child) => child),
+ child: child,
+ );
+ final router = GoRouter(
+ routes: <GoRoute>[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 showHomeValueNotifier = ValueNotifier<bool>(false);
addTearDown(showHomeValueNotifier.dispose);
await tester.pumpWidget(
@@ -106,9 +99,7 @@
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 homeKey = ValueKey<String>('home');
const dismissibleModalKey = ValueKey<String>('dismissibleModal');
@@ -160,9 +151,8 @@
key: state.pageKey,
transitionDuration: transitionDuration,
reverseTransitionDuration: reverseTransitionDuration,
- transitionsBuilder:
- (_, Animation<double> animation, ___, Widget child) =>
- FadeTransition(opacity: animation, child: child),
+ transitionsBuilder: (_, Animation<double> animation, ___, Widget child) =>
+ FadeTransition(opacity: animation, child: child),
child: const LoginScreen(key: loginKey),
),
),
@@ -207,10 +197,6 @@
@override
Widget build(BuildContext context) {
- return const SizedBox(
- width: 200,
- height: 200,
- child: Center(child: Text('Dismissible Modal')),
- );
+ return const SizedBox(width: 200, height: 200, child: Center(child: Text('Dismissible Modal')));
}
}
diff --git a/packages/go_router/test/delegate_test.dart b/packages/go_router/test/delegate_test.dart
index 097feaf..9ded9ad 100644
--- a/packages/go_router/test/delegate_test.dart
+++ b/packages/go_router/test/delegate_test.dart
@@ -30,9 +30,7 @@
return router;
}
-Future<GoRouter> createGoRouterWithStatefulShellRoute(
- WidgetTester tester,
-) async {
+Future<GoRouter> createGoRouterWithStatefulShellRoute(WidgetTester tester) async {
final router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
@@ -46,14 +44,8 @@
path: '/c',
builder: (_, __) => const DummyStatefulWidget(),
routes: <RouteBase>[
- GoRoute(
- path: 'c1',
- builder: (_, __) => const DummyStatefulWidget(),
- ),
- GoRoute(
- path: 'c2',
- builder: (_, __) => const DummyStatefulWidget(),
- ),
+ GoRoute(path: 'c1', builder: (_, __) => const DummyStatefulWidget()),
+ GoRoute(path: 'c2', builder: (_, __) => const DummyStatefulWidget()),
],
),
],
@@ -64,10 +56,7 @@
path: '/d',
builder: (_, __) => const DummyStatefulWidget(),
routes: <RouteBase>[
- GoRoute(
- path: 'd1',
- builder: (_, __) => const DummyStatefulWidget(),
- ),
+ GoRoute(path: 'd1', builder: (_, __) => const DummyStatefulWidget()),
],
),
],
@@ -120,15 +109,12 @@
),
],
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) => PopScope(
- onPopInvokedWithResult: onPopShellRouteBuilder,
- canPop: canPopShellRouteBuilder,
- child: navigationShell,
- ),
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) =>
+ PopScope(
+ onPopInvokedWithResult: onPopShellRouteBuilder,
+ canPop: canPopShellRouteBuilder,
+ child: navigationShell,
+ ),
),
],
);
@@ -140,9 +126,7 @@
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<int>(0);
final GoRouter goRouter = await createGoRouter(
tester,
@@ -156,15 +140,7 @@
goRouter.pop();
valueNotifier.notifyListeners();
await tester.pumpAndSettle();
- expect(
- goRouter
- .routerDelegate
- .currentConfiguration
- .matches
- .last
- .matchedLocation,
- '/',
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.last.matchedLocation, '/');
addTearDown(valueNotifier.dispose);
addTearDown(goRouter.dispose);
@@ -175,19 +151,13 @@
..push('/error');
await tester.pumpAndSettle();
expect(find.byType(ErrorScreen), findsOneWidget);
- final RouteMatchBase last =
- goRouter.routerDelegate.currentConfiguration.matches.last;
+ final RouteMatchBase last = goRouter.routerDelegate.currentConfiguration.matches.last;
await goRouter.routerDelegate.popRoute();
expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.contains(last),
- false,
- );
+ expect(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 {
var didPop = false;
final goRouter = GoRouter(
@@ -222,97 +192,91 @@
expect(find.text('Home'), findsOneWidget);
});
- testWidgets(
- 'PopScope intercepts back button on StatefulShellRoute builder route',
- (WidgetTester tester) async {
- var didPopShellRouteBuilder = false;
- var didPopBranch = false;
- var 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();
-
- // Verify that PopScope intercepted the back button
- expect(didPopShellRouteBuilder, isTrue);
- expect(didPopBranch, isFalse);
- expect(didPopBranchSubRoute, isFalse);
-
- expect(find.text('Home'), findsOneWidget);
- },
- );
-
- testWidgets(
- 'PopScope intercepts back button on StatefulShellRoute branch route',
- (WidgetTester tester) async {
- var didPopShellRouteBuilder = false;
- var didPopBranch = false;
- var 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();
-
- // Verify that PopScope intercepted the back button
- expect(didPopShellRouteBuilder, isFalse);
- expect(didPopBranch, isTrue);
- expect(didPopBranchSubRoute, isFalse);
-
- expect(find.text('Home'), findsOneWidget);
- },
- );
-
- testWidgets(
- 'PopScope intercepts back button on StatefulShellRoute branch sub route',
- (WidgetTester tester) async {
- var didPopShellRouteBuilder = false;
- var didPopBranch = false;
- var didPopBranchSubRoute = false;
-
- final GoRouter goRouter =
- await createGoRouterWithStatefulShellRouteAndPopScopes(
- tester,
- canPopBranchSubRoute: false,
- onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true,
- onPopBranch: (_, __) => didPopBranch = true,
- onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true,
- );
-
- goRouter.push('/c/c1');
- await tester.pumpAndSettle();
-
- expect(find.text('SubRoute'), findsOneWidget);
- await tester.binding.handlePopRoute();
- await tester.pumpAndSettle();
-
- // Verify that PopScope intercepted the back button
- expect(didPopShellRouteBuilder, isFalse);
- expect(didPopBranch, isFalse);
- expect(didPopBranchSubRoute, isTrue);
-
- expect(find.text('SubRoute'), findsOneWidget);
- },
- );
-
- testWidgets('pops more than matches count should return false', (
+ testWidgets('PopScope intercepts back button on StatefulShellRoute builder route', (
WidgetTester tester,
) async {
+ var didPopShellRouteBuilder = false;
+ var didPopBranch = false;
+ var 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();
+
+ // Verify that PopScope intercepted the back button
+ expect(didPopShellRouteBuilder, isTrue);
+ expect(didPopBranch, isFalse);
+ expect(didPopBranchSubRoute, isFalse);
+
+ expect(find.text('Home'), findsOneWidget);
+ });
+
+ testWidgets('PopScope intercepts back button on StatefulShellRoute branch route', (
+ WidgetTester tester,
+ ) async {
+ var didPopShellRouteBuilder = false;
+ var didPopBranch = false;
+ var 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();
+
+ // Verify that PopScope intercepted the back button
+ expect(didPopShellRouteBuilder, isFalse);
+ expect(didPopBranch, isTrue);
+ expect(didPopBranchSubRoute, isFalse);
+
+ expect(find.text('Home'), findsOneWidget);
+ });
+
+ testWidgets('PopScope intercepts back button on StatefulShellRoute branch sub route', (
+ WidgetTester tester,
+ ) async {
+ var didPopShellRouteBuilder = false;
+ var didPopBranch = false;
+ var didPopBranchSubRoute = false;
+
+ final GoRouter goRouter = await createGoRouterWithStatefulShellRouteAndPopScopes(
+ tester,
+ canPopBranchSubRoute: false,
+ onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true,
+ onPopBranch: (_, __) => didPopBranch = true,
+ onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true,
+ );
+
+ goRouter.push('/c/c1');
+ await tester.pumpAndSettle();
+
+ expect(find.text('SubRoute'), findsOneWidget);
+ await tester.binding.handlePopRoute();
+ await tester.pumpAndSettle();
+
+ // Verify that PopScope intercepted the back button
+ expect(didPopShellRouteBuilder, isFalse);
+ expect(didPopBranch, isFalse);
+ expect(didPopBranchSubRoute, isTrue);
+
+ 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();
@@ -354,9 +318,7 @@
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 rootKey = GlobalKey<NavigatorState>();
final navKey = GlobalKey<NavigatorState>();
final GoRouter goRouter = await createRouter(<RouteBase>[
@@ -399,110 +361,77 @@
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)),
);
});
- testWidgets(
- 'It should successfully push a route from outside the the current '
- 'StatefulShellRoute',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(
- tester,
- );
- goRouter.push('/c/c1');
- 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,
- ),
- ),
- );
- },
- );
+ testWidgets('It should successfully push a route from outside the the current '
+ 'StatefulShellRoute', (WidgetTester tester) async {
+ final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(tester);
+ goRouter.push('/c/c1');
+ 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)),
+ );
+ });
- testWidgets(
- 'It should successfully push a route that is a descendant of the current '
- 'StatefulShellRoute branch',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(
- tester,
- );
- goRouter.push('/c/c1');
- await tester.pumpAndSettle();
+ testWidgets('It should successfully push a route that is a descendant of the current '
+ 'StatefulShellRoute branch', (WidgetTester tester) async {
+ final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(tester);
+ goRouter.push('/c/c1');
+ await tester.pumpAndSettle();
- goRouter.push('/c/c2');
- await tester.pumpAndSettle();
+ goRouter.push('/c/c2');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final shellRouteMatch =
- goRouter.routerDelegate.currentConfiguration.matches.last
- as ShellRouteMatch;
- expect(shellRouteMatch.matches.length, 2);
- expect(
- shellRouteMatch.matches[0].pageKey,
- isNot(equals(shellRouteMatch.matches[1].pageKey)),
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final shellRouteMatch =
+ goRouter.routerDelegate.currentConfiguration.matches.last as ShellRouteMatch;
+ expect(shellRouteMatch.matches.length, 2);
+ expect(shellRouteMatch.matches[0].pageKey, isNot(equals(shellRouteMatch.matches[1].pageKey)));
+ });
- testWidgets(
- 'It should successfully push the root of the current StatefulShellRoute '
- 'branch upon itself',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(
- tester,
- );
- goRouter.push('/c');
- await tester.pumpAndSettle();
+ testWidgets('It should successfully push the root of the current StatefulShellRoute '
+ 'branch upon itself', (WidgetTester tester) async {
+ final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(tester);
+ goRouter.push('/c');
+ await tester.pumpAndSettle();
- goRouter.push('/c');
- await tester.pumpAndSettle();
+ goRouter.push('/c');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final shellRouteMatch =
- goRouter.routerDelegate.currentConfiguration.matches.last
- as ShellRouteMatch;
- expect(shellRouteMatch.matches.length, 2);
- expect(
- shellRouteMatch.matches[0].pageKey,
- isNot(equals(shellRouteMatch.matches[1].pageKey)),
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final shellRouteMatch =
+ goRouter.routerDelegate.currentConfiguration.matches.last as ShellRouteMatch;
+ expect(shellRouteMatch.matches.length, 2);
+ expect(shellRouteMatch.matches[0].pageKey, isNot(equals(shellRouteMatch.matches[1].pageKey)));
+ });
});
group('canPop', () {
- testWidgets(
- 'It should return false if there is only 1 match in the stack',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester);
+ testWidgets('It should return false if there is only 1 match in the stack', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester);
- await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(goRouter.routerDelegate.canPop(), false);
- },
- );
- testWidgets(
- 'It should return true if there is more than 1 match in the stack',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester)
- ..push('/a');
+ await tester.pumpAndSettle();
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
+ expect(goRouter.routerDelegate.canPop(), false);
+ });
+ testWidgets('It should return true if there is more than 1 match in the stack', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester)
+ ..push('/a');
- await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- expect(goRouter.routerDelegate.canPop(), true);
- },
- );
+ await tester.pumpAndSettle();
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ expect(goRouter.routerDelegate.canPop(), true);
+ });
testWidgets('It should return false if there are no matches in the stack', (
WidgetTester tester,
) async {
@@ -516,9 +445,7 @@
});
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(
initialLocation: '/',
routes: <GoRoute>[
@@ -533,8 +460,7 @@
goRouter.push('/page-0');
goRouter.routerDelegate.addListener(expectAsync0(() {}));
- final RouteMatchBase first =
- goRouter.routerDelegate.currentConfiguration.matches.first;
+ final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first;
final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last;
goRouter.pushReplacement('/page-1');
expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
@@ -549,63 +475,46 @@
reason: 'The last match should have been removed',
);
expect(
- (goRouter.routerDelegate.currentConfiguration.last
- as ImperativeRouteMatch)
- .matches
- .uri
+ (goRouter.routerDelegate.currentConfiguration.last as ImperativeRouteMatch).matches.uri
.toString(),
'/page-1',
reason: 'The new location should have been pushed',
);
});
- testWidgets(
- 'It should return different pageKey when pushReplacement is called',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester);
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches[0].pageKey,
- isNotNull,
- );
+ testWidgets('It should return different pageKey when pushReplacement is called', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
+ expect(goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, isNotNull);
- goRouter.push('/a');
- await tester.pumpAndSettle();
+ goRouter.push('/a');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final ValueKey<String> prev =
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final ValueKey<String> prev =
+ goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
- goRouter.pushReplacement('/a');
- await tester.pumpAndSettle();
+ goRouter.pushReplacement('/a');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey,
- isNot(equals(prev)),
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ expect(
+ goRouter.routerDelegate.currentConfiguration.matches.last.pageKey,
+ isNot(equals(prev)),
+ );
+ });
});
group('pushReplacementNamed', () {
- 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(
initialLocation: '/',
routes: <GoRoute>[
GoRoute(path: '/', builder: (_, __) => const SizedBox()),
- GoRoute(
- path: '/page-0',
- name: 'page0',
- builder: (_, __) => const SizedBox(),
- ),
- GoRoute(
- path: '/page-1',
- name: 'page1',
- builder: (_, __) => const SizedBox(),
- ),
+ GoRoute(path: '/page-0', name: 'page0', builder: (_, __) => const SizedBox()),
+ GoRoute(path: '/page-1', name: 'page1', builder: (_, __) => const SizedBox()),
],
);
addTearDown(goRouter.dispose);
@@ -614,8 +523,7 @@
goRouter.pushNamed('page0');
goRouter.routerDelegate.addListener(expectAsync0(() {}));
- final RouteMatchBase first =
- goRouter.routerDelegate.currentConfiguration.matches.first;
+ 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);
@@ -642,9 +550,7 @@
});
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(
initialLocation: '/',
routes: <GoRoute>[
@@ -659,8 +565,7 @@
goRouter.push('/page-0');
goRouter.routerDelegate.addListener(expectAsync0(() {}));
- final RouteMatchBase first =
- goRouter.routerDelegate.currentConfiguration.matches.first;
+ final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first;
final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last;
goRouter.replace<void>('/page-1');
expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
@@ -675,96 +580,64 @@
reason: 'The last match should have been removed',
);
expect(
- (goRouter.routerDelegate.currentConfiguration.last
- as ImperativeRouteMatch)
- .matches
- .uri
+ (goRouter.routerDelegate.currentConfiguration.last as ImperativeRouteMatch).matches.uri
.toString(),
'/page-1',
reason: 'The new location should have been pushed',
);
});
- testWidgets(
- 'It should use the same pageKey when replace is called (with the same path)',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester);
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches[0].pageKey,
- isNotNull,
- );
+ testWidgets('It should use the same pageKey when replace is called (with the same path)', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
+ expect(goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, isNotNull);
- goRouter.push('/a');
- await tester.pumpAndSettle();
+ goRouter.push('/a');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final ValueKey<String> prev =
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final ValueKey<String> prev =
+ goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
- goRouter.replace<void>('/a');
- await tester.pumpAndSettle();
+ goRouter.replace<void>('/a');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey,
- prev,
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev);
+ });
- testWidgets(
- 'It should use the same pageKey when replace is called (with a different path)',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester);
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches[0].pageKey,
- isNotNull,
- );
+ testWidgets('It should use the same pageKey when replace is called (with a different path)', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
+ expect(goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, isNotNull);
- goRouter.push('/a');
- await tester.pumpAndSettle();
+ goRouter.push('/a');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final ValueKey<String> prev =
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final ValueKey<String> prev =
+ goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
- goRouter.replace<void>('/');
- await tester.pumpAndSettle();
+ goRouter.replace<void>('/');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey,
- prev,
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev);
+ });
});
group('replaceNamed', () {
- Future<GoRouter> createGoRouter(
- WidgetTester tester, {
- Listenable? refreshListenable,
- }) async {
+ Future<GoRouter> createGoRouter(WidgetTester tester, {Listenable? refreshListenable}) async {
final router = GoRouter(
initialLocation: '/',
routes: <GoRoute>[
- GoRoute(
- path: '/',
- name: 'home',
- builder: (_, __) => const SizedBox(),
- ),
- GoRoute(
- path: '/page-0',
- name: 'page0',
- builder: (_, __) => const SizedBox(),
- ),
- GoRoute(
- path: '/page-1',
- name: 'page1',
- builder: (_, __) => const SizedBox(),
- ),
+ GoRoute(path: '/', name: 'home', builder: (_, __) => const SizedBox()),
+ GoRoute(path: '/page-0', name: 'page0', builder: (_, __) => const SizedBox()),
+ GoRoute(path: '/page-1', name: 'page1', builder: (_, __) => const SizedBox()),
],
);
addTearDown(router.dispose);
@@ -772,16 +645,13 @@
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');
goRouter.routerDelegate.addListener(expectAsync0(() {}));
- final RouteMatchBase first =
- goRouter.routerDelegate.currentConfiguration.matches.first;
+ final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first;
final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last;
goRouter.replaceNamed<void>('page1');
expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
@@ -796,76 +666,57 @@
reason: 'The last match should have been removed',
);
expect(
- (goRouter.routerDelegate.currentConfiguration.last
- as ImperativeRouteMatch)
- .matches
- .uri
+ (goRouter.routerDelegate.currentConfiguration.last as ImperativeRouteMatch).matches.uri
.toString(),
'/page-1',
reason: 'The new location should have been pushed',
);
});
- testWidgets(
- 'It should use the same pageKey when replace is called with the same path',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester);
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.first.pageKey,
- isNotNull,
- );
+ testWidgets('It should use the same pageKey when replace is called with the same path', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.first.pageKey, isNotNull);
- goRouter.pushNamed('page0');
- await tester.pumpAndSettle();
+ goRouter.pushNamed('page0');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final ValueKey<String> prev =
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final ValueKey<String> prev =
+ goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
- goRouter.replaceNamed<void>('page0');
- await tester.pumpAndSettle();
+ goRouter.replaceNamed<void>('page0');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey,
- prev,
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev);
+ });
- testWidgets(
- 'It should use a new pageKey when replace is called with a different path',
- (WidgetTester tester) async {
- final GoRouter goRouter = await createGoRouter(tester);
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.first.pageKey,
- isNotNull,
- );
+ testWidgets('It should use a new pageKey when replace is called with a different path', (
+ WidgetTester tester,
+ ) async {
+ final GoRouter goRouter = await createGoRouter(tester);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.first.pageKey, isNotNull);
- goRouter.pushNamed('page0');
- await tester.pumpAndSettle();
+ goRouter.pushNamed('page0');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- final ValueKey<String> prev =
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ final ValueKey<String> prev =
+ goRouter.routerDelegate.currentConfiguration.matches.last.pageKey;
- goRouter.replaceNamed<void>('home');
- await tester.pumpAndSettle();
+ goRouter.replaceNamed<void>('home');
+ await tester.pumpAndSettle();
- expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
- expect(
- goRouter.routerDelegate.currentConfiguration.matches.last.pageKey,
- prev,
- );
- },
- );
+ expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2);
+ expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev);
+ });
});
- testWidgets('dispose unsubscribes from refreshListenable', (
- WidgetTester tester,
- ) async {
+ testWidgets('dispose unsubscribes from refreshListenable', (WidgetTester tester) async {
final 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 b5ac263..7637d34 100644
--- a/packages/go_router/test/error_page_test.dart
+++ b/packages/go_router/test/error_page_test.dart
@@ -26,9 +26,7 @@
testWidgets(
'clicking the button should redirect to /',
testClickingTheButtonRedirectsToRoot(
- buttonFinder: find.byWidgetPredicate(
- (Widget widget) => widget is GestureDetector,
- ),
+ buttonFinder: find.byWidgetPredicate((Widget widget) => widget is GestureDetector),
widget: widgetsAppBuilder(home: const ErrorScreen(null)),
),
);
diff --git a/packages/go_router/test/exception_handling_test.dart b/packages/go_router/test/exception_handling_test.dart
index 8578c6e..c16290f 100644
--- a/packages/go_router/test/exception_handling_test.dart
+++ b/packages/go_router/test/exception_handling_test.dart
@@ -16,10 +16,7 @@
try {
GoRouter(
routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
],
errorBuilder: (_, __) => const Text(''),
onException: (_, __, ___) {},
@@ -33,10 +30,7 @@
try {
GoRouter(
routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
],
errorBuilder: (_, __) => const Text(''),
errorPageBuilder: (_, __) => const MaterialPage<void>(child: Text('')),
@@ -50,10 +44,7 @@
try {
GoRouter(
routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
],
onException: (_, __, ___) {},
errorPageBuilder: (_, __) => const MaterialPage<void>(child: Text('')),
@@ -70,8 +61,7 @@
<RouteBase>[
GoRoute(
path: '/error',
- builder: (_, GoRouterState state) =>
- Text('redirected ${state.extra}'),
+ builder: (_, GoRouterState state) => Text('redirected ${state.extra}'),
),
],
tester,
@@ -106,12 +96,7 @@
testWidgets('stays on the same page if noop.', (WidgetTester tester) async {
final GoRouter router = await createRouter(
- <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
- ],
+ <RouteBase>[GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home'))],
tester,
onException: (_, __, ___) {},
);
@@ -122,27 +107,20 @@
expect(find.text('home'), findsOneWidget);
});
- testWidgets('can catch errors thrown in redirect callbacks', (
- WidgetTester tester,
- ) async {
+ testWidgets('can catch errors thrown in redirect callbacks', (WidgetTester tester) async {
var exceptionCaught = false;
String? errorMessage;
final GoRouter router = await createRouter(
<RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
GoRoute(
path: '/error-page',
- builder: (_, GoRouterState state) =>
- Text('error handled: ${state.extra}'),
+ builder: (_, GoRouterState state) => Text('error handled: ${state.extra}'),
),
GoRoute(
path: '/trigger-error',
- builder: (_, GoRouterState state) =>
- const Text('should not reach here'),
+ builder: (_, GoRouterState state) => const Text('should not reach here'),
),
],
tester,
@@ -153,12 +131,11 @@
}
return null;
},
- onException:
- (BuildContext context, GoRouterState state, GoRouter router) {
- exceptionCaught = true;
- errorMessage = 'Caught exception for ${state.uri}';
- router.go('/error-page', extra: errorMessage);
- },
+ onException: (BuildContext context, GoRouterState state, GoRouter router) {
+ exceptionCaught = true;
+ errorMessage = 'Caught exception for ${state.uri}';
+ router.go('/error-page', extra: errorMessage);
+ },
);
expect(find.text('home'), findsOneWidget);
@@ -171,10 +148,7 @@
// Verify the exception was caught and handled
expect(exceptionCaught, isTrue);
expect(errorMessage, isNotNull);
- expect(
- find.text('error handled: Caught exception for /trigger-error'),
- findsOneWidget,
- );
+ expect(find.text('error handled: Caught exception for /trigger-error'), findsOneWidget);
expect(find.text('should not reach here'), findsNothing);
});
@@ -185,19 +159,14 @@
final GoRouter router = await createRouter(
<RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
GoRoute(
path: '/error-page',
- builder: (_, GoRouterState state) =>
- const Text('generic error handled'),
+ builder: (_, GoRouterState state) => const Text('generic error handled'),
),
GoRoute(
path: '/trigger-runtime-error',
- builder: (_, GoRouterState state) =>
- const Text('should not reach here'),
+ builder: (_, GoRouterState state) => const Text('should not reach here'),
),
],
tester,
@@ -208,11 +177,10 @@
}
return null;
},
- onException:
- (BuildContext context, GoRouterState state, GoRouter router) {
- exceptionCaught = true;
- router.go('/error-page');
- },
+ onException: (BuildContext context, GoRouterState state, GoRouter router) {
+ exceptionCaught = true;
+ router.go('/error-page');
+ },
);
expect(find.text('home'), findsOneWidget);
diff --git a/packages/go_router/test/extension_test.dart b/packages/go_router/test/extension_test.dart
index d65bf21..9326a85 100644
--- a/packages/go_router/test/extension_test.dart
+++ b/packages/go_router/test/extension_test.dart
@@ -8,23 +8,12 @@
void main() {
group('replaceNamed', () {
- Future<GoRouter> createGoRouter(
- WidgetTester tester, {
- Listenable? refreshListenable,
- }) async {
+ Future<GoRouter> createGoRouter(WidgetTester tester, {Listenable? refreshListenable}) async {
final router = GoRouter(
initialLocation: '/',
routes: <GoRoute>[
- GoRoute(
- path: '/',
- name: 'home',
- builder: (_, __) => const _MyWidget(),
- ),
- GoRoute(
- path: '/page-0/:tab',
- name: 'page-0',
- builder: (_, __) => const SizedBox(),
- ),
+ GoRoute(path: '/', name: 'home', builder: (_, __) => const _MyWidget()),
+ GoRoute(path: '/page-0/:tab', name: 'page-0', builder: (_, __) => const SizedBox()),
],
);
addTearDown(router.dispose);
@@ -32,9 +21,7 @@
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();
diff --git a/packages/go_router/test/extra_codec_test.dart b/packages/go_router/test/extra_codec_test.dart
index 67d832f..06e6e0f 100644
--- a/packages/go_router/test/extra_codec_test.dart
+++ b/packages/go_router/test/extra_codec_test.dart
@@ -12,9 +12,7 @@
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 initialString = 'some string';
const empty = 'empty';
final router = GoRouter(
diff --git a/packages/go_router/test/go_route_test.dart b/packages/go_router/test/go_route_test.dart
index a741577..b72b267 100644
--- a/packages/go_router/test/go_route_test.dart
+++ b/packages/go_router/test/go_route_test.dart
@@ -21,9 +21,7 @@
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 rootNavigatorKey = GlobalKey<NavigatorState>();
final shellNavigatorKey = GlobalKey<NavigatorState>();
@@ -49,17 +47,16 @@
routes: <RouteBase>[
ShellRoute(
parentNavigatorKey: rootNavigatorKey,
- builder:
- (BuildContext context, GoRouterState state, Widget child) {
- return Scaffold(
- body: Column(
- children: <Widget>[
- const Text('Screen D'),
- Expanded(child: child),
- ],
- ),
- );
- },
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Scaffold(
+ body: Column(
+ children: <Widget>[
+ const Text('Screen D'),
+ Expanded(child: child),
+ ],
+ ),
+ );
+ },
routes: <RouteBase>[
GoRoute(
path: 'c',
@@ -75,21 +72,14 @@
),
];
- 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 rootNavigatorKey = GlobalKey<NavigatorState>();
final shellNavigatorKey = GlobalKey<NavigatorState>();
@@ -142,12 +132,7 @@
),
];
- 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);
@@ -166,9 +151,7 @@
ShellRoute(
parentNavigatorKey: key2,
builder: (_, __, Widget child) => child,
- routes: <RouteBase>[
- GoRoute(path: '1', builder: (_, __) => const Text('/route/1')),
- ],
+ routes: <RouteBase>[GoRoute(path: '1', builder: (_, __) => const Text('/route/1'))],
),
],
);
@@ -188,9 +171,7 @@
GoRoute(
path: 'route',
redirect: (_, __) => '/route/1',
- routes: <RouteBase>[
- GoRoute(path: '1', builder: (_, __) => const Text('/route/1')),
- ],
+ routes: <RouteBase>[GoRoute(path: '1', builder: (_, __) => const Text('/route/1'))],
),
],
),
@@ -217,9 +198,7 @@
GoRoute(
path: 'route',
redirect: (_, __) => '/route',
- routes: <RouteBase>[
- GoRoute(path: '1', builder: (_, __) => const Text('/route/1')),
- ],
+ routes: <RouteBase>[GoRoute(path: '1', builder: (_, __) => const Text('/route/1'))],
),
],
),
@@ -232,9 +211,7 @@
expect(tester.takeException(), isAssertionError);
});
- testWidgets('redirects to a valid route based on fragment.', (
- WidgetTester tester,
- ) async {
+ testWidgets('redirects to a valid route based on fragment.', (WidgetTester tester) async {
final GoRouter router = await createRouter(<RouteBase>[
GoRoute(
path: '/',
@@ -254,8 +231,7 @@
routes: <RouteBase>[
GoRoute(
path: '1',
- builder: (_, __) =>
- const Text('/route/1'), // Renders "/route/1" text
+ builder: (_, __) => const Text('/route/1'), // Renders "/route/1" text
),
],
),
@@ -266,14 +242,8 @@
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');
@@ -286,35 +256,34 @@
expect(tester.takeException(), isNull);
});
- testWidgets(
- 'throw if sub route does not conform with parent navigator key',
- (WidgetTester tester) async {
- final key1 = GlobalKey<NavigatorState>();
- final key2 = GlobalKey<NavigatorState>();
- var hasError = false;
- try {
- ShellRoute(
- navigatorKey: key1,
- builder: (_, __, Widget child) => child,
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- redirect: (_, __) => '/route',
- routes: <RouteBase>[
- 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 key1 = GlobalKey<NavigatorState>();
+ final key2 = GlobalKey<NavigatorState>();
+ var hasError = false;
+ try {
+ ShellRoute(
+ navigatorKey: key1,
+ builder: (_, __, Widget child) => child,
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ redirect: (_, __) => '/route',
+ routes: <RouteBase>[
+ 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 2624084..26b4a27 100644
--- a/packages/go_router/test/go_router_state_test.dart
+++ b/packages/go_router/test/go_router_state_test.dart
@@ -75,9 +75,7 @@
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 routes = <GoRoute>[
GoRoute(
path: '/',
@@ -94,9 +92,7 @@
builder: (_, __) {
return Builder(
builder: (BuildContext context) {
- return Text(
- '2 ${GoRouterState.of(context).pathParameters['id']}',
- );
+ return Text('2 ${GoRouterState.of(context).pathParameters['id']}');
},
);
},
@@ -118,9 +114,7 @@
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 key = UniqueKey();
final routes = <GoRoute>[
GoRoute(
@@ -146,16 +140,10 @@
],
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/a',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/a');
expect(tester.widget<Text>(find.byKey(key)).data, '/a');
final GoRouterStateRegistry registry = tester
- .widget<GoRouterStateRegistryScope>(
- find.byType(GoRouterStateRegistryScope),
- )
+ .widget<GoRouterStateRegistryScope>(find.byType(GoRouterStateRegistryScope))
.notifier!;
expect(registry.registry.length, 2);
router.go('/');
@@ -170,9 +158,7 @@
expect(find.byKey(key), findsNothing);
});
- testWidgets('imperative pop clears out registry', (
- WidgetTester tester,
- ) async {
+ testWidgets('imperative pop clears out registry', (WidgetTester tester) async {
final key = UniqueKey();
final nav = GlobalKey<NavigatorState>();
final routes = <GoRoute>[
@@ -199,17 +185,10 @@
],
),
];
- await createRouter(
- routes,
- tester,
- initialLocation: '/a',
- navigatorKey: nav,
- );
+ await createRouter(routes, tester, initialLocation: '/a', navigatorKey: nav);
expect(tester.widget<Text>(find.byKey(key)).data, '/a');
final GoRouterStateRegistry registry = tester
- .widget<GoRouterStateRegistryScope>(
- find.byType(GoRouterStateRegistryScope),
- )
+ .widget<GoRouterStateRegistryScope>(find.byType(GoRouterStateRegistryScope))
.notifier!;
expect(registry.registry.length, 2);
nav.currentState!.pop();
@@ -224,41 +203,36 @@
expect(find.byKey(key), findsNothing);
});
- testWidgets(
- 'GoRouterState look up should be resilient when there is a nested navigator.',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (_, __) {
- return Scaffold(
- appBar: AppBar(),
- body: Navigator(
- pages: <Page<void>>[
- MaterialPage<void>(
- child: Builder(
- builder: (BuildContext context) {
- return Center(
- child: Text(
- GoRouterState.of(context).uri.toString(),
- ),
- );
- },
- ),
+ testWidgets('GoRouterState look up should be resilient when there is a nested navigator.', (
+ WidgetTester tester,
+ ) async {
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) {
+ return Scaffold(
+ appBar: AppBar(),
+ body: Navigator(
+ pages: <Page<void>>[
+ MaterialPage<void>(
+ child: Builder(
+ builder: (BuildContext context) {
+ return Center(child: Text(GoRouterState.of(context).uri.toString()));
+ },
),
- ],
- onPopPage: (Route<Object?> route, Object? result) {
- throw UnimplementedError();
- },
- ),
- );
- },
- ),
- ];
- await createRouter(routes, tester);
- expect(find.text('/'), findsOneWidget);
- },
- );
+ ),
+ ],
+ onPopPage: (Route<Object?> route, Object? result) {
+ throw UnimplementedError();
+ },
+ ),
+ );
+ },
+ ),
+ ];
+ await createRouter(routes, tester);
+ expect(find.text('/'), findsOneWidget);
+ });
testWidgets('GoRouterState topRoute accessible from StatefulShellRoute', (
WidgetTester tester,
@@ -294,9 +268,7 @@
GoRouterState state,
StatefulNavigationShell navigationShell,
) {
- final String? routeName = GoRouterState.of(
- context,
- ).topRoute?.name;
+ final String? routeName = GoRouterState.of(context).topRoute?.name;
final String title = switch (routeName) {
'a' => 'A',
'b' => 'B',
diff --git a/packages/go_router/test/go_router_test.dart b/packages/go_router/test/go_router_test.dart
index d47fee1..32628de 100644
--- a/packages/go_router/test/go_router_test.dart
+++ b/packages/go_router/test/go_router_test.dart
@@ -43,8 +43,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
];
@@ -55,29 +54,25 @@
expect(find.byType(HomeScreen), findsOneWidget);
});
- testWidgets(
- 'If there is more than one route to match, use the first match',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- GoRoute(name: '1', path: '/', builder: dummy),
- GoRoute(name: '2', path: '/', builder: dummy),
- ];
-
- final GoRouter router = await createRouter(routes, tester);
- router.go('/');
- final List<RouteMatchBase> 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', (
+ testWidgets('If there is more than one route to match, use the first match', (
WidgetTester tester,
) async {
final routes = <GoRoute>[
GoRoute(name: '1', path: '/', builder: dummy),
+ GoRoute(name: '2', path: '/', builder: dummy),
+ ];
+
+ final GoRouter router = await createRouter(routes, tester);
+ router.go('/');
+ final List<RouteMatchBase> 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 {
+ final routes = <GoRoute>[
+ GoRoute(name: '1', path: '/', builder: dummy),
GoRoute(name: '2', path: '/a', builder: dummy),
GoRoute(name: '3', path: '/b', builder: dummy),
];
@@ -122,13 +117,11 @@
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();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
expect(find.byType(TestErrorScreen), findsOneWidget);
});
@@ -137,80 +130,66 @@
final routes = <GoRoute>[
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(),
),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/login');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
expect(matches.first.matchedLocation, '/login');
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 routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'page1',
- builder: (BuildContext context, GoRouterState state) =>
- const Page1Screen(),
+ builder: (BuildContext context, GoRouterState state) => const Page1Screen(),
),
],
),
GoRoute(
path: '/login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/login');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> 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 trailing /', (
- WidgetTester tester,
- ) async {
+ testWidgets('match top level route when location has trailing /', (WidgetTester tester) async {
final routes = <GoRoute>[
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(),
),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/login/');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
expect(matches.first.matchedLocation, '/login');
expect(find.byType(LoginScreen), findsOneWidget);
@@ -220,19 +199,14 @@
WidgetTester tester,
) async {
final routes = <GoRoute>[
- GoRoute(
- path: '/profile',
- builder: dummy,
- redirect: (_, __) => '/profile/foo',
- ),
+ GoRoute(path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'),
GoRoute(path: '/profile/:kind', builder: dummy),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/profile/');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
expect(matches.first.matchedLocation, '/profile/foo');
expect(find.byType(DummyScreen), findsOneWidget);
@@ -242,122 +216,96 @@
WidgetTester tester,
) async {
final routes = <GoRoute>[
- GoRoute(
- path: '/profile',
- builder: dummy,
- redirect: (_, __) => '/profile/foo',
- ),
+ GoRoute(path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'),
GoRoute(path: '/profile/:kind', builder: dummy),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/profile/?bar=baz');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> 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 /',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- 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<RouteMatchBase> 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 routes = <GoRoute>[
- 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<RouteMatchBase> 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 routes = <GoRoute>[
- GoRoute(
- path: '/profile',
- 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<RouteMatchBase> 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 routes = <GoRoute>[
- GoRoute(
- path: '/profile',
- 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<RouteMatchBase> 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', (
+ testWidgets('match top level route when location has scheme/host and has trailing /', (
WidgetTester tester,
) async {
+ final routes = <GoRoute>[
+ 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<RouteMatchBase> 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 routes = <GoRoute>[
+ 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<RouteMatchBase> 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 routes = <GoRoute>[
+ GoRoute(path: '/profile', 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<RouteMatchBase> 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 routes = <GoRoute>[
+ GoRoute(path: '/profile', 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<RouteMatchBase> 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 {
// Regression test for https://github.com/flutter/flutter/issues/123369.
final home = UniqueKey();
final settings = UniqueKey();
@@ -373,11 +321,7 @@
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');
@@ -410,9 +354,7 @@
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 routes = <RouteBase>[
GoRoute(
@@ -420,12 +362,9 @@
builder: (_, __) => const Text('home'),
routes: <RouteBase>[
ShellRoute(
- builder:
- (BuildContext context, GoRouterState state, Widget child) {
- return Column(
- children: <Widget>[const Text('shell'), child],
- );
- },
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Column(children: <Widget>[const Text('shell'), child]);
+ },
routes: <GoRoute>[
GoRoute(
path: 'page',
@@ -449,11 +388,7 @@
],
),
];
- 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);
@@ -471,34 +406,25 @@
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 navKey = GlobalKey<NavigatorState>();
final routes = <GoRoute>[
GoRoute(
path: '/',
- pageBuilder: (_, __) =>
- const MaterialPage<Object>(child: HomeScreen()),
+ pageBuilder: (_, __) => const MaterialPage<Object>(child: HomeScreen()),
),
GoRoute(
path: '/page1',
- pageBuilder: (_, __) =>
- const MaterialPage<Object>(child: Page1Screen()),
+ pageBuilder: (_, __) => const MaterialPage<Object>(child: Page1Screen()),
),
GoRoute(
path: '/page2',
- pageBuilder: (_, __) =>
- const MaterialPage<Object>(child: Page2Screen()),
+ pageBuilder: (_, __) => const MaterialPage<Object>(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');
@@ -514,8 +440,7 @@
router.pop();
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches.length, 4);
expect(find.byType(HomeScreen), findsNothing);
expect(find.byType(Page1Screen), findsOneWidget);
@@ -526,13 +451,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -541,8 +464,7 @@
final GoRouter router = await createRouter(routes, tester);
router.go('/login');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches.length, 2);
expect(matches.first.matchedLocation, '/');
expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget);
@@ -554,13 +476,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'family/:fid',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
path: 'person/:pid',
@@ -571,8 +491,7 @@
),
GoRoute(
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -580,8 +499,7 @@
final GoRouter router = await createRouter(routes, tester);
{
- final RouteMatchList matches =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches = router.routerDelegate.currentConfiguration;
expect(matches.matches, hasLength(1));
expect(matches.uri.toString(), '/');
expect(find.byType(HomeScreen), findsOneWidget);
@@ -590,8 +508,7 @@
router.go('/login');
await tester.pumpAndSettle();
{
- final RouteMatchList matches =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches = router.routerDelegate.currentConfiguration;
expect(matches.matches.length, 2);
expect(matches.matches.first.matchedLocation, '/');
expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget);
@@ -602,8 +519,7 @@
router.go('/family/f2');
await tester.pumpAndSettle();
{
- final RouteMatchList matches =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches = router.routerDelegate.currentConfiguration;
expect(matches.matches.length, 2);
expect(matches.matches.first.matchedLocation, '/');
expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget);
@@ -614,8 +530,7 @@
router.go('/family/f2/person/p1');
await tester.pumpAndSettle();
{
- final RouteMatchList matches =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches = router.routerDelegate.currentConfiguration;
expect(matches.matches.length, 3);
expect(matches.matches.first.matchedLocation, '/');
expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget);
@@ -626,34 +541,27 @@
}
});
- 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 routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
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>[
GoRoute(
path: 'bar',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -664,8 +572,7 @@
final GoRouter router = await createRouter(routes, tester);
router.go('/bar');
await tester.pumpAndSettle();
- List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(2));
expect(find.byType(Page1Screen), findsOneWidget);
@@ -720,10 +627,7 @@
name: 'family',
path: 'family/:fid',
builder: (BuildContext context, GoRouterState state) {
- expect(
- state.uri.toString(),
- anyOf(<String>['/family/f2', '/family/f2/person/p1']),
- );
+ expect(state.uri.toString(), anyOf(<String>['/family/f2', '/family/f2/person/p1']));
expect(state.matchedLocation, '/family/f2');
expect(state.name, 'family');
expect(state.path, 'family/:fid');
@@ -743,16 +647,10 @@
expect(state.name, 'person');
expect(state.path, 'person/:pid');
expect(state.fullPath, '/family/:fid/person/:pid');
- expect(state.pathParameters, <String, String>{
- 'fid': 'f2',
- 'pid': 'p1',
- });
+ expect(state.pathParameters, <String, String>{'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']!);
},
),
],
@@ -776,8 +674,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/family/:fid',
@@ -791,8 +688,7 @@
const loc = '/FaMiLy/f2';
router.go(loc);
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
// NOTE: match the lower case, since location is canonicalized to match the
// path case whereas the location can be any case; so long as the path
@@ -810,8 +706,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/family/:fid',
@@ -832,8 +727,7 @@
const loc = '/family/f2';
router.go(loc);
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(router.routerDelegate.currentConfiguration.uri.toString(), loc);
@@ -841,24 +735,19 @@
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 routes = <GoRoute>[
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')),
),
];
@@ -877,29 +766,25 @@
expect(find.byKey(const Key('ABC')), findsOne);
});
- testWidgets(
- 'If there is more than one route to match, use the first match.',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- 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<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
- expect(matches, hasLength(1));
- expect(find.byType(DummyScreen), findsOneWidget);
- },
- );
-
- testWidgets('Handles the Android back button correctly', (
+ testWidgets('If there is more than one route to match, use the first match.', (
WidgetTester tester,
) async {
+ final routes = <GoRoute>[
+ 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<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
+ expect(matches, hasLength(1));
+ expect(find.byType(DummyScreen), findsOneWidget);
+ });
+
+ testWidgets('Handles the Android back button correctly', (WidgetTester tester) async {
final routes = <RouteBase>[
GoRoute(
path: '/',
@@ -1008,18 +893,15 @@
'Handles the Android back button when parentNavigatorKey is set to the root navigator',
(WidgetTester tester) async {
final log = <MethodCall>[];
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(SystemChannels.platform, (
- MethodCall methodCall,
- ) async {
- log.add(methodCall);
- return null;
- });
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (MethodCall methodCall) async {
+ log.add(methodCall);
+ return null;
+ },
+ );
- Future<void> verify(
- AsyncCallback test,
- List<Object> expectations,
- ) async {
+ Future<void> verify(AsyncCallback test, List<Object> expectations) async {
log.clear();
await test();
expect(log, expectations);
@@ -1037,12 +919,7 @@
),
];
- await createRouter(
- routes,
- tester,
- initialLocation: '/a',
- navigatorKey: rootNavigatorKey,
- );
+ await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey);
expect(find.text('Screen A'), findsOneWidget);
await tester.runAsync(() async {
@@ -1057,13 +934,13 @@
WidgetTester tester,
) async {
final log = <MethodCall>[];
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(SystemChannels.platform, (
- MethodCall methodCall,
- ) async {
- log.add(methodCall);
- return null;
- });
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (MethodCall methodCall) async {
+ log.add(methodCall);
+ return null;
+ },
+ );
Future<void> verify(AsyncCallback test, List<Object> expectations) async {
log.clear();
@@ -1099,12 +976,7 @@
),
];
- 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 {
@@ -1115,9 +987,7 @@
});
});
- testWidgets('does not crash when inherited widget changes', (
- WidgetTester tester,
- ) async {
+ testWidgets('does not crash when inherited widget changes', (WidgetTester tester) async {
final notifier = ValueNotifier<String>('initial');
addTearDown(notifier.dispose);
@@ -1154,13 +1024,13 @@
'Handles the Android back button when a second Shell has a GoRoute with parentNavigator key',
(WidgetTester tester) async {
final log = <MethodCall>[];
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(SystemChannels.platform, (
- MethodCall methodCall,
- ) async {
- log.add(methodCall);
- return null;
- });
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (MethodCall methodCall) async {
+ log.add(methodCall);
+ return null;
+ },
+ );
Future<void> verify(AsyncCallback test, List<Object> expectations) async {
log.clear();
@@ -1190,17 +1060,12 @@
routes: <RouteBase>[
ShellRoute(
navigatorKey: shellNavigatorKeyB,
- builder:
- (
- BuildContext context,
- GoRouterState state,
- Widget child,
- ) {
- return Scaffold(
- appBar: AppBar(title: const Text('Shell')),
- body: child,
- );
- },
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Scaffold(
+ appBar: AppBar(title: const Text('Shell')),
+ body: child,
+ );
+ },
routes: <RouteBase>[
GoRoute(
path: 'b',
@@ -1217,12 +1082,7 @@
),
];
- await createRouter(
- routes,
- tester,
- initialLocation: '/a/b',
- navigatorKey: rootNavigatorKey,
- );
+ await createRouter(routes, tester, initialLocation: '/a/b', navigatorKey: rootNavigatorKey);
expect(find.text('Screen B'), findsOneWidget);
// The first pop should not exit the app.
@@ -1247,69 +1107,64 @@
final log = <MethodCall>[];
setUp(() {
GoRouter.optionURLReflectsImperativeAPIs = false;
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(SystemChannels.navigation, (
- MethodCall methodCall,
- ) async {
- log.add(methodCall);
- return null;
- });
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.navigation,
+ (MethodCall methodCall) async {
+ log.add(methodCall);
+ return null;
+ },
+ );
});
tearDown(() {
GoRouter.optionURLReflectsImperativeAPIs = false;
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(SystemChannels.navigation, null);
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.navigation,
+ null,
+ );
log.clear();
});
- testWidgets(
- 'on push shell route with optionURLReflectImperativeAPIs = true',
- (WidgetTester tester) async {
- GoRouter.optionURLReflectsImperativeAPIs = true;
- final routes = <RouteBase>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
- routes: <RouteBase>[
- ShellRoute(
- builder:
- (BuildContext context, GoRouterState state, Widget child) =>
- child,
- routes: <RouteBase>[
- GoRoute(
- path: 'c',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
- ),
- ],
- ),
- ],
- ),
- ];
-
- final GoRouter router = await createRouter(routes, tester);
-
- log.clear();
- router.push('/c?foo=bar');
- final codec = RouteMatchListCodec(router.configuration);
- await tester.pumpAndSettle();
- expect(log, <Object>[
- isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/c?foo=bar',
- false,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
- ]);
- GoRouter.optionURLReflectsImperativeAPIs = false;
- },
- );
-
- testWidgets('on push with optionURLReflectImperativeAPIs = true', (
+ testWidgets('on push shell route with optionURLReflectImperativeAPIs = true', (
WidgetTester tester,
) async {
GoRouter.optionURLReflectsImperativeAPIs = true;
+ final routes = <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
+ routes: <RouteBase>[
+ ShellRoute(
+ builder: (BuildContext context, GoRouterState state, Widget child) => child,
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'c',
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ];
+
+ final GoRouter router = await createRouter(routes, tester);
+
+ log.clear();
+ router.push('/c?foo=bar');
+ final codec = RouteMatchListCodec(router.configuration);
+ await tester.pumpAndSettle();
+ expect(log, <Object>[
+ 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 {
+ GoRouter.optionURLReflectsImperativeAPIs = true;
final routes = <GoRoute>[
GoRoute(path: '/', builder: (_, __) => const DummyScreen()),
GoRoute(path: '/settings', builder: (_, __) => const DummyScreen()),
@@ -1346,11 +1201,7 @@
await tester.pumpAndSettle();
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/',
- false,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
+ IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)),
]);
});
@@ -1359,28 +1210,18 @@
GoRoute(
path: '/',
builder: (_, __) => const DummyScreen(),
- routes: <RouteBase>[
- GoRoute(path: 'settings', builder: (_, __) => const DummyScreen()),
- ],
+ routes: <RouteBase>[GoRoute(path: 'settings', builder: (_, __) => const DummyScreen())],
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/settings',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings');
final codec = RouteMatchListCodec(router.configuration);
log.clear();
router.pop();
await tester.pumpAndSettle();
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/',
- false,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
+ IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)),
]);
});
@@ -1394,10 +1235,7 @@
path: 'settings',
builder: (_, __) => const DummyScreen(),
routes: <RouteBase>[
- GoRoute(
- path: 'profile',
- builder: (_, __) => const DummyScreen(),
- ),
+ GoRoute(path: 'profile', builder: (_, __) => const DummyScreen()),
],
),
],
@@ -1416,11 +1254,7 @@
await tester.pumpAndSettle();
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/',
- false,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
+ IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)),
]);
});
@@ -1430,62 +1264,39 @@
path: '/',
builder: (_, __) => const DummyScreen(),
routes: <RouteBase>[
- GoRoute(
- path: 'settings/:id',
- builder: (_, __) => const DummyScreen(),
- ),
+ GoRoute(path: 'settings/:id', builder: (_, __) => const DummyScreen()),
],
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/settings/123',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings/123');
final codec = RouteMatchListCodec(router.configuration);
log.clear();
router.pop();
await tester.pumpAndSettle();
expect(log, <Object>[
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 routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const DummyScreen(),
- routes: <RouteBase>[
- GoRoute(path: ':id', builder: (_, __) => const DummyScreen()),
- ],
+ routes: <RouteBase>[GoRoute(path: ':id', builder: (_, __) => const DummyScreen())],
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/123/',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/123/');
final codec = RouteMatchListCodec(router.configuration);
log.clear();
router.pop();
await tester.pumpAndSettle();
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/',
- false,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
+ IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)),
]);
});
@@ -1502,10 +1313,9 @@
},
routes: <RouteBase>[
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: <RouteBase>[
GoRoute(
path: 'b',
@@ -1537,11 +1347,7 @@
expect(find.text('Screen C'), findsOneWidget);
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/b/c',
- true,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
+ IsRouteUpdateCall('/b/c', true, codec.encode(router.routerDelegate.currentConfiguration)),
]);
log.clear();
@@ -1551,17 +1357,11 @@
expect(find.text('Home'), findsOneWidget);
expect(log, <Object>[
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 routes = <GoRoute>[
GoRoute(
path: '/',
@@ -1591,8 +1391,7 @@
final arguments = log.last.arguments as Map<Object?, Object?>;
// Stores the state after the last push. This should contain the encoded
// RouteMatchList.
- final Object? state =
- (log.last.arguments as Map<Object?, Object?>)['state'];
+ final Object? state = (log.last.arguments as Map<Object?, Object?>)['state'];
final location = (arguments['location'] ?? arguments['uri']!) as String;
router.go('/');
@@ -1615,9 +1414,7 @@
expect(find.byKey(const ValueKey<String>('home')), findsOneWidget);
});
- testWidgets('works correctly with async redirect', (
- WidgetTester tester,
- ) async {
+ testWidgets('works correctly with async redirect', (WidgetTester tester) async {
final login = UniqueKey();
final routes = <GoRoute>[
GoRoute(path: '/', builder: (_, __) => const DummyScreen()),
@@ -1648,11 +1445,7 @@
expect(tester.takeException(), isNull);
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
- IsRouteUpdateCall(
- '/login',
- true,
- codec.encode(router.routerDelegate.currentConfiguration),
- ),
+ IsRouteUpdateCall('/login', true, codec.encode(router.routerDelegate.currentConfiguration)),
]);
});
});
@@ -1663,8 +1456,7 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
];
@@ -1691,9 +1483,7 @@
testWidgets('match no routes', (WidgetTester tester) async {
await expectLater(() async {
- final routes = <GoRoute>[
- GoRoute(name: 'home', path: '/', builder: dummy),
- ];
+ final routes = <GoRoute>[GoRoute(name: 'home', path: '/', builder: dummy)];
final GoRouter router = await createRouter(routes, tester);
router.goNamed('work');
}, throwsA(isAssertionError));
@@ -1704,14 +1494,12 @@
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(),
),
];
@@ -1724,14 +1512,12 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'login',
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -1746,23 +1532,18 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family/:fid',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
name: 'person',
path: 'person/:pid',
builder: (BuildContext context, GoRouterState state) {
- expect(state.pathParameters, <String, String>{
- 'fid': 'f2',
- 'pid': 'p1',
- });
+ expect(state.pathParameters, <String, String>{'fid': 'f2', 'pid': 'p1'});
return const PersonScreen('dummy', 'dummy');
},
),
@@ -1773,10 +1554,7 @@
];
final GoRouter router = await createRouter(routes, tester);
- router.goNamed(
- 'person',
- pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'},
- );
+ router.goNamed('person', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'});
});
testWidgets('too few params', (WidgetTester tester) async {
@@ -1784,14 +1562,12 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family/:fid',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
name: 'person',
@@ -1816,23 +1592,18 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family/:fid',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
name: 'PeRsOn',
path: 'person/:pid',
builder: (BuildContext context, GoRouterState state) {
- expect(state.pathParameters, <String, String>{
- 'fid': 'f2',
- 'pid': 'p1',
- });
+ expect(state.pathParameters, <String, String>{'fid': 'f2', 'pid': 'p1'});
return const PersonScreen('dummy', 'dummy');
},
),
@@ -1844,10 +1615,7 @@
final GoRouter router = await createRouter(routes, tester);
expect(() {
- router.goNamed(
- 'person',
- pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'},
- );
+ router.goNamed('person', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'});
}, throwsAssertionError);
});
@@ -1856,8 +1624,7 @@
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 {
@@ -1871,16 +1638,12 @@
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: <String, String>{'fid': 'f2', 'pid': 'p1'},
- );
+ router.goNamed('family', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'});
}, throwsA(isAssertionError));
});
@@ -1896,27 +1659,19 @@
name: 'person',
path: 'person:pid',
builder: (BuildContext context, GoRouterState state) =>
- PersonScreen(
- state.pathParameters['fid']!,
- state.pathParameters['pid']!,
- ),
+ PersonScreen(state.pathParameters['fid']!, state.pathParameters['pid']!),
),
],
),
];
final GoRouter router = await createRouter(routes, tester);
- router.goNamed(
- 'person',
- pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'},
- );
+ router.goNamed('person', pathParameters: <String, String>{'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 param1 = 'param w/ spaces and slashes';
final routes = <GoRoute>[
GoRoute(
@@ -1942,9 +1697,7 @@
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 param1 = 'param w/ spaces and slashes';
final routes = <GoRoute>[
GoRoute(
@@ -1975,13 +1728,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -1997,13 +1748,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/home',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -2023,22 +1772,17 @@
final routes = <GoRoute>[
GoRoute(
path: '/home',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'family/:fid',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
name: 'person',
path: 'person/:pid',
builder: (BuildContext context, GoRouterState state) {
- expect(state.pathParameters, <String, String>{
- 'fid': fid,
- 'pid': pid,
- });
+ expect(state.pathParameters, <String, String>{'fid': fid, 'pid': pid});
return const PersonScreen('dummy', 'dummy');
},
),
@@ -2048,11 +1792,7 @@
),
];
- 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();
@@ -2070,20 +1810,16 @@
final routes = <GoRoute>[
GoRoute(
path: '/home',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'family',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
path: 'person',
builder: (BuildContext context, GoRouterState state) {
- expect(state.uri.queryParameters, <String, String>{
- 'pid': pid,
- });
+ expect(state.uri.queryParameters, <String, String>{'pid': pid});
return const PersonScreen('dummy', 'dummy');
},
),
@@ -2093,11 +1829,7 @@
),
];
- 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();
@@ -2114,13 +1846,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/home',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'family/:fid',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
path: 'person/:pid',
@@ -2137,15 +1867,13 @@
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();
expect(find.byType(TestErrorScreen), findsOneWidget);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
});
@@ -2153,13 +1881,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/home',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'family',
- builder: (BuildContext context, GoRouterState state) =>
- const FamilyScreen('dummy'),
+ builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'),
routes: <GoRoute>[
GoRoute(
path: 'person',
@@ -2176,22 +1902,18 @@
routes,
tester,
initialLocation: '/home',
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
router.go('person');
await tester.pumpAndSettle();
expect(find.byType(TestErrorScreen), findsOneWidget);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
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 param1 = 'param w/ spaces and slashes';
final routes = <GoRoute>[
GoRoute(
@@ -2209,11 +1931,7 @@
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/home',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/home');
final loc = 'page1/${Uri.encodeComponent(param1)}';
router.go('./$loc');
@@ -2224,9 +1942,7 @@
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 param1 = 'param w/ spaces and slashes';
final routes = <GoRoute>[
GoRoute(
@@ -2244,11 +1960,7 @@
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/home',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/home');
final loc = Uri(
path: 'page1',
@@ -2269,18 +1981,15 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'dummy',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -2296,10 +2005,7 @@
},
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login');
expect(redirected, isTrue);
redirected = false;
@@ -2307,10 +2013,7 @@
await sendPlatformUrl('/dummy', tester);
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login');
expect(redirected, isTrue);
});
@@ -2321,13 +2024,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
GoRoute(
path: '/trigger-error',
@@ -2345,10 +2046,9 @@
}
return null;
},
- onException:
- (BuildContext context, GoRouterState state, GoRouter router) {
- exceptionCaught = true;
- },
+ onException: (BuildContext context, GoRouterState state, GoRouter router) {
+ exceptionCaught = true;
+ },
);
expect(find.byType(HomeScreen), findsOneWidget);
@@ -2365,22 +2065,18 @@
expect(find.text('should not reach here'), findsNothing);
});
- testWidgets('context extension methods work in redirects', (
- WidgetTester tester,
- ) async {
+ testWidgets('context extension methods work in redirects', (WidgetTester tester) async {
String? capturedNamedLocation;
final routes = <GoRoute>[
GoRoute(
path: '/',
name: 'home',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/login',
name: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
];
@@ -2396,21 +2092,17 @@
expect(capturedNamedLocation, '/login');
});
- testWidgets('redirect can redirect to same path', (
- WidgetTester tester,
- ) async {
+ testWidgets('redirect can redirect to same path', (WidgetTester tester) async {
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'dummy',
// Return same location.
redirect: (_, GoRouterState state) => state.uri.toString(),
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
),
@@ -2429,33 +2121,25 @@
// Directly set the url through platform message.
await sendPlatformUrl('/dummy', tester);
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/dummy',
- );
+ expect(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 routes = <GoRoute>[
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
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(),
),
],
),
@@ -2465,33 +2149,25 @@
routes,
tester,
redirect: (BuildContext context, GoRouterState state) =>
- state.matchedLocation == '/login'
- ? null
- : state.namedLocation('login'),
+ state.matchedLocation == '/login' ? null : state.namedLocation('login'),
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login');
});
testWidgets('route-level redirect', (WidgetTester tester) async {
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
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(),
),
],
),
@@ -2500,25 +2176,18 @@
final GoRouter router = await createRouter(routes, tester);
router.go('/dummy');
await tester.pump();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(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 routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'dummy',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) {
// should never be reached.
assert(false);
@@ -2527,13 +2196,11 @@
),
GoRoute(
path: 'dummy2',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: 'login',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
),
@@ -2552,36 +2219,27 @@
await sendPlatformUrl('/dummy', tester);
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(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 routes = <GoRoute>[
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
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(),
),
],
),
@@ -2590,28 +2248,22 @@
final GoRouter router = await createRouter(routes, tester);
router.go('/dummy');
await tester.pump();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login');
});
testWidgets('multiple mixed redirect', (WidgetTester tester) async {
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
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) => '/',
),
],
@@ -2633,22 +2285,17 @@
final GoRouter router = await createRouter(
<GoRoute>[],
tester,
- redirect: (BuildContext context, GoRouterState state) =>
- state.matchedLocation == '/'
+ 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<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
expect(screen.ex, isNotNull);
});
@@ -2667,17 +2314,13 @@
),
],
tester,
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
expect(screen.ex, isNotNull);
});
@@ -2693,54 +2336,40 @@
tester,
redirect: (BuildContext context, GoRouterState state) =>
state.matchedLocation == '/' ? '/login' : null,
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(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(
<GoRoute>[],
tester,
- redirect: (BuildContext context, GoRouterState state) =>
- state.matchedLocation == '/'
+ 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<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(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 routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/dummy',
@@ -2749,11 +2378,7 @@
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/dummy',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/dummy');
expect(router.routerDelegate.currentConfiguration.uri.toString(), '/');
});
@@ -2761,13 +2386,11 @@
final routes = <GoRoute>[
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(),
),
];
@@ -2787,25 +2410,20 @@
},
);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
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 routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
routes: <RouteBase>[
GoRoute(
path: ':id',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
),
@@ -2824,8 +2442,7 @@
},
);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(2));
});
@@ -2847,21 +2464,14 @@
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: loc,
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: loc);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
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 routes = <GoRoute>[
GoRoute(
path: '/',
@@ -2869,8 +2479,7 @@
routes: <GoRoute>[
GoRoute(
path: 'family/:fid',
- builder: (BuildContext c, GoRouterState s) =>
- FamilyScreen(s.pathParameters['fid']!),
+ builder: (BuildContext c, GoRouterState s) => FamilyScreen(s.pathParameters['fid']!),
routes: <GoRoute>[
GoRoute(
path: 'person/:pid',
@@ -2879,10 +2488,8 @@
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']!),
),
],
),
@@ -2896,14 +2503,11 @@
initialLocation: '/family/f2/person/p1',
);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches.length, 3);
expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget);
expect(find.byType(FamilyScreen, skipOffstage: false), findsOneWidget);
- final PersonScreen page = tester.widget<PersonScreen>(
- find.byType(PersonScreen),
- );
+ final PersonScreen page = tester.widget<PersonScreen>(find.byType(PersonScreen));
expect(page.fid, 'f2');
expect(page.pid, 'p1');
});
@@ -2912,20 +2516,15 @@
final GoRouter router = await createRouter(
<GoRoute>[],
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,
);
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(0));
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
expect(screen.ex, isNotNull);
});
@@ -2976,8 +2575,7 @@
GoRoute(
name: 'home',
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'login',
@@ -3022,19 +2620,16 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'dummy',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/other',
routes: <GoRoute>[
GoRoute(
path: 'dummy2',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) {
assert(false);
return '/other2';
@@ -3044,13 +2639,11 @@
),
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(),
),
],
),
@@ -3062,15 +2655,10 @@
await sendPlatformUrl('/dummy/dummy2', tester);
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/other',
- );
+ expect(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 routes = <RouteBase>[
ShellRoute(
redirect: (BuildContext context, GoRouterState state) => '/dummy',
@@ -3079,20 +2667,17 @@
routes: <RouteBase>[
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(),
),
];
@@ -3101,25 +2686,16 @@
for (final shellRoute in <String>['/other', '/other2']) {
router.go(shellRoute);
await tester.pump();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/dummy',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy');
}
});
- 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 routes = <RouteBase>[
StatefulShellRoute.indexedStack(
redirect: (BuildContext context, GoRouterState state) => '/dummy',
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
return navigationShell;
},
branches: <StatefulShellBranch>[
@@ -3127,8 +2703,7 @@
routes: <RouteBase>[
GoRoute(
path: '/other',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
),
@@ -3136,8 +2711,7 @@
routes: <RouteBase>[
GoRoute(
path: '/other2',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
),
@@ -3145,8 +2719,7 @@
),
GoRoute(
path: '/dummy',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
];
@@ -3155,10 +2728,7 @@
for (final shellRoute in <String>['/other', '/other2']) {
router.go(shellRoute);
await tester.pump();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/dummy',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy');
}
});
});
@@ -3168,35 +2738,25 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'dummy',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/dummy',
- );
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/dummy',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/dummy');
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy');
});
testWidgets('initial location with extra', (WidgetTester tester) async {
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <GoRoute>[
GoRoute(
path: 'dummy',
@@ -3214,10 +2774,7 @@
initialLocation: '/dummy',
initialExtra: 'extra',
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/dummy',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy');
expect(find.byKey(const ValueKey<Object?>('extra')), findsOneWidget);
});
@@ -3225,8 +2782,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/dummy',
@@ -3235,44 +2791,32 @@
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/dummy',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/dummy');
expect(router.routerDelegate.currentConfiguration.uri.toString(), '/');
});
- testWidgets(
- 'does not take precedence over platformDispatcher.defaultRouteName',
- (WidgetTester tester) async {
- TestWidgetsFlutterBinding
- .instance
- .platformDispatcher
- .defaultRouteNameTestValue =
- '/dummy';
+ testWidgets('does not take precedence over platformDispatcher.defaultRouteName', (
+ WidgetTester tester,
+ ) async {
+ TestWidgetsFlutterBinding.instance.platformDispatcher.defaultRouteNameTestValue = '/dummy';
- final routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
- routes: <GoRoute>[
- GoRoute(
- path: 'dummy',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
- ),
- ],
- ),
- ];
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
+ routes: <GoRoute>[
+ 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(
@@ -3292,61 +2836,36 @@
final routes = <GoRoute>[
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();
- },
- );
+ 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();
+ });
- 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();
- },
- );
+ 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();
+ });
- 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(),
- 'https://domain.com/?param=1',
- );
- 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(), 'https://domain.com/?param=1');
+ TestWidgetsFlutterBinding.instance.platformDispatcher.clearDefaultRouteNameTestValue();
+ });
});
group('params', () {
@@ -3354,8 +2873,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/family/:fid',
@@ -3369,8 +2887,7 @@
final loc = '/family/$fid';
router.go(loc);
await tester.pumpAndSettle();
- final RouteMatchList matches =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches = router.routerDelegate.currentConfiguration;
expect(router.routerDelegate.currentConfiguration.uri.toString(), loc);
expect(matches.matches, hasLength(1));
@@ -3383,8 +2900,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/family',
@@ -3398,8 +2914,7 @@
final loc = '/family?fid=$fid';
router.go(loc);
await tester.pumpAndSettle();
- final RouteMatchList matches =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches = router.routerDelegate.currentConfiguration;
expect(router.routerDelegate.currentConfiguration.uri.toString(), loc);
expect(matches.matches, hasLength(1));
@@ -3408,9 +2923,7 @@
}
});
- testWidgets('preserve path param spaces and slashes', (
- WidgetTester tester,
- ) async {
+ testWidgets('preserve path param spaces and slashes', (WidgetTester tester) async {
const param1 = 'param w/ spaces and slashes';
final routes = <GoRoute>[
GoRoute(
@@ -3432,9 +2945,7 @@
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 param1 = 'param w/ spaces and slashes';
final routes = <GoRoute>[
GoRoute(
@@ -3458,8 +2969,7 @@
router.go(loc);
await tester.pumpAndSettle();
- final RouteMatchList matches2 =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList matches2 = router.routerDelegate.currentConfiguration;
expect(find.byType(DummyScreen), findsOneWidget);
expect(matches2.uri.queryParameters['param1'], param1);
});
@@ -3467,9 +2977,7 @@
test('error: duplicate path param', () {
try {
GoRouter(
- routes: <GoRoute>[
- GoRoute(path: '/:id/:blah/:bam/:id/:blah', builder: dummy),
- ],
+ routes: <GoRoute>[GoRoute(path: '/:id/:blah/:bam/:id/:blah', builder: dummy)],
errorBuilder: (BuildContext context, GoRouterState state) =>
TestErrorScreen(state.error!),
initialLocation: '/0/1/2/0/1',
@@ -3533,10 +3041,8 @@
),
GoRoute(
path: '/person',
- builder: (BuildContext context, GoRouterState state) => PersonScreen(
- state.uri.queryParameters['fid']!,
- state.uri.queryParameters['pid']!,
- ),
+ builder: (BuildContext context, GoRouterState state) =>
+ PersonScreen(state.uri.queryParameters['fid']!, state.uri.queryParameters['pid']!),
),
], tester);
@@ -3549,9 +3055,7 @@
);
expect(page1.fid, 'f2');
- final PersonScreen page2 = tester.widget<PersonScreen>(
- find.byType(PersonScreen),
- );
+ final PersonScreen page2 = tester.widget<PersonScreen>(find.byType(PersonScreen));
expect(page2.fid, 'f2');
expect(page2.pid, 'p1');
});
@@ -3582,9 +3086,7 @@
);
expect(page1.fid, 'f2');
- final PersonScreen page2 = tester.widget<PersonScreen>(
- find.byType(PersonScreen),
- );
+ final PersonScreen page2 = tester.widget<PersonScreen>(find.byType(PersonScreen));
expect(page2.fid, 'f2');
expect(page2.pid, 'p1');
});
@@ -3593,8 +3095,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/family/:fid',
@@ -3638,11 +3139,7 @@
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState = navigationShell;
return navigationShell;
},
@@ -3651,8 +3148,7 @@
routes: <RouteBase>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
),
],
),
@@ -3660,8 +3156,7 @@
routes: <RouteBase>[
GoRoute(
path: '/family',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Families'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Families'),
routes: <RouteBase>[
GoRoute(
path: ':fid',
@@ -3687,11 +3182,7 @@
),
];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/a',
- );
+ final GoRouter router = await createRouter(routes, tester, initialLocation: '/a');
const fid = 'f1';
const pid = 'p2';
const loc = '/family/$fid/person/$pid';
@@ -3730,11 +3221,7 @@
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState = navigationShell;
return navigationShell;
},
@@ -3743,8 +3230,7 @@
routes: <RouteBase>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
),
],
),
@@ -3764,12 +3250,7 @@
];
final 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();
@@ -3794,8 +3275,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
name: 'page',
@@ -3803,9 +3283,7 @@
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);
},
),
];
@@ -3820,13 +3298,10 @@
},
);
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
- expectLocationWithQueryParams(
- router.routerDelegate.currentConfiguration.uri.toString(),
- );
+ expectLocationWithQueryParams(router.routerDelegate.currentConfiguration.uri.toString());
expect(
tester.widget<DummyScreen>(find.byType(DummyScreen)),
isA<DummyScreen>().having(
@@ -3854,8 +3329,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
name: 'page',
@@ -3872,13 +3346,10 @@
router.go('/page?q1=v1&q2=v2&q2=v3');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
- expectLocationWithQueryParams(
- router.routerDelegate.currentConfiguration.uri.toString(),
- );
+ expectLocationWithQueryParams(router.routerDelegate.currentConfiguration.uri.toString());
expect(
tester.widget<DummyScreen>(find.byType(DummyScreen)),
isA<DummyScreen>().having(
@@ -3889,9 +3360,7 @@
);
});
- testWidgets('goRouter should rebuild widget if ', (
- WidgetTester tester,
- ) async {
+ testWidgets('goRouter should rebuild widget if ', (WidgetTester tester) async {
const Map<String, dynamic> queryParametersAll = <String, List<dynamic>>{
'q1': <String>['v1'],
'q2': <String>['v2', 'v3'],
@@ -3905,8 +3374,7 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
name: 'page',
@@ -3923,13 +3391,10 @@
router.go('/page?q1=v1&q2=v2&q2=v3');
await tester.pumpAndSettle();
- final List<RouteMatchBase> matches =
- router.routerDelegate.currentConfiguration.matches;
+ final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches;
expect(matches, hasLength(1));
- expectLocationWithQueryParams(
- router.routerDelegate.currentConfiguration.uri.toString(),
- );
+ expectLocationWithQueryParams(router.routerDelegate.currentConfiguration.uri.toString());
expect(
tester.widget<DummyScreen>(find.byType(DummyScreen)),
isA<DummyScreen>().having(
@@ -3946,14 +3411,12 @@
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(),
),
];
@@ -3963,19 +3426,11 @@
const location = '/page1';
const extra = 'Hello';
- testWidgets('calls [namedLocation] on closest GoRouter', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls [namedLocation] on closest GoRouter', (WidgetTester tester) async {
final router = GoRouterNamedLocationSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
- key.currentContext!.namedLocation(
- name,
- pathParameters: params,
- queryParameters: queryParams,
- );
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example'));
+ key.currentContext!.namedLocation(name, pathParameters: params, queryParameters: queryParams);
expect(router.name, name);
expect(router.pathParameters, params);
expect(router.queryParameters, queryParams);
@@ -3984,22 +3439,16 @@
testWidgets('calls [go] on closest GoRouter', (WidgetTester tester) async {
final router = GoRouterGoSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
+ await tester.pumpWidget(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 router = GoRouterGoNamedSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example'));
key.currentContext!.goNamed(
name,
pathParameters: params,
@@ -4012,14 +3461,10 @@
expect(router.extra, extra);
});
- testWidgets('calls [push] on closest GoRouter', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls [push] on closest GoRouter', (WidgetTester tester) async {
final router = GoRouterPushSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example'));
key.currentContext!.push(location, extra: extra);
expect(router.myLocation, location);
expect(router.extra, extra);
@@ -4044,14 +3489,10 @@
expect(router.extra, extra);
});
- testWidgets('calls [pushNamed] on closest GoRouter', (
- WidgetTester tester,
- ) async {
+ testWidgets('calls [pushNamed] on closest GoRouter', (WidgetTester tester) async {
final router = GoRouterPushNamedSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example'));
key.currentContext!.pushNamed(
name,
pathParameters: params,
@@ -4093,22 +3534,16 @@
testWidgets('calls [pop] on closest GoRouter', (WidgetTester tester) async {
final router = GoRouterPopSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
+ await tester.pumpWidget(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 router = GoRouterPopSpy(routes: routes);
addTearDown(router.dispose);
- await tester.pumpWidget(
- MaterialApp.router(routerConfig: router, title: 'GoRouter Example'),
- );
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example'));
key.currentContext!.pop('result');
expect(router.popped, true);
expect(router.poppedResult, 'result');
@@ -4186,53 +3621,52 @@
expect(result, isTrue);
});
- testWidgets(
- 'Pops from the correct Navigator when the Android back button is pressed',
- (WidgetTester tester) async {
- final routes = <RouteBase>[
- ShellRoute(
- builder: (BuildContext context, GoRouterState state, Widget child) {
- return Scaffold(
- body: Column(
- children: <Widget>[
- const Text('Screen A'),
- Expanded(child: child),
- ],
- ),
- );
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/b',
- builder: (BuildContext context, GoRouterState state) {
- return const Scaffold(body: Text('Screen B'));
- },
- routes: <RouteBase>[
- GoRoute(
- path: 'c',
- builder: (BuildContext context, GoRouterState state) {
- return const Scaffold(body: Text('Screen C'));
- },
- ),
+ testWidgets('Pops from the correct Navigator when the Android back button is pressed', (
+ WidgetTester tester,
+ ) async {
+ final routes = <RouteBase>[
+ ShellRoute(
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Scaffold(
+ body: Column(
+ children: <Widget>[
+ const Text('Screen A'),
+ Expanded(child: child),
],
),
- ],
- ),
- ];
+ );
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/b',
+ builder: (BuildContext context, GoRouterState state) {
+ return const Scaffold(body: Text('Screen B'));
+ },
+ routes: <RouteBase>[
+ 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 '
'the root Navigator', (WidgetTester tester) async {
@@ -4272,12 +3706,7 @@
),
];
- 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);
@@ -4306,8 +3735,7 @@
routes: <GoRoute>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
),
],
),
@@ -4315,8 +3743,7 @@
routes: <GoRoute>[
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen B'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen B'),
),
],
),
@@ -4339,16 +3766,13 @@
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 rootNavigatorKey = GlobalKey<NavigatorState>();
final routes = <RouteBase>[
GoRoute(
path: '/root',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Root'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Root'),
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
builder:
@@ -4397,261 +3821,228 @@
expect(find.text('Screen B'), findsOneWidget);
});
- testWidgets(
- 'Navigation with goBranch is correctly handled in StatefulShellRoute',
- (WidgetTester tester) async {
- final rootNavigatorKey = GlobalKey<NavigatorState>();
- final statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>();
- StatefulNavigationShell? routeState;
-
- final routes = <RouteBase>[
- StatefulShellRoute.indexedStack(
- builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeState = navigationShell;
- return navigationShell;
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(
- path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(
- path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen B'),
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(
- path: '/c',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen C'),
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(
- path: '/d',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen D'),
- ),
- ],
- ),
- ],
- ),
- ];
-
- 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 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<Error>()));
- },
- );
-
- testWidgets(
- 'Navigates to correct nested navigation tree in StatefulShellRoute '
- 'and maintains state',
- (WidgetTester tester) async {
- final rootNavigatorKey = GlobalKey<NavigatorState>();
- final statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>();
- StatefulNavigationShell? routeState;
-
- final routes = <RouteBase>[
- StatefulShellRoute.indexedStack(
- builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeState = navigationShell;
- return navigationShell;
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <GoRoute>[
- GoRoute(
- path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
- routes: <RouteBase>[
- GoRoute(
- path: 'detailA',
- builder: (BuildContext context, GoRouterState state) =>
- Column(
- children: <Widget>[
- const Text('Screen A Detail'),
- DummyStatefulWidget(key: statefulWidgetKey),
- ],
- ),
- ),
- ],
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <GoRoute>[
- 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 routes = <RouteBase>[
- GoRoute(
- path: '/:id',
- builder: (_, __) => const Placeholder(),
- routes: <RouteBase>[
- StatefulShellRoute.indexedStack(
- builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeState = navigationShell;
- return navigationShell;
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <GoRoute>[
- GoRoute(
- path: 'a',
- builder: (BuildContext context, GoRouterState state) =>
- Text('a id is ${state.pathParameters['id']}'),
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <GoRoute>[
- 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);
-
- routeState!.goBranch(1);
- await tester.pumpAndSettle();
- expect(find.text('b id is 123'), findsOneWidget);
- },
- );
-
- testWidgets('Maintains state for nested StatefulShellRoute', (
+ testWidgets('Navigation with goBranch is correctly handled in StatefulShellRoute', (
WidgetTester tester,
) async {
final rootNavigatorKey = GlobalKey<NavigatorState>();
final statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>();
+ StatefulNavigationShell? routeState;
+
+ final routes = <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ builder:
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
+ routeState = navigationShell;
+ return navigationShell;
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/a',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/b',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen B'),
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/c',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen C'),
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/d',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen D'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ];
+
+ 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 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<Error>()));
+ });
+
+ testWidgets('Navigates to correct nested navigation tree in StatefulShellRoute '
+ 'and maintains state', (WidgetTester tester) async {
+ final rootNavigatorKey = GlobalKey<NavigatorState>();
+ final statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>();
+ StatefulNavigationShell? routeState;
+
+ final routes = <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ builder:
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
+ routeState = navigationShell;
+ return navigationShell;
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/a',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'detailA',
+ builder: (BuildContext context, GoRouterState state) => Column(
+ children: <Widget>[
+ const Text('Screen A Detail'),
+ DummyStatefulWidget(key: statefulWidgetKey),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <GoRoute>[
+ 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 routes = <RouteBase>[
+ GoRoute(
+ path: '/:id',
+ builder: (_, __) => const Placeholder(),
+ routes: <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ builder:
+ (
+ BuildContext context,
+ GoRouterState state,
+ StatefulNavigationShell navigationShell,
+ ) {
+ routeState = navigationShell;
+ return navigationShell;
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <GoRoute>[
+ GoRoute(
+ path: 'a',
+ builder: (BuildContext context, GoRouterState state) =>
+ Text('a id is ${state.pathParameters['id']}'),
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <GoRoute>[
+ 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);
+
+ routeState!.goBranch(1);
+ await tester.pumpAndSettle();
+ expect(find.text('b id is 123'), findsOneWidget);
+ });
+
+ testWidgets('Maintains state for nested StatefulShellRoute', (WidgetTester tester) async {
+ final rootNavigatorKey = GlobalKey<NavigatorState>();
+ final statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>();
StatefulNavigationShell? routeState1;
StatefulNavigationShell? routeState2;
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState1 = navigationShell;
return navigationShell;
},
@@ -4673,22 +4064,17 @@
routes: <RouteBase>[
GoRoute(
path: '/a',
- builder:
- (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) =>
+ const Text('Screen A'),
routes: <RouteBase>[
GoRoute(
path: 'detailA',
- builder:
- (BuildContext context, GoRouterState state) =>
- Column(
- children: <Widget>[
- const Text('Screen A Detail'),
- DummyStatefulWidget(
- key: statefulWidgetKey,
- ),
- ],
- ),
+ builder: (BuildContext context, GoRouterState state) => Column(
+ children: <Widget>[
+ const Text('Screen A Detail'),
+ DummyStatefulWidget(key: statefulWidgetKey),
+ ],
+ ),
),
],
),
@@ -4698,9 +4084,8 @@
routes: <RouteBase>[
GoRoute(
path: '/b',
- builder:
- (BuildContext context, GoRouterState state) =>
- const Text('Screen B'),
+ builder: (BuildContext context, GoRouterState state) =>
+ const Text('Screen B'),
),
],
),
@@ -4708,9 +4093,8 @@
routes: <RouteBase>[
GoRoute(
path: '/c',
- builder:
- (BuildContext context, GoRouterState state) =>
- const Text('Screen C'),
+ builder: (BuildContext context, GoRouterState state) =>
+ const Text('Screen C'),
),
],
),
@@ -4722,8 +4106,7 @@
routes: <GoRoute>[
GoRoute(
path: '/d',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen D'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen D'),
),
],
),
@@ -4761,103 +4144,94 @@
expect(statefulWidgetKey.currentState?.counter, equals(1));
});
- testWidgets(
- 'Pops from the correct Navigator in a StatefulShellRoute when the '
- 'Android back button is pressed',
- (WidgetTester tester) async {
- final rootNavigatorKey = GlobalKey<NavigatorState>();
- final sectionANavigatorKey = GlobalKey<NavigatorState>();
- final sectionBNavigatorKey = GlobalKey<NavigatorState>();
- StatefulNavigationShell? routeState;
+ testWidgets('Pops from the correct Navigator in a StatefulShellRoute when the '
+ 'Android back button is pressed', (WidgetTester tester) async {
+ final rootNavigatorKey = GlobalKey<NavigatorState>();
+ final sectionANavigatorKey = GlobalKey<NavigatorState>();
+ final sectionBNavigatorKey = GlobalKey<NavigatorState>();
+ StatefulNavigationShell? routeState;
- final routes = <RouteBase>[
- StatefulShellRoute.indexedStack(
- builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeState = navigationShell;
- return navigationShell;
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- navigatorKey: sectionANavigatorKey,
- routes: <GoRoute>[
- GoRoute(
- path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
- routes: <RouteBase>[
- GoRoute(
- path: 'detailA',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A Detail'),
- ),
- ],
- ),
- ],
- ),
- StatefulShellBranch(
- navigatorKey: sectionBNavigatorKey,
- routes: <GoRoute>[
- GoRoute(
- path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen B'),
- routes: <RouteBase>[
- GoRoute(
- path: 'detailB',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen B Detail'),
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ];
+ final routes = <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ builder:
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
+ routeState = navigationShell;
+ return navigationShell;
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ navigatorKey: sectionANavigatorKey,
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/a',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'detailA',
+ builder: (BuildContext context, GoRouterState state) =>
+ const Text('Screen A Detail'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ navigatorKey: sectionBNavigatorKey,
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/b',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen B'),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'detailB',
+ 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 '
'between branches in StatefulShellRoute', (WidgetTester tester) async {
@@ -4867,11 +4241,7 @@
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState = navigationShell;
return navigationShell;
},
@@ -4880,8 +4250,7 @@
routes: <GoRoute>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
),
],
),
@@ -4923,25 +4292,18 @@
});
testWidgets('Pushed non-descendant routes are correctly restored when '
- 'navigating between branches in StatefulShellRoute', (
- WidgetTester tester,
- ) async {
+ 'navigating between branches in StatefulShellRoute', (WidgetTester tester) async {
final rootNavigatorKey = GlobalKey<NavigatorState>();
StatefulNavigationShell? routeState;
final routes = <RouteBase>[
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,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState = navigationShell;
return navigationShell;
},
@@ -4950,8 +4312,7 @@
routes: <GoRoute>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
),
],
),
@@ -4959,8 +4320,7 @@
routes: <GoRoute>[
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen B'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen B'),
),
],
),
@@ -4998,25 +4358,13 @@
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 rootNavigatorKey = GlobalKey<NavigatorState>();
- final statefulWidgetKeyA = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'A',
- );
- final statefulWidgetKeyB = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'B',
- );
- final statefulWidgetKeyC = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'C',
- );
- final statefulWidgetKeyD = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'D',
- );
- final statefulWidgetKeyE = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'E',
- );
+ final statefulWidgetKeyA = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'A');
+ final statefulWidgetKeyB = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'B');
+ final statefulWidgetKeyC = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'C');
+ final statefulWidgetKeyD = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'D');
+ final statefulWidgetKeyE = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'E');
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
@@ -5071,8 +4419,7 @@
routes: <RouteBase>[
GoRoute(
path: '/e',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('E'),
+ builder: (BuildContext context, GoRouterState state) => const Text('E'),
routes: <RouteBase>[
GoRoute(
path: 'details',
@@ -5109,18 +4456,10 @@
WidgetTester tester,
) async {
final rootNavigatorKey = GlobalKey<NavigatorState>();
- final statefulWidgetKeyA = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'A',
- );
- final statefulWidgetKeyB = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'B',
- );
- final statefulWidgetKeyC = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'C',
- );
- final statefulWidgetKeyD = GlobalKey<DummyStatefulWidgetState>(
- debugLabel: 'D',
- );
+ final statefulWidgetKeyA = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'A');
+ final statefulWidgetKeyB = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'B');
+ final statefulWidgetKeyC = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'C');
+ final statefulWidgetKeyD = GlobalKey<DummyStatefulWidgetState>(debugLabel: 'D');
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
@@ -5137,9 +4476,8 @@
routes: <RouteBase>[
GoRoute(
path: '/a',
- builder:
- (BuildContext context, GoRouterState state) =>
- DummyStatefulWidget(key: statefulWidgetKeyA),
+ builder: (BuildContext context, GoRouterState state) =>
+ DummyStatefulWidget(key: statefulWidgetKeyA),
),
],
),
@@ -5148,9 +4486,8 @@
routes: <RouteBase>[
GoRoute(
path: '/b',
- builder:
- (BuildContext context, GoRouterState state) =>
- DummyStatefulWidget(key: statefulWidgetKeyB),
+ builder: (BuildContext context, GoRouterState state) =>
+ DummyStatefulWidget(key: statefulWidgetKeyB),
),
],
),
@@ -5181,12 +4518,7 @@
),
];
- await createRouter(
- routes,
- tester,
- initialLocation: '/c',
- navigatorKey: rootNavigatorKey,
- );
+ await createRouter(routes, tester, initialLocation: '/c', navigatorKey: rootNavigatorKey);
expect(statefulWidgetKeyA.currentState?.counter, equals(0));
expect(statefulWidgetKeyB.currentState?.counter, equals(0));
expect(statefulWidgetKeyC.currentState?.counter, equals(0));
@@ -5201,11 +4533,7 @@
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState = navigationShell;
return navigationShell;
},
@@ -5214,8 +4542,7 @@
routes: <GoRoute>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
),
],
),
@@ -5223,8 +4550,7 @@
routes: <GoRoute>[
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen B'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen B'),
routes: <RouteBase>[
GoRoute(
path: 'details1',
@@ -5245,13 +4571,11 @@
GoRoute(path: '/c', redirect: (_, __) => '/c/main2'),
GoRoute(
path: '/c/main1',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen C1'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen C1'),
),
GoRoute(
path: '/c/main2',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen C2'),
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen C2'),
),
],
),
@@ -5294,135 +4618,125 @@
expect(find.text('Screen C2'), findsNothing);
});
- testWidgets(
- 'Pushed top-level route is correctly handled by StatefulShellRoute',
- (WidgetTester tester) async {
- final rootNavigatorKey = GlobalKey<NavigatorState>();
- final nestedNavigatorKey = GlobalKey<NavigatorState>();
- StatefulNavigationShell? routeState;
+ testWidgets('Pushed top-level route is correctly handled by StatefulShellRoute', (
+ WidgetTester tester,
+ ) async {
+ final rootNavigatorKey = GlobalKey<NavigatorState>();
+ final nestedNavigatorKey = GlobalKey<NavigatorState>();
+ StatefulNavigationShell? routeState;
- final routes = <RouteBase>[
- // First level shell
- StatefulShellRoute.indexedStack(
- builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeState = navigationShell;
- return navigationShell;
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <GoRoute>[
- GoRoute(
- path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('Screen A'),
- ),
- ],
- ),
- StatefulShellBranch(
- routes: <RouteBase>[
- // Second level / nested shell
- StatefulShellRoute.indexedStack(
- builder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) => navigationShell,
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <GoRoute>[
- GoRoute(
- path: '/b1',
- builder:
- (BuildContext context, GoRouterState state) =>
- const Text('Screen B1'),
- ),
- ],
- ),
- StatefulShellBranch(
- navigatorKey: nestedNavigatorKey,
- routes: <GoRoute>[
- 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'),
- ),
- ];
+ final routes = <RouteBase>[
+ // First level shell
+ StatefulShellRoute.indexedStack(
+ builder:
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
+ routeState = navigationShell;
+ return navigationShell;
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/a',
+ builder: (BuildContext context, GoRouterState state) => const Text('Screen A'),
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ routes: <RouteBase>[
+ // Second level / nested shell
+ StatefulShellRoute.indexedStack(
+ builder:
+ (
+ BuildContext context,
+ GoRouterState state,
+ StatefulNavigationShell navigationShell,
+ ) => navigationShell,
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/b1',
+ builder: (BuildContext context, GoRouterState state) =>
+ const Text('Screen B1'),
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ navigatorKey: nestedNavigatorKey,
+ routes: <GoRoute>[
+ 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'),
+ ),
+ ];
- 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 '
@@ -5431,9 +4745,7 @@
skip: true,
(WidgetTester tester) async {
final rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
- final statefulShellKey = GlobalKey<StatefulNavigationShellState>(
- debugLabel: 'shell',
- );
+ final statefulShellKey = GlobalKey<StatefulNavigationShellState>(debugLabel: 'shell');
StatefulNavigationShell? routeState;
StatefulShellBranch makeBranch(String name) => StatefulShellBranch(
navigatorKey: GlobalKey<NavigatorState>(debugLabel: 'branch-$name'),
@@ -5442,8 +4754,7 @@
routes: <GoRoute>[
GoRoute(
path: '/$name',
- builder: (BuildContext context, GoRouterState state) =>
- Text('Screen $name'),
+ builder: (BuildContext context, GoRouterState state) => Text('Screen $name'),
),
],
);
@@ -5468,9 +4779,7 @@
),
];
- final config = ValueNotifier<RoutingConfig>(
- RoutingConfig(routes: createRoutes(true)),
- );
+ final config = ValueNotifier<RoutingConfig>(RoutingConfig(routes: createRoutes(true)));
addTearDown(config.dispose);
await createRouterWithRoutingConfig(
navigatorKey: rootNavigatorKey,
@@ -5481,8 +4790,9 @@
);
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);
@@ -5501,77 +4811,68 @@
group('Imperative navigation', () {
group('canPop', () {
- testWidgets(
- 'It should return false if Navigator.canPop() returns false.',
- (WidgetTester tester) async {
- final navigatorKey = GlobalKey<NavigatorState>();
- final router = GoRouter(
- initialLocation: '/',
- navigatorKey: navigatorKey,
- routes: <GoRoute>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, _) {
- return Scaffold(
- body: TextButton(
- onPressed: () async {
- navigatorKey.currentState!.push(
- MaterialPageRoute<void>(
- builder: (BuildContext context) {
- return const Scaffold(
- body: Text('pageless route'),
- );
- },
- ),
- );
- },
- child: const Text('Push'),
- ),
- );
- },
- ),
- GoRoute(path: '/a', builder: (_, __) => const DummyScreen()),
- ],
- );
- addTearDown(router.dispose);
-
- await tester.pumpWidget(
- MaterialApp.router(
- routeInformationProvider: router.routeInformationProvider,
- routeInformationParser: router.routeInformationParser,
- routerDelegate: router.routerDelegate,
- ),
- );
-
- expect(router.canPop(), false);
-
- await tester.tap(find.text('Push'));
- await tester.pumpAndSettle();
-
- expect(
- find.text('pageless route', skipOffstage: false),
- findsOneWidget,
- );
- expect(router.canPop(), true);
- },
- );
-
- testWidgets('It checks if ShellRoute navigators can pop', (
+ testWidgets('It should return false if Navigator.canPop() returns false.', (
WidgetTester tester,
) async {
+ final navigatorKey = GlobalKey<NavigatorState>();
+ final router = GoRouter(
+ initialLocation: '/',
+ navigatorKey: navigatorKey,
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, _) {
+ return Scaffold(
+ body: TextButton(
+ onPressed: () async {
+ navigatorKey.currentState!.push(
+ MaterialPageRoute<void>(
+ builder: (BuildContext context) {
+ return const Scaffold(body: Text('pageless route'));
+ },
+ ),
+ );
+ },
+ child: const Text('Push'),
+ ),
+ );
+ },
+ ),
+ GoRoute(path: '/a', builder: (_, __) => const DummyScreen()),
+ ],
+ );
+ addTearDown(router.dispose);
+
+ await tester.pumpWidget(
+ MaterialApp.router(
+ routeInformationProvider: router.routeInformationProvider,
+ routeInformationParser: router.routeInformationParser,
+ routerDelegate: router.routerDelegate,
+ ),
+ );
+
+ expect(router.canPop(), false);
+
+ await tester.tap(find.text('Push'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('pageless route', skipOffstage: false), findsOneWidget);
+ expect(router.canPop(), true);
+ });
+
+ testWidgets('It checks if ShellRoute navigators can pop', (WidgetTester tester) async {
final shellNavigatorKey = GlobalKey<NavigatorState>();
final router = GoRouter(
initialLocation: '/a',
routes: <RouteBase>[
ShellRoute(
navigatorKey: shellNavigatorKey,
- builder:
- (BuildContext context, GoRouterState state, Widget child) {
- return Scaffold(
- appBar: AppBar(title: const Text('Shell')),
- body: child,
- );
- },
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Scaffold(
+ appBar: AppBar(title: const Text('Shell')),
+ body: child,
+ );
+ },
routes: <GoRoute>[
GoRoute(
path: '/a',
@@ -5582,9 +4883,7 @@
shellNavigatorKey.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
- return const Scaffold(
- body: Text('pageless route'),
- );
+ return const Scaffold(body: Text('pageless route'));
},
),
);
@@ -5614,10 +4913,7 @@
await tester.tap(find.text('Push'));
await tester.pumpAndSettle();
- expect(
- find.text('pageless route', skipOffstage: false),
- findsOneWidget,
- );
+ expect(find.text('pageless route', skipOffstage: false), findsOneWidget);
expect(router.canPop(), true);
});
@@ -5653,9 +4949,7 @@
GoRoute(
path: 'detail',
builder: (BuildContext context, _) {
- return const Scaffold(
- body: Text('Screen B detail'),
- );
+ return const Scaffold(body: Text('Screen B detail'));
},
),
],
@@ -5681,19 +4975,14 @@
router.go('/b/detail');
await tester.pumpAndSettle();
- expect(
- find.text('Screen B detail', skipOffstage: false),
- findsOneWidget,
- );
+ 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 {
+ testWidgets('Pageless route should include in can pop', (WidgetTester tester) async {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
@@ -5702,8 +4991,56 @@
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
- builder:
- (BuildContext context, GoRouterState state, Widget child) {
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Scaffold(
+ body: Center(
+ child: Column(
+ children: <Widget>[
+ const Text('Shell'),
+ Expanded(child: child),
+ ],
+ ),
+ ),
+ );
+ },
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('A Screen'))],
+ ),
+ ],
+ );
+ addTearDown(router.dispose);
+
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+
+ expect(router.canPop(), isFalse);
+ expect(find.text('A Screen'), findsOneWidget);
+ expect(find.text('Shell'), findsOneWidget);
+ showDialog<void>(context: root.currentContext!, builder: (_) => const Text('A dialog'));
+ await tester.pumpAndSettle();
+ expect(find.text('A dialog'), findsOneWidget);
+ expect(router.canPop(), isTrue);
+ });
+ });
+
+ group('pop', () {
+ testWidgets('Should pop from the correct navigator when parentNavigatorKey is set', (
+ WidgetTester tester,
+ ) async {
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
+
+ final router = GoRouter(
+ initialLocation: '/a/b',
+ navigatorKey: root,
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, _) {
+ return const Scaffold(body: Text('Home'));
+ },
+ routes: <RouteBase>[
+ ShellRoute(
+ navigatorKey: shell,
+ builder: (BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: Center(
child: Column(
@@ -5715,113 +5052,51 @@
),
);
},
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('A Screen')),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'a',
+ builder: (_, __) => const Text('A Screen'),
+ routes: <RouteBase>[
+ GoRoute(
+ parentNavigatorKey: root,
+ path: 'b',
+ builder: (_, __) => const Text('B Screen'),
+ ),
+ ],
+ ),
+ ],
+ ),
],
),
],
);
addTearDown(router.dispose);
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpWidget(
+ MaterialApp.router(
+ routeInformationProvider: router.routeInformationProvider,
+ routeInformationParser: router.routeInformationParser,
+ routerDelegate: router.routerDelegate,
+ ),
+ );
- expect(router.canPop(), isFalse);
+ expect(router.canPop(), isTrue);
+ expect(find.text('B Screen'), findsOneWidget);
+ expect(find.text('A Screen'), findsNothing);
+ expect(find.text('Shell'), findsNothing);
+ expect(find.text('Home'), findsNothing);
+ router.pop();
+ await tester.pumpAndSettle();
expect(find.text('A Screen'), findsOneWidget);
expect(find.text('Shell'), findsOneWidget);
- showDialog<void>(
- context: root.currentContext!,
- builder: (_) => const Text('A dialog'),
- );
- await tester.pumpAndSettle();
- expect(find.text('A dialog'), findsOneWidget);
expect(router.canPop(), isTrue);
+ router.pop();
+ await tester.pumpAndSettle();
+ expect(find.text('Home'), findsOneWidget);
+ expect(find.text('Shell'), findsNothing);
});
- });
- group('pop', () {
- testWidgets(
- 'Should pop from the correct navigator when parentNavigatorKey is set',
- (WidgetTester tester) async {
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
-
- final router = GoRouter(
- initialLocation: '/a/b',
- navigatorKey: root,
- routes: <GoRoute>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, _) {
- return const Scaffold(body: Text('Home'));
- },
- routes: <RouteBase>[
- ShellRoute(
- navigatorKey: shell,
- builder:
- (
- BuildContext context,
- GoRouterState state,
- Widget child,
- ) {
- return Scaffold(
- body: Center(
- child: Column(
- children: <Widget>[
- const Text('Shell'),
- Expanded(child: child),
- ],
- ),
- ),
- );
- },
- routes: <RouteBase>[
- GoRoute(
- path: 'a',
- builder: (_, __) => const Text('A Screen'),
- routes: <RouteBase>[
- GoRoute(
- parentNavigatorKey: root,
- path: 'b',
- builder: (_, __) => const Text('B Screen'),
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- );
- addTearDown(router.dispose);
-
- await tester.pumpWidget(
- MaterialApp.router(
- routeInformationProvider: router.routeInformationProvider,
- routeInformationParser: router.routeInformationParser,
- routerDelegate: router.routerDelegate,
- ),
- );
-
- expect(router.canPop(), isTrue);
- expect(find.text('B Screen'), findsOneWidget);
- expect(find.text('A Screen'), findsNothing);
- expect(find.text('Shell'), findsNothing);
- expect(find.text('Home'), findsNothing);
- router.pop();
- await tester.pumpAndSettle();
- expect(find.text('A Screen'), findsOneWidget);
- expect(find.text('Shell'), findsOneWidget);
- expect(router.canPop(), isTrue);
- router.pop();
- await tester.pumpAndSettle();
- expect(find.text('Home'), findsOneWidget);
- expect(find.text('Shell'), findsNothing);
- },
- );
-
- testWidgets('Should pop dialog if it is present', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should pop dialog if it is present', (WidgetTester tester) async {
final root = GlobalKey<NavigatorState>(debugLabel: 'root');
final shell = GlobalKey<NavigatorState>(debugLabel: 'shell');
@@ -5837,28 +5112,20 @@
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
- builder:
- (
- BuildContext context,
- GoRouterState state,
- Widget child,
- ) {
- return Scaffold(
- body: Center(
- child: Column(
- children: <Widget>[
- const Text('Shell'),
- Expanded(child: child),
- ],
- ),
- ),
- );
- },
+ builder: (BuildContext context, GoRouterState state, Widget child) {
+ return Scaffold(
+ body: Center(
+ child: Column(
+ children: <Widget>[
+ const Text('Shell'),
+ Expanded(child: child),
+ ],
+ ),
+ ),
+ );
+ },
routes: <RouteBase>[
- GoRoute(
- path: 'a',
- builder: (_, __) => const Text('A Screen'),
- ),
+ GoRoute(path: 'a', builder: (_, __) => const Text('A Screen')),
],
),
],
@@ -5890,9 +5157,7 @@
expect(result, isTrue);
});
- testWidgets('Triggers a Hero inside a ShellRoute', (
- WidgetTester tester,
- ) async {
+ testWidgets('Triggers a Hero inside a ShellRoute', (WidgetTester tester) async {
final heroKey = UniqueKey();
const kHeroTag = 'hero';
@@ -5923,11 +5188,7 @@
],
),
];
- 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);
@@ -5992,30 +5253,25 @@
expect(foundRouter, router);
});
- testWidgets(
- 'It should return null if there is no go router in the widget tree',
- (WidgetTester tester) async {
- const key = Key('key');
- await tester.pumpWidget(const SizedBox(key: key));
+ testWidgets('It should return null if there is no go router in the widget tree', (
+ WidgetTester tester,
+ ) async {
+ const key = Key('key');
+ await tester.pumpWidget(const SizedBox(key: key));
- final Element context = tester.element(find.byKey(key));
- expect(GoRouter.maybeOf(context), isNull);
- },
- );
+ final Element context = tester.element(find.byKey(key));
+ expect(GoRouter.maybeOf(context), isNull);
+ });
});
group('state restoration', () {
testWidgets('Restores state correctly', (WidgetTester tester) async {
- final statefulWidgetKeyA =
- GlobalKey<DummyRestorableStatefulWidgetState>();
+ final statefulWidgetKeyA = GlobalKey<DummyRestorableStatefulWidgetState>();
final routes = <RouteBase>[
GoRoute(
path: '/a',
- pageBuilder: createPageBuilder(
- restorationId: 'screenA',
- child: const Text('Screen A'),
- ),
+ pageBuilder: createPageBuilder(restorationId: 'screenA', child: const Text('Screen A')),
routes: <RouteBase>[
GoRoute(
path: 'detail',
@@ -6036,12 +5292,7 @@
),
];
- 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));
@@ -6058,28 +5309,18 @@
WidgetTester tester,
) async {
final rootNavigatorKey = GlobalKey<NavigatorState>();
- final statefulWidgetKeyA =
- GlobalKey<DummyRestorableStatefulWidgetState>();
- final statefulWidgetKeyB =
- GlobalKey<DummyRestorableStatefulWidgetState>();
- final statefulWidgetKeyC =
- GlobalKey<DummyRestorableStatefulWidgetState>();
+ final statefulWidgetKeyA = GlobalKey<DummyRestorableStatefulWidgetState>();
+ final statefulWidgetKeyB = GlobalKey<DummyRestorableStatefulWidgetState>();
+ final statefulWidgetKeyC = GlobalKey<DummyRestorableStatefulWidgetState>();
StatefulNavigationShell? routeState;
final routes = <RouteBase>[
StatefulShellRoute.indexedStack(
restorationScopeId: 'shell',
pageBuilder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
routeState = navigationShell;
- return MaterialPage<dynamic>(
- restorationId: 'shellWidget',
- child: navigationShell,
- );
+ return MaterialPage<dynamic>(restorationId: 'shellWidget', child: navigationShell);
},
branches: <StatefulShellBranch>[
StatefulShellBranch(
@@ -6215,178 +5456,168 @@
expect(statefulWidgetKeyC.currentState?.counter, equals(0));
});
- testWidgets(
- 'Restores state of imperative routes in StatefulShellRoute correctly',
- (WidgetTester tester) async {
- final rootNavigatorKey = GlobalKey<NavigatorState>();
- final statefulWidgetKeyA =
- GlobalKey<DummyRestorableStatefulWidgetState>();
- final statefulWidgetKeyB =
- GlobalKey<DummyRestorableStatefulWidgetState>();
- StatefulNavigationShell? routeStateRoot;
- StatefulNavigationShell? routeStateNested;
+ testWidgets('Restores state of imperative routes in StatefulShellRoute correctly', (
+ WidgetTester tester,
+ ) async {
+ final rootNavigatorKey = GlobalKey<NavigatorState>();
+ final statefulWidgetKeyA = GlobalKey<DummyRestorableStatefulWidgetState>();
+ final statefulWidgetKeyB = GlobalKey<DummyRestorableStatefulWidgetState>();
+ StatefulNavigationShell? routeStateRoot;
+ StatefulNavigationShell? routeStateNested;
- final routes = <RouteBase>[
- StatefulShellRoute.indexedStack(
- restorationScopeId: 'shell',
- pageBuilder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeStateRoot = navigationShell;
- return MaterialPage<dynamic>(
- restorationId: 'shellWidget',
- child: navigationShell,
- );
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- restorationScopeId: 'branchA',
- routes: <GoRoute>[
- GoRoute(
- path: '/a',
- pageBuilder: createPageBuilder(
- restorationId: 'screenA',
- child: const Text('Screen A'),
- ),
- routes: <RouteBase>[
- GoRoute(
- path: 'detailA',
- pageBuilder: createPageBuilder(
- restorationId: 'screenADetail',
- child: Column(
- children: <Widget>[
- const Text('Screen A Detail'),
- DummyRestorableStatefulWidget(
- key: statefulWidgetKeyA,
- restorationId: 'counterA',
- ),
- ],
- ),
+ final routes = <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ restorationScopeId: 'shell',
+ pageBuilder:
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
+ routeStateRoot = navigationShell;
+ return MaterialPage<dynamic>(restorationId: 'shellWidget', child: navigationShell);
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ restorationScopeId: 'branchA',
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/a',
+ pageBuilder: createPageBuilder(
+ restorationId: 'screenA',
+ child: const Text('Screen A'),
+ ),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'detailA',
+ pageBuilder: createPageBuilder(
+ restorationId: 'screenADetail',
+ child: Column(
+ children: <Widget>[
+ const Text('Screen A Detail'),
+ DummyRestorableStatefulWidget(
+ key: statefulWidgetKeyA,
+ restorationId: 'counterA',
+ ),
+ ],
),
),
- ],
- ),
- ],
- ),
- StatefulShellBranch(
- restorationScopeId: 'branchB',
- routes: <RouteBase>[
- StatefulShellRoute.indexedStack(
- restorationScopeId: 'branchB-nested-shell',
- pageBuilder:
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
- routeStateNested = navigationShell;
- return MaterialPage<dynamic>(
- restorationId: 'shellWidget-nested',
- child: navigationShell,
- );
- },
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- restorationScopeId: 'branchB-nested',
- routes: <GoRoute>[
- GoRoute(
- path: '/b',
- pageBuilder: createPageBuilder(
- restorationId: 'screenB',
- child: const Text('Screen B'),
- ),
- routes: <RouteBase>[
- GoRoute(
- path: 'detailB',
- pageBuilder: createPageBuilder(
- restorationId: 'screenBDetail',
- child: Column(
- children: <Widget>[
- const Text('Screen B Detail'),
- DummyRestorableStatefulWidget(
- key: statefulWidgetKeyB,
- restorationId: 'counterB',
- ),
- ],
- ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ restorationScopeId: 'branchB',
+ routes: <RouteBase>[
+ StatefulShellRoute.indexedStack(
+ restorationScopeId: 'branchB-nested-shell',
+ pageBuilder:
+ (
+ BuildContext context,
+ GoRouterState state,
+ StatefulNavigationShell navigationShell,
+ ) {
+ routeStateNested = navigationShell;
+ return MaterialPage<dynamic>(
+ restorationId: 'shellWidget-nested',
+ child: navigationShell,
+ );
+ },
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ restorationScopeId: 'branchB-nested',
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/b',
+ pageBuilder: createPageBuilder(
+ restorationId: 'screenB',
+ child: const Text('Screen B'),
+ ),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'detailB',
+ pageBuilder: createPageBuilder(
+ restorationId: 'screenBDetail',
+ child: Column(
+ children: <Widget>[
+ const Text('Screen B Detail'),
+ DummyRestorableStatefulWidget(
+ key: statefulWidgetKeyB,
+ restorationId: 'counterB',
+ ),
+ ],
),
),
- ],
- ),
- ],
- ),
- StatefulShellBranch(
- restorationScopeId: 'branchC-nested',
- routes: <GoRoute>[
- GoRoute(
- path: '/c',
- pageBuilder: createPageBuilder(
- restorationId: 'screenC',
- child: const Text('Screen C'),
),
+ ],
+ ),
+ ],
+ ),
+ StatefulShellBranch(
+ restorationScopeId: 'branchC-nested',
+ routes: <GoRoute>[
+ GoRoute(
+ path: '/c',
+ pageBuilder: createPageBuilder(
+ restorationId: 'screenC',
+ child: const Text('Screen C'),
),
- ],
- ),
- ],
- ),
- ],
- ),
- ],
- ),
- ];
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ];
- 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));
+ 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));
- 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
@@ -6398,39 +5629,31 @@
routes: <RouteBase>[
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(),
),
],
),
throwsA(const TypeMatcher<AssertionError>()),
);
});
- testWidgets('Test override using routeInformationProvider', (
- WidgetTester tester,
- ) async {
- tester.binding.platformDispatcher.defaultRouteNameTestValue =
- '/some-route';
- final String platformRoute =
- WidgetsBinding.instance.platformDispatcher.defaultRouteName;
+ testWidgets('Test override using routeInformationProvider', (WidgetTester tester) async {
+ tester.binding.platformDispatcher.defaultRouteNameTestValue = '/some-route';
+ final String platformRoute = WidgetsBinding.instance.platformDispatcher.defaultRouteName;
const expectedInitialRoute = '/kyc';
expect(platformRoute != expectedInitialRoute, isTrue);
final routes = <RouteBase>[
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(),
),
];
@@ -6440,136 +5663,118 @@
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 router = GoRouter(
- initialLocation: '/foo',
- routes: <RouteBase>[
- GoRoute(
- path: '/foo',
- builder: dummy,
- routes: <GoRoute>[
- 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 routes = <RouteBase>[
+ testWidgets('test the pathParameters in redirect when the Router is recreated', (
+ WidgetTester tester,
+ ) async {
+ final router = GoRouter(
+ initialLocation: '/foo',
+ routes: <RouteBase>[
GoRoute(
- name: 'home',
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
- ),
- GoRoute(
- name: 'books',
- path: '/books',
- 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: <RouteBase>[
+ path: '/foo',
+ builder: dummy,
+ routes: <GoRoute>[
GoRoute(
- name: 'tulips',
- path: '/tulips',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('tulips'),
+ 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));
+ });
- final GoRouter router = await createRouter(routes, tester);
- await tester.pumpAndSettle();
-
- 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.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.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');
- },
- );
-
- testWidgets('should allow route paths without leading /', (
+ testWidgets('should return the current GoRouterState when router.currentState is called', (
WidgetTester tester,
) async {
+ final routes = <RouteBase>[
+ GoRoute(
+ name: 'home',
+ path: '/',
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
+ ),
+ GoRoute(
+ name: 'books',
+ path: '/books',
+ 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: <RouteBase>[
+ GoRoute(
+ name: 'tulips',
+ path: '/tulips',
+ builder: (BuildContext context, GoRouterState state) => const Text('tulips'),
+ ),
+ ],
+ ),
+ ];
+
+ final GoRouter router = await createRouter(routes, tester);
+ await tester.pumpAndSettle();
+
+ 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.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.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');
+ });
+
+ testWidgets('should allow route paths without leading /', (WidgetTester tester) async {
final routes = <GoRoute>[
GoRoute(
path: '/', // root cannot be empty (existing assert)
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'child-route',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('/child-route'),
+ builder: (BuildContext context, GoRouterState state) => const Text('/child-route'),
routes: <RouteBase>[
GoRoute(
path: 'grand-child-route',
@@ -6578,8 +5783,7 @@
),
GoRoute(
path: 'redirected-grand-child-route',
- redirect: (BuildContext context, GoRouterState state) =>
- '/child-route',
+ redirect: (BuildContext context, GoRouterState state) => '/child-route',
),
],
),
@@ -6605,19 +5809,15 @@
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 routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: '/child-route',
- builder: (BuildContext context, GoRouterState state) =>
- const Text('/child-route'),
+ builder: (BuildContext context, GoRouterState state) => const Text('/child-route'),
routes: <RouteBase>[
GoRoute(
path: '/grand-child-route',
@@ -6626,8 +5826,7 @@
),
GoRoute(
path: '/redirected-grand-child-route',
- redirect: (BuildContext context, GoRouterState state) =>
- '/child-route',
+ redirect: (BuildContext context, GoRouterState state) => '/child-route',
),
],
),
@@ -6655,11 +5854,7 @@
}
class TestInheritedNotifier extends InheritedNotifier<ValueNotifier<String>> {
- const TestInheritedNotifier({
- super.key,
- required super.notifier,
- required super.child,
- });
+ const TestInheritedNotifier({super.key, required super.notifier, required super.child});
}
class IsRouteUpdateCall extends Matcher {
diff --git a/packages/go_router/test/imperative_api_test.dart b/packages/go_router/test/imperative_api_test.dart
index b56d0ee..f161693 100644
--- a/packages/go_router/test/imperative_api_test.dart
+++ b/packages/go_router/test/imperative_api_test.dart
@@ -33,11 +33,7 @@
],
),
];
- 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);
@@ -73,11 +69,7 @@
],
),
];
- 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);
@@ -89,9 +81,7 @@
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 home = UniqueKey();
final a = UniqueKey();
@@ -117,11 +107,7 @@
],
),
];
- 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);
@@ -139,9 +125,7 @@
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 b = UniqueKey();
final a = UniqueKey();
@@ -175,11 +159,7 @@
],
),
];
- 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);
@@ -192,9 +172,7 @@
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 inside = UniqueKey();
final outside = UniqueKey();
@@ -218,11 +196,7 @@
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);
@@ -281,11 +255,7 @@
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 5028e88..5376ddc 100644
--- a/packages/go_router/test/information_provider_test.dart
+++ b/packages/go_router/test/information_provider_test.dart
@@ -12,9 +12,7 @@
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 provider = GoRouteInformationProvider(
initialLocation: initialRoute,
initialExtra: null,
@@ -24,18 +22,14 @@
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 provider = GoRouteInformationProvider(
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', (
@@ -51,18 +45,14 @@
);
addTearDown(provider.dispose);
provider.addListener(expectAsync0(() {}));
- provider.didPushRouteInformation(
- RouteInformation(uri: Uri.parse(expectedUriString)),
- );
+ provider.didPushRouteInformation(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 expectedScheme = 'https';
const expectedHost = 'www.example.com';
const expectedPath = '/some/path';
@@ -73,9 +63,7 @@
);
addTearDown(provider.dispose);
provider.addListener(expectAsync0(() {}));
- provider.didPushRouteInformation(
- RouteInformation(uri: Uri.parse(expectedUriString)),
- );
+ provider.didPushRouteInformation(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');
@@ -101,9 +89,7 @@
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 systemChannelsMock = _SystemChannelsNavigationMock();
late final provider = GoRouteInformationProvider(
initialLocation: initialRoute,
@@ -123,19 +109,18 @@
class _SystemChannelsNavigationMock {
_SystemChannelsNavigationMock() {
- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
- .setMockMethodCallHandler(SystemChannels.navigation, (
- MethodCall methodCall,
- ) async {
- if (methodCall.method == 'routeInformationUpdated' &&
- methodCall.arguments is Map<String, dynamic>) {
- final args = methodCall.arguments as Map<String, dynamic>;
- final String? uri =
- args['location'] as String? ?? args['uri'] as String?;
- uriIsNeglected[uri ?? ''] = args['replace'] as bool;
- }
- return null;
- });
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.navigation,
+ (MethodCall methodCall) async {
+ if (methodCall.method == 'routeInformationUpdated' &&
+ methodCall.arguments is Map<String, dynamic>) {
+ final args = methodCall.arguments as Map<String, dynamic>;
+ final String? uri = args['location'] as String? ?? args['uri'] as String?;
+ uriIsNeglected[uri ?? ''] = args['replace'] as bool;
+ }
+ return null;
+ },
+ );
}
Map<String, bool> uriIsNeglected = <String, bool>{};
diff --git a/packages/go_router/test/inherited_test.dart b/packages/go_router/test/inherited_test.dart
index 96e3f9a..bf61306 100644
--- a/packages/go_router/test/inherited_test.dart
+++ b/packages/go_router/test/inherited_test.dart
@@ -13,9 +13,7 @@
group('updateShouldNotify', () {
test('does not update when goRouter does not change', () {
final goRouter = GoRouter(
- routes: <GoRoute>[
- GoRoute(path: '/', builder: (_, __) => const Page1()),
- ],
+ routes: <GoRoute>[GoRoute(path: '/', builder: (_, __) => const Page1())],
);
final bool shouldNotify = setupInheritedGoRouterChange(
oldGoRouter: goRouter,
@@ -26,14 +24,10 @@
test('does not update even when goRouter changes', () {
final oldGoRouter = GoRouter(
- routes: <GoRoute>[
- GoRoute(path: '/', builder: (_, __) => const Page1()),
- ],
+ routes: <GoRoute>[GoRoute(path: '/', builder: (_, __) => const Page1())],
);
final newGoRouter = GoRouter(
- routes: <GoRoute>[
- GoRoute(path: '/', builder: (_, __) => const Page2()),
- ],
+ routes: <GoRoute>[GoRoute(path: '/', builder: (_, __) => const Page2())],
);
final bool shouldNotify = setupInheritedGoRouterChange(
oldGoRouter: oldGoRouter,
@@ -47,10 +41,7 @@
final goRouter = GoRouter(
routes: <GoRoute>[GoRoute(path: '/', builder: (_, __) => const Page1())],
);
- final inheritedGoRouter = InheritedGoRouter(
- goRouter: goRouter,
- child: Container(),
- );
+ final inheritedGoRouter = InheritedGoRouter(goRouter: goRouter, child: Container());
final properties = DiagnosticPropertiesBuilder();
inheritedGoRouter.debugFillProperties(properties);
expect(properties.properties.length, 1);
@@ -58,9 +49,7 @@
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 router = MockGoRouter();
await tester.pumpWidget(
MaterialApp(
@@ -101,18 +90,9 @@
});
}
-bool setupInheritedGoRouterChange({
- required GoRouter oldGoRouter,
- required GoRouter newGoRouter,
-}) {
- final oldInheritedGoRouter = InheritedGoRouter(
- goRouter: oldGoRouter,
- child: Container(),
- );
- final newInheritedGoRouter = InheritedGoRouter(
- goRouter: newGoRouter,
- child: Container(),
- );
+bool setupInheritedGoRouterChange({required GoRouter oldGoRouter, required GoRouter newGoRouter}) {
+ final oldInheritedGoRouter = InheritedGoRouter(goRouter: oldGoRouter, child: Container());
+ final newInheritedGoRouter = InheritedGoRouter(goRouter: newGoRouter, child: Container());
return newInheritedGoRouter.updateShouldNotify(oldInheritedGoRouter);
}
@@ -145,9 +125,7 @@
class MockGoRouter extends GoRouter {
MockGoRouter()
: super.routingConfig(
- routingConfig: const ConstantRoutingConfig(
- RoutingConfig(routes: <RouteBase>[]),
- ),
+ routingConfig: const ConstantRoutingConfig(RoutingConfig(routes: <RouteBase>[])),
);
late String latestPushedName;
diff --git a/packages/go_router/test/logging_test.dart b/packages/go_router/test/logging_test.dart
index 6d8098a..76c4d7f 100644
--- a/packages/go_router/test/logging_test.dart
+++ b/packages/go_router/test/logging_test.dart
@@ -30,23 +30,20 @@
logger.info('message');
});
- testWidgets(
- 'It should not log anything the if debugLogDiagnostics is false',
- (WidgetTester tester) async {
- testDeveloperLog = expectAsync1((LogRecord data) {}, count: 0);
- final StreamSubscription<LogRecord> subscription = Logger.root.onRecord
- .listen(expectAsync1((LogRecord data) {}, count: 0));
- addTearDown(subscription.cancel);
- GoRouter(
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
- ],
- );
- },
- );
+ testWidgets('It should not log anything the if debugLogDiagnostics is false', (
+ WidgetTester tester,
+ ) async {
+ testDeveloperLog = expectAsync1((LogRecord data) {}, count: 0);
+ final StreamSubscription<LogRecord> subscription = Logger.root.onRecord.listen(
+ expectAsync1((LogRecord data) {}, count: 0),
+ );
+ addTearDown(subscription.cancel);
+ GoRouter(
+ routes: <RouteBase>[
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
+ ],
+ );
+ });
testWidgets(
'It should log the known routes and the initial route if debugLogDiagnostics is true',
@@ -61,10 +58,7 @@
GoRouter(
debugLogDiagnostics: true,
routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
],
);
@@ -90,10 +84,7 @@
GoRouter(
debugLogDiagnostics: true,
routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, GoRouterState state) => const Text('home'),
- ),
+ GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')),
],
);
diff --git a/packages/go_router/test/match_test.dart b/packages/go_router/test/match_test.dart
index 1b12d2e..bcf1d6d 100644
--- a/packages/go_router/test/match_test.dart
+++ b/packages/go_router/test/match_test.dart
@@ -117,11 +117,7 @@
path: 'c',
builder: _builder,
routes: <RouteBase>[
- GoRoute(
- parentNavigatorKey: root,
- path: 'd',
- builder: _builder,
- ),
+ GoRoute(parentNavigatorKey: root, path: 'd', builder: _builder),
],
),
],
@@ -142,26 +138,13 @@
rootNavigatorKey: root,
);
expect(matches.length, 4);
- expect(
- matches[0].route,
- isA<GoRoute>().having((GoRoute route) => route.path, 'path', '/'),
- );
+ expect(matches[0].route, isA<GoRoute>().having((GoRoute route) => route.path, 'path', '/'));
expect(
matches[1].route,
- isA<ShellRoute>().having(
- (ShellRoute route) => route.navigatorKey,
- 'navigator key',
- shell1,
- ),
+ isA<ShellRoute>().having((ShellRoute route) => route.navigatorKey, 'navigator key', shell1),
);
- expect(
- matches[2].route,
- isA<GoRoute>().having((GoRoute route) => route.path, 'path', 'b'),
- );
- expect(
- matches[3].route,
- isA<GoRoute>().having((GoRoute route) => route.path, 'path', 'd'),
- );
+ expect(matches[2].route, isA<GoRoute>().having((GoRoute route) => route.path, 'path', 'b'));
+ expect(matches[3].route, isA<GoRoute>().having((GoRoute route) => route.path, 'path', 'd'));
});
group('ImperativeRouteMatch', () {
@@ -196,63 +179,30 @@
final completer2 = Completer<void>();
test('can equal and has', () async {
- var match1 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList1,
- completer: completer1,
- );
- var match2 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList1,
- completer: completer1,
- );
+ var match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1);
+ var match2 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1);
expect(match1 == match2, isTrue);
expect(match1.hashCode == match2.hashCode, isTrue);
- match1 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList1,
- completer: completer1,
- );
- match2 = ImperativeRouteMatch(
- pageKey: key2,
- matches: matchList1,
- completer: completer1,
- );
+ match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1);
+ match2 = ImperativeRouteMatch(pageKey: key2, matches: matchList1, completer: completer1);
expect(match1 == match2, isFalse);
expect(match1.hashCode == match2.hashCode, isFalse);
- match1 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList1,
- completer: completer1,
- );
- match2 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList2,
- completer: completer1,
- );
+ match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1);
+ match2 = ImperativeRouteMatch(pageKey: key1, matches: matchList2, completer: completer1);
expect(match1 == match2, isFalse);
expect(match1.hashCode == match2.hashCode, isFalse);
- match1 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList1,
- completer: completer1,
- );
- match2 = ImperativeRouteMatch(
- pageKey: key1,
- matches: matchList1,
- completer: completer2,
- );
+ match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1);
+ match2 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer2);
expect(match1 == match2, isFalse);
expect(match1.hashCode == match2.hashCode, isFalse);
});
});
}
-Widget _builder(BuildContext context, GoRouterState state) =>
- const Placeholder();
+Widget _builder(BuildContext context, GoRouterState state) => const Placeholder();
Widget _shellBuilder(BuildContext context, GoRouterState state, Widget child) =>
const Placeholder();
diff --git a/packages/go_router/test/matching_test.dart b/packages/go_router/test/matching_test.dart
index 23d2179..379fb43 100644
--- a/packages/go_router/test/matching_test.dart
+++ b/packages/go_router/test/matching_test.dart
@@ -12,22 +12,15 @@
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 routes = <GoRoute>[
GoRoute(
path: '/page-0',
- builder: (BuildContext context, GoRouterState state) =>
- const Placeholder(),
+ 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'));
@@ -36,8 +29,7 @@
test('RouteMatchList compares', () async {
final route = GoRoute(
path: '/page-0',
- builder: (BuildContext context, GoRouterState state) =>
- const Placeholder(),
+ builder: (BuildContext context, GoRouterState state) => const Placeholder(),
);
final params1 = <String, String>{};
final List<RouteMatchBase> match1 = RouteMatchBase.match(
@@ -55,17 +47,9 @@
pathParameters: params2,
);
- final matches1 = RouteMatchList(
- matches: match1,
- uri: Uri.parse(''),
- pathParameters: params1,
- );
+ final matches1 = RouteMatchList(matches: match1, uri: Uri.parse(''), pathParameters: params1);
- final matches2 = RouteMatchList(
- matches: match2,
- uri: Uri.parse(''),
- pathParameters: params2,
- );
+ final matches2 = RouteMatchList(matches: match2, uri: Uri.parse(''), pathParameters: params2);
final matches3 = RouteMatchList(
matches: match2,
@@ -82,13 +66,11 @@
routes: <GoRoute>[
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Placeholder(),
+ builder: (BuildContext context, GoRouterState state) => const Placeholder(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Placeholder(),
+ builder: (BuildContext context, GoRouterState state) => const Placeholder(),
),
],
redirectLimit: 0,
diff --git a/packages/go_router/test/material_test.dart b/packages/go_router/test/material_test.dart
index 9a56c9e..c862e90 100644
--- a/packages/go_router/test/material_test.dart
+++ b/packages/go_router/test/material_test.dart
@@ -11,22 +11,16 @@
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 key = GlobalKey<_DummyStatefulWidgetState>();
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 key = GlobalKey<_DummyStatefulWidgetState>();
- await tester.pumpWidget(
- CupertinoApp(home: DummyStatefulWidget(key: key)),
- );
+ await tester.pumpWidget(CupertinoApp(home: DummyStatefulWidget(key: key)));
final bool isMaterial = isMaterialApp(key.currentContext! as Element);
expect(isMaterial, false);
});
@@ -55,9 +49,7 @@
group('GoRouterMaterialErrorScreen', () {
testWidgets(
'shows "page not found" by default',
- testPageNotFound(
- widget: const MaterialApp(home: MaterialErrorScreen(null)),
- ),
+ testPageNotFound(widget: const MaterialApp(home: MaterialErrorScreen(null))),
);
final exception = Exception('Something went wrong!');
diff --git a/packages/go_router/test/name_case_test.dart b/packages/go_router/test/name_case_test.dart
index 672cdef..84010a7 100644
--- a/packages/go_router/test/name_case_test.dart
+++ b/packages/go_router/test/name_case_test.dart
@@ -12,19 +12,13 @@
final router = GoRouter(
routes: <GoRoute>[
GoRoute(path: '/', name: 'Name', builder: (_, __) => const ScreenA()),
- GoRoute(
- path: '/path',
- name: 'name',
- builder: (_, __) => const ScreenB(),
- ),
+ 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'),
- );
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Testcase'));
// go to ScreenB
router.goNamed('name');
diff --git a/packages/go_router/test/on_enter_test.dart b/packages/go_router/test/on_enter_test.dart
index 2fb09cc..2760d61 100644
--- a/packages/go_router/test/on_enter_test.dart
+++ b/packages/go_router/test/on_enter_test.dart
@@ -18,9 +18,7 @@
return Future<void>.delayed(Duration.zero).then((_) => router.dispose());
});
- testWidgets('Should set current/next state correctly', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should set current/next state correctly', (WidgetTester tester) async {
GoRouterState? capturedCurrentState;
GoRouterState? capturedNextState;
var onEnterCallCount = 0;
@@ -58,9 +56,7 @@
expect(capturedCurrentState?.uri.path, capturedNextState?.uri.path);
});
- testWidgets('Should block navigation when onEnter returns false', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should block navigation when onEnter returns false', (WidgetTester tester) async {
final navigationAttempts = <String>[];
var currentPath = '/';
@@ -75,9 +71,7 @@
) async {
navigationAttempts.add(next.uri.path);
currentPath = current.uri.path;
- return next.uri.path.contains('blocked')
- ? const Block.stop()
- : const Allow();
+ return next.uri.path.contains('blocked') ? const Block.stop() : const Allow();
},
routes: <RouteBase>[
GoRoute(
@@ -96,44 +90,36 @@
final BuildContext context = tester.element(find.byType(Router<Object>));
final GoRouteInformationParser parser = router.routeInformationParser;
- final RouteMatchList beforeBlockedNav =
- router.routerDelegate.currentConfiguration;
+ final RouteMatchList beforeBlockedNav = router.routerDelegate.currentConfiguration;
// Try blocked route
- final RouteMatchList blockedMatch = await parser
- .parseRouteInformationWithDependencies(
- RouteInformation(
- uri: Uri.parse('/blocked'),
- state: RouteInformationState<void>(type: NavigatingType.go),
- ),
- context,
- );
+ final RouteMatchList blockedMatch = await parser.parseRouteInformationWithDependencies(
+ RouteInformation(
+ uri: Uri.parse('/blocked'),
+ state: RouteInformationState<void>(type: NavigatingType.go),
+ ),
+ context,
+ );
await tester.pumpAndSettle();
- expect(
- blockedMatch.uri.toString(),
- equals(beforeBlockedNav.uri.toString()),
- );
+ expect(blockedMatch.uri.toString(), equals(beforeBlockedNav.uri.toString()));
expect(currentPath, equals('/'));
expect(navigationAttempts, contains('/blocked'));
// Try allowed route
- final RouteMatchList allowedMatch = await parser
- .parseRouteInformationWithDependencies(
- RouteInformation(
- uri: Uri.parse('/allowed'),
- state: RouteInformationState<void>(type: NavigatingType.go),
- ),
- context,
- );
+ final RouteMatchList allowedMatch = await parser.parseRouteInformationWithDependencies(
+ RouteInformation(
+ uri: Uri.parse('/allowed'),
+ state: RouteInformationState<void>(type: NavigatingType.go),
+ ),
+ context,
+ );
expect(allowedMatch.uri.path, equals('/allowed'));
expect(navigationAttempts, contains('/allowed'));
await tester.pumpAndSettle();
});
- testWidgets('Should allow navigation when onEnter returns true', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should allow navigation when onEnter returns true', (WidgetTester tester) async {
var onEnterCallCount = 0;
router = GoRouter(
@@ -146,25 +132,20 @@
GoRouter goRouter,
) async {
onEnterCallCount++;
- return next.uri.path.contains('block')
- ? const Block.stop()
- : const Allow();
+ return next.uri.path.contains('block') ? const Block.stop() : const Allow();
},
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
routes: <GoRoute>[
GoRoute(
path: 'allowed',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Allowed'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Allowed'))),
),
GoRoute(
path: 'block',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Blocked'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Blocked'))),
),
],
),
@@ -189,79 +170,67 @@
expect(onEnterCallCount, greaterThan(0));
});
- testWidgets(
- 'Should trigger onException when the redirection limit is exceeded',
- (WidgetTester tester) async {
- final completer = Completer<void>();
- Object? capturedError;
-
- router = GoRouter(
- initialLocation: '/start',
- redirectLimit: 2,
- onException:
- (BuildContext context, GoRouterState state, GoRouter goRouter) {
- capturedError = state.error;
- goRouter.go('/fallback');
- completer.complete();
- },
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- ) async {
- if (next.uri.path == '/recursive') {
- return Block.then(() => goRouter.push('/recursive'));
- }
- return const Allow();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/start',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Start'))),
- ),
- GoRoute(
- path: '/recursive',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Recursive'))),
- ),
- GoRoute(
- path: '/fallback',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Fallback'))),
- ),
- ],
- );
-
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
-
- router.go('/recursive');
- await completer.future;
- await tester.pumpAndSettle();
-
- expect(capturedError, isNotNull);
- expect(
- capturedError.toString(),
- contains('Too many onEnter calls detected'),
- );
- expect(find.text('Fallback'), findsOneWidget);
- },
- );
-
- testWidgets('Should handle `go` usage in onEnter', (
+ testWidgets('Should trigger onException when the redirection limit is exceeded', (
WidgetTester tester,
) async {
+ final completer = Completer<void>();
+ Object? capturedError;
+
+ router = GoRouter(
+ initialLocation: '/start',
+ redirectLimit: 2,
+ onException: (BuildContext context, GoRouterState state, GoRouter goRouter) {
+ capturedError = state.error;
+ goRouter.go('/fallback');
+ completer.complete();
+ },
+ onEnter:
+ (
+ BuildContext context,
+ GoRouterState current,
+ GoRouterState next,
+ GoRouter goRouter,
+ ) async {
+ if (next.uri.path == '/recursive') {
+ return Block.then(() => goRouter.push('/recursive'));
+ }
+ return const Allow();
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/start',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Start'))),
+ ),
+ GoRoute(
+ path: '/recursive',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Recursive'))),
+ ),
+ GoRoute(
+ path: '/fallback',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Fallback'))),
+ ),
+ ],
+ );
+
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
+
+ router.go('/recursive');
+ await completer.future;
+ await tester.pumpAndSettle();
+
+ expect(capturedError, isNotNull);
+ expect(capturedError.toString(), contains('Too many onEnter calls detected'));
+ expect(find.text('Fallback'), findsOneWidget);
+ });
+
+ testWidgets('Should handle `go` usage in onEnter', (WidgetTester tester) async {
var isAuthenticatedResult = false;
- Future<bool> isAuthenticated() =>
- Future<bool>.value(isAuthenticatedResult);
+ Future<bool> isAuthenticated() => Future<bool>.value(isAuthenticatedResult);
final paramsSink = StreamController<({String current, String next})>();
- final Stream<({String current, String next})> paramsStream = paramsSink
- .stream
+ final Stream<({String current, String next})> paramsStream = paramsSink.stream
.asBroadcastStream();
router = GoRouter(
@@ -273,13 +242,8 @@
GoRouterState next,
GoRouter goRouter,
) async {
- final bool isProtected = next.uri.toString().contains(
- 'protected',
- );
- paramsSink.add((
- current: current.uri.toString(),
- next: next.uri.toString(),
- ));
+ final bool isProtected = next.uri.toString().contains('protected');
+ paramsSink.add((current: current.uri.toString(), next: next.uri.toString()));
if (!isProtected) {
return const Allow();
@@ -292,18 +256,15 @@
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/protected',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Protected'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Protected'))),
),
GoRoute(
path: '/sign-in',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Sign-in'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Sign-in'))),
),
],
);
@@ -333,9 +294,7 @@
await paramsSink.close();
});
- testWidgets('Should handle `goNamed` usage in onEnter', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should handle `goNamed` usage in onEnter', (WidgetTester tester) async {
final navigationAttempts = <String>[];
router = GoRouter(
@@ -353,9 +312,7 @@
return Block.then(
() => goRouter.goNamed(
'login-page',
- queryParameters: <String, String>{
- 'from': next.uri.toString(),
- },
+ queryParameters: <String, String>{'from': next.uri.toString()},
),
);
}
@@ -364,14 +321,11 @@
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/requires-auth',
- builder: (_, __) => const Scaffold(
- body: Center(child: Text('Authenticated Content')),
- ),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Authenticated Content'))),
),
GoRoute(
path: '/login',
@@ -381,9 +335,7 @@
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- Text(
- 'Login Page - From: ${state.uri.queryParameters['from'] ?? 'unknown'}',
- ),
+ Text('Login Page - From: ${state.uri.queryParameters['from'] ?? 'unknown'}'),
ElevatedButton(
onPressed: () => router.go('/home'),
child: const Text('Go Home'),
@@ -407,17 +359,13 @@
expect(find.text('Login Page - From: /requires-auth'), findsOneWidget);
});
- testWidgets('Should handle `push` usage in onEnter', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should handle `push` usage in onEnter', (WidgetTester tester) async {
const isAuthenticatedResult = false;
- Future<bool> isAuthenticated() =>
- Future<bool>.value(isAuthenticatedResult);
+ Future<bool> isAuthenticated() => Future<bool>.value(isAuthenticatedResult);
final paramsSink = StreamController<({String current, String next})>();
- final Stream<({String current, String next})> paramsStream = paramsSink
- .stream
+ final Stream<({String current, String next})> paramsStream = paramsSink.stream
.asBroadcastStream();
router = GoRouter(
@@ -429,13 +377,8 @@
GoRouterState next,
GoRouter goRouter,
) async {
- final bool isProtected = next.uri.toString().contains(
- 'protected',
- );
- paramsSink.add((
- current: current.uri.toString(),
- next: next.uri.toString(),
- ));
+ final bool isProtected = next.uri.toString().contains('protected');
+ paramsSink.add((current: current.uri.toString(), next: next.uri.toString()));
if (!isProtected) {
return const Allow();
}
@@ -453,13 +396,11 @@
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/protected',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Protected'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Protected'))),
),
GoRoute(
path: '/sign-in',
@@ -495,9 +436,7 @@
await paramsSink.close();
});
- testWidgets('Should handle `replace` usage in onEnter', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should handle `replace` usage in onEnter', (WidgetTester tester) async {
final navigationHistory = <String>[];
router = GoRouter(
@@ -521,18 +460,15 @@
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/old-page',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Old Page'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Old Page'))),
),
GoRoute(
path: '/new-version',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('New Version'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('New Version'))),
),
],
);
@@ -555,9 +491,7 @@
expect(find.text('Home'), findsOneWidget);
});
- testWidgets('Should handle `pushReplacement` usage in onEnter', (
- WidgetTester tester,
- ) async {
+ testWidgets('Should handle `pushReplacement` usage in onEnter', (WidgetTester tester) async {
final navigationLog = <String>[];
router = GoRouter(
@@ -581,13 +515,11 @@
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/outdated',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Outdated'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Outdated'))),
),
GoRoute(
path: '/updated',
@@ -598,8 +530,7 @@
children: <Widget>[
const Text('Updated'),
ElevatedButton(
- onPressed: () =>
- router.go('/home'), // Use go instead of pop
+ onPressed: () => router.go('/home'), // Use go instead of pop
child: const Text('Go Home'),
),
],
@@ -630,182 +561,165 @@
expect(find.text('Home'), findsOneWidget);
});
- testWidgets(
- 'onEnter should handle protected route redirection with query parameters',
- (WidgetTester tester) async {
- // Test setup
- var isAuthenticatedResult = false;
- Future<bool> isAuthenticated() =>
- Future<bool>.value(isAuthenticatedResult);
+ testWidgets('onEnter should handle protected route redirection with query parameters', (
+ WidgetTester tester,
+ ) async {
+ // Test setup
+ var isAuthenticatedResult = false;
+ Future<bool> isAuthenticated() => Future<bool>.value(isAuthenticatedResult);
- // Stream to capture onEnter calls
- final paramsSink = StreamController<({String current, String next})>();
- // Use broadcast stream for potentially multiple listeners/expects if needed,
- // although expectLater handles one listener well.
- final Stream<({String current, String next})> paramsStream = paramsSink
- .stream
- .asBroadcastStream();
+ // Stream to capture onEnter calls
+ final paramsSink = StreamController<({String current, String next})>();
+ // Use broadcast stream for potentially multiple listeners/expects if needed,
+ // although expectLater handles one listener well.
+ final Stream<({String current, String next})> paramsStream = paramsSink.stream
+ .asBroadcastStream();
- // Helper to navigate after sign-in button press
- void goToRedirect(GoRouter router, GoRouterState state) {
- final String? redirect = state.uri.queryParameters['redirectTo'];
- // Use null check and Uri.tryParse for safety
- if (redirect != null && Uri.tryParse(redirect) != null) {
- // Decode potentially encoded URI component
- router.go(Uri.decodeComponent(redirect));
- } else {
- // Fallback if redirectTo is missing or invalid
- router.go('/home');
- }
+ // Helper to navigate after sign-in button press
+ void goToRedirect(GoRouter router, GoRouterState state) {
+ final String? redirect = state.uri.queryParameters['redirectTo'];
+ // Use null check and Uri.tryParse for safety
+ if (redirect != null && Uri.tryParse(redirect) != null) {
+ // Decode potentially encoded URI component
+ router.go(Uri.decodeComponent(redirect));
+ } else {
+ // Fallback if redirectTo is missing or invalid
+ router.go('/home');
}
+ }
- router = GoRouter(
- initialLocation: '/home',
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- // Renamed parameter to avoid shadowing router variable
- ) async {
- // Log the navigation attempt state URIs
- paramsSink.add((
- current: current.uri.toString(),
- next: next.uri.toString(),
- ));
+ router = GoRouter(
+ initialLocation: '/home',
+ onEnter:
+ (
+ BuildContext context,
+ GoRouterState current,
+ GoRouterState next,
+ GoRouter goRouter,
+ // Renamed parameter to avoid shadowing router variable
+ ) async {
+ // Log the navigation attempt state URIs
+ paramsSink.add((current: current.uri.toString(), next: next.uri.toString()));
- final isNavigatingToProtected = next.uri.path == '/protected';
+ final isNavigatingToProtected = next.uri.path == '/protected';
- // Allow navigation if not going to the protected route
- if (!isNavigatingToProtected) {
- return const Allow();
- }
+ // Allow navigation if not going to the protected route
+ if (!isNavigatingToProtected) {
+ return const Allow();
+ }
- // Allow navigation if authenticated
- if (await isAuthenticated()) {
- return const Allow();
- }
+ // Allow navigation if authenticated
+ if (await isAuthenticated()) {
+ return const Allow();
+ }
- // If unauthenticated and going to protected route:
- // 1. Redirect to sign-in using pushNamed, passing the intended destination
- await goRouter.pushNamed<void>(
- 'sign-in', // Return type likely void or not needed
- queryParameters: <String, String>{
- 'redirectTo': next.uri.toString(), // Pass the full next URI
- },
- );
- // 2. Block the original navigation to '/protected'
- return const Block.stop();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/home',
- name: 'home', // Good practice to name routes
- builder: (_, __) => const Scaffold(
- body: Center(child: Text('Home Screen')),
- ), // Unique text
- ),
- GoRoute(
- path: '/protected',
- name: 'protected', // Good practice to name routes
- builder: (_, __) => const Scaffold(
- body: Center(child: Text('Protected Screen')),
- ), // Unique text
- ),
- GoRoute(
- path: '/sign-in',
- name: 'sign-in',
- builder: (_, GoRouterState state) => Scaffold(
- appBar: AppBar(
- title: const Text('Sign In Screen Title'), // Unique text
- ),
- body: Center(
- child: ElevatedButton(
- child: const Text('Sign In Button'), // Unique text
- onPressed: () => goToRedirect(router, state),
- ),
+ // If unauthenticated and going to protected route:
+ // 1. Redirect to sign-in using pushNamed, passing the intended destination
+ await goRouter.pushNamed<void>(
+ 'sign-in', // Return type likely void or not needed
+ queryParameters: <String, String>{
+ 'redirectTo': next.uri.toString(), // Pass the full next URI
+ },
+ );
+ // 2. Block the original navigation to '/protected'
+ return const Block.stop();
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/home',
+ name: 'home', // Good practice to name routes
+ builder: (_, __) =>
+ const Scaffold(body: Center(child: Text('Home Screen'))), // Unique text
+ ),
+ GoRoute(
+ path: '/protected',
+ name: 'protected', // Good practice to name routes
+ builder: (_, __) =>
+ const Scaffold(body: Center(child: Text('Protected Screen'))), // Unique text
+ ),
+ GoRoute(
+ path: '/sign-in',
+ name: 'sign-in',
+ builder: (_, GoRouterState state) => Scaffold(
+ appBar: AppBar(
+ title: const Text('Sign In Screen Title'), // Unique text
+ ),
+ body: Center(
+ child: ElevatedButton(
+ child: const Text('Sign In Button'), // Unique text
+ onPressed: () => goToRedirect(router, state),
),
),
),
- ],
- );
-
- // Expect the stream of onEnter calls to emit events in this specific order
- // We use unawaited because expectLater returns a Future that completes
- // when the expectation is met or fails, but we want the test execution
- // (pumping widgets, triggering actions) to proceed concurrently.
- unawaited(
- expectLater(
- paramsStream,
- emitsInOrder(<dynamic>[
- // 1. Initial Load to '/home'
- equals((current: '/home', next: '/home')),
- // 2. Attempt go('/protected') -> onEnter blocks
- equals((current: '/home', next: '/protected')),
- // 3. onEnter runs for the push('/sign-in?redirectTo=...') triggered internally
- equals((
- current: '/home',
- next: '/sign-in?redirectTo=%2Fprotected',
- )),
- // 4. Tap button -> go('/protected') -> onEnter allows access
- equals((
- current:
- // State when button is tapped
- '/sign-in?redirectTo=%2Fprotected',
- // Target of the 'go' call
- next: '/protected',
- )),
- ]),
),
- );
+ ],
+ );
- // Initial widget pump
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- // Let initial navigation and builds complete
- await tester.pumpAndSettle();
- // Verify initial screen
- expect(find.text('Home Screen'), findsOneWidget);
+ // Expect the stream of onEnter calls to emit events in this specific order
+ // We use unawaited because expectLater returns a Future that completes
+ // when the expectation is met or fails, but we want the test execution
+ // (pumping widgets, triggering actions) to proceed concurrently.
+ unawaited(
+ expectLater(
+ paramsStream,
+ emitsInOrder(<dynamic>[
+ // 1. Initial Load to '/home'
+ equals((current: '/home', next: '/home')),
+ // 2. Attempt go('/protected') -> onEnter blocks
+ equals((current: '/home', next: '/protected')),
+ // 3. onEnter runs for the push('/sign-in?redirectTo=...') triggered internally
+ equals((current: '/home', next: '/sign-in?redirectTo=%2Fprotected')),
+ // 4. Tap button -> go('/protected') -> onEnter allows access
+ equals((
+ current:
+ // State when button is tapped
+ '/sign-in?redirectTo=%2Fprotected',
+ // Target of the 'go' call
+ next: '/protected',
+ )),
+ ]),
+ ),
+ );
- // Trigger navigation to protected route (user is not authenticated)
- router.go('/protected');
- // Allow navigation/redirection to complete
- await tester.pumpAndSettle();
+ // Initial widget pump
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ // Let initial navigation and builds complete
+ await tester.pumpAndSettle();
+ // Verify initial screen
+ expect(find.text('Home Screen'), findsOneWidget);
- // Verify state after redirection to sign-in
- expect(
- router.state.uri.toString(),
- equals('/sign-in?redirectTo=%2Fprotected'),
- );
- // Verify app bar title
- expect(find.text('Sign In Screen Title'), findsOneWidget);
- // Verify button exists
- expect(
- find.widgetWithText(ElevatedButton, 'Sign In Button'),
- findsOneWidget,
- );
- // BackButton appears because sign-in was pushed onto the stack
- expect(find.byType(BackButton), findsOneWidget);
+ // Trigger navigation to protected route (user is not authenticated)
+ router.go('/protected');
+ // Allow navigation/redirection to complete
+ await tester.pumpAndSettle();
- // Simulate successful authentication
- isAuthenticatedResult = true;
+ // Verify state after redirection to sign-in
+ expect(router.state.uri.toString(), equals('/sign-in?redirectTo=%2Fprotected'));
+ // Verify app bar title
+ expect(find.text('Sign In Screen Title'), findsOneWidget);
+ // Verify button exists
+ expect(find.widgetWithText(ElevatedButton, 'Sign In Button'), findsOneWidget);
+ // BackButton appears because sign-in was pushed onto the stack
+ expect(find.byType(BackButton), findsOneWidget);
- // Trigger navigation back to protected route by tapping the sign-in button
- await tester.tap(find.widgetWithText(ElevatedButton, 'Sign In Button'));
- // Allow navigation to protected route to complete
- await tester.pumpAndSettle();
+ // Simulate successful authentication
+ isAuthenticatedResult = true;
- // Verify final state
- expect(router.state.uri.toString(), equals('/protected'));
- // Verify final screen
- expect(find.text('Protected Screen'), findsOneWidget);
- // Verify sign-in screen is gone
- expect(find.text('Sign In Screen Title'), findsNothing);
+ // Trigger navigation back to protected route by tapping the sign-in button
+ await tester.tap(find.widgetWithText(ElevatedButton, 'Sign In Button'));
+ // Allow navigation to protected route to complete
+ await tester.pumpAndSettle();
- // Close the stream controller
- await paramsSink.close();
- },
- );
+ // Verify final state
+ expect(router.state.uri.toString(), equals('/protected'));
+ // Verify final screen
+ expect(find.text('Protected Screen'), findsOneWidget);
+ // Verify sign-in screen is gone
+ expect(find.text('Sign In Screen Title'), findsNothing);
+
+ // Close the stream controller
+ await paramsSink.close();
+ });
testWidgets('Should handle sequential navigation steps in onEnter', (
WidgetTester tester,
@@ -843,13 +757,11 @@
routes: <RouteBase>[
GoRoute(
path: '/start',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Start'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Start'))),
),
GoRoute(
path: '/multi-step',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Multi Step'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Multi Step'))),
),
GoRoute(
path: '/step-one',
@@ -908,13 +820,12 @@
// to avoid triggering the exception when navigating to the fallback route.
router = GoRouter(
initialLocation: '/error',
- onException:
- (BuildContext context, GoRouterState state, GoRouter goRouter) {
- capturedError = state.error;
- // Navigate to a safe fallback route.
- goRouter.go('/fallback');
- completer.complete();
- },
+ onException: (BuildContext context, GoRouterState state, GoRouter goRouter) {
+ capturedError = state.error;
+ // Navigate to a safe fallback route.
+ goRouter.go('/fallback');
+ completer.complete();
+ },
onEnter:
(
BuildContext context,
@@ -932,13 +843,11 @@
routes: <RouteBase>[
GoRoute(
path: '/error',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Error Page'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Error Page'))),
),
GoRoute(
path: '/fallback',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Fallback Page'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Fallback Page'))),
),
],
);
@@ -959,9 +868,7 @@
expect(find.text('Fallback Page'), findsOneWidget);
});
- testWidgets('onEnter has priority over deprecated redirect', (
- WidgetTester tester,
- ) async {
+ testWidgets('onEnter has priority over deprecated redirect', (WidgetTester tester) async {
var redirectCallCount = 0;
var onEnterCallCount = 0;
var lastOnEnterBlocked = false;
@@ -1032,10 +939,7 @@
routes: <GoRoute>[
GoRoute(path: '/page1', builder: (_, __) => const Text('Page 1')),
GoRoute(path: '/page2', builder: (_, __) => const Text('Page 2')),
- GoRoute(
- path: '/protected',
- builder: (_, __) => const Text('Protected'),
- ),
+ GoRoute(path: '/protected', builder: (_, __) => const Text('Protected')),
],
onEnter: (_, GoRouterState current, GoRouterState next, ___) async {
capturedCurrentPath = current.uri.path;
@@ -1070,9 +974,7 @@
expect(capturedNextPath, equals('/protected'));
});
- testWidgets('pop does not call onEnter but restore does', (
- WidgetTester tester,
- ) async {
+ testWidgets('pop does not call onEnter but restore does', (WidgetTester tester) async {
var onEnterCount = 0;
router = GoRouter(
@@ -1114,9 +1016,7 @@
// Explicit restore would call onEnter (tested separately in integration)
});
- testWidgets('restore navigation calls onEnter for re-validation', (
- WidgetTester tester,
- ) async {
+ testWidgets('restore navigation calls onEnter for re-validation', (WidgetTester tester) async {
var onEnterCount = 0;
var allowNavigation = true;
@@ -1157,17 +1057,16 @@
final GoRouteInformationParser parser = router.routeInformationParser;
// Create a restore navigation to protected route
- final RouteMatchList restoredMatch = await parser
- .parseRouteInformationWithDependencies(
- RouteInformation(
- uri: Uri.parse('/protected'),
- state: RouteInformationState<void>(
- type: NavigatingType.restore,
- baseRouteMatchList: router.routerDelegate.currentConfiguration,
- ),
- ),
- context,
- );
+ final RouteMatchList restoredMatch = await parser.parseRouteInformationWithDependencies(
+ RouteInformation(
+ uri: Uri.parse('/protected'),
+ state: RouteInformationState<void>(
+ type: NavigatingType.restore,
+ baseRouteMatchList: router.routerDelegate.currentConfiguration,
+ ),
+ ),
+ context,
+ );
// onEnter should be called again for restore
expect(onEnterCount, 3);
@@ -1175,17 +1074,16 @@
// Now simulate session expired - block on restore
allowNavigation = false;
- final RouteMatchList blockedRestore = await parser
- .parseRouteInformationWithDependencies(
- RouteInformation(
- uri: Uri.parse('/protected'),
- state: RouteInformationState<void>(
- type: NavigatingType.restore,
- baseRouteMatchList: router.routerDelegate.currentConfiguration,
- ),
- ),
- context,
- );
+ final RouteMatchList blockedRestore = await parser.parseRouteInformationWithDependencies(
+ RouteInformation(
+ uri: Uri.parse('/protected'),
+ state: RouteInformationState<void>(
+ type: NavigatingType.restore,
+ baseRouteMatchList: router.routerDelegate.currentConfiguration,
+ ),
+ ),
+ context,
+ );
// onEnter called again but blocks this time
expect(onEnterCount, 4);
@@ -1193,49 +1091,45 @@
expect(blockedRestore.uri.path, equals('/protected'));
});
- testWidgets(
- 'goNamed supports fragment (hash) and preserves it in state.uri',
- (WidgetTester tester) async {
- router = GoRouter(
- initialLocation: '/',
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Root'))),
- ),
- GoRoute(
- path: '/article/:id',
- name: 'article',
- builder: (_, GoRouterState state) {
- return Scaffold(
- body: Center(
- child: Text(
- 'article=${state.pathParameters['id']};frag=${state.uri.fragment}',
- ),
- ),
- );
- },
- ),
- ],
- );
+ testWidgets('goNamed supports fragment (hash) and preserves it in state.uri', (
+ WidgetTester tester,
+ ) async {
+ router = GoRouter(
+ initialLocation: '/',
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Root'))),
+ ),
+ GoRoute(
+ path: '/article/:id',
+ name: 'article',
+ builder: (_, GoRouterState state) {
+ return Scaffold(
+ body: Center(
+ child: Text('article=${state.pathParameters['id']};frag=${state.uri.fragment}'),
+ ),
+ );
+ },
+ ),
+ ],
+ );
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
- // Navigate with a fragment
- router.goNamed(
- 'article',
- pathParameters: <String, String>{'id': '42'},
- fragment: 'section-2',
- );
- await tester.pumpAndSettle();
+ // Navigate with a fragment
+ router.goNamed(
+ 'article',
+ pathParameters: <String, String>{'id': '42'},
+ fragment: 'section-2',
+ );
+ await tester.pumpAndSettle();
- expect(router.state.uri.path, '/article/42');
- expect(router.state.uri.fragment, 'section-2');
- expect(find.text('article=42;frag=section-2'), findsOneWidget);
- },
- );
+ expect(router.state.uri.path, '/article/42');
+ expect(router.state.uri.fragment, 'section-2');
+ expect(find.text('article=42;frag=section-2'), findsOneWidget);
+ });
testWidgets('relative "./" navigation resolves against current location', (
WidgetTester tester,
@@ -1245,13 +1139,11 @@
routes: <RouteBase>[
GoRoute(
path: '/parent',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Parent'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Parent'))),
routes: <RouteBase>[
GoRoute(
path: 'child',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Child'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Child'))),
),
],
),
@@ -1291,8 +1183,7 @@
routes: <RouteBase>[
GoRoute(
path: '/',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Root'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Root'))),
),
GoRoute(
path: '/old',
@@ -1302,8 +1193,7 @@
),
GoRoute(
path: '/new',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('New'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('New'))),
),
],
);
@@ -1323,61 +1213,55 @@
expect(find.text('New'), findsOneWidget);
});
- testWidgets(
- 'Allow(then) error is reported but does not revert navigation',
- (WidgetTester tester) async {
- // Capture FlutterError.reportError calls
- FlutterErrorDetails? reported;
- final void Function(FlutterErrorDetails)? oldHandler =
- FlutterError.onError;
- FlutterError.onError = (FlutterErrorDetails details) {
- reported = details;
- };
- addTearDown(() => FlutterError.onError = oldHandler);
-
- router = GoRouter(
- initialLocation: '/home',
- onEnter: (_, __, GoRouterState next, ___) async {
- if (next.uri.path == '/boom') {
- // Allow, but run a failing "then" callback
- return Allow(then: () => throw StateError('then blew up'));
- }
- return const Allow();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
- ),
- GoRoute(
- path: '/boom',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Boom'))),
- ),
- ],
- );
-
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
- expect(find.text('Home'), findsOneWidget);
-
- router.go('/boom');
- await tester.pumpAndSettle(); // commits nav + runs deferred microtask
-
- // Navigation should be committed
- expect(router.state.uri.path, equals('/boom'));
- expect(find.text('Boom'), findsOneWidget);
-
- // Error from deferred callback should be reported (but not crash)
- expect(reported, isNotNull);
- expect(reported!.exception.toString(), contains('then blew up'));
- },
- );
-
- testWidgets('Hard-stop vs chaining resets onEnter history', (
+ testWidgets('Allow(then) error is reported but does not revert navigation', (
WidgetTester tester,
) async {
+ // Capture FlutterError.reportError calls
+ FlutterErrorDetails? reported;
+ final void Function(FlutterErrorDetails)? oldHandler = FlutterError.onError;
+ FlutterError.onError = (FlutterErrorDetails details) {
+ reported = details;
+ };
+ addTearDown(() => FlutterError.onError = oldHandler);
+
+ router = GoRouter(
+ initialLocation: '/home',
+ onEnter: (_, __, GoRouterState next, ___) async {
+ if (next.uri.path == '/boom') {
+ // Allow, but run a failing "then" callback
+ return Allow(then: () => throw StateError('then blew up'));
+ }
+ return const Allow();
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/home',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
+ ),
+ GoRoute(
+ path: '/boom',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Boom'))),
+ ),
+ ],
+ );
+
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
+ expect(find.text('Home'), findsOneWidget);
+
+ router.go('/boom');
+ await tester.pumpAndSettle(); // commits nav + runs deferred microtask
+
+ // Navigation should be committed
+ expect(router.state.uri.path, equals('/boom'));
+ expect(find.text('Boom'), findsOneWidget);
+
+ // Error from deferred callback should be reported (but not crash)
+ expect(reported, isNotNull);
+ expect(reported!.exception.toString(), contains('then blew up'));
+ });
+
+ testWidgets('Hard-stop vs chaining resets onEnter history', (WidgetTester tester) async {
// With redirectLimit=1:
// - Block.stop() resets history so repeated attempts don't hit the limit.
// - Block.then(() => go(...)) keeps history and will exceed the limit.
@@ -1407,18 +1291,15 @@
routes: <RouteBase>[
GoRoute(
path: '/start',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Start'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Start'))),
),
GoRoute(
path: '/blocked-once',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('BlockedOnce'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('BlockedOnce'))),
),
GoRoute(
path: '/chain',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Chain'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Chain'))),
),
],
);
@@ -1492,10 +1373,7 @@
await tester.pumpAndSettle();
// Verify execution order: onEnter -> legacy -> route-level
- expect(
- calls,
- containsAllInOrder(<String>['onEnter', 'legacy', 'route-level']),
- );
+ expect(calls, containsAllInOrder(<String>['onEnter', 'legacy', 'route-level']));
expect(router.state.uri.path, '/redirected');
expect(find.text('Redirected'), findsOneWidget);
@@ -1518,37 +1396,96 @@
);
// Verify restore also follows same order
- expect(
- calls,
- containsAllInOrder(<String>['onEnter', 'legacy', 'route-level']),
- );
+ expect(calls, containsAllInOrder(<String>['onEnter', 'legacy', 'route-level']));
});
- testWidgets(
- 'onEnter blocking prevents stale state restoration (pop case)',
- (WidgetTester tester) async {
- // This test reproduces https://github.com/flutter/flutter/issues/178853
- // 1. Push A -> B
- // 2. Pop B -> A (simulating system back)
- // 3. Go A -> Blocked
- // 4. onEnter blocks
- // 5. Ensure we stay on A and don't "restore" B (stale state)
+ testWidgets('onEnter blocking prevents stale state restoration (pop case)', (
+ WidgetTester tester,
+ ) async {
+ // This test reproduces https://github.com/flutter/flutter/issues/178853
+ // 1. Push A -> B
+ // 2. Pop B -> A (simulating system back)
+ // 3. Go A -> Blocked
+ // 4. onEnter blocks
+ // 5. Ensure we stay on A and don't "restore" B (stale state)
+
+ router = GoRouter(
+ initialLocation: '/home',
+ onEnter: (_, __, GoRouterState next, ___) =>
+ next.uri.path == '/blocked' ? const Block.stop() : const Allow(),
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/home',
+ builder: (_, __) => const Scaffold(body: Text('Home')),
+ ),
+ GoRoute(
+ path: '/allowed',
+ builder: (_, __) => const Scaffold(body: Text('Allowed')),
+ ),
+ GoRoute(
+ path: '/blocked',
+ builder: (_, __) => const Scaffold(body: Text('Blocked')),
+ ),
+ ],
+ );
+
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
+ expect(find.text('Home'), findsOneWidget);
+
+ // 1. Push allowed
+ router.push('/allowed');
+ await tester.pumpAndSettle();
+ expect(find.text('Allowed'), findsOneWidget);
+
+ // 2. Pop (simulating system back / imperative pop)
+ final NavigatorState navigator = tester.state(find.byType(Navigator).last);
+ navigator.pop();
+ await tester.pumpAndSettle();
+ expect(find.text('Home'), findsOneWidget);
+
+ // 3. Attempt blocked navigation
+ router.go('/blocked');
+ await tester.pumpAndSettle();
+
+ // 4. Verify blocking worked
+ expect(find.text('Blocked'), findsNothing);
+
+ // 5. Verify we didn't restore the popped route (Allowed)
+ expect(find.text('Allowed'), findsNothing);
+ expect(find.text('Home'), findsOneWidget);
+ });
+
+ group('with refreshListenable', () {
+ testWidgets('Block.then(router.go) navigates after refreshListenable fires', (
+ WidgetTester tester,
+ ) async {
+ final isAuthenticated = ValueNotifier<bool>(true);
+ addTearDown(isAuthenticated.dispose);
router = GoRouter(
initialLocation: '/home',
- onEnter: (_, __, GoRouterState next, ___) =>
- next.uri.path == '/blocked' ? const Block.stop() : const Allow(),
+ refreshListenable: isAuthenticated,
+ onEnter:
+ (BuildContext context, GoRouterState current, GoRouterState next, GoRouter goRouter) {
+ // Public routes — always allow
+ if (next.uri.path == '/login') {
+ return const Allow();
+ }
+
+ // Protected routes — require auth
+ if (!isAuthenticated.value) {
+ return Block.then(() => goRouter.go('/login'));
+ }
+ return const Allow();
+ },
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) => const Scaffold(body: Text('Home')),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
- path: '/allowed',
- builder: (_, __) => const Scaffold(body: Text('Allowed')),
- ),
- GoRoute(
- path: '/blocked',
- builder: (_, __) => const Scaffold(body: Text('Blocked')),
+ path: '/login',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Login'))),
),
],
);
@@ -1557,140 +1494,59 @@
await tester.pumpAndSettle();
expect(find.text('Home'), findsOneWidget);
- // 1. Push allowed
- router.push('/allowed');
+ // Toggle auth off — refreshListenable fires, guard blocks and
+ // calls router.go('/login') in Block.then callback.
+ isAuthenticated.value = false;
await tester.pumpAndSettle();
- expect(find.text('Allowed'), findsOneWidget);
- // 2. Pop (simulating system back / imperative pop)
- final NavigatorState navigator = tester.state(
- find.byType(Navigator).last,
+ // The callback navigation must commit.
+ expect(router.state.uri.path, equals('/login'));
+ expect(find.text('Login'), findsOneWidget);
+ });
+
+ testWidgets('Block.then(router.goNamed) navigates after refreshListenable fires', (
+ WidgetTester tester,
+ ) async {
+ final isAuthenticated = ValueNotifier<bool>(true);
+ addTearDown(isAuthenticated.dispose);
+
+ router = GoRouter(
+ initialLocation: '/home',
+ refreshListenable: isAuthenticated,
+ onEnter:
+ (BuildContext context, GoRouterState current, GoRouterState next, GoRouter goRouter) {
+ if (next.uri.path == '/login') {
+ return const Allow();
+ }
+
+ if (!isAuthenticated.value) {
+ return Block.then(() => goRouter.goNamed('login'));
+ }
+ return const Allow();
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/home',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
+ ),
+ GoRoute(
+ path: '/login',
+ name: 'login',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Login'))),
+ ),
+ ],
);
- navigator.pop();
+
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
await tester.pumpAndSettle();
expect(find.text('Home'), findsOneWidget);
- // 3. Attempt blocked navigation
- router.go('/blocked');
+ isAuthenticated.value = false;
await tester.pumpAndSettle();
- // 4. Verify blocking worked
- expect(find.text('Blocked'), findsNothing);
-
- // 5. Verify we didn't restore the popped route (Allowed)
- expect(find.text('Allowed'), findsNothing);
- expect(find.text('Home'), findsOneWidget);
- },
- );
-
- group('with refreshListenable', () {
- testWidgets(
- 'Block.then(router.go) navigates after refreshListenable fires',
- (WidgetTester tester) async {
- final isAuthenticated = ValueNotifier<bool>(true);
- addTearDown(isAuthenticated.dispose);
-
- router = GoRouter(
- initialLocation: '/home',
- refreshListenable: isAuthenticated,
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- ) {
- // Public routes — always allow
- if (next.uri.path == '/login') {
- return const Allow();
- }
-
- // Protected routes — require auth
- if (!isAuthenticated.value) {
- return Block.then(() => goRouter.go('/login'));
- }
- return const Allow();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
- ),
- GoRoute(
- path: '/login',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Login'))),
- ),
- ],
- );
-
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
- expect(find.text('Home'), findsOneWidget);
-
- // Toggle auth off — refreshListenable fires, guard blocks and
- // calls router.go('/login') in Block.then callback.
- isAuthenticated.value = false;
- await tester.pumpAndSettle();
-
- // The callback navigation must commit.
- expect(router.state.uri.path, equals('/login'));
- expect(find.text('Login'), findsOneWidget);
- },
- );
-
- testWidgets(
- 'Block.then(router.goNamed) navigates after refreshListenable fires',
- (WidgetTester tester) async {
- final isAuthenticated = ValueNotifier<bool>(true);
- addTearDown(isAuthenticated.dispose);
-
- router = GoRouter(
- initialLocation: '/home',
- refreshListenable: isAuthenticated,
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- ) {
- if (next.uri.path == '/login') {
- return const Allow();
- }
-
- if (!isAuthenticated.value) {
- return Block.then(() => goRouter.goNamed('login'));
- }
- return const Allow();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
- ),
- GoRoute(
- path: '/login',
- name: 'login',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Login'))),
- ),
- ],
- );
-
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
- expect(find.text('Home'), findsOneWidget);
-
- isAuthenticated.value = false;
- await tester.pumpAndSettle();
-
- expect(router.state.uri.path, equals('/login'));
- expect(find.text('Login'), findsOneWidget);
- },
- );
+ expect(router.state.uri.path, equals('/login'));
+ expect(find.text('Login'), findsOneWidget);
+ });
testWidgets(
'Block.then(router.go) navigates after multiple rapid refreshListenable emissions',
@@ -1720,13 +1576,11 @@
routes: <RouteBase>[
GoRoute(
path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/login',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Login'))),
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Login'))),
),
],
);
@@ -1746,107 +1600,91 @@
},
);
- testWidgets(
- 'Allow.then(router.go) navigates after refreshListenable fires',
- (WidgetTester tester) async {
- final shouldRedirect = ValueNotifier<bool>(false);
- addTearDown(shouldRedirect.dispose);
+ testWidgets('Allow.then(router.go) navigates after refreshListenable fires', (
+ WidgetTester tester,
+ ) async {
+ final shouldRedirect = ValueNotifier<bool>(false);
+ addTearDown(shouldRedirect.dispose);
- router = GoRouter(
- initialLocation: '/home',
- refreshListenable: shouldRedirect,
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- ) {
- if (next.uri.path == '/dashboard') {
- return const Allow();
- }
-
- if (shouldRedirect.value && next.uri.path == '/home') {
- return Allow(then: () => goRouter.go('/dashboard'));
- }
+ router = GoRouter(
+ initialLocation: '/home',
+ refreshListenable: shouldRedirect,
+ onEnter:
+ (BuildContext context, GoRouterState current, GoRouterState next, GoRouter goRouter) {
+ if (next.uri.path == '/dashboard') {
return const Allow();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
- ),
- GoRoute(
- path: '/dashboard',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Dashboard'))),
- ),
- ],
- );
+ }
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
- expect(find.text('Home'), findsOneWidget);
+ if (shouldRedirect.value && next.uri.path == '/home') {
+ return Allow(then: () => goRouter.go('/dashboard'));
+ }
+ return const Allow();
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/home',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
+ ),
+ GoRoute(
+ path: '/dashboard',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Dashboard'))),
+ ),
+ ],
+ );
- shouldRedirect.value = true;
- await tester.pumpAndSettle();
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
+ expect(find.text('Home'), findsOneWidget);
- expect(router.state.uri.path, equals('/dashboard'));
- expect(find.text('Dashboard'), findsOneWidget);
- },
- );
+ shouldRedirect.value = true;
+ await tester.pumpAndSettle();
- testWidgets(
- 'Block.then error is reported after refreshListenable fires',
- (WidgetTester tester) async {
- final trigger = ValueNotifier<bool>(false);
- addTearDown(trigger.dispose);
+ expect(router.state.uri.path, equals('/dashboard'));
+ expect(find.text('Dashboard'), findsOneWidget);
+ });
- FlutterErrorDetails? reported;
- final void Function(FlutterErrorDetails)? oldHandler =
- FlutterError.onError;
- FlutterError.onError = (FlutterErrorDetails details) {
- reported = details;
- };
- addTearDown(() => FlutterError.onError = oldHandler);
+ testWidgets('Block.then error is reported after refreshListenable fires', (
+ WidgetTester tester,
+ ) async {
+ final trigger = ValueNotifier<bool>(false);
+ addTearDown(trigger.dispose);
- router = GoRouter(
- initialLocation: '/home',
- refreshListenable: trigger,
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- ) {
- if (trigger.value && next.uri.path == '/home') {
- return Block.then(() => throw StateError('callback error'));
- }
- return const Allow();
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/home',
- builder: (_, __) =>
- const Scaffold(body: Center(child: Text('Home'))),
- ),
- ],
- );
+ FlutterErrorDetails? reported;
+ final void Function(FlutterErrorDetails)? oldHandler = FlutterError.onError;
+ FlutterError.onError = (FlutterErrorDetails details) {
+ reported = details;
+ };
+ addTearDown(() => FlutterError.onError = oldHandler);
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
- expect(find.text('Home'), findsOneWidget);
+ router = GoRouter(
+ initialLocation: '/home',
+ refreshListenable: trigger,
+ onEnter:
+ (BuildContext context, GoRouterState current, GoRouterState next, GoRouter goRouter) {
+ if (trigger.value && next.uri.path == '/home') {
+ return Block.then(() => throw StateError('callback error'));
+ }
+ return const Allow();
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/home',
+ builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))),
+ ),
+ ],
+ );
- trigger.value = true;
- await tester.pumpAndSettle();
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
+ expect(find.text('Home'), findsOneWidget);
- // Error should be reported (not swallowed)
- expect(reported, isNotNull);
- expect(reported!.exception.toString(), contains('callback error'));
- },
- );
+ trigger.value = true;
+ await tester.pumpAndSettle();
+
+ // Error should be reported (not swallowed)
+ expect(reported, isNotNull);
+ expect(reported!.exception.toString(), contains('callback error'));
+ });
});
// Tests for onEnter interaction with chained redirects.
@@ -1905,67 +1743,60 @@
expect(redirectCallCount, 3);
});
- testWidgets(
- 'onEnter called once when route-level triggers top-level redirect',
- (WidgetTester tester) async {
- // Route-level on /src: /src -> /dst
- // Top-level: /dst -> /final
- // onEnter should be called exactly once.
- var onEnterCallCount = 0;
-
- router = GoRouter(
- initialLocation: '/src',
- onEnter:
- (
- BuildContext context,
- GoRouterState current,
- GoRouterState next,
- GoRouter goRouter,
- ) async {
- onEnterCallCount++;
- return const Allow();
- },
- redirect: (BuildContext context, GoRouterState state) {
- if (state.matchedLocation == '/dst') {
- return '/final';
- }
- return null;
- },
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, __) => const Text('Home'),
- routes: <RouteBase>[
- GoRoute(
- path: 'src',
- builder: (_, __) => const Text('Src'),
- redirect: (BuildContext context, GoRouterState state) =>
- '/dst',
- ),
- ],
- ),
- GoRoute(path: '/dst', builder: (_, __) => const Text('Dst')),
- GoRoute(path: '/final', builder: (_, __) => const Text('Final')),
- ],
- );
-
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pumpAndSettle();
-
- // Chain should resolve to /final.
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/final',
- );
- expect(find.text('Final'), findsOneWidget);
- // onEnter should be called exactly once for the initial navigation.
- expect(onEnterCallCount, 1);
- },
- );
-
- testWidgets('onEnter block prevents redirect chain evaluation', (
+ testWidgets('onEnter called once when route-level triggers top-level redirect', (
WidgetTester tester,
) async {
+ // Route-level on /src: /src -> /dst
+ // Top-level: /dst -> /final
+ // onEnter should be called exactly once.
+ var onEnterCallCount = 0;
+
+ router = GoRouter(
+ initialLocation: '/src',
+ onEnter:
+ (
+ BuildContext context,
+ GoRouterState current,
+ GoRouterState next,
+ GoRouter goRouter,
+ ) async {
+ onEnterCallCount++;
+ return const Allow();
+ },
+ redirect: (BuildContext context, GoRouterState state) {
+ if (state.matchedLocation == '/dst') {
+ return '/final';
+ }
+ return null;
+ },
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Text('Home'),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'src',
+ builder: (_, __) => const Text('Src'),
+ redirect: (BuildContext context, GoRouterState state) => '/dst',
+ ),
+ ],
+ ),
+ GoRoute(path: '/dst', builder: (_, __) => const Text('Dst')),
+ GoRoute(path: '/final', builder: (_, __) => const Text('Final')),
+ ],
+ );
+
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pumpAndSettle();
+
+ // Chain should resolve to /final.
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final');
+ expect(find.text('Final'), findsOneWidget);
+ // onEnter should be called exactly once for the initial navigation.
+ expect(onEnterCallCount, 1);
+ });
+
+ testWidgets('onEnter block prevents redirect chain evaluation', (WidgetTester tester) async {
// onEnter blocks navigation to /a.
// Top-level redirect: /a -> /b (should never be evaluated).
var redirectCallCount = 0;
diff --git a/packages/go_router/test/on_exit_test.dart b/packages/go_router/test/on_exit_test.dart
index 56f5c61..dc0ae6a 100644
--- a/packages/go_router/test/on_exit_test.dart
+++ b/packages/go_router/test/on_exit_test.dart
@@ -18,13 +18,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: home),
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home),
routes: <GoRoute>[
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;
},
@@ -33,11 +31,7 @@
),
];
- 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();
@@ -57,24 +51,18 @@
final routes = <GoRoute>[
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('/');
@@ -94,13 +82,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: home),
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home),
routes: <GoRoute>[
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;
},
@@ -109,11 +95,7 @@
),
];
- 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();
@@ -141,24 +123,18 @@
final routes = <GoRoute>[
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('/');
@@ -179,16 +155,13 @@
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 {
var allow = false;
final home = UniqueKey();
final routes = <GoRoute>[
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;
},
@@ -205,16 +178,13 @@
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 {
var allow = false;
final home = UniqueKey();
final routes = <GoRoute>[
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;
},
@@ -242,8 +212,7 @@
routes: <RouteBase>[
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;
},
@@ -275,13 +244,11 @@
final routes = <GoRoute>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: home),
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home),
routes: <GoRoute>[
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;
@@ -289,8 +256,7 @@
routes: <GoRoute>[
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;
@@ -298,8 +264,7 @@
routes: <GoRoute>[
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;
@@ -313,11 +278,7 @@
),
];
- 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();
@@ -337,214 +298,158 @@
expect(onExitState1.uri.toString(), '/1');
});
- testWidgets(
- 'It should provide the correct path parameters to the onExit callback',
- (WidgetTester tester) async {
- final page0 = UniqueKey();
- final page1 = UniqueKey();
- final page2 = UniqueKey();
- final page3 = UniqueKey();
- late final GoRouterState onExitState1;
- late final GoRouterState onExitState2;
- late final GoRouterState onExitState3;
- final routes = <GoRoute>[
- GoRoute(
- path: '/route-0/:id0',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: page0),
- ),
- GoRoute(
- path: '/route-1/:id1',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: page1),
- onExit: (BuildContext context, GoRouterState state) {
- onExitState1 = state;
- return true;
- },
- ),
- GoRoute(
- path: '/route-2/:id2',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: page2),
- onExit: (BuildContext context, GoRouterState state) {
- onExitState2 = state;
- return true;
- },
- ),
- GoRoute(
- path: '/route-3/:id3',
- builder: (BuildContext context, GoRouterState state) {
- return DummyScreen(key: page3);
- },
- onExit: (BuildContext context, GoRouterState state) {
- onExitState3 = state;
- return true;
- },
- ),
- ];
+ testWidgets('It should provide the correct path parameters to the onExit callback', (
+ WidgetTester tester,
+ ) async {
+ final page0 = UniqueKey();
+ final page1 = UniqueKey();
+ final page2 = UniqueKey();
+ final page3 = UniqueKey();
+ late final GoRouterState onExitState1;
+ late final GoRouterState onExitState2;
+ late final GoRouterState onExitState3;
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/route-0/:id0',
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page0),
+ ),
+ GoRoute(
+ path: '/route-1/:id1',
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1),
+ onExit: (BuildContext context, GoRouterState state) {
+ onExitState1 = state;
+ return true;
+ },
+ ),
+ GoRoute(
+ path: '/route-2/:id2',
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page2),
+ onExit: (BuildContext context, GoRouterState state) {
+ onExitState2 = state;
+ return true;
+ },
+ ),
+ GoRoute(
+ path: '/route-3/:id3',
+ builder: (BuildContext context, GoRouterState state) {
+ return DummyScreen(key: page3);
+ },
+ onExit: (BuildContext context, GoRouterState state) {
+ onExitState3 = state;
+ return true;
+ },
+ ),
+ ];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/route-0/0?param0=0',
- );
- unawaited(router.push('/route-1/1?param1=1'));
- unawaited(router.push('/route-2/2?param2=2'));
- unawaited(router.push('/route-3/3?param3=3'));
+ final GoRouter router = await createRouter(
+ routes,
+ tester,
+ initialLocation: '/route-0/0?param0=0',
+ );
+ unawaited(router.push('/route-1/1?param1=1'));
+ unawaited(router.push('/route-2/2?param2=2'));
+ unawaited(router.push('/route-3/3?param3=3'));
- await tester.pumpAndSettle();
- expect(find.byKey(page3), findsOne);
+ await tester.pumpAndSettle();
+ expect(find.byKey(page3), findsOne);
- router.pop();
- await tester.pumpAndSettle();
- expect(find.byKey(page2), findsOne);
- expect(onExitState3.uri.toString(), '/route-3/3?param3=3');
- expect(onExitState3.pathParameters, const <String, String>{'id3': '3'});
- expect(onExitState3.fullPath, '/route-3/:id3');
+ router.pop();
+ await tester.pumpAndSettle();
+ expect(find.byKey(page2), findsOne);
+ expect(onExitState3.uri.toString(), '/route-3/3?param3=3');
+ expect(onExitState3.pathParameters, const <String, String>{'id3': '3'});
+ expect(onExitState3.fullPath, '/route-3/:id3');
- router.pop();
- await tester.pumpAndSettle();
- expect(find.byKey(page1), findsOne);
- expect(onExitState2.uri.toString(), '/route-2/2?param2=2');
- expect(onExitState2.pathParameters, const <String, String>{'id2': '2'});
- expect(onExitState2.fullPath, '/route-2/:id2');
+ router.pop();
+ await tester.pumpAndSettle();
+ expect(find.byKey(page1), findsOne);
+ expect(onExitState2.uri.toString(), '/route-2/2?param2=2');
+ expect(onExitState2.pathParameters, const <String, String>{'id2': '2'});
+ expect(onExitState2.fullPath, '/route-2/:id2');
- router.pop();
- await tester.pumpAndSettle();
- expect(find.byKey(page0), findsOne);
- expect(onExitState1.uri.toString(), '/route-1/1?param1=1');
- expect(onExitState1.pathParameters, const <String, String>{'id1': '1'});
- expect(onExitState1.fullPath, '/route-1/:id1');
- },
- );
+ router.pop();
+ await tester.pumpAndSettle();
+ expect(find.byKey(page0), findsOne);
+ expect(onExitState1.uri.toString(), '/route-1/1?param1=1');
+ expect(onExitState1.pathParameters, const <String, String>{'id1': '1'});
+ expect(onExitState1.fullPath, '/route-1/:id1');
+ });
- testWidgets(
- 'It should provide the correct path parameters to the onExit callback during a go',
- (WidgetTester tester) async {
- final page0 = UniqueKey();
- final page1 = UniqueKey();
- final page2 = UniqueKey();
- final page3 = UniqueKey();
- late final GoRouterState onExitState0;
- late final GoRouterState onExitState1;
- late final GoRouterState onExitState2;
- final routes = <GoRoute>[
- GoRoute(
- path: '/route-0/:id0',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: page0),
- onExit: (BuildContext context, GoRouterState state) {
- onExitState0 = state;
- return true;
- },
- ),
- GoRoute(
- path: '/route-1/:id1',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: page1),
- onExit: (BuildContext context, GoRouterState state) {
- onExitState1 = state;
- return true;
- },
- ),
- GoRoute(
- path: '/route-2/:id2',
- builder: (BuildContext context, GoRouterState state) =>
- DummyScreen(key: page2),
- onExit: (BuildContext context, GoRouterState state) {
- onExitState2 = state;
- return true;
- },
- ),
- GoRoute(
- path: '/route-3/:id3',
- builder: (BuildContext context, GoRouterState state) {
- return DummyScreen(key: page3);
- },
- ),
- ];
+ testWidgets('It should provide the correct path parameters to the onExit callback during a go', (
+ WidgetTester tester,
+ ) async {
+ final page0 = UniqueKey();
+ final page1 = UniqueKey();
+ final page2 = UniqueKey();
+ final page3 = UniqueKey();
+ late final GoRouterState onExitState0;
+ late final GoRouterState onExitState1;
+ late final GoRouterState onExitState2;
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/route-0/:id0',
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page0),
+ onExit: (BuildContext context, GoRouterState state) {
+ onExitState0 = state;
+ return true;
+ },
+ ),
+ GoRoute(
+ path: '/route-1/:id1',
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1),
+ onExit: (BuildContext context, GoRouterState state) {
+ onExitState1 = state;
+ return true;
+ },
+ ),
+ GoRoute(
+ path: '/route-2/:id2',
+ builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page2),
+ onExit: (BuildContext context, GoRouterState state) {
+ onExitState2 = state;
+ return true;
+ },
+ ),
+ GoRoute(
+ path: '/route-3/:id3',
+ builder: (BuildContext context, GoRouterState state) {
+ return DummyScreen(key: page3);
+ },
+ ),
+ ];
- final GoRouter router = await createRouter(
- routes,
- tester,
- initialLocation: '/route-0/0?param0=0',
- );
- expect(find.byKey(page0), findsOne);
+ final GoRouter router = await createRouter(
+ routes,
+ tester,
+ initialLocation: '/route-0/0?param0=0',
+ );
+ expect(find.byKey(page0), findsOne);
- router.go('/route-1/1?param1=1');
- await tester.pumpAndSettle();
- expect(find.byKey(page1), findsOne);
- expect(onExitState0.uri.toString(), '/route-0/0?param0=0');
- expect(onExitState0.pathParameters, const <String, String>{'id0': '0'});
- expect(onExitState0.fullPath, '/route-0/:id0');
+ router.go('/route-1/1?param1=1');
+ await tester.pumpAndSettle();
+ expect(find.byKey(page1), findsOne);
+ expect(onExitState0.uri.toString(), '/route-0/0?param0=0');
+ expect(onExitState0.pathParameters, const <String, String>{'id0': '0'});
+ expect(onExitState0.fullPath, '/route-0/:id0');
- router.go('/route-2/2?param2=2');
- await tester.pumpAndSettle();
- expect(find.byKey(page2), findsOne);
- expect(onExitState1.uri.toString(), '/route-1/1?param1=1');
- expect(onExitState1.pathParameters, const <String, String>{'id1': '1'});
- expect(onExitState1.fullPath, '/route-1/:id1');
+ router.go('/route-2/2?param2=2');
+ await tester.pumpAndSettle();
+ expect(find.byKey(page2), findsOne);
+ expect(onExitState1.uri.toString(), '/route-1/1?param1=1');
+ expect(onExitState1.pathParameters, const <String, String>{'id1': '1'});
+ expect(onExitState1.fullPath, '/route-1/:id1');
- router.go('/route-3/3?param3=3');
- await tester.pumpAndSettle();
- expect(find.byKey(page3), findsOne);
- expect(onExitState2.uri.toString(), '/route-2/2?param2=2');
- expect(onExitState2.pathParameters, const <String, String>{'id2': '2'});
- expect(onExitState2.fullPath, '/route-2/:id2');
- },
- );
+ router.go('/route-3/3?param3=3');
+ await tester.pumpAndSettle();
+ expect(find.byKey(page3), findsOne);
+ expect(onExitState2.uri.toString(), '/route-2/2?param2=2');
+ expect(onExitState2.pathParameters, const <String, String>{'id2': '2'});
+ expect(onExitState2.fullPath, '/route-2/:id2');
+ });
// Regression test: pop() with onExit + async redirect must not restore
// stale configuration.
- testWidgets(
- 'pop does not call restore with stale config when route has onExit',
- (WidgetTester tester) async {
- final homeKey = UniqueKey();
- final detailKey = UniqueKey();
-
- final GoRouter router = await createRouter(
- <RouteBase>[
- GoRoute(
- path: '/',
- builder: (_, __) => DummyScreen(key: homeKey),
- routes: <RouteBase>[
- GoRoute(
- path: 'detail',
- onExit: (_, __) => true,
- builder: (_, __) => DummyScreen(key: detailKey),
- ),
- ],
- ),
- ],
- tester,
- initialLocation: '/detail',
- redirect: (_, GoRouterState state) async {
- // Async redirect — completes in a later microtask.
- await Future<void>.delayed(Duration.zero);
- return null;
- },
- );
-
- await tester.pumpAndSettle();
- expect(find.byKey(detailKey), findsOneWidget);
-
- router.pop();
- await tester.pumpAndSettle();
-
- // The detail route should be gone after pop.
- expect(
- find.byKey(detailKey),
- findsNothing,
- reason:
- 'Route with onExit should be properly popped '
- 'even when async redirect is present',
- );
- expect(find.byKey(homeKey), findsOneWidget);
- },
- );
-
- // Verify that pop is correctly cancelled when onExit returns false.
- testWidgets('pop is cancelled when onExit returns false', (
+ testWidgets('pop does not call restore with stale config when route has onExit', (
WidgetTester tester,
) async {
final homeKey = UniqueKey();
@@ -558,6 +463,51 @@
routes: <RouteBase>[
GoRoute(
path: 'detail',
+ onExit: (_, __) => true,
+ builder: (_, __) => DummyScreen(key: detailKey),
+ ),
+ ],
+ ),
+ ],
+ tester,
+ initialLocation: '/detail',
+ redirect: (_, GoRouterState state) async {
+ // Async redirect — completes in a later microtask.
+ await Future<void>.delayed(Duration.zero);
+ return null;
+ },
+ );
+
+ await tester.pumpAndSettle();
+ expect(find.byKey(detailKey), findsOneWidget);
+
+ router.pop();
+ await tester.pumpAndSettle();
+
+ // The detail route should be gone after pop.
+ expect(
+ find.byKey(detailKey),
+ findsNothing,
+ reason:
+ 'Route with onExit should be properly popped '
+ 'even when async redirect is present',
+ );
+ expect(find.byKey(homeKey), findsOneWidget);
+ });
+
+ // Verify that pop is correctly cancelled when onExit returns false.
+ testWidgets('pop is cancelled when onExit returns false', (WidgetTester tester) async {
+ final homeKey = UniqueKey();
+ final detailKey = UniqueKey();
+
+ final GoRouter router = await createRouter(
+ <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => DummyScreen(key: homeKey),
+ routes: <RouteBase>[
+ GoRoute(
+ path: 'detail',
onExit: (_, __) => false, // Always prevent leaving.
builder: (_, __) => DummyScreen(key: detailKey),
),
diff --git a/packages/go_router/test/parser_test.dart b/packages/go_router/test/parser_test.dart
index d6d4d18..8adadd7 100644
--- a/packages/go_router/test/parser_test.dart
+++ b/packages/go_router/test/parser_test.dart
@@ -22,26 +22,18 @@
int redirectLimit = 5,
GoRouterRedirect? redirect,
}) async {
- final router = GoRouter(
- routes: routes,
- redirectLimit: redirectLimit,
- redirect: redirect,
- );
+ final router = GoRouter(routes: routes, redirectLimit: redirectLimit, redirect: redirect);
addTearDown(router.dispose);
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 routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- GoRoute(path: 'abc', builder: (_, __) => const Placeholder()),
- ],
+ routes: <GoRoute>[GoRoute(path: 'abc', builder: (_, __) => const Placeholder())],
),
];
final GoRouteInformationParser parser = await createParser(
@@ -53,11 +45,10 @@
final BuildContext context = tester.element(find.byType(Router<Object>));
- RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/'),
- context,
- );
+ RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/'),
+ context,
+ );
List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 1);
expect(matchesObj.uri.toString(), '/');
@@ -81,48 +72,14 @@
expect(matches[1].route, routes[0].routes[0]);
});
- testWidgets(
- 'GoRouteInformationParser can handle empty path for non http uri',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- 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<Object>));
-
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('elbaapp://domain'),
- context,
- );
- final List<RouteMatchBase> matches = matchesObj.matches;
- expect(matches.length, 1);
- expect(matchesObj.uri.toString(), 'elbaapp://domain/');
- },
- );
-
- testWidgets('GoRouteInformationParser cleans up uri', (
+ testWidgets('GoRouteInformationParser can handle empty path for non http uri', (
WidgetTester tester,
) async {
final routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- GoRoute(path: 'abc', builder: (_, __) => const Placeholder()),
- ],
+ routes: <GoRoute>[GoRoute(path: 'abc', builder: (_, __) => const Placeholder())],
),
];
final GoRouteInformationParser parser = await createParser(
@@ -134,11 +91,36 @@
final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('http://domain/abc/?query=bde'),
- context,
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('elbaapp://domain'),
+ context,
+ );
+ final List<RouteMatchBase> matches = matchesObj.matches;
+ expect(matches.length, 1);
+ expect(matchesObj.uri.toString(), 'elbaapp://domain/');
+ });
+
+ testWidgets('GoRouteInformationParser cleans up uri', (WidgetTester tester) async {
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Placeholder(),
+ routes: <GoRoute>[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<Object>));
+
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('http://domain/abc/?query=bde'),
+ context,
+ );
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), 'http://domain/abc?query=bde');
@@ -151,11 +133,8 @@
const expectedHost = 'www.example.com';
const expectedQuery = 'abc=def';
const expectedFragment = 'abc';
- const expectedUriString =
- '$expectedScheme://$expectedHost/?$expectedQuery#$expectedFragment';
- final routes = <GoRoute>[
- GoRoute(path: '/', builder: (_, __) => const Placeholder()),
- ];
+ const expectedUriString = '$expectedScheme://$expectedHost/?$expectedQuery#$expectedFragment';
+ final routes = <GoRoute>[GoRoute(path: '/', builder: (_, __) => const Placeholder())];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
@@ -165,11 +144,10 @@
final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation(expectedUriString),
- context,
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation(expectedUriString),
+ context,
+ );
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 1);
expect(matchesObj.uri.toString(), expectedUriString);
@@ -197,9 +175,7 @@
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- GoRoute(path: 'abc', builder: (_, __) => const Placeholder()),
- ],
+ routes: <GoRoute>[GoRoute(path: 'abc', builder: (_, __) => const Placeholder())],
),
];
final GoRouteInformationParser parser = await createParser(
@@ -211,11 +187,10 @@
final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation(expectedUriString),
- context,
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation(expectedUriString),
+ context,
+ );
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), expectedUriString);
@@ -241,40 +216,28 @@
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- GoRoute(path: 'abc', builder: (_, __) => const Placeholder()),
- ],
+ routes: <GoRoute>[GoRoute(path: 'abc', builder: (_, __) => const Placeholder())],
),
];
GoRouter.optionURLReflectsImperativeAPIs = true;
- final GoRouter router = await createRouter(
- routes,
- tester,
- navigatorKey: navKey,
- );
+ 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;
+ final RouteMatchList matchList = router.routerDelegate.currentConfiguration;
expect(matchList.uri.toString(), '/abc');
expect(matchList.matches.length, 3);
- final RouteInformation restoredRouteInformation = router
- .routeInformationParser
+ 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!,
- );
+ final RouteMatchList parsedRouteMatch = await router.routeInformationParser
+ .parseRouteInformationWithDependencies(restoredRouteInformation, navKey.currentContext!);
expect(parsedRouteMatch.uri.toString(), '/abc');
expect(parsedRouteMatch.matches.length, 3);
@@ -288,21 +251,9 @@
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
- GoRoute(
- path: 'abc',
- name: 'lowercase',
- builder: (_, __) => const Placeholder(),
- ),
- GoRoute(
- path: 'efg',
- name: 'camelCase',
- builder: (_, __) => const Placeholder(),
- ),
- GoRoute(
- path: 'hij',
- name: 'snake_case',
- builder: (_, __) => const Placeholder(),
- ),
+ GoRoute(path: 'abc', name: 'lowercase', builder: (_, __) => const Placeholder()),
+ GoRoute(path: 'efg', name: 'camelCase', builder: (_, __) => const Placeholder()),
+ GoRoute(path: 'hij', name: 'snake_case', builder: (_, __) => const Placeholder()),
],
),
];
@@ -321,10 +272,7 @@
// With query parameters
expect(configuration.namedLocation('lowercase'), '/abc');
expect(
- configuration.namedLocation(
- 'lowercase',
- queryParameters: const <String, String>{'q': '1'},
- ),
+ configuration.namedLocation('lowercase', queryParameters: const <String, String>{'q': '1'}),
'/abc?q=1',
);
expect(
@@ -336,42 +284,35 @@
);
});
- test(
- 'GoRouteInformationParser can retrieve route by name with query parameters',
- () async {
- final routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- GoRoute(
- path: 'abc',
- name: 'routeName',
- builder: (_, __) => const Placeholder(),
- ),
- ],
- ),
- ];
+ test('GoRouteInformationParser can retrieve route by name with query parameters', () async {
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Placeholder(),
+ routes: <GoRoute>[
+ GoRoute(path: 'abc', name: 'routeName', builder: (_, __) => const Placeholder()),
+ ],
+ ),
+ ];
- final RouteConfiguration configuration = createRouteConfiguration(
- routes: routes,
- redirectLimit: 100,
- topRedirect: (_, __) => null,
- navigatorKey: GlobalKey<NavigatorState>(),
- );
+ final RouteConfiguration configuration = createRouteConfiguration(
+ routes: routes,
+ redirectLimit: 100,
+ topRedirect: (_, __) => null,
+ navigatorKey: GlobalKey<NavigatorState>(),
+ );
- expect(
- configuration.namedLocation(
- 'routeName',
- queryParameters: const <String, dynamic>{
- 'q1': 'v1',
- 'q2': <String>['v2', 'v3'],
- },
- ),
- '/abc?q1=v1&q2=v2&q2=v3',
- );
- },
- );
+ expect(
+ configuration.namedLocation(
+ 'routeName',
+ queryParameters: const <String, dynamic>{
+ 'q1': 'v1',
+ 'q2': <String>['v2', 'v3'],
+ },
+ ),
+ '/abc?q1=v1&q2=v2&q2=v3',
+ );
+ });
testWidgets('GoRouteInformationParser returns error when unknown route', (
WidgetTester tester,
@@ -380,9 +321,7 @@
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- GoRoute(path: 'abc', builder: (_, __) => const Placeholder()),
- ],
+ routes: <GoRoute>[GoRoute(path: 'abc', builder: (_, __) => const Placeholder())],
),
];
final GoRouteInformationParser parser = await createParser(
@@ -394,52 +333,42 @@
final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/def'),
- context,
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/def'),
+ context,
+ );
final List<RouteMatchBase> 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 routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- 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 calls redirector with correct uri when unknown route', (
+ WidgetTester tester,
+ ) async {
+ String? lastRedirectLocation;
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Placeholder(),
+ routes: <GoRoute>[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<Object>));
- await parser.parseRouteInformationWithDependencies(
- createRouteInformation('/def'),
- context,
- );
- expect(lastRedirectLocation, '/def');
- },
- );
+ final BuildContext context = tester.element(find.byType(Router<Object>));
+ await parser.parseRouteInformationWithDependencies(createRouteInformation('/def'), context);
+ expect(lastRedirectLocation, '/def');
+ });
testWidgets('GoRouteInformationParser can work with route parameters', (
WidgetTester tester,
@@ -449,10 +378,7 @@
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
- GoRoute(
- path: ':uid/family/:fid',
- builder: (_, __) => const Placeholder(),
- ),
+ GoRoute(path: ':uid/family/:fid', builder: (_, __) => const Placeholder()),
],
),
];
@@ -464,11 +390,10 @@
);
final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/123/family/456'),
- context,
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/123/family/456'),
+ context,
+ );
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
@@ -482,144 +407,128 @@
expect(matches[1].matchedLocation, '/123/family/456');
});
- testWidgets(
- 'GoRouteInformationParser processes top level redirect when there is no match',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- 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;
- },
+ testWidgets('GoRouteInformationParser processes top level redirect when there is no match', (
+ WidgetTester tester,
+ ) async {
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Placeholder(),
+ routes: <GoRoute>[
+ 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<Object>));
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/random/uri'),
+ context,
+ );
+ final List<RouteMatchBase> matches = matchesObj.matches;
+
+ expect(matches.length, 2);
+ expect(matchesObj.uri.toString(), '/123/family/345');
+ expect(matches[0].matchedLocation, '/');
+
+ expect(matches[1].matchedLocation, '/123/family/345');
+ });
+
+ testWidgets('GoRouteInformationParser can do route level redirect when there is a match', (
+ WidgetTester tester,
+ ) async {
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/',
+ builder: (_, __) => const Placeholder(),
+ routes: <GoRoute>[
+ 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<Object>));
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/redirect'),
+ context,
+ );
+ final List<RouteMatchBase> matches = matchesObj.matches;
+
+ expect(matches.length, 2);
+ expect(matchesObj.uri.toString(), '/123/family/345');
+ expect(matches[0].matchedLocation, '/');
+
+ expect(matches[1].matchedLocation, '/123/family/345');
+ });
+
+ testWidgets('GoRouteInformationParser throws an exception when route is malformed', (
+ WidgetTester tester,
+ ) async {
+ final routes = <GoRoute>[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<Object>));
+ expect(() async {
+ await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('::Not valid URI::'),
+ context,
);
+ }, throwsA(isA<FormatException>()));
+ });
- final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/random/uri'),
- context,
- );
- final List<RouteMatchBase> matches = matchesObj.matches;
+ testWidgets('GoRouteInformationParser returns an error if a redirect is detected.', (
+ WidgetTester tester,
+ ) async {
+ final routes = <GoRoute>[
+ GoRoute(
+ path: '/abc',
+ builder: (_, __) => const Placeholder(),
+ redirect: (BuildContext context, GoRouterState state) => state.uri.toString(),
+ ),
+ ];
+ final GoRouteInformationParser parser = await createParser(
+ tester,
+ routes: routes,
+ redirect: (_, __) => null,
+ );
- expect(matches.length, 2);
- expect(matchesObj.uri.toString(), '/123/family/345');
- expect(matches[0].matchedLocation, '/');
+ final BuildContext context = tester.element(find.byType(Router<Object>));
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/abd'),
+ context,
+ );
+ final List<RouteMatchBase> matches = matchesObj.matches;
- expect(matches[1].matchedLocation, '/123/family/345');
- },
- );
-
- testWidgets(
- 'GoRouteInformationParser can do route level redirect when there is a match',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (_, __) => const Placeholder(),
- routes: <GoRoute>[
- 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<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/redirect'),
- context,
- );
- final List<RouteMatchBase> matches = matchesObj.matches;
-
- expect(matches.length, 2);
- expect(matchesObj.uri.toString(), '/123/family/345');
- expect(matches[0].matchedLocation, '/');
-
- expect(matches[1].matchedLocation, '/123/family/345');
- },
- );
-
- testWidgets(
- 'GoRouteInformationParser throws an exception when route is malformed',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- 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<Object>));
- expect(() async {
- await parser.parseRouteInformationWithDependencies(
- createRouteInformation('::Not valid URI::'),
- context,
- );
- }, throwsA(isA<FormatException>()));
- },
- );
-
- testWidgets(
- 'GoRouteInformationParser returns an error if a redirect is detected.',
- (WidgetTester tester) async {
- final routes = <GoRoute>[
- 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<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/abd'),
- context,
- );
- final List<RouteMatchBase> 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 routes = <RouteBase>[
@@ -650,11 +559,10 @@
);
final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('/a'),
- context,
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('/a'),
+ context,
+ );
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches, hasLength(1));
@@ -663,29 +571,25 @@
expect(matchesObj.error, isNull);
});
- testWidgets(
- 'GoRouteInformationParser can handle path without leading slash',
- (WidgetTester tester) async {
- final routes = <RouteBase>[
- GoRoute(path: '/abc', builder: (_, __) => const Placeholder()),
- ];
- final GoRouteInformationParser parser = await createParser(
- tester,
- routes: routes,
- redirectLimit: 100,
- redirect: (_, __) => null,
- );
+ testWidgets('GoRouteInformationParser can handle path without leading slash', (
+ WidgetTester tester,
+ ) async {
+ final routes = <RouteBase>[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<Object>));
+ final BuildContext context = tester.element(find.byType(Router<Object>));
- final RouteMatchList matchesObj = await parser
- .parseRouteInformationWithDependencies(
- createRouteInformation('abc'),
- context,
- );
- final List<RouteMatchBase> matches = matchesObj.matches;
- expect(matches.length, 1);
- expect(matchesObj.uri.toString(), '/abc');
- },
- );
+ final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies(
+ createRouteInformation('abc'),
+ context,
+ );
+ final List<RouteMatchBase> matches = matchesObj.matches;
+ expect(matches.length, 1);
+ expect(matchesObj.uri.toString(), '/abc');
+ });
}
diff --git a/packages/go_router/test/path_utils_test.dart b/packages/go_router/test/path_utils_test.dart
index 6dbf911..2855340 100644
--- a/packages/go_router/test/path_utils_test.dart
+++ b/packages/go_router/test/path_utils_test.dart
@@ -9,11 +9,7 @@
test('patternToRegExp without path parameter', () async {
const pattern = '/settings/detail';
final pathParameter = <String>[];
- 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);
@@ -26,21 +22,14 @@
test('patternToRegExp with path parameter', () async {
const pattern = '/user/:id/book/:bookId';
final pathParameter = <String>[];
- 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<String, String> parameterValues = extractPathParameters(
- pathParameter,
- match!,
- );
+ final Map<String, String> parameterValues = extractPathParameters(pathParameter, match!);
expect(parameterValues.length, 2);
expect(parameterValues[pathParameter[0]], '123');
expect(parameterValues[pathParameter[1]], '456');
@@ -54,20 +43,13 @@
test('patternToPath without path parameter', () async {
const pattern = '/settings/detail';
final pathParameter = <String>[];
- final RegExp regex = patternToRegExp(
- pattern,
- pathParameter,
- caseSensitive: true,
- );
+ final RegExp regex = patternToRegExp(pattern, pathParameter, caseSensitive: true);
const url = '/settings/detail';
final RegExpMatch? match = regex.firstMatch(url);
expect(match, isNotNull);
- final Map<String, String> parameterValues = extractPathParameters(
- pathParameter,
- match!,
- );
+ final Map<String, String> parameterValues = extractPathParameters(pathParameter, match!);
final String restoredUrl = patternToPath(pattern, parameterValues);
expect(url, restoredUrl);
@@ -76,20 +58,13 @@
test('patternToPath with path parameter', () async {
const pattern = '/user/:id/book/:bookId';
final pathParameter = <String>[];
- final RegExp regex = patternToRegExp(
- pattern,
- pathParameter,
- caseSensitive: true,
- );
+ final RegExp regex = patternToRegExp(pattern, pathParameter, caseSensitive: true);
const url = '/user/123/book/456';
final RegExpMatch? match = regex.firstMatch(url);
expect(match, isNotNull);
- final Map<String, String> parameterValues = extractPathParameters(
- pathParameter,
- match!,
- );
+ final Map<String, String> parameterValues = extractPathParameters(pathParameter, match!);
final String restoredUrl = patternToPath(pattern, parameterValues);
expect(url, restoredUrl);
@@ -111,10 +86,7 @@
test('concatenateUris', () {
void verify(String pathA, String pathB, String expected) {
- final result = concatenateUris(
- Uri.parse(pathA),
- Uri.parse(pathB),
- ).toString();
+ final result = concatenateUris(Uri.parse(pathA), Uri.parse(pathB)).toString();
expect(result, expected);
}
@@ -134,8 +106,7 @@
});
test('canonicalUri', () {
- void verify(String path, String expected) =>
- expect(canonicalUri(path), expected);
+ void verify(String path, String expected) => expect(canonicalUri(path), expected);
verify('/a', '/a');
verify('/a/', '/a');
verify('/', '/');
diff --git a/packages/go_router/test/rebuild_test.dart b/packages/go_router/test/rebuild_test.dart
index b037945..981aab6 100644
--- a/packages/go_router/test/rebuild_test.dart
+++ b/packages/go_router/test/rebuild_test.dart
@@ -9,14 +9,9 @@
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 routes = <GoRoute>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, __) => const HomePage(),
- ),
+ GoRoute(path: '/', builder: (BuildContext context, __) => const HomePage()),
GoRoute(
path: '/1',
builder: (BuildContext context, __) {
diff --git a/packages/go_router/test/redirect_chain_test.dart b/packages/go_router/test/redirect_chain_test.dart
index 7eee128..41a262b 100644
--- a/packages/go_router/test/redirect_chain_test.dart
+++ b/packages/go_router/test/redirect_chain_test.dart
@@ -27,18 +27,15 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const Page1Screen(),
+ builder: (BuildContext context, GoRouterState state) => const Page1Screen(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Page2Screen(),
+ builder: (BuildContext context, GoRouterState state) => const Page2Screen(),
),
],
tester,
@@ -60,30 +57,24 @@
expect(redirectLog, <String>['/', '/a', '/b']);
});
- testWidgets('top-level redirect chain with three hops', (
- WidgetTester tester,
- ) async {
+ testWidgets('top-level redirect chain with three hops', (WidgetTester tester) async {
final GoRouter router = await createRouter(
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/step1',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/step2',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/step3',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -97,10 +88,7 @@
},
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/step3',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/step3');
expect(find.byType(LoginScreen), findsOneWidget);
});
@@ -109,18 +97,15 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -143,26 +128,21 @@
expect(find.byType(LoginScreen), findsOneWidget);
});
- testWidgets('top-level redirect chain loop detection', (
- WidgetTester tester,
- ) async {
+ testWidgets('top-level redirect chain loop detection', (WidgetTester tester) async {
// Redirect loop: / -> /a -> /b -> /a (loop)
await createRouter(
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
tester,
@@ -174,35 +154,25 @@
_ => null,
};
},
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
- expect(
- (screen.ex as GoException).message,
- startsWith('redirect loop detected'),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
+ expect((screen.ex as GoException).message, startsWith('redirect loop detected'));
});
- testWidgets('top-level redirect chain loop to initial location', (
- WidgetTester tester,
- ) async {
+ testWidgets('top-level redirect chain loop to initial location', (WidgetTester tester) async {
// Redirect loop returning to initial location: / -> /a -> /
await createRouter(
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
tester,
@@ -213,42 +183,31 @@
_ => null,
};
},
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
- expect(
- (screen.ex as GoException).message,
- startsWith('redirect loop detected'),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
+ expect((screen.ex as GoException).message, startsWith('redirect loop detected'));
});
- testWidgets('top-level redirect chain into route-level redirect', (
- WidgetTester tester,
- ) async {
+ testWidgets('top-level redirect chain into route-level redirect', (WidgetTester tester) async {
// Top-level: / -> /intermediate
// Route-level on /intermediate: /intermediate -> /final
final GoRouter router = await createRouter(
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/intermediate',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/final',
),
GoRoute(
path: '/final',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -260,16 +219,11 @@
},
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/final',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final');
expect(find.byType(LoginScreen), findsOneWidget);
});
- testWidgets('route-level redirect triggers top-level redirect', (
- WidgetTester tester,
- ) async {
+ testWidgets('route-level redirect triggers top-level redirect', (WidgetTester tester) async {
// Route-level on /src: /src -> /dst
// Top-level: /dst -> /final
final topRedirectLog = <String>[];
@@ -277,26 +231,22 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'src',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/dst',
),
],
),
GoRoute(
path: '/dst',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/final',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -310,10 +260,7 @@
},
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/final',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final');
expect(find.byType(LoginScreen), findsOneWidget);
// Top-level redirect was evaluated on /dst (after route-level redirect).
expect(topRedirectLog, contains('/dst'));
@@ -328,13 +275,11 @@
<RouteBase>[
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(),
),
],
tester,
@@ -347,42 +292,33 @@
},
);
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/login',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login');
expect(find.byType(LoginScreen), findsOneWidget);
// Redirect is called twice: once for /, once for /login.
expect(callCount, 2);
});
- testWidgets('top-level redirect chain respects redirect limit', (
- WidgetTester tester,
- ) async {
+ testWidgets('top-level redirect chain respects redirect limit', (WidgetTester tester) async {
// Endless chain: /0 -> /1 -> /2 -> ... with a low limit.
await createRouter(
<RouteBase>[
for (int i = 0; i <= 20; i++)
GoRoute(
path: '/$i',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
tester,
initialLocation: '/0',
redirect: (BuildContext context, GoRouterState state) {
- final RegExpMatch? match = RegExp(
- r'^/(\d+)$',
- ).firstMatch(state.matchedLocation);
+ final RegExpMatch? match = RegExp(r'^/(\d+)$').firstMatch(state.matchedLocation);
if (match != null) {
final int current = int.parse(match.group(1)!);
return '/${current + 1}';
}
return null;
},
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
expect(find.byType(TestErrorScreen), findsOneWidget);
@@ -397,18 +333,15 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -427,53 +360,43 @@
expect(find.byType(LoginScreen), findsOneWidget);
});
- testWidgets(
- 'top-level redirect chain fails when exceeding redirect limit',
- (WidgetTester tester) async {
- // Chain of 2 redirects: / -> /a -> /b. With limit=1, the second
- // redirect exceeds the limit and should error.
- await createRouter(
- <RouteBase>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
- ),
- GoRoute(
- path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
- ),
- GoRoute(
- path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
- ),
- ],
- tester,
- redirect: (BuildContext context, GoRouterState state) {
- return switch (state.matchedLocation) {
- '/' => '/a',
- '/a' => '/b',
- _ => null,
- };
- },
- redirectLimit: 1,
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
- );
+ testWidgets('top-level redirect chain fails when exceeding redirect limit', (
+ WidgetTester tester,
+ ) async {
+ // Chain of 2 redirects: / -> /a -> /b. With limit=1, the second
+ // redirect exceeds the limit and should error.
+ await createRouter(
+ <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
+ ),
+ GoRoute(
+ path: '/a',
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
+ ),
+ GoRoute(
+ path: '/b',
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
+ ),
+ ],
+ tester,
+ redirect: (BuildContext context, GoRouterState state) {
+ return switch (state.matchedLocation) {
+ '/' => '/a',
+ '/a' => '/b',
+ _ => null,
+ };
+ },
+ redirectLimit: 1,
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
+ );
- // 2 redirects with limit=1 should error.
- expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
- expect(
- (screen.ex as GoException).message,
- startsWith('too many redirects'),
- );
- },
- );
+ // 2 redirects with limit=1 should error.
+ expect(find.byType(TestErrorScreen), findsOneWidget);
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
+ expect((screen.ex as GoException).message, startsWith('too many redirects'));
+ });
testWidgets('top-level and route-level redirects share redirect limit', (
WidgetTester tester,
@@ -486,25 +409,21 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/b',
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/c',
),
GoRoute(
path: '/c',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -515,41 +434,30 @@
return null;
},
redirectLimit: 2,
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
// Combined chain of 3 redirects exceeds the shared limit of 2.
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
- expect(
- (screen.ex as GoException).message,
- startsWith('too many redirects'),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
+ expect((screen.ex as GoException).message, startsWith('too many redirects'));
});
- testWidgets('async top-level redirect chain loop detection', (
- WidgetTester tester,
- ) async {
+ testWidgets('async top-level redirect chain loop detection', (WidgetTester tester) async {
// Async redirect loop: / -> /a -> /b -> /a (loop)
await createRouter(
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
],
tester,
@@ -562,25 +470,17 @@
_ => null,
};
},
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
);
await tester.pumpAndSettle();
expect(find.byType(TestErrorScreen), findsOneWidget);
- final TestErrorScreen screen = tester.widget<TestErrorScreen>(
- find.byType(TestErrorScreen),
- );
- expect(
- (screen.ex as GoException).message,
- startsWith('redirect loop detected'),
- );
+ final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen));
+ expect((screen.ex as GoException).message, startsWith('redirect loop detected'));
});
- testWidgets('async top-level redirect into route-level redirect', (
- WidgetTester tester,
- ) async {
+ testWidgets('async top-level redirect into route-level redirect', (WidgetTester tester) async {
// Async top-level: / -> /mid (async)
// Route-level on /mid: /mid -> /final (sync)
// Exercises the async boundary between top-level and route-level
@@ -589,19 +489,16 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/mid',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/final',
),
GoRoute(
path: '/final',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -616,10 +513,7 @@
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/final',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final');
expect(find.byType(LoginScreen), findsOneWidget);
});
@@ -632,13 +526,11 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'src',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) async {
await Future<void>.delayed(Duration.zero);
return '/dst';
@@ -648,13 +540,11 @@
),
GoRoute(
path: '/dst',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/final',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -669,10 +559,7 @@
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/final',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final');
expect(find.byType(LoginScreen), findsOneWidget);
});
@@ -685,26 +572,22 @@
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'src',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
redirect: (BuildContext context, GoRouterState state) => '/dst',
),
],
),
GoRoute(
path: '/dst',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/final',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
@@ -720,139 +603,122 @@
await tester.pumpAndSettle();
- expect(
- router.routerDelegate.currentConfiguration.uri.toString(),
- '/final',
- );
+ expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final');
expect(find.byType(LoginScreen), findsOneWidget);
});
- testWidgets(
- 'context disposal during async top-level redirect does not crash',
- (WidgetTester tester) async {
- // Simulate context disposal while an async top-level redirect is
- // in flight. The router should handle this gracefully — not navigate
- // to /target after the context is unmounted.
- final redirectStarted = Completer<void>();
- final proceedRedirect = Completer<void>();
+ testWidgets('context disposal during async top-level redirect does not crash', (
+ WidgetTester tester,
+ ) async {
+ // Simulate context disposal while an async top-level redirect is
+ // in flight. The router should handle this gracefully — not navigate
+ // to /target after the context is unmounted.
+ final redirectStarted = Completer<void>();
+ final proceedRedirect = Completer<void>();
- final router = GoRouter(
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
- ),
- GoRoute(
- path: '/target',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
- ),
- ],
- redirect: (BuildContext context, GoRouterState state) async {
- if (state.matchedLocation == '/') {
+ final router = GoRouter(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
+ ),
+ GoRoute(
+ path: '/target',
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
+ ),
+ ],
+ redirect: (BuildContext context, GoRouterState state) async {
+ if (state.matchedLocation == '/') {
+ redirectStarted.complete();
+ await proceedRedirect.future;
+ return '/target';
+ }
+ return null;
+ },
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
+ );
+ addTearDown(router.dispose);
+
+ // Mount the router.
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pump();
+
+ // Wait for the redirect to start.
+ await redirectStarted.future;
+
+ // Unmount the MaterialApp.router, which disposes the router context.
+ await tester.pumpWidget(const SizedBox.shrink());
+
+ // Let the redirect complete after context is unmounted.
+ proceedRedirect.complete();
+ await tester.pumpAndSettle();
+
+ // The router should NOT have navigated to /target.
+ expect(find.byType(LoginScreen), findsNothing);
+ });
+
+ testWidgets('context disposal during async route-level redirect does not crash', (
+ WidgetTester tester,
+ ) async {
+ // Same as above but for route-level async redirects.
+ final redirectStarted = Completer<void>();
+ final proceedRedirect = Completer<void>();
+
+ final router = GoRouter(
+ routes: <RouteBase>[
+ GoRoute(
+ path: '/',
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
+ redirect: (BuildContext context, GoRouterState state) async {
redirectStarted.complete();
await proceedRedirect.future;
return '/target';
- }
- return null;
- },
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
- );
- addTearDown(router.dispose);
+ },
+ ),
+ GoRoute(
+ path: '/target',
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
+ ),
+ ],
+ errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!),
+ );
+ addTearDown(router.dispose);
- // Mount the router.
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pump();
+ await tester.pumpWidget(MaterialApp.router(routerConfig: router));
+ await tester.pump();
- // Wait for the redirect to start.
- await redirectStarted.future;
+ await redirectStarted.future;
- // Unmount the MaterialApp.router, which disposes the router context.
- await tester.pumpWidget(const SizedBox.shrink());
+ // Unmount the MaterialApp.router.
+ await tester.pumpWidget(const SizedBox.shrink());
- // Let the redirect complete after context is unmounted.
- proceedRedirect.complete();
- await tester.pumpAndSettle();
+ // Let the redirect complete after context is unmounted.
+ proceedRedirect.complete();
+ await tester.pumpAndSettle();
- // The router should NOT have navigated to /target.
- expect(find.byType(LoginScreen), findsNothing);
- },
- );
+ // The router should NOT have navigated to /target.
+ expect(find.byType(LoginScreen), findsNothing);
+ });
- testWidgets(
- 'context disposal during async route-level redirect does not crash',
- (WidgetTester tester) async {
- // Same as above but for route-level async redirects.
- final redirectStarted = Completer<void>();
- final proceedRedirect = Completer<void>();
-
- final router = GoRouter(
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
- redirect: (BuildContext context, GoRouterState state) async {
- redirectStarted.complete();
- await proceedRedirect.future;
- return '/target';
- },
- ),
- GoRoute(
- path: '/target',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
- ),
- ],
- errorBuilder: (BuildContext context, GoRouterState state) =>
- TestErrorScreen(state.error!),
- );
- addTearDown(router.dispose);
-
- await tester.pumpWidget(MaterialApp.router(routerConfig: router));
- await tester.pump();
-
- await redirectStarted.future;
-
- // Unmount the MaterialApp.router.
- await tester.pumpWidget(const SizedBox.shrink());
-
- // Let the redirect complete after context is unmounted.
- proceedRedirect.complete();
- await tester.pumpAndSettle();
-
- // The router should NOT have navigated to /target.
- expect(find.byType(LoginScreen), findsNothing);
- },
- );
-
- testWidgets('top-level redirect chain works with router.go()', (
- WidgetTester tester,
- ) async {
+ testWidgets('top-level redirect chain works with router.go()', (WidgetTester tester) async {
// Start at /, no redirect from /. Navigate to /a which chains to /c.
final GoRouter router = await createRouter(
<RouteBase>[
GoRoute(
path: '/',
- builder: (BuildContext context, GoRouterState state) =>
- const HomeScreen(),
+ builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
),
GoRoute(
path: '/a',
- builder: (BuildContext context, GoRouterState state) =>
- const DummyScreen(),
+ builder: (BuildContext context, GoRouterState state) => const DummyScreen(),
),
GoRoute(
path: '/b',
- builder: (BuildContext context, GoRouterState state) =>
- const Page1Screen(),
+ builder: (BuildContext context, GoRouterState state) => const Page1Screen(),
),
GoRoute(
path: '/c',
- builder: (BuildContext context, GoRouterState state) =>
- const LoginScreen(),
+ builder: (BuildContext context, GoRouterState state) => const LoginScreen(),
),
],
tester,
diff --git a/packages/go_router/test/route_data_test.dart b/packages/go_router/test/route_data_test.dart
index 9a00890..cc3fd91 100644
--- a/packages/go_router/test/route_data_test.dart
+++ b/packages/go_router/test/route_data_test.dart
@@ -13,24 +13,21 @@
const _GoRouteDataBuild();
@override
- Widget build(BuildContext context, GoRouterState state) =>
- const SizedBox(key: Key('build'));
+ Widget build(BuildContext context, GoRouterState state) => const SizedBox(key: Key('build'));
}
class _RelativeGoRouteDataBuild extends RelativeGoRouteData {
const _RelativeGoRouteDataBuild();
@override
- Widget build(BuildContext context, GoRouterState state) =>
- const SizedBox(key: Key('build'));
+ Widget build(BuildContext context, GoRouterState state) => const SizedBox(key: Key('build'));
}
class _ShellRouteDataRedirectPage extends ShellRouteData {
const _ShellRouteDataRedirectPage();
@override
- FutureOr<String> redirect(BuildContext context, GoRouterState state) =>
- '/build-page';
+ FutureOr<String> redirect(BuildContext context, GoRouterState state) => '/build-page';
}
class _ShellRouteDataBuilder extends ShellRouteData {
@@ -73,10 +70,7 @@
final ShellRoute _shellRouteDataBuilder = ShellRouteData.$route(
factory: (GoRouterState state) => const _ShellRouteDataBuilder(),
routes: <RouteBase>[
- GoRouteData.$route(
- path: '/child',
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- ),
+ GoRouteData.$route(path: '/child', factory: (GoRouterState state) => const _GoRouteDataBuild()),
],
);
@@ -100,21 +94,17 @@
const _ShellRouteDataPageBuilder();
@override
- Page<void> pageBuilder(
- BuildContext context,
- GoRouterState state,
- Widget navigator,
- ) => MaterialPage<void>(
- child: SizedBox(key: const Key('page-builder'), child: navigator),
- );
+ Page<void> pageBuilder(BuildContext context, GoRouterState state, Widget navigator) =>
+ MaterialPage<void>(
+ child: SizedBox(key: const Key('page-builder'), child: navigator),
+ );
}
class _StatefulShellRouteDataRedirectPage extends StatefulShellRouteData {
const _StatefulShellRouteDataRedirectPage();
@override
- FutureOr<String> redirect(BuildContext context, GoRouterState state) =>
- '/build-page';
+ FutureOr<String> redirect(BuildContext context, GoRouterState state) => '/build-page';
}
final GoRoute _goRouteDataBuildPage = GoRouteData.$route(
@@ -130,10 +120,7 @@
final ShellRoute _shellRouteDataPageBuilder = ShellRouteData.$route(
factory: (GoRouterState state) => const _ShellRouteDataPageBuilder(),
routes: <RouteBase>[
- GoRouteData.$route(
- path: '/child',
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- ),
+ GoRouteData.$route(path: '/child', factory: (GoRouterState state) => const _GoRouteDataBuild()),
],
);
@@ -156,27 +143,23 @@
const _StatefulShellRouteDataBuilder();
@override
- Widget builder(
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigator,
- ) => SizedBox(key: const Key('builder'), child: navigator);
+ Widget builder(BuildContext context, GoRouterState state, StatefulNavigationShell navigator) =>
+ SizedBox(key: const Key('builder'), child: navigator);
}
-final StatefulShellRoute _statefulShellRouteDataBuilder =
- StatefulShellRouteData.$route(
- factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(),
- branches: <StatefulShellBranch>[
- StatefulShellBranchData.$branch(
- routes: <RouteBase>[
- GoRouteData.$route(
- path: '/child',
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- ),
- ],
+final StatefulShellRoute _statefulShellRouteDataBuilder = StatefulShellRouteData.$route(
+ factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(),
+ branches: <StatefulShellBranch>[
+ StatefulShellBranchData.$branch(
+ routes: <RouteBase>[
+ GoRouteData.$route(
+ path: '/child',
+ factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
- );
+ ),
+ ],
+);
class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData {
const _StatefulShellRouteDataPageBuilder();
@@ -191,36 +174,32 @@
);
}
-final StatefulShellRoute _statefulShellRouteDataPageBuilder =
- StatefulShellRouteData.$route(
- factory: (GoRouterState state) =>
- const _StatefulShellRouteDataPageBuilder(),
- branches: <StatefulShellBranch>[
- StatefulShellBranchData.$branch(
- routes: <RouteBase>[
- GoRouteData.$route(
- path: '/child',
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- ),
- ],
+final StatefulShellRoute _statefulShellRouteDataPageBuilder = StatefulShellRouteData.$route(
+ factory: (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(),
+ branches: <StatefulShellBranch>[
+ StatefulShellBranchData.$branch(
+ routes: <RouteBase>[
+ GoRouteData.$route(
+ path: '/child',
+ factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
- );
+ ),
+ ],
+);
class _GoRouteDataRedirectPage extends GoRouteData {
const _GoRouteDataRedirectPage();
@override
- FutureOr<String> redirect(BuildContext context, GoRouterState state) =>
- '/build-page';
+ FutureOr<String> redirect(BuildContext context, GoRouterState state) => '/build-page';
}
class _RelativeGoRouteDataRedirectPage extends RelativeGoRouteData {
const _RelativeGoRouteDataRedirectPage();
@override
- FutureOr<String> redirect(BuildContext context, GoRouterState state) =>
- '/build-page';
+ FutureOr<String> redirect(BuildContext context, GoRouterState state) => '/build-page';
}
final GoRoute _goRouteDataRedirect = GoRouteData.$route(
@@ -275,65 +254,52 @@
expect(find.byKey(const Key('buildPage')), findsNothing);
});
- testWidgets(
- 'It should build the page from the overridden buildPage method',
- (WidgetTester tester) async {
- final goRouter = GoRouter(
- initialLocation: '/build-page',
- 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 build a go route with the default case sensitivity',
- (WidgetTester tester) async {
- final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route(
- path: '/path',
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- );
-
- expect(routeWithDefaultCaseSensitivity.caseSensitive, true);
- },
- );
-
- testWidgets(
- 'It should build a go route with the overridden case sensitivity',
- (WidgetTester tester) async {
- final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route(
- path: '/path',
- caseSensitive: false,
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- );
-
- expect(routeWithDefaultCaseSensitivity.caseSensitive, false);
- },
- );
-
- testWidgets('It should throw because there is no code generated', (
+ testWidgets('It should build the page from the overridden buildPage method', (
WidgetTester tester,
) async {
+ final goRouter = GoRouter(initialLocation: '/build-page', 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 build a go route with the default case sensitivity', (
+ WidgetTester tester,
+ ) async {
+ final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route(
+ path: '/path',
+ factory: (GoRouterState state) => const _GoRouteDataBuild(),
+ );
+
+ expect(routeWithDefaultCaseSensitivity.caseSensitive, true);
+ });
+
+ testWidgets('It should build a go route with the overridden case sensitivity', (
+ WidgetTester tester,
+ ) async {
+ final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route(
+ path: '/path',
+ caseSensitive: false,
+ factory: (GoRouterState state) => const _GoRouteDataBuild(),
+ );
+
+ expect(routeWithDefaultCaseSensitivity.caseSensitive, false);
+ });
+
+ testWidgets('It should throw because there is no code generated', (WidgetTester tester) async {
final errors = <FlutterErrorDetails>[];
- FlutterError.onError = (FlutterErrorDetails details) =>
- errors.add(details);
+ FlutterError.onError = (FlutterErrorDetails details) => errors.add(details);
const errorText = 'Should be generated';
- Future<void> expectUnimplementedError(
- void Function(BuildContext) onTap,
- ) async {
+ Future<void> expectUnimplementedError(void Function(BuildContext) onTap) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
- builder: (BuildContext context) => GestureDetector(
- child: const Text('Tap'),
- onTap: () => onTap(context),
- ),
+ builder: (BuildContext context) =>
+ GestureDetector(child: const Text('Tap'), onTap: () => onTap(context)),
),
),
);
@@ -373,79 +339,59 @@
testWidgets('It should build the page from the overridden build method', (
WidgetTester tester,
) async {
- final goRouter = GoRouter(
- initialLocation: '/build',
- routes: _relativeRoutes,
- );
+ final goRouter = GoRouter(initialLocation: '/build', routes: _relativeRoutes);
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',
- (WidgetTester tester) async {
- final goRouter = GoRouter(
- initialLocation: '/build-page',
- routes: _relativeRoutes,
- );
- 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 build a go route with the default case sensitivity',
- (WidgetTester tester) async {
- final GoRoute routeWithDefaultCaseSensitivity =
- RelativeGoRouteData.$route(
- path: 'path',
- factory: (GoRouterState state) =>
- const _RelativeGoRouteDataBuild(),
- );
-
- expect(routeWithDefaultCaseSensitivity.caseSensitive, true);
- },
- );
-
- testWidgets(
- 'It should build a go route with the overridden case sensitivity',
- (WidgetTester tester) async {
- final GoRoute routeWithDefaultCaseSensitivity =
- RelativeGoRouteData.$route(
- path: 'path',
- caseSensitive: false,
- factory: (GoRouterState state) =>
- const _RelativeGoRouteDataBuild(),
- );
-
- expect(routeWithDefaultCaseSensitivity.caseSensitive, false);
- },
- );
-
- testWidgets('It should throw because there is no code generated', (
+ testWidgets('It should build the page from the overridden buildPage method', (
WidgetTester tester,
) async {
+ final goRouter = GoRouter(initialLocation: '/build-page', routes: _relativeRoutes);
+ 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 build a go route with the default case sensitivity', (
+ WidgetTester tester,
+ ) async {
+ final GoRoute routeWithDefaultCaseSensitivity = RelativeGoRouteData.$route(
+ path: 'path',
+ factory: (GoRouterState state) => const _RelativeGoRouteDataBuild(),
+ );
+
+ expect(routeWithDefaultCaseSensitivity.caseSensitive, true);
+ });
+
+ testWidgets('It should build a go route with the overridden case sensitivity', (
+ WidgetTester tester,
+ ) async {
+ final GoRoute routeWithDefaultCaseSensitivity = RelativeGoRouteData.$route(
+ path: 'path',
+ caseSensitive: false,
+ factory: (GoRouterState state) => const _RelativeGoRouteDataBuild(),
+ );
+
+ expect(routeWithDefaultCaseSensitivity.caseSensitive, false);
+ });
+
+ testWidgets('It should throw because there is no code generated', (WidgetTester tester) async {
final errors = <FlutterErrorDetails>[];
- FlutterError.onError = (FlutterErrorDetails details) =>
- errors.add(details);
+ FlutterError.onError = (FlutterErrorDetails details) => errors.add(details);
const errorText = 'Should be generated';
- Future<void> expectUnimplementedError(
- void Function(BuildContext) onTap,
- ) async {
+ Future<void> expectUnimplementedError(void Function(BuildContext) onTap) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
- builder: (BuildContext context) => GestureDetector(
- child: const Text('Tap'),
- onTap: () => onTap(context),
- ),
+ builder: (BuildContext context) =>
+ GestureDetector(child: const Text('Tap'), onTap: () => onTap(context)),
),
),
);
@@ -509,13 +455,11 @@
initialLocation: '/child/test',
routes: <RouteBase>[
ShellRouteData.$route(
- factory: (GoRouterState state) =>
- const _ShellRouteDataWithKey(Key('under-shell')),
+ factory: (GoRouterState state) => const _ShellRouteDataWithKey(Key('under-shell')),
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
- factory: (GoRouterState state) =>
- const _GoRouteDataBuildWithKey(Key('under')),
+ factory: (GoRouterState state) => const _GoRouteDataBuildWithKey(Key('under')),
routes: <RouteBase>[
ShellRouteData.$route(
factory: (GoRouterState state) =>
@@ -555,19 +499,18 @@
expect(find.byKey(const Key('above')), findsNothing);
});
- testWidgets(
- 'It should build the page from the overridden buildPage method',
- (WidgetTester tester) async {
- final goRouter = GoRouter(
- initialLocation: '/child',
- routes: <RouteBase>[_shellRouteDataPageBuilder],
- );
- addTearDown(goRouter.dispose);
- await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
- expect(find.byKey(const Key('builder')), findsNothing);
- expect(find.byKey(const Key('page-builder')), findsOneWidget);
- },
- );
+ testWidgets('It should build the page from the overridden buildPage method', (
+ WidgetTester tester,
+ ) async {
+ final goRouter = GoRouter(
+ initialLocation: '/child',
+ routes: <RouteBase>[_shellRouteDataPageBuilder],
+ );
+ addTearDown(goRouter.dispose);
+ await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
+ expect(find.byKey(const Key('builder')), findsNothing);
+ expect(find.byKey(const Key('page-builder')), findsOneWidget);
+ });
testWidgets('It should redirect using the overridden redirect method', (
WidgetTester tester,
@@ -597,26 +540,24 @@
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(
- initialLocation: '/child',
- routes: <RouteBase>[_statefulShellRouteDataPageBuilder],
- );
- addTearDown(goRouter.dispose);
- await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
- expect(find.byKey(const Key('builder')), findsNothing);
- expect(find.byKey(const Key('page-builder')), findsOneWidget);
- },
- );
+ testWidgets('It should build the page from the overridden buildPage method', (
+ WidgetTester tester,
+ ) async {
+ final goRouter = GoRouter(
+ initialLocation: '/child',
+ routes: <RouteBase>[_statefulShellRouteDataPageBuilder],
+ );
+ addTearDown(goRouter.dispose);
+ await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
+ expect(find.byKey(const Key('builder')), findsNothing);
+ expect(find.byKey(const Key('page-builder')), findsOneWidget);
+ });
test('Can assign parent navigator key', () {
final key = GlobalKey<NavigatorState>();
final StatefulShellRoute route = StatefulShellRouteData.$route(
parentNavigatorKey: key,
- factory: (GoRouterState state) =>
- const _StatefulShellRouteDataPageBuilder(),
+ factory: (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(),
branches: <StatefulShellBranch>[
StatefulShellBranchData.$branch(
routes: <RouteBase>[
@@ -657,43 +598,38 @@
expect(find.byKey(const Key('buildPage')), findsOneWidget);
});
- testWidgets(
- 'It should redirect using the overridden StatefulShellRoute redirect method',
- (WidgetTester tester) async {
- final goRouter = GoRouter(
- initialLocation: '/child',
- routes: <RouteBase>[
- _goRouteDataBuildPage,
- StatefulShellRouteData.$route(
- factory: (GoRouterState state) =>
- const _StatefulShellRouteDataRedirectPage(),
- branches: <StatefulShellBranch>[
- StatefulShellBranchData.$branch(
- routes: <GoRoute>[
- GoRouteData.$route(
- path: '/child',
- factory: (GoRouterState state) => const _GoRouteDataBuild(),
- ),
- ],
- ),
- ],
- ),
- ],
- );
- 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', (
+ WidgetTester tester,
+ ) async {
+ final goRouter = GoRouter(
+ initialLocation: '/child',
+ routes: <RouteBase>[
+ _goRouteDataBuildPage,
+ StatefulShellRouteData.$route(
+ factory: (GoRouterState state) => const _StatefulShellRouteDataRedirectPage(),
+ branches: <StatefulShellBranch>[
+ StatefulShellBranchData.$branch(
+ routes: <GoRoute>[
+ GoRouteData.$route(
+ path: '/child',
+ factory: (GoRouterState state) => const _GoRouteDataBuild(),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ );
+ 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(
- initialLocation: '/redirect-with-state',
- routes: _routes,
- );
+ final 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);
@@ -714,11 +650,7 @@
name: 'name',
caseSensitive: false,
routes: <TypedRoute<RouteData>>[
- TypedGoRoute<GoRouteData>(
- path: 'sub-path',
- name: 'subName',
- caseSensitive: false,
- ),
+ TypedGoRoute<GoRouteData>(path: 'sub-path', name: 'subName', caseSensitive: false),
],
);
@@ -729,38 +661,21 @@
expect(
typedGoRoute.routes.single,
isA<TypedGoRoute<GoRouteData>>()
- .having(
- (TypedGoRoute<GoRouteData> route) => route.path,
- 'path',
- 'sub-path',
- )
- .having(
- (TypedGoRoute<GoRouteData> route) => route.name,
- 'name',
- 'subName',
- )
- .having(
- (TypedGoRoute<GoRouteData> route) => route.caseSensitive,
- 'caseSensitive',
- false,
- ),
+ .having((TypedGoRoute<GoRouteData> route) => route.path, 'path', 'sub-path')
+ .having((TypedGoRoute<GoRouteData> route) => route.name, 'name', 'subName')
+ .having((TypedGoRoute<GoRouteData> route) => route.caseSensitive, 'caseSensitive', false),
);
});
test('CustomParameterCodec with required parameters', () {
- const customParameterCodec = CustomParameterCodec(
- encode: toBase64,
- decode: fromBase64,
- );
+ const customParameterCodec = CustomParameterCodec(encode: toBase64, decode: fromBase64);
expect(customParameterCodec.encode, toBase64);
expect(customParameterCodec.decode, fromBase64);
});
test('TypedRelativeGoRoute with default parameters', () {
- const typedGoRoute = TypedRelativeGoRoute<RelativeGoRouteData>(
- path: 'path',
- );
+ const typedGoRoute = TypedRelativeGoRoute<RelativeGoRouteData>(path: 'path');
expect(typedGoRoute.path, 'path');
expect(typedGoRoute.caseSensitive, true);
@@ -772,10 +687,7 @@
path: 'path',
caseSensitive: false,
routes: <TypedRoute<RouteData>>[
- TypedRelativeGoRoute<RelativeGoRouteData>(
- path: 'sub-path',
- caseSensitive: false,
- ),
+ TypedRelativeGoRoute<RelativeGoRouteData>(path: 'sub-path', caseSensitive: false),
],
);
@@ -791,8 +703,7 @@
'sub-path',
)
.having(
- (TypedRelativeGoRoute<RelativeGoRouteData> route) =>
- route.caseSensitive,
+ (TypedRelativeGoRoute<RelativeGoRouteData> route) => route.caseSensitive,
'caseSensitive',
false,
),
@@ -800,9 +711,7 @@
});
test('TypedQueryParameter stores the name', () {
- const TypedQueryParameter<dynamic> parameter = TypedQueryParameter(
- name: 'customName',
- );
+ const TypedQueryParameter<dynamic> parameter = TypedQueryParameter(name: 'customName');
expect(parameter.name, 'customName');
});
diff --git a/packages/go_router/test/routing_config_test.dart b/packages/go_router/test/routing_config_test.dart
index 762526a..5ddcbfa 100644
--- a/packages/go_router/test/routing_config_test.dart
+++ b/packages/go_router/test/routing_config_test.dart
@@ -13,9 +13,7 @@
testWidgets('routing config works', (WidgetTester tester) async {
final config = ValueNotifier<RoutingConfig>(
RoutingConfig(
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('home')),
- ],
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('home'))],
redirect: (_, __) => '/',
),
);
@@ -28,14 +26,10 @@
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 config = ValueNotifier<RoutingConfig>(
RoutingConfig(
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('home')),
- ],
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('home'))],
),
);
addTearDown(config.dispose);
@@ -43,22 +37,16 @@
expect(find.text('home'), findsOneWidget);
config.value = RoutingConfig(
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('home1')),
- ],
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('home1'))],
);
await tester.pumpAndSettle();
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 config = ValueNotifier<RoutingConfig>(
RoutingConfig(
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('home')),
- ],
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('home'))],
),
);
addTearDown(config.dispose);
@@ -83,9 +71,7 @@
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 config = ValueNotifier<RoutingConfig>(
RoutingConfig(
routes: <RouteBase>[
@@ -107,17 +93,13 @@
expect(find.text('/abc'), findsOneWidget);
config.value = RoutingConfig(
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('home')),
- ],
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('home'))],
);
await tester.pumpAndSettle();
expect(find.text('error'), findsOneWidget);
});
- testWidgets('routing config works after routing changes case 3', (
- WidgetTester tester,
- ) async {
+ testWidgets('routing config works after routing changes case 3', (WidgetTester tester) async {
final key = GlobalKey<_StatefulTestState>(debugLabel: 'testState');
final rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
@@ -126,8 +108,7 @@
routes: <RouteBase>[
GoRoute(
path: '/',
- builder: (_, __) =>
- StatefulTest(key: key, child: const Text('home')),
+ builder: (_, __) => StatefulTest(key: key, child: const Text('home')),
),
],
),
@@ -169,11 +150,8 @@
routes: <RouteBase>[
ShellRoute(
navigatorKey: shellNavigatorKey,
- routes: <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('home')),
- ],
- builder: (_, __, Widget widget) =>
- StatefulTest(key: key, child: widget),
+ routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => const Text('home'))],
+ builder: (_, __, Widget widget) => StatefulTest(key: key, child: widget),
),
],
),
@@ -196,8 +174,7 @@
GoRoute(path: '/', builder: (_, __) => const Text('home')),
GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')),
],
- builder: (_, __, Widget widget) =>
- StatefulTest(key: key, child: widget),
+ builder: (_, __, Widget widget) => StatefulTest(key: key, child: widget),
),
],
);
@@ -207,18 +184,12 @@
},
);
- testWidgets('routing config works with named route', (
- WidgetTester tester,
- ) async {
+ testWidgets('routing config works with named route', (WidgetTester tester) async {
final config = ValueNotifier<RoutingConfig>(
RoutingConfig(
routes: <RouteBase>[
GoRoute(path: '/', builder: (_, __) => const Text('home')),
- GoRoute(
- path: '/abc',
- name: 'abc',
- builder: (_, __) => const Text('/abc'),
- ),
+ GoRoute(path: '/abc', name: 'abc', builder: (_, __) => const Text('/abc')),
],
),
);
@@ -237,16 +208,8 @@
config.value = RoutingConfig(
routes: <RouteBase>[
- GoRoute(
- path: '/',
- name: 'home',
- builder: (_, __) => const Text('home'),
- ),
- GoRoute(
- path: '/abc',
- name: 'def',
- builder: (_, __) => const Text('def'),
- ),
+ GoRoute(path: '/', name: 'home', builder: (_, __) => const Text('home')),
+ GoRoute(path: '/abc', name: 'def', builder: (_, __) => const Text('def')),
],
);
await tester.pumpAndSettle();
diff --git a/packages/go_router/test/shell_route_observers_test.dart b/packages/go_router/test/shell_route_observers_test.dart
index 8d95373..bf09bce 100644
--- a/packages/go_router/test/shell_route_observers_test.dart
+++ b/packages/go_router/test/shell_route_observers_test.dart
@@ -28,50 +28,42 @@
expect(shell.observers!.length, 1);
});
- testWidgets(
- 'GoRouter observers should be notified when navigating within ShellRoute',
- (WidgetTester tester) async {
- final observer = MockObserver();
+ testWidgets('GoRouter observers should be notified when navigating within ShellRoute', (
+ WidgetTester tester,
+ ) async {
+ final observer = MockObserver();
- final root = GlobalKey<NavigatorState>(debugLabel: 'root');
- await createRouter(
- <RouteBase>[
- GoRoute(path: '/', builder: (_, __) => const Text('Home')),
- ShellRoute(
- builder: (_, __, Widget child) => child,
- routes: <RouteBase>[
- GoRoute(path: '/test1', builder: (_, __) => const Text('Test1')),
- ],
- ),
- StatefulShellRoute.indexedStack(
- builder: (_, __, Widget child) => child,
- branches: <StatefulShellBranch>[
- StatefulShellBranch(
- routes: <RouteBase>[
- GoRoute(
- path: '/test2',
- builder: (_, __) => const Text('Test2'),
- ),
- ],
- ),
- ],
- ),
- ],
- tester,
- navigatorKey: root,
- observers: <NavigatorObserver>[observer],
- );
- await tester.pumpAndSettle();
+ final root = GlobalKey<NavigatorState>(debugLabel: 'root');
+ await createRouter(
+ <RouteBase>[
+ GoRoute(path: '/', builder: (_, __) => const Text('Home')),
+ ShellRoute(
+ builder: (_, __, Widget child) => child,
+ routes: <RouteBase>[GoRoute(path: '/test1', builder: (_, __) => const Text('Test1'))],
+ ),
+ StatefulShellRoute.indexedStack(
+ builder: (_, __, Widget child) => child,
+ branches: <StatefulShellBranch>[
+ StatefulShellBranch(
+ routes: <RouteBase>[GoRoute(path: '/test2', builder: (_, __) => const Text('Test2'))],
+ ),
+ ],
+ ),
+ ],
+ tester,
+ navigatorKey: root,
+ observers: <NavigatorObserver>[observer],
+ );
+ await tester.pumpAndSettle();
- root.currentContext!.push('/test1');
- await tester.pumpAndSettle();
- expect(observer.getCallCount('/test1'), 1);
+ root.currentContext!.push('/test1');
+ await tester.pumpAndSettle();
+ expect(observer.getCallCount('/test1'), 1);
- root.currentContext!.push('/test2');
- await tester.pumpAndSettle();
- expect(observer.getCallCount('/test2'), 1);
- },
- );
+ root.currentContext!.push('/test2');
+ await tester.pumpAndSettle();
+ expect(observer.getCallCount('/test2'), 1);
+ });
}
class MockObserver extends NavigatorObserver {
diff --git a/packages/go_router/test/shell_route_system_back_test.dart b/packages/go_router/test/shell_route_system_back_test.dart
index 3d7ef89..ac2fca2 100644
--- a/packages/go_router/test/shell_route_system_back_test.dart
+++ b/packages/go_router/test/shell_route_system_back_test.dart
@@ -138,9 +138,7 @@
GoRoute(
path: 'comment',
builder: (BuildContext context, GoRouterState state) {
- return Scaffold(
- appBar: AppBar(title: const Text('Comment')),
- );
+ return Scaffold(appBar: AppBar(title: const Text('Comment')));
},
),
],
diff --git a/packages/go_router/test/stateful_shell_route_system_back_test.dart b/packages/go_router/test/stateful_shell_route_system_back_test.dart
index 834af97..7e66d58 100644
--- a/packages/go_router/test/stateful_shell_route_system_back_test.dart
+++ b/packages/go_router/test/stateful_shell_route_system_back_test.dart
@@ -147,9 +147,7 @@
GoRoute(
path: 'comment',
builder: (BuildContext context, GoRouterState state) {
- return Scaffold(
- appBar: AppBar(title: const Text('Comment')),
- );
+ return Scaffold(appBar: AppBar(title: const Text('Comment')));
},
),
],
diff --git a/packages/go_router/test/test_helpers.dart b/packages/go_router/test/test_helpers.dart
index 6a0b849..8851ad8 100644
--- a/packages/go_router/test/test_helpers.dart
+++ b/packages/go_router/test/test_helpers.dart
@@ -17,27 +17,18 @@
initialLocation: '/',
routes: <GoRoute>[
GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()),
- GoRoute(
- path: '/error',
- builder: (_, __) => TestErrorScreen(TestFailure('Exception')),
- ),
+ GoRoute(path: '/error', builder: (_, __) => TestErrorScreen(TestFailure('Exception'))),
],
);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
return goRouter;
}
-Widget fakeNavigationBuilder(
- BuildContext context,
- GoRouterState state,
- Widget child,
-) => child;
+Widget fakeNavigationBuilder(BuildContext context, GoRouterState state, Widget child) => child;
class GoRouterNamedLocationSpy extends GoRouter {
GoRouterNamedLocationSpy({required List<RouteBase> routes})
- : super.routingConfig(
- routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)),
- );
+ : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)));
String? name;
Map<String, String>? pathParameters;
@@ -61,9 +52,7 @@
class GoRouterGoSpy extends GoRouter {
GoRouterGoSpy({required List<RouteBase> routes})
- : super.routingConfig(
- routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)),
- );
+ : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)));
String? myLocation;
Object? extra;
@@ -77,9 +66,7 @@
class GoRouterGoNamedSpy extends GoRouter {
GoRouterGoNamedSpy({required List<RouteBase> routes})
- : super.routingConfig(
- routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)),
- );
+ : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)));
String? name;
Map<String, String>? pathParameters;
@@ -105,9 +92,7 @@
class GoRouterPushSpy extends GoRouter {
GoRouterPushSpy({required List<RouteBase> routes})
- : super.routingConfig(
- routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)),
- );
+ : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)));
String? myLocation;
Object? extra;
@@ -122,9 +107,7 @@
class GoRouterPushNamedSpy extends GoRouter {
GoRouterPushNamedSpy({required List<RouteBase> routes})
- : super.routingConfig(
- routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)),
- );
+ : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)));
String? name;
Map<String, String>? pathParameters;
@@ -148,9 +131,7 @@
class GoRouterPopSpy extends GoRouter {
GoRouterPopSpy({required List<RouteBase> routes})
- : super.routingConfig(
- routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)),
- );
+ : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)));
bool popped = false;
Object? poppedResult;
@@ -196,9 +177,7 @@
addTearDown(goRouter.dispose);
await tester.pumpWidget(
MaterialApp.router(
- restorationScopeId: restorationScopeId != null
- ? '$restorationScopeId-root'
- : null,
+ restorationScopeId: restorationScopeId != null ? '$restorationScopeId-root' : null,
routerConfig: goRouter,
),
);
@@ -231,9 +210,7 @@
addTearDown(goRouter.dispose);
await tester.pumpWidget(
MaterialApp.router(
- restorationScopeId: restorationScopeId != null
- ? '$restorationScopeId-root'
- : null,
+ restorationScopeId: restorationScopeId != null ? '$restorationScopeId-root' : null,
routerConfig: goRouter,
),
);
@@ -282,10 +259,7 @@
}
class DummyScreen extends StatelessWidget {
- const DummyScreen({
- this.queryParametersAll = const <String, dynamic>{},
- super.key,
- });
+ const DummyScreen({this.queryParametersAll = const <String, dynamic>{}, super.key});
final Map<String, dynamic> queryParametersAll;
@@ -324,8 +298,7 @@
State<StatefulWidget> createState() => DummyRestorableStatefulWidgetState();
}
-class DummyRestorableStatefulWidgetState
- extends State<DummyRestorableStatefulWidget>
+class DummyRestorableStatefulWidgetState extends State<DummyRestorableStatefulWidget>
with RestorationMixin {
final RestorableInt _counter = RestorableInt(0);
@@ -356,9 +329,7 @@
}
Future<void> simulateAndroidBackButton(WidgetTester tester) async {
- final ByteData message = const JSONMethodCodec().encodeMethodCall(
- const MethodCall('popRoute'),
- );
+ final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/navigation',
message,
@@ -370,19 +341,12 @@
await tester.dragFrom(const Offset(0, 300), const Offset(500, 300));
}
-GoRouterPageBuilder createPageBuilder({
- String? restorationId,
- required Widget child,
-}) =>
+GoRouterPageBuilder createPageBuilder({String? restorationId, required Widget child}) =>
(BuildContext context, GoRouterState state) =>
MaterialPage<dynamic>(restorationId: restorationId, child: child);
StatefulShellRouteBuilder mockStackedShellBuilder =
- (
- BuildContext context,
- GoRouterState state,
- StatefulNavigationShell navigationShell,
- ) {
+ (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
return navigationShell;
};
@@ -411,11 +375,7 @@
}) {
return RouteConfiguration(
ConstantRoutingConfig(
- RoutingConfig(
- routes: routes,
- redirect: topRedirect,
- redirectLimit: redirectLimit,
- ),
+ RoutingConfig(routes: routes, redirect: topRedirect, redirectLimit: redirectLimit),
),
navigatorKey: navigatorKey,
);
diff --git a/packages/go_router/tool/run_tests.dart b/packages/go_router/tool/run_tests.dart
index 0c1e0f9..ca09bed 100644
--- a/packages/go_router/tool/run_tests.dart
+++ b/packages/go_router/tool/run_tests.dart
@@ -19,9 +19,7 @@
// that references `go_router`, and running `dart fix --compare-to-golden`
// on the temp directory.
Future<void> main(List<String> args) async {
- final Directory goRouterPackageRoot = File.fromUri(
- Platform.script,
- ).parent.parent;
+ final Directory goRouterPackageRoot = File.fromUri(Platform.script).parent.parent;
final Directory testTempDir = await Directory.systemTemp.createTemp();
@@ -34,10 +32,7 @@
// Copy the test_fixes folder to the temporary testFixesTargetDir.
//
// This also creates the proper pubspec.yaml in the temp directory.
- await _prepareTemplate(
- packageRoot: goRouterPackageRoot,
- testTempDir: testTempDir,
- );
+ await _prepareTemplate(packageRoot: goRouterPackageRoot, testTempDir: testTempDir);
// Run dart pub get in the temp directory to set it up.
final int pubGetStatusCode = await _runProcess('dart', <String>[
@@ -98,11 +93,7 @@
return process;
}
-Future<int> _runProcess(
- String command,
- List<String> arguments, {
- String? workingDirectory,
-}) async {
+Future<int> _runProcess(String command, List<String> arguments, {String? workingDirectory}) async {
final Process process = await _streamOutput(
Process.start(command, arguments, workingDirectory: workingDirectory),
);
diff --git a/packages/go_router_builder/example/analysis_options.yaml b/packages/go_router_builder/example/analysis_options.yaml
new file mode 100644
index 0000000..fbc265c
--- /dev/null
+++ b/packages/go_router_builder/example/analysis_options.yaml
@@ -0,0 +1,6 @@
+# This example's build output is used as a golden reference for the builder
+# output. Since we want the output to default to what the default formatter
+# would use, rather than the custom line length used in this repository, use
+# 80 for this example so it matches.
+formatter:
+ page_width: 80
diff --git a/packages/go_router_builder/lib/src/go_router_generator.dart b/packages/go_router_builder/lib/src/go_router_generator.dart
index 80fb3ab..9f0f841 100644
--- a/packages/go_router_builder/lib/src/go_router_generator.dart
+++ b/packages/go_router_builder/lib/src/go_router_generator.dart
@@ -28,9 +28,7 @@
const GoRouterGenerator();
TypeChecker get _typeChecker => TypeChecker.any(
- _annotations.keys.map(
- (String annotation) => TypeChecker.fromUrl('$_routeDataUrl#$annotation'),
- ),
+ _annotations.keys.map((String annotation) => TypeChecker.fromUrl('$_routeDataUrl#$annotation')),
);
@override
@@ -58,14 +56,8 @@
///
/// This public method is for testing purposes and should not be called
/// directly.
- void generateForAnnotation(
- LibraryReader library,
- Set<String> values,
- Set<String> getters,
- ) {
- for (final AnnotatedElement annotatedElement in library.annotatedWith(
- _typeChecker,
- )) {
+ void generateForAnnotation(LibraryReader library, Set<String> values, Set<String> getters) {
+ for (final AnnotatedElement annotatedElement in library.annotatedWith(_typeChecker)) {
final InfoIterable generatedValue = _generateForAnnotatedElement(
annotatedElement.element,
annotatedElement.annotation,
@@ -75,17 +67,11 @@
}
}
- InfoIterable _generateForAnnotatedElement(
- Element element,
- ConstantReader annotation,
- ) {
+ InfoIterable _generateForAnnotatedElement(Element element, ConstantReader annotation) {
final String typedAnnotation = withoutNullability(
annotation.objectValue.type!.getDisplayString(),
);
- final String type = typedAnnotation.substring(
- 0,
- typedAnnotation.indexOf('<'),
- );
+ final String type = typedAnnotation.substring(0, typedAnnotation.indexOf('<'));
final String routeData = _annotations[type]!;
if (element is! ClassElement) {
throw InvalidGenerationSourceError(
@@ -95,9 +81,7 @@
}
final dataChecker = TypeChecker.fromUrl('$_routeDataUrl#$routeData');
- if (!element.allSupertypes.any(
- (InterfaceType element) => dataChecker.isExactlyType(element),
- )) {
+ if (!element.allSupertypes.any((InterfaceType element) => dataChecker.isExactlyType(element))) {
throw InvalidGenerationSourceError(
'The @$type annotation can only be applied to classes that '
'extend or implement `$routeData`.',
@@ -105,9 +89,6 @@
);
}
- return RouteBaseConfig.fromAnnotation(
- annotation,
- element,
- ).generateMembers();
+ return RouteBaseConfig.fromAnnotation(annotation, element).generateMembers();
}
}
diff --git a/packages/go_router_builder/lib/src/path_utils.dart b/packages/go_router_builder/lib/src/path_utils.dart
index 607f9fa..e495ce7 100644
--- a/packages/go_router_builder/lib/src/path_utils.dart
+++ b/packages/go_router_builder/lib/src/path_utils.dart
@@ -15,8 +15,7 @@
/// final pathParameters = pathParametersFromPattern(pattern); // {'id', 'bookId'}
/// ```
Set<String> pathParametersFromPattern(String pattern) => <String>{
- for (final RegExpMatch match in _parameterRegExp.allMatches(pattern))
- match[1]!,
+ for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) match[1]!,
};
/// Reconstructs the full path from a [pattern] and path parameters.
diff --git a/packages/go_router_builder/lib/src/route_config.dart b/packages/go_router_builder/lib/src/route_config.dart
index 4ee1e96..7de0c2d 100644
--- a/packages/go_router_builder/lib/src/route_config.dart
+++ b/packages/go_router_builder/lib/src/route_config.dart
@@ -83,8 +83,7 @@
'${restorationScopeId == null ? '' : 'restorationScopeId: $restorationScopeId,'}';
@override
- String get factorConstructorParameters =>
- 'factory: $_extensionName._fromState,';
+ String get factorConstructorParameters => 'factory: $_extensionName._fromState,';
@override
String get routeDataClassName => 'ShellRouteData';
@@ -128,8 +127,7 @@
'${navigatorContainerBuilder == null ? '' : 'navigatorContainerBuilder: $navigatorContainerBuilder,'}';
@override
- String get factorConstructorParameters =>
- 'factory: $_extensionName._fromState,';
+ String get factorConstructorParameters => 'factory: $_extensionName._fromState,';
@override
String get routeDataClassName => 'StatefulShellRouteData';
@@ -190,9 +188,7 @@
mixin _GoRouteMixin on RouteBaseConfig {
String get _basePathForLocation;
- late final Set<String> _pathParams = pathParametersFromPattern(
- _basePathForLocation,
- );
+ late final Set<String> _pathParams = pathParametersFromPattern(_basePathForLocation);
// construct path bits using parent bits
// if there are any queryParam objects, add in the `queryParam` bits
@@ -226,17 +222,13 @@
/// The definition of the mixin to be generated.
String get _mixinDefinition;
- FormalParameterElement? get _extraParam =>
- _ctor.formalParameters.singleWhereOrNull(
- (FormalParameterElement element) => element.isExtraField,
- );
+ FormalParameterElement? get _extraParam => _ctor.formalParameters.singleWhereOrNull(
+ (FormalParameterElement element) => element.isExtraField,
+ );
String get _fromStateConstructor {
final buffer = StringBuffer('=>');
- if (_ctor.isConst &&
- _ctorParams.isEmpty &&
- _ctorQueryParams.isEmpty &&
- _extraParam == null) {
+ if (_ctor.isConst && _ctorParams.isEmpty && _ctorQueryParams.isEmpty && _extraParam == null) {
buffer.writeln('const ');
}
@@ -254,9 +246,7 @@
}
String get _castedSelf {
- if (_pathParams.isEmpty &&
- _ctorQueryParams.isEmpty &&
- _extraParam == null) {
+ if (_pathParams.isEmpty && _ctorQueryParams.isEmpty && _extraParam == null) {
return '';
}
@@ -273,14 +263,8 @@
);
}
}
- final List<ElementAnnotation>? metadata = _fieldMetadata(
- element.displayName,
- );
- final String fromStateExpression = decodeParameter(
- element,
- _pathParams,
- metadata,
- );
+ final List<ElementAnnotation>? metadata = _fieldMetadata(element.displayName);
+ final String fromStateExpression = decodeParameter(element, _pathParams, metadata);
if (element.isPositional) {
return '$fromStateExpression,';
@@ -343,17 +327,16 @@
return buffer.toString();
}
- late final List<FormalParameterElement> _ctorParams = _ctor.formalParameters
- .where((FormalParameterElement element) {
- if (_pathParams.contains(element.displayName)) {
- return true;
- }
- return false;
- })
- .toList();
+ late final List<FormalParameterElement> _ctorParams = _ctor.formalParameters.where((
+ FormalParameterElement element,
+ ) {
+ if (_pathParams.contains(element.displayName)) {
+ return true;
+ }
+ return false;
+ }).toList();
- late final List<FormalParameterElement> _ctorQueryParams = _ctor
- .formalParameters
+ late final List<FormalParameterElement> _ctorQueryParams = _ctor.formalParameters
.where(
(FormalParameterElement element) =>
!_pathParams.contains(element.displayName) && !element.isExtraField,
@@ -364,34 +347,24 @@
final ConstructorElement? ctor = routeDataClass.unnamedConstructor;
if (ctor == null) {
- throw InvalidGenerationSourceError(
- 'Missing default constructor',
- element: routeDataClass,
- );
+ throw InvalidGenerationSourceError('Missing default constructor', element: routeDataClass);
}
return ctor;
}
@override
- Iterable<String> classDeclarations() => <String>[
- _mixinDefinition,
- ..._enumDeclarations(),
- ];
+ Iterable<String> classDeclarations() => <String>[_mixinDefinition, ..._enumDeclarations()];
/// Returns code representing the constant maps that contain the `enum` to
/// [String] mapping for each referenced enum.
Iterable<String> _enumDeclarations() {
final enumParamTypes = <InterfaceType>{};
- for (final ctorParam in <FormalParameterElement>[
- ..._ctorParams,
- ..._ctorQueryParams,
- ]) {
+ for (final ctorParam in <FormalParameterElement>[..._ctorParams, ..._ctorQueryParams]) {
DartType potentialEnumType = ctorParam.type;
if (potentialEnumType is ParameterizedType &&
(ctorParam.type as ParameterizedType).typeArguments.isNotEmpty) {
- potentialEnumType =
- (ctorParam.type as ParameterizedType).typeArguments.first;
+ potentialEnumType = (ctorParam.type as ParameterizedType).typeArguments.first;
}
if (potentialEnumType.isEnum) {
@@ -443,8 +416,7 @@
RouteBaseConfig? config = this;
while (config != null) {
if (config
- case GoRouteConfig(:final String path) ||
- RelativeGoRouteConfig(:final String path)) {
+ case GoRouteConfig(:final String path) || RelativeGoRouteConfig(:final String path)) {
pathSegments.add(path);
}
config = config.parent;
@@ -459,10 +431,9 @@
@override
String get _mixinDefinition {
final bool hasMixin =
- getNodeDeclaration<ClassDeclaration>(routeDataClass)
- ?.withClause
- ?.mixinTypes
- .any((NamedType e) => e.name.toString() == _mixinName) ??
+ getNodeDeclaration<ClassDeclaration>(
+ routeDataClass,
+ )?.withClause?.mixinTypes.any((NamedType e) => e.name.toString() == _mixinName) ??
false;
if (!hasMixin) {
@@ -534,10 +505,9 @@
@override
String get _mixinDefinition {
final bool hasMixin =
- getNodeDeclaration<ClassDeclaration>(routeDataClass)
- ?.withClause
- ?.mixinTypes
- .any((NamedType e) => e.name.toString() == _mixinName) ??
+ getNodeDeclaration<ClassDeclaration>(
+ routeDataClass,
+ )?.withClause?.mixinTypes.any((NamedType e) => e.name.toString() == _mixinName) ??
false;
if (!hasMixin) {
@@ -591,10 +561,7 @@
RouteBaseConfig._({required this.routeDataClass, required this.parent});
/// Creates a new [RouteBaseConfig] represented the annotation data in [reader].
- factory RouteBaseConfig.fromAnnotation(
- ConstantReader reader,
- InterfaceElement element,
- ) {
+ factory RouteBaseConfig.fromAnnotation(ConstantReader reader, InterfaceElement element) {
final definition = RouteBaseConfig._fromAnnotation(reader, element, null);
if (element != definition.routeDataClass) {
@@ -625,8 +592,7 @@
);
}
- final bool isRelative =
- isAncestorRelative || typeName == 'TypedRelativeGoRoute';
+ final bool isRelative = isAncestorRelative || typeName == 'TypedRelativeGoRoute';
final DartType typeParamType = type.typeArguments.single;
if (typeParamType is! InterfaceType) {
@@ -646,18 +612,12 @@
value = ShellRouteConfig._(
routeDataClass: classElement,
parent: parent,
- navigatorKey: _generateParameterGetterCode(
- classElement,
- parameterName: r'$navigatorKey',
- ),
+ navigatorKey: _generateParameterGetterCode(classElement, parameterName: r'$navigatorKey'),
parentNavigatorKey: _generateParameterGetterCode(
classElement,
parameterName: r'$parentNavigatorKey',
),
- observers: _generateParameterGetterCode(
- classElement,
- parameterName: r'$observers',
- ),
+ observers: _generateParameterGetterCode(classElement, parameterName: r'$observers'),
restorationScopeId: _generateParameterGetterCode(
classElement,
parameterName: r'$restorationScopeId',
@@ -684,10 +644,7 @@
value = StatefulShellBranchConfig._(
routeDataClass: classElement,
parent: parent,
- navigatorKey: _generateParameterGetterCode(
- classElement,
- parameterName: r'$navigatorKey',
- ),
+ navigatorKey: _generateParameterGetterCode(classElement, parameterName: r'$navigatorKey'),
restorationScopeId: _generateParameterGetterCode(
classElement,
parameterName: r'$restorationScopeId',
@@ -696,14 +653,8 @@
classElement,
parameterName: r'$initialLocation',
),
- observers: _generateParameterGetterCode(
- classElement,
- parameterName: r'$observers',
- ),
- preload: _generateParameterGetterCode(
- classElement,
- parameterName: r'$preload',
- ),
+ observers: _generateParameterGetterCode(classElement, parameterName: r'$observers'),
+ preload: _generateParameterGetterCode(classElement, parameterName: r'$preload'),
);
case 'TypedGoRoute':
final ConstantReader pathValue = reader.read('path');
@@ -782,8 +733,7 @@
final RouteBaseConfig? parent;
static String _generateChildrenGetterName(String name) {
- return (name == 'TypedStatefulShellRoute' ||
- name == 'StatefulShellRouteData')
+ return (name == 'TypedStatefulShellRoute' || name == 'StatefulShellRouteData')
? 'branches'
: 'routes';
}
@@ -797,9 +747,7 @@
if (!element.isStatic || element.displayName != parameterName) {
return false;
}
- if (parameterName.toLowerCase().contains(
- RegExp('navigatorKey | observers'),
- )) {
+ if (parameterName.toLowerCase().contains(RegExp('navigatorKey | observers'))) {
final DartType type = element.type;
if (type is! ParameterizedType) {
return false;
@@ -809,8 +757,7 @@
return false;
}
final DartType typeArgument = typeArguments.single;
- if (withoutNullability(typeArgument.getDisplayString()) !=
- 'NavigatorState') {
+ if (withoutNullability(typeArgument.getDisplayString()) != 'NavigatorState') {
return false;
}
}
@@ -836,10 +783,8 @@
}
/// Generates all of the members that correspond to `this`.
- InfoIterable generateMembers() => InfoIterable._(
- members: _generateMembers().toList(),
- routeGetterName: _routeGetterName,
- );
+ InfoIterable generateMembers() =>
+ InfoIterable._(members: _generateMembers().toList(), routeGetterName: _routeGetterName);
Iterable<String> _generateMembers() sync* {
final items = <String>[_rootDefinition()];
@@ -853,9 +798,7 @@
yield* items
.expand(
(String e) => helperNames.entries
- .where(
- (MapEntry<String, String> element) => e.contains(element.key),
- )
+ .where((MapEntry<String, String> element) => e.contains(element.key))
.map((MapEntry<String, String> e) => e.value),
)
.toSet();
@@ -897,8 +840,7 @@
''';
}
- PropertyAccessorElement? _field(String name) =>
- routeDataClass.getGetter(name);
+ PropertyAccessorElement? _field(String name) => routeDataClass.getGetter(name);
List<ElementAnnotation>? _fieldMetadata(String name) => routeDataClass.fields
.firstWhereOrNull((FieldElement element) => element.displayName == name)
diff --git a/packages/go_router_builder/lib/src/type_helpers.dart b/packages/go_router_builder/lib/src/type_helpers.dart
index 39d8f0b..2fd45cd 100644
--- a/packages/go_router_builder/lib/src/type_helpers.dart
+++ b/packages/go_router_builder/lib/src/type_helpers.dart
@@ -55,15 +55,11 @@
];
/// Checks if has a function that converts string to string, such as encode and decode.
-bool _isStringToStringFunction(
- ExecutableElement? executableElement,
- String name,
-) {
+bool _isStringToStringFunction(ExecutableElement? executableElement, String name) {
if (executableElement == null) {
return false;
}
- final List<FormalParameterElement> parameters =
- executableElement.formalParameters;
+ final List<FormalParameterElement> parameters = executableElement.formalParameters;
return parameters.length == 1 &&
parameters.first.type.isDartCoreString &&
executableElement.returnType.isDartCoreString;
@@ -98,14 +94,12 @@
if (annotatedDecoder != null) {
// If there is a custom decoder, use it directly.
- final stateValueAccess =
- 'state.${_stateValueAccess(element, pathParameters)}';
+ final stateValueAccess = 'state.${_stateValueAccess(element, pathParameters)}';
String decoded;
if (!element.type.isNullableType && !element.hasDefaultValue) {
decoded = '$annotatedDecoder($stateValueAccess)';
} else {
- decoded =
- '($stateValueAccess == null ? null : $annotatedDecoder($stateValueAccess!))';
+ decoded = '($stateValueAccess == null ? null : $annotatedDecoder($stateValueAccess!))';
}
if (element.isOptional && element.hasDefaultValue) {
@@ -165,10 +159,7 @@
/// Returns the encoded [String] value for [element], if its type is supported.
///
/// Otherwise, throws an [InvalidGenerationSourceError].
-String encodeField(
- PropertyAccessorElement element,
- List<ElementAnnotation>? metadata,
-) {
+String encodeField(PropertyAccessorElement element, List<ElementAnnotation>? metadata) {
final String? annotatedEncoder = element.encoder;
if (annotatedEncoder != null) {
final fieldAccess = '$selfFieldName.${element.displayName}';
@@ -226,10 +217,10 @@
return null;
}
- final parsedLibrary =
- session.getParsedLibraryByElement(element.library) as ParsedLibraryResult;
- final FragmentDeclarationResult? declaration = parsedLibrary
- .getFragmentDeclaration(element.firstFragment);
+ final parsedLibrary = session.getParsedLibraryByElement(element.library) as ParsedLibraryResult;
+ final FragmentDeclarationResult? declaration = parsedLibrary.getFragmentDeclaration(
+ element.firstFragment,
+ );
final AstNode? node = declaration?.node;
return node is T ? node : null;
@@ -246,10 +237,7 @@
for (final _TypeHelper helper in _helpers) {
if (helper._matchesType(param.type)) {
- return helper._compare(
- '$selfFieldName.${param.displayName}',
- param.defaultValueCode!,
- );
+ return helper._compare('$selfFieldName.${param.displayName}', param.defaultValueCode!);
}
}
@@ -261,25 +249,19 @@
}
/// Gets the name of the `const` map generated to help encode [Enum] types.
-String enumMapName(InterfaceType type) =>
- '_\$${type.element.displayName}EnumMap';
+String enumMapName(InterfaceType type) => '_\$${type.element.displayName}EnumMap';
/// Gets the name of the `const` map generated to help encode [Json] types.
String jsonMapName(InterfaceType type) => type.element.displayName;
-String _stateValueAccess(
- FormalParameterElement element,
- Set<String> pathParameters,
-) {
+String _stateValueAccess(FormalParameterElement element, Set<String> pathParameters) {
if (element.isExtraField) {
// ignore: avoid_redundant_argument_values
return 'extra as ${element.type.getDisplayString()}';
}
late String access;
- final suffix = !element.type.isNullableType && !element.hasDefaultValue
- ? '!'
- : '';
+ final suffix = !element.type.isNullableType && !element.hasDefaultValue ? '!' : '';
if (pathParameters.contains(element.displayName)) {
access = 'pathParameters[${escapeDartString(element.displayName)}]$suffix';
} else {
@@ -334,16 +316,11 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
- bool _matchesType(DartType type) => const TypeChecker.typeNamed(
- BigInt,
- inSdk: true,
- ).isAssignableFromType(type);
+ bool _matchesType(DartType type) =>
+ const TypeChecker.typeNamed(BigInt, inSdk: true).isAssignableFromType(type);
}
class _TypeHelperBool extends _TypeHelperWithHelper {
@@ -354,10 +331,7 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
bool _matchesType(DartType type) => type.isDartCoreBool;
@@ -376,16 +350,11 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
- bool _matchesType(DartType type) => const TypeChecker.typeNamed(
- DateTime,
- inSdk: true,
- ).isAssignableFromType(type);
+ bool _matchesType(DartType type) =>
+ const TypeChecker.typeNamed(DateTime, inSdk: true).isAssignableFromType(type);
}
class _TypeHelperDouble extends _TypeHelperWithHelper {
@@ -401,10 +370,7 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
bool _matchesType(DartType type) => type.isDartCoreDouble;
@@ -418,11 +384,7 @@
'${enumMapName(paramType as InterfaceType)}.$enumExtensionHelperName';
@override
- String _encode(
- String fieldName,
- DartType type,
- String? customEncoder,
- ) => _fieldWithEncoder(
+ String _encode(String fieldName, DartType type, String? customEncoder) => _fieldWithEncoder(
'${enumMapName(type as InterfaceType)}[$fieldName${type.ensureNotNull}]',
customEncoder,
);
@@ -456,8 +418,7 @@
throw NullableDefaultValueError(parameterElement);
}
- final stateValue =
- 'state.${_stateValueAccess(parameterElement, pathParameters)}';
+ final stateValue = 'state.${_stateValueAccess(parameterElement, pathParameters)}';
final String castType;
if (paramType.isNullableType || parameterElement.hasDefaultValue) {
castType = '$paramType${paramType.isNullableType ? '' : '?'}';
@@ -475,9 +436,7 @@
'.$enumExtensionHelperName($stateValue) as $castType';
}
- final String representationTypeName = withoutNullability(
- representationType.getDisplayString(),
- );
+ final String representationTypeName = withoutNullability(representationType.getDisplayString());
if (paramType.isNullableType || parameterElement.hasDefaultValue) {
return "$representationTypeName.tryParse($stateValue ?? '') as $castType";
} else {
@@ -514,18 +473,12 @@
representationType.isDartCoreNum ||
representationType.isDartCoreBool ||
representationType.isEnum ||
- const TypeChecker.typeNamed(
- BigInt,
- inSdk: true,
- ).isAssignableFromType(representationType) ||
+ const TypeChecker.typeNamed(BigInt, inSdk: true).isAssignableFromType(representationType) ||
const TypeChecker.typeNamed(
DateTime,
inSdk: true,
).isAssignableFromType(representationType) ||
- const TypeChecker.typeNamed(
- Uri,
- inSdk: true,
- ).isAssignableFromType(representationType);
+ const TypeChecker.typeNamed(Uri, inSdk: true).isAssignableFromType(representationType);
}
}
@@ -542,10 +495,7 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
bool _matchesType(DartType type) => type.isDartCoreInt;
@@ -564,10 +514,7 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
bool _matchesType(DartType type) => type.isDartCoreNum;
@@ -604,10 +551,7 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- '$fieldName${type.ensureNotNull}.toString()',
- customEncoder,
- );
+ _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder);
@override
bool _matchesType(DartType type) =>
@@ -635,15 +579,13 @@
var convertToNotNull = '';
for (final _TypeHelper helper in _helpers) {
- if (helper._matchesType(iterableType) &&
- helper is _TypeHelperWithHelper) {
+ if (helper._matchesType(iterableType) && helper is _TypeHelperWithHelper) {
if (!iterableType.isNullableType) {
convertToNotNull = '.cast<$iterableType>()';
}
entriesTypeDecoder = helper.helperName(iterableType);
if (customDecoder != null) {
- entriesTypeDecoder =
- '(e) => $entriesTypeDecoder($customDecoder(e))';
+ entriesTypeDecoder = '(e) => $entriesTypeDecoder($customDecoder(e))';
}
}
}
@@ -656,8 +598,7 @@
inSdk: true,
).isAssignableFromType(parameterElement.type)) {
iterableCaster += '.toList()';
- if (!parameterElement.type.isNullableType &&
- !parameterElement.hasDefaultValue) {
+ if (!parameterElement.type.isNullableType && !parameterElement.hasDefaultValue) {
fallBack = '?? const []';
}
} else if (const TypeChecker.typeNamed(
@@ -665,8 +606,7 @@
inSdk: true,
).isAssignableFromType(parameterElement.type)) {
iterableCaster += '.toSet()';
- if (!parameterElement.type.isNullableType &&
- !parameterElement.hasDefaultValue) {
+ if (!parameterElement.type.isNullableType && !parameterElement.hasDefaultValue) {
fallBack = '?? const {}';
}
}
@@ -703,14 +643,11 @@
}
@override
- bool _matchesType(DartType type) => const TypeChecker.typeNamed(
- Iterable,
- inSdk: true,
- ).isAssignableFromType(type);
+ bool _matchesType(DartType type) =>
+ const TypeChecker.typeNamed(Iterable, inSdk: true).isAssignableFromType(type);
@override
- String _compare(String value1, String value2) =>
- '!$iterablesEqualHelperName($value1, $value2)';
+ String _compare(String value1, String value2) => '!$iterablesEqualHelperName($value1, $value2)';
}
class _TypeHelperJson extends _TypeHelperWithHelper {
@@ -723,10 +660,7 @@
@override
String _encode(String fieldName, DartType type, String? customEncoder) =>
- _fieldWithEncoder(
- 'jsonEncode($fieldName${type.ensureNotNull}.toJson())',
- customEncoder,
- );
+ _fieldWithEncoder('jsonEncode($fieldName${type.ensureNotNull}.toJson())', customEncoder);
@override
bool _matchesType(DartType type) {
@@ -734,10 +668,7 @@
return false;
}
- final MethodElement? toJsonMethod = type.lookUpMethod(
- 'toJson',
- type.element.library,
- );
+ final MethodElement? toJsonMethod = type.lookUpMethod('toJson', type.element.library);
if (toJsonMethod == null ||
!toJsonMethod.isPublic ||
toJsonMethod.formalParameters.isNotEmpty) {
@@ -750,16 +681,12 @@
return _matchesType(type.typeArguments.first);
}
- final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor(
- 'fromJson',
- );
+ final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor('fromJson');
if (fromJsonMethod == null ||
!fromJsonMethod.isPublic ||
fromJsonMethod.formalParameters.length != 1 ||
- withoutNullability(
- fromJsonMethod.formalParameters.first.type.getDisplayString(),
- ) !=
+ withoutNullability(fromJsonMethod.formalParameters.first.type.getDisplayString()) !=
'Map<String, dynamic>') {
throw InvalidGenerationSourceError(
'The parameter type '
@@ -793,9 +720,7 @@
bool _isNestedTemplate(InterfaceType type) {
// check if has fromJson constructor
- final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor(
- 'fromJson',
- );
+ final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor('fromJson');
if (fromJsonMethod == null || !fromJsonMethod.isPublic) {
return false;
}
@@ -805,15 +730,13 @@
}
// check if fromJson method receive two parameters
- final List<FormalParameterElement> parameters =
- fromJsonMethod.formalParameters;
+ final List<FormalParameterElement> parameters = fromJsonMethod.formalParameters;
if (parameters.length != 2) {
return false;
}
final FormalParameterElement firstParam = parameters[0];
- if (withoutNullability(firstParam.type.getDisplayString()) !=
- 'Map<String, dynamic>') {
+ if (withoutNullability(firstParam.type.getDisplayString()) != 'Map<String, dynamic>') {
throw InvalidGenerationSourceError(
'The parameter type '
'`${withoutNullability(type.getDisplayString())}` not have a supported fromJson definition.',
@@ -865,10 +788,7 @@
'${helperName(paramType)})';
}
final nullableSuffix =
- paramType.isNullableType ||
- (paramType.isEnum && !paramType.isNullableType)
- ? '!'
- : '';
+ paramType.isNullableType || (paramType.isEnum && !paramType.isNullableType) ? '!' : '';
final String decode = _fieldWithEncoder(
'state.${_stateValueAccess(parameterElement, pathParameters)} ${!parameterElement.isRequired ? " ?? '' " : ''}',
@@ -898,9 +818,7 @@
final typedQueryParameterReader = ConstantReader(
_typedQueryParameterChecker.firstAnnotationOf(this),
);
- final String name =
- typedQueryParameterReader.peek('name')?.stringValue ??
- displayName.kebab;
+ final String name = typedQueryParameterReader.peek('name')?.stringValue ?? displayName.kebab;
return escapeDartString(name);
}
@@ -911,11 +829,7 @@
_typedQueryParameterChecker.firstAnnotationOf(this),
);
- return typedQueryParameterReader
- .peek('decoder')
- ?.objectValue
- .toFunctionValue()
- ?.qualifiedName;
+ return typedQueryParameterReader.peek('decoder')?.objectValue.toFunctionValue()?.qualifiedName;
}
/// Returns the name of the encoder function for this parameter, if it has a
@@ -925,11 +839,7 @@
_typedQueryParameterChecker.firstAnnotationOf(this),
);
- return typedQueryParameterReader
- .peek('encoder')
- ?.objectValue
- .toFunctionValue()
- ?.qualifiedName;
+ return typedQueryParameterReader.peek('encoder')?.objectValue.toFunctionValue()?.qualifiedName;
}
/// Returns the name of the compare function for this parameter, if it has a
@@ -939,11 +849,7 @@
_typedQueryParameterChecker.firstAnnotationOf(this),
);
- return typedQueryParameterReader
- .peek('compare')
- ?.objectValue
- .toFunctionValue()
- ?.qualifiedName;
+ return typedQueryParameterReader.peek('compare')?.objectValue.toFunctionValue()?.qualifiedName;
}
}
@@ -952,9 +858,7 @@
/// Returns the name of the encoder function for this property, if it has a
/// `TypedQueryParameter` annotation with an encoder specified.
String? get encoder {
- return (enclosingElement as InterfaceElement)
- .unnamedConstructor
- ?.formalParameters
+ return (enclosingElement as InterfaceElement).unnamedConstructor?.formalParameters
.firstWhereOrNull((parameter) => parameter.displayName == displayName)
?.encoder;
}
diff --git a/packages/go_router_builder/test/path_utils_test.dart b/packages/go_router_builder/test/path_utils_test.dart
index 6857819..ccdd256 100644
--- a/packages/go_router_builder/test/path_utils_test.dart
+++ b/packages/go_router_builder/test/path_utils_test.dart
@@ -12,10 +12,7 @@
expect(pathParametersFromPattern('/user'), const <String>{});
expect(pathParametersFromPattern('/user/:id'), const <String>{'id'});
expect(pathParametersFromPattern('/user/:id/book'), const <String>{'id'});
- expect(
- pathParametersFromPattern('/user/:id/book/:bookId'),
- const <String>{'id', 'bookId'},
- );
+ expect(pathParametersFromPattern('/user/:id/book/:bookId'), const <String>{'id', 'bookId'});
});
});
@@ -23,14 +20,9 @@
test('It should replace the path parameters with their values', () {
expect(patternToPath('/', const <String, String>{}), '/');
expect(patternToPath('/user', const <String, String>{}), '/user');
+ expect(patternToPath('/user/:id', const <String, String>{'id': 'user-id'}), '/user/user-id');
expect(
- patternToPath('/user/:id', const <String, String>{'id': 'user-id'}),
- '/user/user-id',
- );
- expect(
- patternToPath('/user/:id/book', const <String, String>{
- 'id': 'user-id',
- }),
+ patternToPath('/user/:id/book', const <String, String>{'id': 'user-id'}),
'/user/user-id/book',
);
expect(
diff --git a/packages/go_router_builder/test_inputs/case_sensitivity.dart b/packages/go_router_builder/test_inputs/case_sensitivity.dart
index 29dc2df..af09fe0 100644
--- a/packages/go_router_builder/test_inputs/case_sensitivity.dart
+++ b/packages/go_router_builder/test_inputs/case_sensitivity.dart
@@ -10,8 +10,5 @@
@TypedGoRoute<CaseSensitiveRoute>(path: '/case-sensitive-route')
class CaseSensitiveRoute extends GoRouteData with $CaseSensitiveRoute {}
-@TypedGoRoute<NotCaseSensitiveRoute>(
- path: '/not-case-sensitive-route',
- caseSensitive: false,
-)
+@TypedGoRoute<NotCaseSensitiveRoute>(path: '/not-case-sensitive-route', caseSensitive: false)
class NotCaseSensitiveRoute extends GoRouteData with $NotCaseSensitiveRoute {}
diff --git a/packages/go_router_builder/test_inputs/custom_encoder.dart b/packages/go_router_builder/test_inputs/custom_encoder.dart
index 6bf82b3..279d425 100644
--- a/packages/go_router_builder/test_inputs/custom_encoder.dart
+++ b/packages/go_router_builder/test_inputs/custom_encoder.dart
@@ -7,9 +7,7 @@
import 'package:go_router/go_router.dart';
String fromBase64(String value) {
- return const Utf8Decoder().convert(
- base64Url.decode(base64Url.normalize(value)),
- );
+ return const Utf8Decoder().convert(base64Url.decode(base64Url.normalize(value)));
}
String toBase64(String value) {
@@ -29,8 +27,7 @@
mixin $CustomParameterComplexRoute {}
@TypedGoRoute<CustomParameterComplexRoute>(path: '/:id/')
-class CustomParameterComplexRoute extends GoRouteData
- with $CustomParameterComplexRoute {
+class CustomParameterComplexRoute extends GoRouteData with $CustomParameterComplexRoute {
CustomParameterComplexRoute({
required this.id,
this.dir = '',
diff --git a/packages/go_router_builder/test_inputs/extension_type_parameter.dart b/packages/go_router_builder/test_inputs/extension_type_parameter.dart
index 3163b36..d699630 100644
--- a/packages/go_router_builder/test_inputs/extension_type_parameter.dart
+++ b/packages/go_router_builder/test_inputs/extension_type_parameter.dart
@@ -37,8 +37,7 @@
ExtensionTypeParam();
}
-class ExtensionTypeStringParam extends GoRouteData
- with $ExtensionTypeStringParam {
+class ExtensionTypeStringParam extends GoRouteData with $ExtensionTypeStringParam {
ExtensionTypeStringParam({
required this.s,
required this.requiredValue,
@@ -51,11 +50,8 @@
final StringExtensionType optionalDefaultValue;
}
-class ExtensionTypeStringDefaultParam extends GoRouteData
- with $ExtensionTypeStringDefaultParam {
- ExtensionTypeStringDefaultParam({
- this.s = const StringExtensionType('default'),
- });
+class ExtensionTypeStringDefaultParam extends GoRouteData with $ExtensionTypeStringDefaultParam {
+ ExtensionTypeStringDefaultParam({this.s = const StringExtensionType('default')});
final StringExtensionType s;
}
@@ -72,14 +68,12 @@
final IntExtensionType optionalDefaultValue;
}
-class ExtensionTypeIntDefaultParam extends GoRouteData
- with $ExtensionTypeIntDefaultParam {
+class ExtensionTypeIntDefaultParam extends GoRouteData with $ExtensionTypeIntDefaultParam {
ExtensionTypeIntDefaultParam({this.x = const IntExtensionType(42)});
final IntExtensionType x;
}
-class ExtensionTypeDoubleParam extends GoRouteData
- with $ExtensionTypeDoubleParam {
+class ExtensionTypeDoubleParam extends GoRouteData with $ExtensionTypeDoubleParam {
ExtensionTypeDoubleParam({
required this.d,
required this.requiredValue,
@@ -133,8 +127,7 @@
final EnumExtensionType optionalDefaultValue;
}
-class ExtensionTypeBigIntParam extends GoRouteData
- with $ExtensionTypeBigIntParam {
+class ExtensionTypeBigIntParam extends GoRouteData with $ExtensionTypeBigIntParam {
ExtensionTypeBigIntParam({
required this.bi,
required this.requiredValue,
@@ -147,8 +140,7 @@
final BigIntExtensionType? optionalNullableValue;
}
-class ExtensionTypeDateTimeParam extends GoRouteData
- with $ExtensionTypeDateTimeParam {
+class ExtensionTypeDateTimeParam extends GoRouteData with $ExtensionTypeDateTimeParam {
ExtensionTypeDateTimeParam({
required this.dt,
required this.optionalValue,
diff --git a/packages/go_router_builder/test_inputs/go_relative.dart b/packages/go_router_builder/test_inputs/go_relative.dart
index 53d7fe7..8215101 100644
--- a/packages/go_router_builder/test_inputs/go_relative.dart
+++ b/packages/go_router_builder/test_inputs/go_relative.dart
@@ -9,26 +9,19 @@
mixin $RelativeRoute {}
mixin $InnerRelativeRoute {}
-const TypedRelativeGoRoute<RelativeRoute> relativeRoute =
- TypedRelativeGoRoute<RelativeRoute>(
- path: 'relative-route',
- routes: <TypedRoute<RouteData>>[
- TypedRelativeGoRoute<InnerRelativeRoute>(path: 'inner-relative-route'),
- ],
- );
+const TypedRelativeGoRoute<RelativeRoute> relativeRoute = TypedRelativeGoRoute<RelativeRoute>(
+ path: 'relative-route',
+ routes: <TypedRoute<RouteData>>[
+ TypedRelativeGoRoute<InnerRelativeRoute>(path: 'inner-relative-route'),
+ ],
+);
-@TypedGoRoute<Route1>(
- path: 'route-1',
- routes: <TypedRoute<RouteData>>[relativeRoute],
-)
+@TypedGoRoute<Route1>(path: 'route-1', routes: <TypedRoute<RouteData>>[relativeRoute])
class Route1 extends GoRouteData with $Route1 {
const Route1();
}
-@TypedGoRoute<Route2>(
- path: 'route-2',
- routes: <TypedRoute<RouteData>>[relativeRoute],
-)
+@TypedGoRoute<Route2>(path: 'route-2', routes: <TypedRoute<RouteData>>[relativeRoute])
class Route2 extends GoRouteData with $Route2 {
const Route2();
}
diff --git a/packages/go_router_builder/test_inputs/iterable_with_default_value.dart b/packages/go_router_builder/test_inputs/iterable_with_default_value.dart
index 23eaa3f..a927a36 100644
--- a/packages/go_router_builder/test_inputs/iterable_with_default_value.dart
+++ b/packages/go_router_builder/test_inputs/iterable_with_default_value.dart
@@ -7,8 +7,7 @@
mixin $IterableDefaultValueRoute {}
@TypedGoRoute<IterableDefaultValueRoute>(path: '/iterable-default-value-route')
-class IterableDefaultValueRoute extends GoRouteData
- with $IterableDefaultValueRoute {
+class IterableDefaultValueRoute extends GoRouteData with $IterableDefaultValueRoute {
IterableDefaultValueRoute({this.param = const <int>[0]});
final Iterable<int> param;
}
diff --git a/packages/go_router_builder/test_inputs/list.dart b/packages/go_router_builder/test_inputs/list.dart
index 1699fa7..7e9478f 100644
--- a/packages/go_router_builder/test_inputs/list.dart
+++ b/packages/go_router_builder/test_inputs/list.dart
@@ -8,11 +8,7 @@
@TypedGoRoute<ListRoute>(path: '/list-route')
class ListRoute extends GoRouteData with $ListRoute {
- ListRoute({
- required this.ids,
- this.nullableIds,
- this.idsWithDefaultValue = const <int>[0],
- });
+ ListRoute({required this.ids, this.nullableIds, this.idsWithDefaultValue = const <int>[0]});
final List<int> ids;
final List<int>? nullableIds;
final List<int> idsWithDefaultValue;
diff --git a/packages/go_router_builder/test_inputs/nullable_default_value.dart b/packages/go_router_builder/test_inputs/nullable_default_value.dart
index d6986fa..6f0302c 100644
--- a/packages/go_router_builder/test_inputs/nullable_default_value.dart
+++ b/packages/go_router_builder/test_inputs/nullable_default_value.dart
@@ -7,8 +7,7 @@
mixin $NullableDefaultValueRoute {}
@TypedGoRoute<NullableDefaultValueRoute>(path: '/nullable-default-value-route')
-class NullableDefaultValueRoute extends GoRouteData
- with $NullableDefaultValueRoute {
+class NullableDefaultValueRoute extends GoRouteData with $NullableDefaultValueRoute {
NullableDefaultValueRoute({this.param = 0});
final int? param;
}
diff --git a/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart b/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart
index 28d7f14..208213e 100644
--- a/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart
+++ b/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart
@@ -8,21 +8,15 @@
mixin $RelativeRoute {}
mixin $NonRelativeRoute {}
-@TypedGoRoute<HomeRoute>(
- path: '/',
- routes: <TypedRoute<RouteData>>[relativeRoute],
-)
+@TypedGoRoute<HomeRoute>(path: '/', routes: <TypedRoute<RouteData>>[relativeRoute])
class HomeRoute extends GoRouteData with $HomeRoute {
const HomeRoute();
}
-const TypedRelativeGoRoute<RelativeRoute> relativeRoute =
- TypedRelativeGoRoute<RelativeRoute>(
- path: 'relative-route',
- routes: <TypedRoute<RouteData>>[
- TypedGoRoute<NonRelativeRoute>(path: 'non-relative-route'),
- ],
- );
+const TypedRelativeGoRoute<RelativeRoute> relativeRoute = TypedRelativeGoRoute<RelativeRoute>(
+ path: 'relative-route',
+ routes: <TypedRoute<RouteData>>[TypedGoRoute<NonRelativeRoute>(path: 'non-relative-route')],
+);
class RelativeRoute extends RelativeGoRouteData with $RelativeRoute {
const RelativeRoute();
diff --git a/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart b/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart
index 4261e9c..953b9d7 100644
--- a/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart
+++ b/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart
@@ -9,19 +9,15 @@
mixin $RelativeRoute {}
mixin $AbsoluteRoute {}
-@TypedGoRoute<HomeRoute>(
- path: '/',
- routes: <TypedRoute<RouteData>>[relativeRoute],
-)
+@TypedGoRoute<HomeRoute>(path: '/', routes: <TypedRoute<RouteData>>[relativeRoute])
class HomeRoute extends GoRouteData with $HomeRoute {
const HomeRoute();
}
-const TypedRelativeGoRoute<RelativeRoute> relativeRoute =
- TypedRelativeGoRoute<RelativeRoute>(
- path: 'relative-route',
- routes: <TypedRoute<RouteData>>[shellRoute],
- );
+const TypedRelativeGoRoute<RelativeRoute> relativeRoute = TypedRelativeGoRoute<RelativeRoute>(
+ path: 'relative-route',
+ routes: <TypedRoute<RouteData>>[shellRoute],
+);
const TypedShellRoute<ShellRoute> shellRoute = TypedShellRoute<ShellRoute>(
routes: <TypedRoute<RouteData>>[absoluteRoute],
diff --git a/packages/go_router_builder/test_inputs/required_extra_value.dart b/packages/go_router_builder/test_inputs/required_extra_value.dart
index 0d6143f..a1ce647 100644
--- a/packages/go_router_builder/test_inputs/required_extra_value.dart
+++ b/packages/go_router_builder/test_inputs/required_extra_value.dart
@@ -7,8 +7,7 @@
mixin $RequiredExtraValueRoute {}
@TypedGoRoute<RequiredExtraValueRoute>(path: '/default-value-route')
-class RequiredExtraValueRoute extends GoRouteData
- with $RequiredExtraValueRoute {
+class RequiredExtraValueRoute extends GoRouteData with $RequiredExtraValueRoute {
RequiredExtraValueRoute({required this.$extra});
final int $extra;
}
diff --git a/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart b/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart
index 5981238..0dd2a09 100644
--- a/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart
+++ b/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart
@@ -6,9 +6,7 @@
mixin $RequiredNullableTypeArgumentsExtraValueRoute {}
-@TypedGoRoute<RequiredNullableTypeArgumentsExtraValueRoute>(
- path: '/default-value-route',
-)
+@TypedGoRoute<RequiredNullableTypeArgumentsExtraValueRoute>(path: '/default-value-route')
class RequiredNullableTypeArgumentsExtraValueRoute extends GoRouteData
with $RequiredNullableTypeArgumentsExtraValueRoute {
RequiredNullableTypeArgumentsExtraValueRoute({required this.$extra});
diff --git a/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart b/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart
index ad31cab..70cc38c 100644
--- a/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart
+++ b/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart
@@ -7,8 +7,7 @@
mixin $NullableRequiredParamInPath {}
@TypedGoRoute<NullableRequiredParamInPath>(path: 'bob/:id')
-class NullableRequiredParamInPath extends GoRouteData
- with $NullableRequiredParamInPath {
+class NullableRequiredParamInPath extends GoRouteData with $NullableRequiredParamInPath {
NullableRequiredParamInPath({required this.id});
final int? id;
}
diff --git a/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart b/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart
index 03f440c..9a89928 100644
--- a/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart
+++ b/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart
@@ -7,8 +7,7 @@
mixin $NullableRequiredParamNotInPath {}
@TypedGoRoute<NullableRequiredParamNotInPath>(path: 'bob')
-class NullableRequiredParamNotInPath extends GoRouteData
- with $NullableRequiredParamNotInPath {
+class NullableRequiredParamNotInPath extends GoRouteData with $NullableRequiredParamNotInPath {
NullableRequiredParamNotInPath({required this.id});
final int? id;
}
diff --git a/packages/go_router_builder/test_inputs/set.dart b/packages/go_router_builder/test_inputs/set.dart
index fe2623a..9df22b3 100644
--- a/packages/go_router_builder/test_inputs/set.dart
+++ b/packages/go_router_builder/test_inputs/set.dart
@@ -8,11 +8,7 @@
@TypedGoRoute<SetRoute>(path: '/set-route')
class SetRoute extends GoRouteData with $SetRoute {
- SetRoute({
- required this.ids,
- this.nullableIds,
- this.idsWithDefaultValue = const <int>{0},
- });
+ SetRoute({required this.ids, this.nullableIds, this.idsWithDefaultValue = const <int>{0}});
final Set<int> ids;
final Set<int>? nullableIds;
final Set<int> idsWithDefaultValue;
diff --git a/packages/go_router_builder/test_inputs/typed_query_parameter.dart b/packages/go_router_builder/test_inputs/typed_query_parameter.dart
index 5aa56ad..5426a61 100644
--- a/packages/go_router_builder/test_inputs/typed_query_parameter.dart
+++ b/packages/go_router_builder/test_inputs/typed_query_parameter.dart
@@ -26,8 +26,7 @@
}
@TypedGoRoute<OverriddenParameterNameRoute>(path: '/typed-go-route-parameter')
-class OverriddenParameterNameRoute extends GoRouteData
- with $OverriddenParameterNameRoute {
+class OverriddenParameterNameRoute extends GoRouteData with $OverriddenParameterNameRoute {
OverriddenParameterNameRoute({
@TypedQueryParameter(name: 'parameterNameOverride') this.withAnnotation,
@TypedQueryParameter(name: 'name with space') this.withSpace,
@@ -41,10 +40,7 @@
decoder: CustomParameter.decode,
compare: CustomParameter.compare,
)
- this.customFieldWithDefaultValue = const CustomParameter(
- valueString: 'default',
- valueInt: 0,
- ),
+ this.customFieldWithDefaultValue = const CustomParameter(valueString: 'default', valueInt: 0),
});
final int? withAnnotation;
final String? withSpace;
diff --git a/packages/go_router_builder/tool/run_tests.dart b/packages/go_router_builder/tool/run_tests.dart
index d1b8b84..bfd42c7 100644
--- a/packages/go_router_builder/tool/run_tests.dart
+++ b/packages/go_router_builder/tool/run_tests.dart
@@ -19,9 +19,7 @@
const GoRouterGenerator generator = GoRouterGenerator();
Future<void> main() async {
- final formatter = dart_style.DartFormatter(
- languageVersion: await _packageVersion(),
- );
+ final formatter = dart_style.DartFormatter(languageVersion: await _packageVersion());
final dir = Directory('test_inputs');
final List<File> testFiles = dir
.listSync()
@@ -68,9 +66,7 @@
}
Future<Version> _packageVersion() async {
- final PackageConfig packageConfig = await loadPackageConfigUri(
- Isolate.packageConfigSync!,
- );
+ final PackageConfig packageConfig = await loadPackageConfigUri(Isolate.packageConfigSync!);
final Uri pkgUri = Platform.script.resolve('../pubspec.yaml');
final Package? package = packageConfig.packageOf(pkgUri);
if (package == null) {
diff --git a/packages/google_adsense/doc/ad_unit_widget.md b/packages/google_adsense/doc/ad_unit_widget.md
index f8b7535..07ec014 100644
--- a/packages/google_adsense/doc/ad_unit_widget.md
+++ b/packages/google_adsense/doc/ad_unit_widget.md
@@ -102,10 +102,7 @@
<?code-excerpt "../example/lib/ad_unit_widget.dart (constraints)"?>
```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/doc/initialization.md b/packages/google_adsense/doc/initialization.md
index d1870a5..3b63185 100644
--- a/packages/google_adsense/doc/initialization.md
+++ b/packages/google_adsense/doc/initialization.md
@@ -43,10 +43,7 @@
```dart
await adSense.initialize(
'0123456789012345',
- adSenseCodeParameters: AdSenseCodeParameters(
- adbreakTest: 'on',
- adFrequencyHint: '30s',
- ),
+ adSenseCodeParameters: AdSenseCodeParameters(adbreakTest: 'on', adFrequencyHint: '30s'),
);
```
diff --git a/packages/google_adsense/example/integration_test/core_test.dart b/packages/google_adsense/example/integration_test/core_test.dart
index aee9f02..749bdb9 100644
--- a/packages/google_adsense/example/integration_test/core_test.dart
+++ b/packages/google_adsense/example/integration_test/core_test.dart
@@ -44,9 +44,7 @@
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(
@@ -67,27 +65,16 @@
final 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 {
+ testWidgets('Skips initialization if script is already present.', (WidgetTester _) async {
final script = web.HTMLScriptElement()
..id = 'previously-injected'
..src = testScriptUrl;
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 935d018..8179768 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,9 +44,7 @@
});
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;
@@ -76,44 +74,38 @@
expect(size.height, expectedHeight);
});
- testWidgets(
- 'Fixed size (without adFormat) ad units respect flutter constraints',
- (WidgetTester tester) async {
- const double maxHeight = 100;
- const constraints = BoxConstraints(maxHeight: maxHeight);
-
- // When
- mockAdsByGoogle(mockAd(size: const Size(320, 157)));
-
- await adSense.initialize(testClient);
-
- final 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', (
+ testWidgets('Fixed size (without adFormat) ad units respect flutter constraints', (
WidgetTester tester,
) async {
+ const double maxHeight = 100;
+ const constraints = BoxConstraints(maxHeight: maxHeight);
+
+ // When
+ mockAdsByGoogle(mockAd(size: const Size(320, 157)));
+
+ await adSense.initialize(testClient);
+
+ final 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));
@@ -176,9 +168,7 @@
Container(
constraints: const BoxConstraints(maxHeight: 100),
child: AdUnitWidget(
- configuration: AdUnitConfiguration.displayAdUnit(
- adSlot: testSlot,
- ),
+ configuration: AdUnitConfiguration.displayAdUnit(adSlot: testSlot),
adClient: adSense.adClient,
onInjected: tracker.createCallback(),
),
@@ -205,11 +195,7 @@
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(1)).height, 0, reason: 'Unfulfilled ad should be 0x0');
expect(
tester.getSize(adUnits.at(2)).height,
100,
@@ -220,11 +206,7 @@
}
// Pumps an AdUnit Widget into a given tester, with some parameters
-Future<void> pumpAdWidget(
- Widget adUnit,
- WidgetTester tester,
- CallbackTracker tracker,
-) async {
+Future<void> pumpAdWidget(Widget adUnit, WidgetTester tester, CallbackTracker tracker) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: Center(child: adUnit)),
diff --git a/packages/google_adsense/example/integration_test/h5_test.dart b/packages/google_adsense/example/integration_test/h5_test.dart
index c98a121..26af3ce 100644
--- a/packages/google_adsense/example/integration_test/h5_test.dart
+++ b/packages/google_adsense/example/integration_test/h5_test.dart
@@ -41,9 +41,7 @@
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) {
@@ -52,9 +50,7 @@
mockAdsByGoogle(
mockAdBreak(
- adBreakDonePlacementInfo: AdBreakDonePlacementInfo(
- breakName: 'ok-for-tests'.toJS,
- ),
+ adBreakDonePlacementInfo: AdBreakDonePlacementInfo(breakName: 'ok-for-tests'.toJS),
),
);
await adSense.initialize('_');
@@ -79,10 +75,7 @@
mockAdsByGoogle(mockAdBreak());
await adSense.initialize('_');
- final adBreakPlacement = AdBreakPlacement(
- type: BreakType.reward,
- name: 'my-test-break',
- );
+ final adBreakPlacement = AdBreakPlacement(type: BreakType.reward, name: 'my-test-break');
h5GamesAds.adBreak(adBreakPlacement);
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 5001ef9..8967f3e 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
@@ -23,10 +23,7 @@
// 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/integration_test/script_tag_test.dart b/packages/google_adsense/example/integration_test/script_tag_test.dart
index 7daa95e..f8ba31f 100644
--- a/packages/google_adsense/example/integration_test/script_tag_test.dart
+++ b/packages/google_adsense/example/integration_test/script_tag_test.dart
@@ -25,8 +25,7 @@
await adSense.initialize(testClient);
// Then
- final injected =
- web.document.head?.lastElementChild as web.HTMLScriptElement?;
+ final injected = web.document.head?.lastElementChild as web.HTMLScriptElement?;
expect(injected, isNotNull);
expect(injected!.src, expectedScriptUrl);
diff --git a/packages/google_adsense/example/lib/ad_unit_widget.dart b/packages/google_adsense/example/lib/ad_unit_widget.dart
index db201cb..39f5243 100644
--- a/packages/google_adsense/example/lib/ad_unit_widget.dart
+++ b/packages/google_adsense/example/lib/ad_unit_widget.dart
@@ -77,10 +77,7 @@
),
// #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(
diff --git a/packages/google_adsense/example/lib/h5.dart b/packages/google_adsense/example/lib/h5.dart
index 98d2dde..9ff6e12 100644
--- a/packages/google_adsense/example/lib/h5.dart
+++ b/packages/google_adsense/example/lib/h5.dart
@@ -16,10 +16,7 @@
// #docregion initialize-with-code-parameters
await adSense.initialize(
'0123456789012345',
- adSenseCodeParameters: AdSenseCodeParameters(
- adbreakTest: 'on',
- adFrequencyHint: '30s',
- ),
+ adSenseCodeParameters: AdSenseCodeParameters(adbreakTest: 'on', adFrequencyHint: '30s'),
);
// #enddocregion initialize-with-code-parameters
runApp(const MyApp());
@@ -170,23 +167,16 @@
),
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: <Widget>[
const Text('🪙 Available coins:'),
- Text(
- '$_coins',
- style: Theme.of(context).textTheme.displayLarge,
- ),
+ Text('$_coins', style: Theme.of(context).textTheme.displayLarge),
TextButton.icon(
- onPressed: _h5Ready && !adBreakAvailable
- ? _requestRewardedAd
- : null,
+ onPressed: _h5Ready && !adBreakAvailable ? _requestRewardedAd : null,
label: const Text('Prepare Reward'),
icon: const Icon(Icons.download_rounded),
),
@@ -199,9 +189,7 @@
),
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'),
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 baf3a7a..360b8dd 100644
--- a/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart
+++ b/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart
@@ -77,12 +77,9 @@
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(),
+ 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',
};
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 dbb8cb9..7d92a0e 100644
--- a/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart
+++ b/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart
@@ -52,8 +52,7 @@
State<AdUnitWidget> createState() => _AdUnitWidgetWebState();
}
-class _AdUnitWidgetWebState extends State<AdUnitWidget>
- with AutomaticKeepAliveClientMixin {
+class _AdUnitWidgetWebState extends State<AdUnitWidget> with AutomaticKeepAliveClientMixin {
static int _adUnitCounter = 0;
static final JSString _adStatusKey = 'adStatus'.toJS;
@@ -86,18 +85,13 @@
}
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
- if (!widget._adUnitConfiguration.params.containsKey(
- AdUnitParams.AD_FORMAT,
- )) {
+ 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,
- ),
+ child: HtmlElementView.fromTagName(tagName: 'div', onElementCreated: _onElementCreated),
);
},
);
@@ -131,8 +125,7 @@
web.MutationObserver(
(JSArray<JSObject> entries, web.MutationObserver observer) {
for (final JSObject entry in entries.toDart) {
- final target =
- (entry as web.MutationRecord).target as web.HTMLElement;
+ final target = (entry as web.MutationRecord).target as web.HTMLElement;
if (_isLoaded(target)) {
if (_isFilled(target)) {
debugLog(
@@ -162,9 +155,7 @@
}
static void _onElementAttached(web.HTMLElement element) {
- debugLog(
- '$element attached with w=${element.offsetWidth} and h=${element.offsetHeight}',
- );
+ debugLog('$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} ',
);
@@ -172,17 +163,13 @@
}
bool _isLoaded(web.HTMLElement target) {
- final bool isLoaded = target.dataset
- .getProperty(_adStatusKey)
- .isDefinedAndNotNull;
+ final bool isLoaded = target.dataset.getProperty(_adStatusKey).isDefinedAndNotNull;
debugLog('Ad isLoaded: $isLoaded');
return isLoaded;
}
bool _isFilled(web.HTMLElement target) {
- final String? adStatus = target.dataset
- .getProperty<JSString?>(_adStatusKey)
- ?.toDart;
+ final String? adStatus = target.dataset.getProperty<JSString?>(_adStatusKey)?.toDart;
debugLog('Ad isFilled? $adStatus');
if (adStatus == AdStatus.FILLED) {
return true;
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 15660f1..bdf19db 100644
--- a/packages/google_adsense/lib/src/core/adsense_code_parameters.dart
+++ b/packages/google_adsense/lib/src/core/adsense_code_parameters.dart
@@ -46,15 +46,13 @@
String? adFrequencyHint,
}) : _adSenseCodeParameters = <String, String>{
if (adHost != null) 'adHost': adHost,
- if (admobInterstitialSlot != null)
- 'admobInterstitialSlot': admobInterstitialSlot,
+ 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 (tagForUnderAgeOfConsent != null) 'tagForUnderAgeOfConsent': tagForUnderAgeOfConsent,
if (adFrequencyHint != null) 'adFrequencyHint': adFrequencyHint,
};
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 f570abc..518d880 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
@@ -11,8 +11,7 @@
import 'package_web_tweaks.dart';
// The URL of the ads by google client.
-const String _URL =
- 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
+const String _URL = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
/// Loads the JS SDK for [adClient].
///
@@ -42,9 +41,7 @@
try {
final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy(
trustedTypePolicyName,
- web.TrustedTypePolicyOptions(
- createScriptURL: ((JSString url) => url).toJS,
- ),
+ web.TrustedTypePolicyOptions(createScriptURL: ((JSString url) => url).toJS),
);
script.trustedSrc = policy.createScriptURLNoArgs(scriptUrl);
} catch (e) {
@@ -61,10 +58,7 @@
}
// Applies a map of [attributes] to the `dataset` of [element].
-void _applyDataAttributes(
- web.HTMLElement element,
- Map<String, String>? attributes,
-) {
+void _applyDataAttributes(web.HTMLElement element, Map<String, String>? attributes) {
attributes?.forEach((String key, String value) {
element.dataset.setProperty(key.toJS, value.toJS);
});
diff --git a/packages/google_adsense/lib/src/h5/h5.dart b/packages/google_adsense/lib/src/h5/h5.dart
index 2f0a517..82a9b30 100644
--- a/packages/google_adsense/lib/src/h5/h5.dart
+++ b/packages/google_adsense/lib/src/h5/h5.dart
@@ -7,8 +7,7 @@
import '../core/js_interop/adsbygoogle.dart';
import 'h5_js_interop.dart';
-export 'enums.dart'
- show BreakFormat, BreakStatus, BreakType, PreloadAdBreaks, SoundEnabled;
+export 'enums.dart' show BreakFormat, BreakStatus, BreakType, PreloadAdBreaks, SoundEnabled;
export 'h5_js_interop.dart'
show
AdBreakDonePlacementInfo,
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 e08ca63..fdc70a9 100644
--- a/packages/google_adsense/lib/src/h5/h5_js_interop.dart
+++ b/packages/google_adsense/lib/src/h5/h5_js_interop.dart
@@ -176,9 +176,7 @@
/// {@macro pkg_google_adsense_parameter_h5_adBreakDone}
///
/// See: https://developers.google.com/ad-placement/apis#prerolls
- factory AdBreakPlacement.preroll({
- required H5AdBreakDoneCallback? adBreakDone,
- }) {
+ factory AdBreakPlacement.preroll({required H5AdBreakDoneCallback? adBreakDone}) {
return AdBreakPlacement(type: BreakType.preroll, adBreakDone: adBreakDone);
}
@@ -297,14 +295,12 @@
external JSString? _breakName;
/// The format of the break. See [BreakFormat].
- BreakFormat? get breakFormat =>
- BreakFormat.values.maybe(_breakFormat?.toDart);
+ BreakFormat? get breakFormat => BreakFormat.values.maybe(_breakFormat?.toDart);
@JS('breakFormat')
external JSString? _breakFormat;
/// The status of this placement. See [BreakStatus].
- BreakStatus? get breakStatus =>
- BreakStatus.values.maybe(_breakStatus?.toDart);
+ BreakStatus? get breakStatus => BreakStatus.values.maybe(_breakStatus?.toDart);
@JS('breakStatus')
external JSString? _breakStatus;
}
@@ -321,8 +317,7 @@
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_fonts/README.md b/packages/google_fonts/README.md
index 6ac5cee..d7d3287 100644
--- a/packages/google_fonts/README.md
+++ b/packages/google_fonts/README.md
@@ -42,9 +42,7 @@
```dart
Text(
'This is Google Fonts',
- style: GoogleFonts.lato(
- textStyle: const TextStyle(color: Colors.blue, letterSpacing: .5),
- ),
+ style: GoogleFonts.lato(textStyle: const TextStyle(color: Colors.blue, letterSpacing: .5)),
),
```
@@ -54,9 +52,7 @@
```dart
Text(
'This is Google Fonts',
- style: GoogleFonts.lato(
- textStyle: Theme.of(context).textTheme.headlineMedium,
- ),
+ style: GoogleFonts.lato(textStyle: Theme.of(context).textTheme.headlineMedium),
),
```
@@ -96,9 +92,7 @@
ThemeData _buildTheme(Brightness brightness) {
final baseTheme = ThemeData(brightness: brightness);
- return baseTheme.copyWith(
- textTheme: GoogleFonts.latoTextTheme(baseTheme.textTheme),
- );
+ return baseTheme.copyWith(textTheme: GoogleFonts.latoTextTheme(baseTheme.textTheme));
}
```
@@ -112,9 +106,9 @@
return MaterialApp(
// ···
theme: ThemeData(
- textTheme: GoogleFonts.latoTextTheme(textTheme).copyWith(
- bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium),
- ),
+ textTheme: GoogleFonts.latoTextTheme(
+ textTheme,
+ ).copyWith(bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium)),
),
// ···
);
diff --git a/packages/google_fonts/example/lib/example_font_selection.dart b/packages/google_fonts/example/lib/example_font_selection.dart
index 5c31dc1..af160a7 100644
--- a/packages/google_fonts/example/lib/example_font_selection.dart
+++ b/packages/google_fonts/example/lib/example_font_selection.dart
@@ -27,9 +27,7 @@
@override
void initState() {
_selectedFont = fonts.first;
- _googleFontsPending = GoogleFonts.pendingFonts(<TextStyle>[
- GoogleFonts.getFont(_selectedFont),
- ]);
+ _googleFontsPending = GoogleFonts.pendingFonts(<TextStyle>[GoogleFonts.getFont(_selectedFont)]);
super.initState();
}
@@ -63,18 +61,13 @@
onSelected: (String? newValue) {
setState(() {
_selectedFont = newValue!;
- _googleFontsPending = GoogleFonts.pendingFonts(
- <TextStyle>[GoogleFonts.getFont(_selectedFont)],
- );
+ _googleFontsPending = GoogleFonts.pendingFonts(<TextStyle>[
+ GoogleFonts.getFont(_selectedFont),
+ ]);
});
},
- dropdownMenuEntries: GoogleFonts.asMap().keys.map((
- String font,
- ) {
- return DropdownMenuEntry<String>(
- label: font,
- value: font,
- );
+ dropdownMenuEntries: GoogleFonts.asMap().keys.map((String font) {
+ return DropdownMenuEntry<String>(label: font, value: font);
}).toList(),
),
],
@@ -83,24 +76,16 @@
Expanded(
child: FutureBuilder<List<void>>(
future: _googleFontsPending,
- builder:
- (
- BuildContext context,
- AsyncSnapshot<List<void>> snapshot,
- ) {
- if (snapshot.connectionState !=
- ConnectionState.done) {
- return const SizedBox();
- }
+ builder: (BuildContext context, AsyncSnapshot<List<void>> snapshot) {
+ if (snapshot.connectionState != ConnectionState.done) {
+ return const SizedBox();
+ }
- return Text(
- _textEditingController.text,
- style: GoogleFonts.getFont(
- _selectedFont,
- fontSize: 50.0,
- ),
- );
- },
+ return Text(
+ _textEditingController.text,
+ style: GoogleFonts.getFont(_selectedFont, fontSize: 50.0),
+ );
+ },
),
),
],
diff --git a/packages/google_fonts/example/lib/example_simple.dart b/packages/google_fonts/example/lib/example_simple.dart
index f968de0..a5d38da 100644
--- a/packages/google_fonts/example/lib/example_simple.dart
+++ b/packages/google_fonts/example/lib/example_simple.dart
@@ -55,10 +55,7 @@
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
- Text(
- 'You have pushed the button this many times:',
- style: pushButtonTextStyle,
- ),
+ Text('You have pushed the button this many times:', style: pushButtonTextStyle),
Text('$_counter', style: counterTextStyle),
],
);
diff --git a/packages/google_fonts/example/lib/main.dart b/packages/google_fonts/example/lib/main.dart
index 31b2ab8..646f9df 100644
--- a/packages/google_fonts/example/lib/main.dart
+++ b/packages/google_fonts/example/lib/main.dart
@@ -32,9 +32,7 @@
],
),
),
- body: const TabBarView(
- children: <Widget>[ExampleSimple(), ExampleFontSelection()],
- ),
+ body: const TabBarView(children: <Widget>[ExampleSimple(), ExampleFontSelection()]),
),
),
);
diff --git a/packages/google_fonts/example/lib/readme_excerpts.dart b/packages/google_fonts/example/lib/readme_excerpts.dart
index 8574e08..49b0b68 100644
--- a/packages/google_fonts/example/lib/readme_excerpts.dart
+++ b/packages/google_fonts/example/lib/readme_excerpts.dart
@@ -20,17 +20,13 @@
// #docregion ExistingStyle
Text(
'This is Google Fonts',
- style: GoogleFonts.lato(
- textStyle: const TextStyle(color: Colors.blue, letterSpacing: .5),
- ),
+ style: GoogleFonts.lato(textStyle: const TextStyle(color: Colors.blue, letterSpacing: .5)),
),
// #enddocregion ExistingStyle
// #docregion ExistingThemeStyle
Text(
'This is Google Fonts',
- style: GoogleFonts.lato(
- textStyle: Theme.of(context).textTheme.headlineMedium,
- ),
+ style: GoogleFonts.lato(textStyle: Theme.of(context).textTheme.headlineMedium),
),
// #enddocregion ExistingThemeStyle
// #docregion ExistingStyleWithOverrides
@@ -88,9 +84,7 @@
ThemeData _buildTheme(Brightness brightness) {
final baseTheme = ThemeData(brightness: brightness);
- return baseTheme.copyWith(
- textTheme: GoogleFonts.latoTextTheme(baseTheme.textTheme),
- );
+ return baseTheme.copyWith(textTheme: GoogleFonts.latoTextTheme(baseTheme.textTheme));
}
// #enddocregion AppThemeSimple
@@ -109,9 +103,9 @@
title: 'Example',
// #docregion AppThemeComplex
theme: ThemeData(
- textTheme: GoogleFonts.latoTextTheme(textTheme).copyWith(
- bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium),
- ),
+ textTheme: GoogleFonts.latoTextTheme(
+ textTheme,
+ ).copyWith(bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium)),
),
// #enddocregion AppThemeComplex
home: const Text('placeholder'),
diff --git a/packages/google_fonts/example/test/widget_test.dart b/packages/google_fonts/example/test/widget_test.dart
index 3f0a488..35fb91e 100644
--- a/packages/google_fonts/example/test/widget_test.dart
+++ b/packages/google_fonts/example/test/widget_test.dart
@@ -9,9 +9,7 @@
// Consider `flutter test --no-test-assets` if assets are not required.
void main() {
testWidgets('Can specify text style', (WidgetTester tester) async {
- await tester.pumpWidget(
- MaterialApp(home: Text('Hello', style: GoogleFonts.aBeeZee())),
- );
+ await tester.pumpWidget(MaterialApp(home: Text('Hello', style: GoogleFonts.aBeeZee())));
});
testWidgets('Can specify text theme', (WidgetTester tester) async {
@@ -19,9 +17,7 @@
await tester.pumpWidget(
MaterialApp(
- theme: baseTheme.copyWith(
- textTheme: GoogleFonts.aBeeZeeTextTheme(baseTheme.textTheme),
- ),
+ theme: baseTheme.copyWith(textTheme: GoogleFonts.aBeeZeeTextTheme(baseTheme.textTheme)),
),
);
});
diff --git a/packages/google_fonts/generator/fonts.pb.dart b/packages/google_fonts/generator/fonts.pb.dart
index 2508ac6..cae17df 100644
--- a/packages/google_fonts/generator/fonts.pb.dart
+++ b/packages/google_fonts/generator/fonts.pb.dart
@@ -43,14 +43,11 @@
[$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(json, registry);
- static final $pb.BuilderInfo _i = $pb.BuilderInfo(
- _omitMessageNames ? '' : 'FileSpec',
- package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'),
- createEmptyInstance: create)
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'FileSpec',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create)
..aOS(1, _omitFieldNames ? '' : 'filename')
..aInt64(2, _omitFieldNames ? '' : 'fileSize')
- ..a<$core.List<$core.int>>(
- 3, _omitFieldNames ? '' : 'hash', $pb.PbFieldType.OY)
+ ..a<$core.List<$core.int>>(3, _omitFieldNames ? '' : 'hash', $pb.PbFieldType.OY)
..hasRequiredFields = false;
@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
@@ -120,10 +117,8 @@
[$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(json, registry);
- static final $pb.BuilderInfo _i = $pb.BuilderInfo(
- _omitMessageNames ? '' : 'IntRange',
- package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'),
- createEmptyInstance: create)
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'IntRange',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create)
..aI(1, _omitFieldNames ? '' : 'start')
..aI(2, _omitFieldNames ? '' : 'end')
..hasRequiredFields = false;
@@ -188,10 +183,8 @@
[$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(json, registry);
- static final $pb.BuilderInfo _i = $pb.BuilderInfo(
- _omitMessageNames ? '' : 'FloatRange',
- package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'),
- createEmptyInstance: create)
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'FloatRange',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create)
..aD(1, _omitFieldNames ? '' : 'start', fieldType: $pb.PbFieldType.OF)
..aD(2, _omitFieldNames ? '' : 'end', fieldType: $pb.PbFieldType.OF)
..hasRequiredFields = false;
@@ -210,8 +203,8 @@
@$core.override
FloatRange createEmptyInstance() => create();
@$core.pragma('dart2js:noInline')
- static FloatRange getDefault() => _defaultInstance ??=
- $pb.GeneratedMessage.$_defaultFor<FloatRange>(create);
+ static FloatRange getDefault() =>
+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<FloatRange>(create);
static FloatRange? _defaultInstance;
@$pb.TagNumber(1)
@@ -265,18 +258,12 @@
[$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(json, registry);
- static final $pb.BuilderInfo _i = $pb.BuilderInfo(
- _omitMessageNames ? '' : 'Font',
- package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'),
- createEmptyInstance: create)
- ..aOM<FileSpec>(1, _omitFieldNames ? '' : 'file',
- subBuilder: FileSpec.create)
- ..aOM<IntRange>(2, _omitFieldNames ? '' : 'weight',
- subBuilder: IntRange.create)
- ..aOM<FloatRange>(3, _omitFieldNames ? '' : 'width',
- subBuilder: FloatRange.create)
- ..aOM<FloatRange>(4, _omitFieldNames ? '' : 'italic',
- subBuilder: FloatRange.create)
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Font',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create)
+ ..aOM<FileSpec>(1, _omitFieldNames ? '' : 'file', subBuilder: FileSpec.create)
+ ..aOM<IntRange>(2, _omitFieldNames ? '' : 'weight', subBuilder: IntRange.create)
+ ..aOM<FloatRange>(3, _omitFieldNames ? '' : 'width', subBuilder: FloatRange.create)
+ ..aOM<FloatRange>(4, _omitFieldNames ? '' : 'italic', subBuilder: FloatRange.create)
..aI(7, _omitFieldNames ? '' : 'ttcIndex')
..aOS(8, _omitFieldNames ? '' : 'postScriptName')
..aOB(9, _omitFieldNames ? '' : 'isVf')
@@ -296,8 +283,7 @@
@$core.override
Font createEmptyInstance() => create();
@$core.pragma('dart2js:noInline')
- static Font getDefault() =>
- _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Font>(create);
+ static Font getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Font>(create);
static Font? _defaultInstance;
@$pb.TagNumber(1)
@@ -407,10 +393,8 @@
[$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(json, registry);
- static final $pb.BuilderInfo _i = $pb.BuilderInfo(
- _omitMessageNames ? '' : 'FontFamily',
- package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'),
- createEmptyInstance: create)
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'FontFamily',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create)
..aOS(1, _omitFieldNames ? '' : 'name')
..aI(2, _omitFieldNames ? '' : 'version')
..pPM<Font>(4, _omitFieldNames ? '' : 'fonts', subBuilder: Font.create)
@@ -430,8 +414,8 @@
@$core.override
FontFamily createEmptyInstance() => create();
@$core.pragma('dart2js:noInline')
- static FontFamily getDefault() => _defaultInstance ??=
- $pb.GeneratedMessage.$_defaultFor<FontFamily>(create);
+ static FontFamily getDefault() =>
+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<FontFamily>(create);
static FontFamily? _defaultInstance;
@$pb.TagNumber(1)
@@ -482,12 +466,9 @@
[$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(json, registry);
- static final $pb.BuilderInfo _i = $pb.BuilderInfo(
- _omitMessageNames ? '' : 'Directory',
- package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'),
- createEmptyInstance: create)
- ..pPM<FontFamily>(1, _omitFieldNames ? '' : 'family',
- subBuilder: FontFamily.create)
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Directory',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create)
+ ..pPM<FontFamily>(1, _omitFieldNames ? '' : 'family', subBuilder: FontFamily.create)
..aI(5, _omitFieldNames ? '' : 'version')
..aOS(6, _omitFieldNames ? '' : 'description')
..hasRequiredFields = false;
@@ -534,7 +515,5 @@
void clearDescription() => $_clearField(6);
}
-const $core.bool _omitFieldNames =
- $core.bool.fromEnvironment('protobuf.omit_field_names');
-const $core.bool _omitMessageNames =
- $core.bool.fromEnvironment('protobuf.omit_message_names');
+const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names');
+const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names');
diff --git a/packages/google_fonts/generator/generator.dart b/packages/google_fonts/generator/generator.dart
index ce943bc..1508b79 100644
--- a/packages/google_fonts/generator/generator.dart
+++ b/packages/google_fonts/generator/generator.dart
@@ -13,8 +13,7 @@
import 'fonts.pb.dart';
const String _generatedAllPartsFilePath = 'lib/src/google_fonts_all_parts.dart';
-String _generatedPartFilePath(String part) =>
- 'lib/src/google_fonts_parts/part_$part.dart';
+String _generatedPartFilePath(String part) => 'lib/src/google_fonts_parts/part_$part.dart';
const String _familiesSupportedPath = 'generator/families_supported';
const String _familiesDiffPath = 'generator/families_diff';
@@ -35,9 +34,7 @@
print(_success);
print('\nGenerating $_familiesSupportedPath & $_familiesDiffPath ...');
- File(
- _familiesSupportedPath,
- ).writeAsStringSync(familiesDelta.printableSupported());
+ File(_familiesSupportedPath).writeAsStringSync(familiesDelta.printableSupported());
File(_familiesDiffPath).writeAsStringSync(familiesDelta.markdownDiff());
print(_success);
@@ -66,9 +63,7 @@
Uri url(int directoryVersion) {
final String paddedVersion = directoryVersion.toString().padLeft(3, '0');
- return Uri.parse(
- 'https://fonts.gstatic.com/s/f/directory$paddedVersion.pb',
- );
+ return Uri.parse('https://fonts.gstatic.com/s/f/directory$paddedVersion.pb');
}
var didReachLatestUrl = false;
@@ -98,8 +93,7 @@
var i = 1;
for (final FontFamily family in fontDirectory.family) {
for (final Font font in family.fonts) {
- final urlString =
- 'https://fonts.gstatic.com/s/a/${_hashToString(font.file.hash)}.ttf';
+ final urlString = 'https://fonts.gstatic.com/s/a/${_hashToString(font.file.hash)}.ttf';
final Uri url = Uri.parse(urlString);
await _tryUrl(client, url, font);
print('Verified URL ($i/$totalFonts): $urlString');
@@ -114,8 +108,7 @@
final http.Response fileContents = await client.get(url);
final int actualFileLength = fileContents.bodyBytes.length;
final actualFileHash = sha256.convert(fileContents.bodyBytes).toString();
- if (font.file.fileSize != actualFileLength ||
- _hashToString(font.file.hash) != actualFileHash) {
+ if (font.file.fileSize != actualFileLength || _hashToString(font.file.hash) != actualFileHash) {
throw Exception('Font from $url did not match length of or checksum.');
}
} catch (e) {
@@ -147,14 +140,10 @@
void _init(Directory fontDirectory) {
// Currently supported families.
- final familiesSupported = Set<String>.from(
- File(_familiesSupportedPath).readAsLinesSync(),
- );
+ final familiesSupported = Set<String>.from(File(_familiesSupportedPath).readAsLinesSync());
// Newly supported families.
- all = Set<String>.from(
- fontDirectory.family.map<String>((FontFamily item) => item.name),
- );
+ all = Set<String>.from(fontDirectory.family.map<String>((FontFamily item) => item.name));
added = all.difference(familiesSupported);
removed = familiesSupported.difference(all);
@@ -166,12 +155,8 @@
// Diff of font families, suitable for markdown
// (e.g. CHANGELOG, PR description).
String markdownDiff() {
- final Iterable<String> addedPrintable = added.map(
- (String family) => ' - `$family`',
- );
- final Iterable<String> removedPrintable = removed.map(
- (String family) => ' - `$family`',
- );
+ final Iterable<String> addedPrintable = added.map((String family) => ' - `$family`');
+ final Iterable<String> removedPrintable = removed.map((String family) => ' - `$family`');
var diff = '';
if (addedPrintable.isNotEmpty) {
@@ -265,16 +250,13 @@
for (final Font variant in filteredVariants)
<String, Object>{
'variantWeight': variant.weight.start,
- 'variantStyle': variant.italic.start.round() == 1
- ? 'italic'
- : 'normal',
+ 'variantStyle': variant.italic.start.round() == 1 ? 'italic' : 'normal',
'hash': _hashToString(variant.file.hash),
'length': variant.file.fileSize,
},
],
'themeParams': <Map<String, String>>[
- for (final String themeParam in themeParams)
- <String, String>{'value': themeParam},
+ for (final String themeParam in themeParams) <String, String>{'value': themeParam},
],
});
}
@@ -288,9 +270,7 @@
final String firstLetter = methodName[0];
if (!methodsByLetter.containsKey(firstLetter)) {
allParts.add(<String, dynamic>{
- 'partFilePath': _generatedPartFilePath(
- firstLetter,
- ).replaceFirst('lib/src/', ''),
+ 'partFilePath': _generatedPartFilePath(firstLetter).replaceFirst('lib/src/', ''),
});
methodsByLetter[firstLetter] = <Map<String, dynamic>>[map];
} else {
@@ -303,10 +283,7 @@
File('generator/google_fonts_part.tmpl').readAsStringSync(),
htmlEscapeValues: false,
);
- methodsByLetter.forEach((
- String letter,
- List<Map<String, dynamic>> methods,
- ) async {
+ methodsByLetter.forEach((String letter, List<Map<String, dynamic>> methods) async {
final String renderedTemplate = partTemplate.renderString(<String, Object>{
'part': letter.toUpperCase(),
'method': methods,
@@ -319,12 +296,10 @@
File('generator/google_fonts.tmpl').readAsStringSync(),
htmlEscapeValues: false,
);
- final String renderedTemplate = template.renderString(
- <String, List<Map<String, dynamic>>>{
- 'allParts': allParts,
- 'method': methods,
- },
- );
+ final String renderedTemplate = template.renderString(<String, List<Map<String, dynamic>>>{
+ 'allParts': allParts,
+ 'method': methods,
+ });
_writeDartFile(_generatedAllPartsFilePath, renderedTemplate);
}
diff --git a/packages/google_fonts/lib/src/file_io.dart b/packages/google_fonts/lib/src/file_io.dart
index 83d7fa6..3d1689d 100644
--- a/packages/google_fonts/lib/src/file_io.dart
+++ b/packages/google_fonts/lib/src/file_io.dart
@@ -30,9 +30,6 @@
/// Stubbed out version of loadFontFromDeviceFileSystem from
/// `file_io_desktop_and_mobile.dart`.
-Future<ByteData?> loadFontFromDeviceFileSystem({
- required String name,
- required String fileHash,
-}) {
+Future<ByteData?> loadFontFromDeviceFileSystem({required String name, required String fileHash}) {
return Future<ByteData?>.value();
}
diff --git a/packages/google_fonts/lib/src/google_fonts_all_parts.dart b/packages/google_fonts/lib/src/google_fonts_all_parts.dart
index 1cace54..69ae98a 100644
--- a/packages/google_fonts/lib/src/google_fonts_all_parts.dart
+++ b/packages/google_fonts/lib/src/google_fonts_all_parts.dart
@@ -122,8 +122,7 @@
/// );
/// }
/// ```
- static Future<List<void>> pendingFonts([List<dynamic>? _]) =>
- Future.wait(pendingFontFutures);
+ static Future<List<void>> pendingFonts([List<dynamic>? _]) => Future.wait(pendingFontFutures);
/// Get a map of all available fonts.
///
@@ -2053,8 +2052,7 @@
///
/// Returns a map where the key is the name of the font family and the value
/// is the corresponding [GoogleFonts] `TextTheme` method.
- static Map<String, TextTheme Function([TextTheme?])>
- _asMapOfTextThemes() => const {
+ static Map<String, TextTheme Function([TextTheme?])> _asMapOfTextThemes() => const {
'ABeeZee': PartA.aBeeZeeTextTheme,
'ADLaM Display': PartA.aDLaMDisplayTextTheme,
'AR One Sans': PartA.arOneSansTextTheme,
@@ -3079,8 +3077,7 @@
'Noto Sans': PartN.notoSansTextTheme,
'Noto Sans Adlam': PartN.notoSansAdlamTextTheme,
'Noto Sans Adlam Unjoined': PartN.notoSansAdlamUnjoinedTextTheme,
- 'Noto Sans Anatolian Hieroglyphs':
- PartN.notoSansAnatolianHieroglyphsTextTheme,
+ 'Noto Sans Anatolian Hieroglyphs': PartN.notoSansAnatolianHieroglyphsTextTheme,
'Noto Sans Arabic': PartN.notoSansArabicTextTheme,
'Noto Sans Armenian': PartN.notoSansArmenianTextTheme,
'Noto Sans Avestan': PartN.notoSansAvestanTextTheme,
@@ -3108,8 +3105,7 @@
'Noto Sans Devanagari': PartN.notoSansDevanagariTextTheme,
'Noto Sans Display': PartN.notoSansDisplayTextTheme,
'Noto Sans Duployan': PartN.notoSansDuployanTextTheme,
- 'Noto Sans Egyptian Hieroglyphs':
- PartN.notoSansEgyptianHieroglyphsTextTheme,
+ 'Noto Sans Egyptian Hieroglyphs': PartN.notoSansEgyptianHieroglyphsTextTheme,
'Noto Sans Elbasan': PartN.notoSansElbasanTextTheme,
'Noto Sans Elymaic': PartN.notoSansElymaicTextTheme,
'Noto Sans Ethiopic': PartN.notoSansEthiopicTextTheme,
@@ -3127,10 +3123,8 @@
'Noto Sans Hebrew': PartN.notoSansHebrewTextTheme,
'Noto Sans Imperial Aramaic': PartN.notoSansImperialAramaicTextTheme,
'Noto Sans Indic Siyaq Numbers': PartN.notoSansIndicSiyaqNumbersTextTheme,
- 'Noto Sans Inscriptional Pahlavi':
- PartN.notoSansInscriptionalPahlaviTextTheme,
- 'Noto Sans Inscriptional Parthian':
- PartN.notoSansInscriptionalParthianTextTheme,
+ 'Noto Sans Inscriptional Pahlavi': PartN.notoSansInscriptionalPahlaviTextTheme,
+ 'Noto Sans Inscriptional Parthian': PartN.notoSansInscriptionalParthianTextTheme,
'Noto Sans JP': PartN.notoSansJpTextTheme,
'Noto Sans Javanese': PartN.notoSansJavaneseTextTheme,
'Noto Sans KR': PartN.notoSansKrTextTheme,
@@ -3285,8 +3279,7 @@
'Noto Serif Vithkuqi': PartN.notoSerifVithkuqiTextTheme,
'Noto Serif Yezidi': PartN.notoSerifYezidiTextTheme,
'Noto Traditional Nushu': PartN.notoTraditionalNushuTextTheme,
- 'Noto Znamenny Musical Notation':
- PartN.notoZnamennyMusicalNotationTextTheme,
+ 'Noto Znamenny Musical Notation': PartN.notoZnamennyMusicalNotationTextTheme,
'Nova Cut': PartN.novaCutTextTheme,
'Nova Flat': PartN.novaFlatTextTheme,
'Nova Mono': PartN.novaMonoTextTheme,
@@ -4358,22 +4351,19 @@
static const alumniSansCollegiateOne = PartA.alumniSansCollegiateOne;
/// See [PartA.alumniSansCollegiateOneTextTheme].
- static const alumniSansCollegiateOneTextTheme =
- PartA.alumniSansCollegiateOneTextTheme;
+ static const alumniSansCollegiateOneTextTheme = PartA.alumniSansCollegiateOneTextTheme;
/// See [PartA.alumniSansInlineOne].
static const alumniSansInlineOne = PartA.alumniSansInlineOne;
/// See [PartA.alumniSansInlineOneTextTheme].
- static const alumniSansInlineOneTextTheme =
- PartA.alumniSansInlineOneTextTheme;
+ static const alumniSansInlineOneTextTheme = PartA.alumniSansInlineOneTextTheme;
/// See [PartA.alumniSansPinstripe].
static const alumniSansPinstripe = PartA.alumniSansPinstripe;
/// See [PartA.alumniSansPinstripeTextTheme].
- static const alumniSansPinstripeTextTheme =
- PartA.alumniSansPinstripeTextTheme;
+ static const alumniSansPinstripeTextTheme = PartA.alumniSansPinstripeTextTheme;
/// See [PartA.alumniSansSc].
static const alumniSansSc = PartA.alumniSansSc;
@@ -4541,8 +4531,7 @@
static const annieUseYourTelescope = PartA.annieUseYourTelescope;
/// See [PartA.annieUseYourTelescopeTextTheme].
- static const annieUseYourTelescopeTextTheme =
- PartA.annieUseYourTelescopeTextTheme;
+ static const annieUseYourTelescopeTextTheme = PartA.annieUseYourTelescopeTextTheme;
/// See [PartA.anonymousPro].
static const anonymousPro = PartA.anonymousPro;
@@ -4782,22 +4771,19 @@
static const atkinsonHyperlegible = PartA.atkinsonHyperlegible;
/// See [PartA.atkinsonHyperlegibleTextTheme].
- static const atkinsonHyperlegibleTextTheme =
- PartA.atkinsonHyperlegibleTextTheme;
+ static const atkinsonHyperlegibleTextTheme = PartA.atkinsonHyperlegibleTextTheme;
/// See [PartA.atkinsonHyperlegibleMono].
static const atkinsonHyperlegibleMono = PartA.atkinsonHyperlegibleMono;
/// See [PartA.atkinsonHyperlegibleMonoTextTheme].
- static const atkinsonHyperlegibleMonoTextTheme =
- PartA.atkinsonHyperlegibleMonoTextTheme;
+ static const atkinsonHyperlegibleMonoTextTheme = PartA.atkinsonHyperlegibleMonoTextTheme;
/// See [PartA.atkinsonHyperlegibleNext].
static const atkinsonHyperlegibleNext = PartA.atkinsonHyperlegibleNext;
/// See [PartA.atkinsonHyperlegibleNextTextTheme].
- static const atkinsonHyperlegibleNextTextTheme =
- PartA.atkinsonHyperlegibleNextTextTheme;
+ static const atkinsonHyperlegibleNextTextTheme = PartA.atkinsonHyperlegibleNextTextTheme;
/// See [PartA.atma].
static const atma = PartA.atma;
@@ -5079,8 +5065,7 @@
static const barlowSemiCondensed = PartB.barlowSemiCondensed;
/// See [PartB.barlowSemiCondensedTextTheme].
- static const barlowSemiCondensedTextTheme =
- PartB.barlowSemiCondensedTextTheme;
+ static const barlowSemiCondensedTextTheme = PartB.barlowSemiCondensedTextTheme;
/// See [PartB.barriecito].
static const barriecito = PartB.barriecito;
@@ -5254,8 +5239,7 @@
static const bigShouldersStencil = PartB.bigShouldersStencil;
/// See [PartB.bigShouldersStencilTextTheme].
- static const bigShouldersStencilTextTheme =
- PartB.bigShouldersStencilTextTheme;
+ static const bigShouldersStencilTextTheme = PartB.bigShouldersStencilTextTheme;
/// See [PartB.bigelowRules].
static const bigelowRules = PartB.bigelowRules;
@@ -5321,8 +5305,7 @@
static const bitcountGridDoubleInk = PartB.bitcountGridDoubleInk;
/// See [PartB.bitcountGridDoubleInkTextTheme].
- static const bitcountGridDoubleInkTextTheme =
- PartB.bitcountGridDoubleInkTextTheme;
+ static const bitcountGridDoubleInkTextTheme = PartB.bitcountGridDoubleInkTextTheme;
/// See [PartB.bitcountGridSingle].
static const bitcountGridSingle = PartB.bitcountGridSingle;
@@ -5334,8 +5317,7 @@
static const bitcountGridSingleInk = PartB.bitcountGridSingleInk;
/// See [PartB.bitcountGridSingleInkTextTheme].
- static const bitcountGridSingleInkTextTheme =
- PartB.bitcountGridSingleInkTextTheme;
+ static const bitcountGridSingleInkTextTheme = PartB.bitcountGridSingleInkTextTheme;
/// See [PartB.bitcountInk].
static const bitcountInk = PartB.bitcountInk;
@@ -5353,8 +5335,7 @@
static const bitcountPropDoubleInk = PartB.bitcountPropDoubleInk;
/// See [PartB.bitcountPropDoubleInkTextTheme].
- static const bitcountPropDoubleInkTextTheme =
- PartB.bitcountPropDoubleInkTextTheme;
+ static const bitcountPropDoubleInkTextTheme = PartB.bitcountPropDoubleInkTextTheme;
/// See [PartB.bitcountPropSingle].
static const bitcountPropSingle = PartB.bitcountPropSingle;
@@ -5366,8 +5347,7 @@
static const bitcountPropSingleInk = PartB.bitcountPropSingleInk;
/// See [PartB.bitcountPropSingleInkTextTheme].
- static const bitcountPropSingleInkTextTheme =
- PartB.bitcountPropSingleInkTextTheme;
+ static const bitcountPropSingleInkTextTheme = PartB.bitcountPropSingleInkTextTheme;
/// See [PartB.bitcountSingle].
static const bitcountSingle = PartB.bitcountSingle;
@@ -5391,8 +5371,7 @@
static const blackAndWhitePicture = PartB.blackAndWhitePicture;
/// See [PartB.blackAndWhitePictureTextTheme].
- static const blackAndWhitePictureTextTheme =
- PartB.blackAndWhitePictureTextTheme;
+ static const blackAndWhitePictureTextTheme = PartB.blackAndWhitePictureTextTheme;
/// See [PartB.blackHanSans].
static const blackHanSans = PartB.blackHanSans;
@@ -5644,8 +5623,7 @@
static const cactusClassicalSerif = PartC.cactusClassicalSerif;
/// See [PartC.cactusClassicalSerifTextTheme].
- static const cactusClassicalSerifTextTheme =
- PartC.cactusClassicalSerifTextTheme;
+ static const cactusClassicalSerifTextTheme = PartC.cactusClassicalSerifTextTheme;
/// See [PartC.caesarDressing].
static const caesarDressing = PartC.caesarDressing;
@@ -5993,8 +5971,7 @@
static const chocolateClassicalSans = PartC.chocolateClassicalSans;
/// See [PartC.chocolateClassicalSansTextTheme].
- static const chocolateClassicalSansTextTheme =
- PartC.chocolateClassicalSansTextTheme;
+ static const chocolateClassicalSansTextTheme = PartC.chocolateClassicalSansTextTheme;
/// See [PartC.chokokutai].
static const chokokutai = PartC.chokokutai;
@@ -6636,8 +6613,7 @@
static const eduNswActFoundation = PartE.eduNswActFoundation;
/// See [PartE.eduNswActFoundationTextTheme].
- static const eduNswActFoundationTextTheme =
- PartE.eduNswActFoundationTextTheme;
+ static const eduNswActFoundationTextTheme = PartE.eduNswActFoundationTextTheme;
/// See [PartE.eduNswActHandPre].
static const eduNswActHandPre = PartE.eduNswActHandPre;
@@ -6997,8 +6973,7 @@
static const firaSansExtraCondensed = PartF.firaSansExtraCondensed;
/// See [PartF.firaSansExtraCondensedTextTheme].
- static const firaSansExtraCondensedTextTheme =
- PartF.firaSansExtraCondensedTextTheme;
+ static const firaSansExtraCondensedTextTheme = PartF.firaSansExtraCondensedTextTheme;
/// See [PartF.fjallaOne].
static const fjallaOne = PartF.fjallaOne;
@@ -7490,8 +7465,7 @@
static const goudyBookletter1911 = PartG.goudyBookletter1911;
/// See [PartG.goudyBookletter1911TextTheme].
- static const goudyBookletter1911TextTheme =
- PartG.goudyBookletter1911TextTheme;
+ static const goudyBookletter1911TextTheme = PartG.goudyBookletter1911TextTheme;
/// See [PartG.gowunBatang].
static const gowunBatang = PartG.gowunBatang;
@@ -7863,8 +7837,7 @@
static const ibmPlexSansDevanagari = PartI.ibmPlexSansDevanagari;
/// See [PartI.ibmPlexSansDevanagariTextTheme].
- static const ibmPlexSansDevanagariTextTheme =
- PartI.ibmPlexSansDevanagariTextTheme;
+ static const ibmPlexSansDevanagariTextTheme = PartI.ibmPlexSansDevanagariTextTheme;
/// See [PartI.ibmPlexSansHebrew].
static const ibmPlexSansHebrew = PartI.ibmPlexSansHebrew;
@@ -7894,8 +7867,7 @@
static const ibmPlexSansThaiLooped = PartI.ibmPlexSansThaiLooped;
/// See [PartI.ibmPlexSansThaiLoopedTextTheme].
- static const ibmPlexSansThaiLoopedTextTheme =
- PartI.ibmPlexSansThaiLoopedTextTheme;
+ static const ibmPlexSansThaiLoopedTextTheme = PartI.ibmPlexSansThaiLoopedTextTheme;
/// See [PartI.ibmPlexSerif].
static const ibmPlexSerif = PartI.ibmPlexSerif;
@@ -7949,8 +7921,7 @@
static const imFellFrenchCanonSc = PartI.imFellFrenchCanonSc;
/// See [PartI.imFellFrenchCanonScTextTheme].
- static const imFellFrenchCanonScTextTheme =
- PartI.imFellFrenchCanonScTextTheme;
+ static const imFellFrenchCanonScTextTheme = PartI.imFellFrenchCanonScTextTheme;
/// See [PartI.imFellGreatPrimer].
static const imFellGreatPrimer = PartI.imFellGreatPrimer;
@@ -7962,8 +7933,7 @@
static const imFellGreatPrimerSc = PartI.imFellGreatPrimerSc;
/// See [PartI.imFellGreatPrimerScTextTheme].
- static const imFellGreatPrimerScTextTheme =
- PartI.imFellGreatPrimerScTextTheme;
+ static const imFellGreatPrimerScTextTheme = PartI.imFellGreatPrimerScTextTheme;
/// See [PartI.iansui].
static const iansui = PartI.iansui;
@@ -8167,8 +8137,7 @@
static const jacquardaBastarda9Charted = PartJ.jacquardaBastarda9Charted;
/// See [PartJ.jacquardaBastarda9ChartedTextTheme].
- static const jacquardaBastarda9ChartedTextTheme =
- PartJ.jacquardaBastarda9ChartedTextTheme;
+ static const jacquardaBastarda9ChartedTextTheme = PartJ.jacquardaBastarda9ChartedTextTheme;
/// See [PartJ.jacquesFrancois].
static const jacquesFrancois = PartJ.jacquesFrancois;
@@ -8180,8 +8149,7 @@
static const jacquesFrancoisShadow = PartJ.jacquesFrancoisShadow;
/// See [PartJ.jacquesFrancoisShadowTextTheme].
- static const jacquesFrancoisShadowTextTheme =
- PartJ.jacquesFrancoisShadowTextTheme;
+ static const jacquesFrancoisShadowTextTheme = PartJ.jacquesFrancoisShadowTextTheme;
/// See [PartJ.jaini].
static const jaini = PartJ.jaini;
@@ -8367,8 +8335,7 @@
static const justMeAgainDownHere = PartJ.justMeAgainDownHere;
/// See [PartJ.justMeAgainDownHereTextTheme].
- static const justMeAgainDownHereTextTheme =
- PartJ.justMeAgainDownHereTextTheme;
+ static const justMeAgainDownHereTextTheme = PartJ.justMeAgainDownHereTextTheme;
/// See [PartK.k2d].
static const k2d = PartK.k2d;
@@ -8944,8 +8911,7 @@
static const libertinusSerifDisplay = PartL.libertinusSerifDisplay;
/// See [PartL.libertinusSerifDisplayTextTheme].
- static const libertinusSerifDisplayTextTheme =
- PartL.libertinusSerifDisplayTextTheme;
+ static const libertinusSerifDisplayTextTheme = PartL.libertinusSerifDisplayTextTheme;
/// See [PartL.libreBarcode128].
static const libreBarcode128 = PartL.libreBarcode128;
@@ -8957,8 +8923,7 @@
static const libreBarcode128Text = PartL.libreBarcode128Text;
/// See [PartL.libreBarcode128TextTextTheme].
- static const libreBarcode128TextTextTheme =
- PartL.libreBarcode128TextTextTheme;
+ static const libreBarcode128TextTextTheme = PartL.libreBarcode128TextTextTheme;
/// See [PartL.libreBarcode39].
static const libreBarcode39 = PartL.libreBarcode39;
@@ -8970,15 +8935,13 @@
static const libreBarcode39Extended = PartL.libreBarcode39Extended;
/// See [PartL.libreBarcode39ExtendedTextTheme].
- static const libreBarcode39ExtendedTextTheme =
- PartL.libreBarcode39ExtendedTextTheme;
+ static const libreBarcode39ExtendedTextTheme = PartL.libreBarcode39ExtendedTextTheme;
/// See [PartL.libreBarcode39ExtendedText].
static const libreBarcode39ExtendedText = PartL.libreBarcode39ExtendedText;
/// See [PartL.libreBarcode39ExtendedTextTextTheme].
- static const libreBarcode39ExtendedTextTextTheme =
- PartL.libreBarcode39ExtendedTextTextTheme;
+ static const libreBarcode39ExtendedTextTextTheme = PartL.libreBarcode39ExtendedTextTextTheme;
/// See [PartL.libreBarcode39Text].
static const libreBarcode39Text = PartL.libreBarcode39Text;
@@ -8990,8 +8953,7 @@
static const libreBarcodeEan13Text = PartL.libreBarcodeEan13Text;
/// See [PartL.libreBarcodeEan13TextTextTheme].
- static const libreBarcodeEan13TextTextTheme =
- PartL.libreBarcodeEan13TextTextTheme;
+ static const libreBarcodeEan13TextTextTheme = PartL.libreBarcodeEan13TextTextTheme;
/// See [PartL.libreBaskerville].
static const libreBaskerville = PartL.libreBaskerville;
@@ -9369,8 +9331,7 @@
static const manufacturingConsent = PartM.manufacturingConsent;
/// See [PartM.manufacturingConsentTextTheme].
- static const manufacturingConsentTextTheme =
- PartM.manufacturingConsentTextTheme;
+ static const manufacturingConsentTextTheme = PartM.manufacturingConsentTextTheme;
/// See [PartM.marcellus].
static const marcellus = PartM.marcellus;
@@ -9808,15 +9769,13 @@
static const montserratAlternates = PartM.montserratAlternates;
/// See [PartM.montserratAlternatesTextTheme].
- static const montserratAlternatesTextTheme =
- PartM.montserratAlternatesTextTheme;
+ static const montserratAlternatesTextTheme = PartM.montserratAlternatesTextTheme;
/// See [PartM.montserratUnderline].
static const montserratUnderline = PartM.montserratUnderline;
/// See [PartM.montserratUnderlineTextTheme].
- static const montserratUnderlineTextTheme =
- PartM.montserratUnderlineTextTheme;
+ static const montserratUnderlineTextTheme = PartM.montserratUnderlineTextTheme;
/// See [PartM.mooLahLah].
static const mooLahLah = PartM.mooLahLah;
@@ -9852,8 +9811,7 @@
static const mountainsOfChristmas = PartM.mountainsOfChristmas;
/// See [PartM.mountainsOfChristmasTextTheme].
- static const mountainsOfChristmasTextTheme =
- PartM.mountainsOfChristmasTextTheme;
+ static const mountainsOfChristmasTextTheme = PartM.mountainsOfChristmasTextTheme;
/// See [PartM.mouseMemoirs].
static const mouseMemoirs = PartM.mouseMemoirs;
@@ -10207,16 +10165,13 @@
static const notoSansAdlamUnjoined = PartN.notoSansAdlamUnjoined;
/// See [PartN.notoSansAdlamUnjoinedTextTheme].
- static const notoSansAdlamUnjoinedTextTheme =
- PartN.notoSansAdlamUnjoinedTextTheme;
+ static const notoSansAdlamUnjoinedTextTheme = PartN.notoSansAdlamUnjoinedTextTheme;
/// See [PartN.notoSansAnatolianHieroglyphs].
- static const notoSansAnatolianHieroglyphs =
- PartN.notoSansAnatolianHieroglyphs;
+ static const notoSansAnatolianHieroglyphs = PartN.notoSansAnatolianHieroglyphs;
/// See [PartN.notoSansAnatolianHieroglyphsTextTheme].
- static const notoSansAnatolianHieroglyphsTextTheme =
- PartN.notoSansAnatolianHieroglyphsTextTheme;
+ static const notoSansAnatolianHieroglyphsTextTheme = PartN.notoSansAnatolianHieroglyphsTextTheme;
/// See [PartN.notoSansArabic].
static const notoSansArabic = PartN.notoSansArabic;
@@ -10294,8 +10249,7 @@
static const notoSansCanadianAboriginal = PartN.notoSansCanadianAboriginal;
/// See [PartN.notoSansCanadianAboriginalTextTheme].
- static const notoSansCanadianAboriginalTextTheme =
- PartN.notoSansCanadianAboriginalTextTheme;
+ static const notoSansCanadianAboriginalTextTheme = PartN.notoSansCanadianAboriginalTextTheme;
/// See [PartN.notoSansCarian].
static const notoSansCarian = PartN.notoSansCarian;
@@ -10307,8 +10261,7 @@
static const notoSansCaucasianAlbanian = PartN.notoSansCaucasianAlbanian;
/// See [PartN.notoSansCaucasianAlbanianTextTheme].
- static const notoSansCaucasianAlbanianTextTheme =
- PartN.notoSansCaucasianAlbanianTextTheme;
+ static const notoSansCaucasianAlbanianTextTheme = PartN.notoSansCaucasianAlbanianTextTheme;
/// See [PartN.notoSansChakma].
static const notoSansChakma = PartN.notoSansChakma;
@@ -10356,8 +10309,7 @@
static const notoSansCyproMinoan = PartN.notoSansCyproMinoan;
/// See [PartN.notoSansCyproMinoanTextTheme].
- static const notoSansCyproMinoanTextTheme =
- PartN.notoSansCyproMinoanTextTheme;
+ static const notoSansCyproMinoanTextTheme = PartN.notoSansCyproMinoanTextTheme;
/// See [PartN.notoSansDeseret].
static const notoSansDeseret = PartN.notoSansDeseret;
@@ -10387,8 +10339,7 @@
static const notoSansEgyptianHieroglyphs = PartN.notoSansEgyptianHieroglyphs;
/// See [PartN.notoSansEgyptianHieroglyphsTextTheme].
- static const notoSansEgyptianHieroglyphsTextTheme =
- PartN.notoSansEgyptianHieroglyphsTextTheme;
+ static const notoSansEgyptianHieroglyphsTextTheme = PartN.notoSansEgyptianHieroglyphsTextTheme;
/// See [PartN.notoSansElbasan].
static const notoSansElbasan = PartN.notoSansElbasan;
@@ -10442,8 +10393,7 @@
static const notoSansGunjalaGondi = PartN.notoSansGunjalaGondi;
/// See [PartN.notoSansGunjalaGondiTextTheme].
- static const notoSansGunjalaGondiTextTheme =
- PartN.notoSansGunjalaGondiTextTheme;
+ static const notoSansGunjalaGondiTextTheme = PartN.notoSansGunjalaGondiTextTheme;
/// See [PartN.notoSansGurmukhi].
static const notoSansGurmukhi = PartN.notoSansGurmukhi;
@@ -10461,8 +10411,7 @@
static const notoSansHanifiRohingya = PartN.notoSansHanifiRohingya;
/// See [PartN.notoSansHanifiRohingyaTextTheme].
- static const notoSansHanifiRohingyaTextTheme =
- PartN.notoSansHanifiRohingyaTextTheme;
+ static const notoSansHanifiRohingyaTextTheme = PartN.notoSansHanifiRohingyaTextTheme;
/// See [PartN.notoSansHanunoo].
static const notoSansHanunoo = PartN.notoSansHanunoo;
@@ -10486,27 +10435,22 @@
static const notoSansImperialAramaic = PartN.notoSansImperialAramaic;
/// See [PartN.notoSansImperialAramaicTextTheme].
- static const notoSansImperialAramaicTextTheme =
- PartN.notoSansImperialAramaicTextTheme;
+ static const notoSansImperialAramaicTextTheme = PartN.notoSansImperialAramaicTextTheme;
/// See [PartN.notoSansIndicSiyaqNumbers].
static const notoSansIndicSiyaqNumbers = PartN.notoSansIndicSiyaqNumbers;
/// See [PartN.notoSansIndicSiyaqNumbersTextTheme].
- static const notoSansIndicSiyaqNumbersTextTheme =
- PartN.notoSansIndicSiyaqNumbersTextTheme;
+ static const notoSansIndicSiyaqNumbersTextTheme = PartN.notoSansIndicSiyaqNumbersTextTheme;
/// See [PartN.notoSansInscriptionalPahlavi].
- static const notoSansInscriptionalPahlavi =
- PartN.notoSansInscriptionalPahlavi;
+ static const notoSansInscriptionalPahlavi = PartN.notoSansInscriptionalPahlavi;
/// See [PartN.notoSansInscriptionalPahlaviTextTheme].
- static const notoSansInscriptionalPahlaviTextTheme =
- PartN.notoSansInscriptionalPahlaviTextTheme;
+ static const notoSansInscriptionalPahlaviTextTheme = PartN.notoSansInscriptionalPahlaviTextTheme;
/// See [PartN.notoSansInscriptionalParthian].
- static const notoSansInscriptionalParthian =
- PartN.notoSansInscriptionalParthian;
+ static const notoSansInscriptionalParthian = PartN.notoSansInscriptionalParthian;
/// See [PartN.notoSansInscriptionalParthianTextTheme].
static const notoSansInscriptionalParthianTextTheme =
@@ -10666,8 +10610,7 @@
static const notoSansMasaramGondi = PartN.notoSansMasaramGondi;
/// See [PartN.notoSansMasaramGondiTextTheme].
- static const notoSansMasaramGondiTextTheme =
- PartN.notoSansMasaramGondiTextTheme;
+ static const notoSansMasaramGondiTextTheme = PartN.notoSansMasaramGondiTextTheme;
/// See [PartN.notoSansMath].
static const notoSansMath = PartN.notoSansMath;
@@ -10679,29 +10622,25 @@
static const notoSansMayanNumerals = PartN.notoSansMayanNumerals;
/// See [PartN.notoSansMayanNumeralsTextTheme].
- static const notoSansMayanNumeralsTextTheme =
- PartN.notoSansMayanNumeralsTextTheme;
+ static const notoSansMayanNumeralsTextTheme = PartN.notoSansMayanNumeralsTextTheme;
/// See [PartN.notoSansMedefaidrin].
static const notoSansMedefaidrin = PartN.notoSansMedefaidrin;
/// See [PartN.notoSansMedefaidrinTextTheme].
- static const notoSansMedefaidrinTextTheme =
- PartN.notoSansMedefaidrinTextTheme;
+ static const notoSansMedefaidrinTextTheme = PartN.notoSansMedefaidrinTextTheme;
/// See [PartN.notoSansMeeteiMayek].
static const notoSansMeeteiMayek = PartN.notoSansMeeteiMayek;
/// See [PartN.notoSansMeeteiMayekTextTheme].
- static const notoSansMeeteiMayekTextTheme =
- PartN.notoSansMeeteiMayekTextTheme;
+ static const notoSansMeeteiMayekTextTheme = PartN.notoSansMeeteiMayekTextTheme;
/// See [PartN.notoSansMendeKikakui].
static const notoSansMendeKikakui = PartN.notoSansMendeKikakui;
/// See [PartN.notoSansMendeKikakuiTextTheme].
- static const notoSansMendeKikakuiTextTheme =
- PartN.notoSansMendeKikakuiTextTheme;
+ static const notoSansMendeKikakuiTextTheme = PartN.notoSansMendeKikakuiTextTheme;
/// See [PartN.notoSansMeroitic].
static const notoSansMeroitic = PartN.notoSansMeroitic;
@@ -10761,8 +10700,7 @@
static const notoSansNKoUnjoined = PartN.notoSansNKoUnjoined;
/// See [PartN.notoSansNKoUnjoinedTextTheme].
- static const notoSansNKoUnjoinedTextTheme =
- PartN.notoSansNKoUnjoinedTextTheme;
+ static const notoSansNKoUnjoinedTextTheme = PartN.notoSansNKoUnjoinedTextTheme;
/// See [PartN.notoSansNabataean].
static const notoSansNabataean = PartN.notoSansNabataean;
@@ -10780,8 +10718,7 @@
static const notoSansNandinagari = PartN.notoSansNandinagari;
/// See [PartN.notoSansNandinagariTextTheme].
- static const notoSansNandinagariTextTheme =
- PartN.notoSansNandinagariTextTheme;
+ static const notoSansNandinagariTextTheme = PartN.notoSansNandinagariTextTheme;
/// See [PartN.notoSansNewTaiLue].
static const notoSansNewTaiLue = PartN.notoSansNewTaiLue;
@@ -10817,8 +10754,7 @@
static const notoSansOldHungarian = PartN.notoSansOldHungarian;
/// See [PartN.notoSansOldHungarianTextTheme].
- static const notoSansOldHungarianTextTheme =
- PartN.notoSansOldHungarianTextTheme;
+ static const notoSansOldHungarianTextTheme = PartN.notoSansOldHungarianTextTheme;
/// See [PartN.notoSansOldItalic].
static const notoSansOldItalic = PartN.notoSansOldItalic;
@@ -10830,8 +10766,7 @@
static const notoSansOldNorthArabian = PartN.notoSansOldNorthArabian;
/// See [PartN.notoSansOldNorthArabianTextTheme].
- static const notoSansOldNorthArabianTextTheme =
- PartN.notoSansOldNorthArabianTextTheme;
+ static const notoSansOldNorthArabianTextTheme = PartN.notoSansOldNorthArabianTextTheme;
/// See [PartN.notoSansOldPermic].
static const notoSansOldPermic = PartN.notoSansOldPermic;
@@ -10855,8 +10790,7 @@
static const notoSansOldSouthArabian = PartN.notoSansOldSouthArabian;
/// See [PartN.notoSansOldSouthArabianTextTheme].
- static const notoSansOldSouthArabianTextTheme =
- PartN.notoSansOldSouthArabianTextTheme;
+ static const notoSansOldSouthArabianTextTheme = PartN.notoSansOldSouthArabianTextTheme;
/// See [PartN.notoSansOldTurkic].
static const notoSansOldTurkic = PartN.notoSansOldTurkic;
@@ -10886,8 +10820,7 @@
static const notoSansPahawhHmong = PartN.notoSansPahawhHmong;
/// See [PartN.notoSansPahawhHmongTextTheme].
- static const notoSansPahawhHmongTextTheme =
- PartN.notoSansPahawhHmongTextTheme;
+ static const notoSansPahawhHmongTextTheme = PartN.notoSansPahawhHmongTextTheme;
/// See [PartN.notoSansPalmyrene].
static const notoSansPalmyrene = PartN.notoSansPalmyrene;
@@ -10917,8 +10850,7 @@
static const notoSansPsalterPahlavi = PartN.notoSansPsalterPahlavi;
/// See [PartN.notoSansPsalterPahlaviTextTheme].
- static const notoSansPsalterPahlaviTextTheme =
- PartN.notoSansPsalterPahlaviTextTheme;
+ static const notoSansPsalterPahlaviTextTheme = PartN.notoSansPsalterPahlaviTextTheme;
/// See [PartN.notoSansRejang].
static const notoSansRejang = PartN.notoSansRejang;
@@ -10972,8 +10904,7 @@
static const notoSansSignWriting = PartN.notoSansSignWriting;
/// See [PartN.notoSansSignWritingTextTheme].
- static const notoSansSignWritingTextTheme =
- PartN.notoSansSignWritingTextTheme;
+ static const notoSansSignWritingTextTheme = PartN.notoSansSignWritingTextTheme;
/// See [PartN.notoSansSinhala].
static const notoSansSinhala = PartN.notoSansSinhala;
@@ -10991,8 +10922,7 @@
static const notoSansSoraSompeng = PartN.notoSansSoraSompeng;
/// See [PartN.notoSansSoraSompengTextTheme].
- static const notoSansSoraSompengTextTheme =
- PartN.notoSansSoraSompengTextTheme;
+ static const notoSansSoraSompengTextTheme = PartN.notoSansSoraSompengTextTheme;
/// See [PartN.notoSansSoyombo].
static const notoSansSoyombo = PartN.notoSansSoyombo;
@@ -11016,8 +10946,7 @@
static const notoSansSylotiNagri = PartN.notoSansSylotiNagri;
/// See [PartN.notoSansSylotiNagriTextTheme].
- static const notoSansSylotiNagriTextTheme =
- PartN.notoSansSylotiNagriTextTheme;
+ static const notoSansSylotiNagriTextTheme = PartN.notoSansSylotiNagriTextTheme;
/// See [PartN.notoSansSymbols].
static const notoSansSymbols = PartN.notoSansSymbols;
@@ -11041,15 +10970,13 @@
static const notoSansSyriacEastern = PartN.notoSansSyriacEastern;
/// See [PartN.notoSansSyriacEasternTextTheme].
- static const notoSansSyriacEasternTextTheme =
- PartN.notoSansSyriacEasternTextTheme;
+ static const notoSansSyriacEasternTextTheme = PartN.notoSansSyriacEasternTextTheme;
/// See [PartN.notoSansSyriacWestern].
static const notoSansSyriacWestern = PartN.notoSansSyriacWestern;
/// See [PartN.notoSansSyriacWesternTextTheme].
- static const notoSansSyriacWesternTextTheme =
- PartN.notoSansSyriacWesternTextTheme;
+ static const notoSansSyriacWesternTextTheme = PartN.notoSansSyriacWesternTextTheme;
/// See [PartN.notoSansTc].
static const notoSansTc = PartN.notoSansTc;
@@ -11103,8 +11030,7 @@
static const notoSansTamilSupplement = PartN.notoSansTamilSupplement;
/// See [PartN.notoSansTamilSupplementTextTheme].
- static const notoSansTamilSupplementTextTheme =
- PartN.notoSansTamilSupplementTextTheme;
+ static const notoSansTamilSupplementTextTheme = PartN.notoSansTamilSupplementTextTheme;
/// See [PartN.notoSansTangsa].
static const notoSansTangsa = PartN.notoSansTangsa;
@@ -11188,8 +11114,7 @@
static const notoSansZanabazarSquare = PartN.notoSansZanabazarSquare;
/// See [PartN.notoSansZanabazarSquareTextTheme].
- static const notoSansZanabazarSquareTextTheme =
- PartN.notoSansZanabazarSquareTextTheme;
+ static const notoSansZanabazarSquareTextTheme = PartN.notoSansZanabazarSquareTextTheme;
/// See [PartN.notoSerif].
static const notoSerif = PartN.notoSerif;
@@ -11225,8 +11150,7 @@
static const notoSerifDevanagari = PartN.notoSerifDevanagari;
/// See [PartN.notoSerifDevanagariTextTheme].
- static const notoSerifDevanagariTextTheme =
- PartN.notoSerifDevanagariTextTheme;
+ static const notoSerifDevanagariTextTheme = PartN.notoSerifDevanagariTextTheme;
/// See [PartN.notoSerifDisplay].
static const notoSerifDisplay = PartN.notoSerifDisplay;
@@ -11238,8 +11162,7 @@
static const notoSerifDivesAkuru = PartN.notoSerifDivesAkuru;
/// See [PartN.notoSerifDivesAkuruTextTheme].
- static const notoSerifDivesAkuruTextTheme =
- PartN.notoSerifDivesAkuruTextTheme;
+ static const notoSerifDivesAkuruTextTheme = PartN.notoSerifDivesAkuruTextTheme;
/// See [PartN.notoSerifDogra].
static const notoSerifDogra = PartN.notoSerifDogra;
@@ -11293,8 +11216,7 @@
static const notoSerifHentaigana = PartN.notoSerifHentaigana;
/// See [PartN.notoSerifHentaiganaTextTheme].
- static const notoSerifHentaiganaTextTheme =
- PartN.notoSerifHentaiganaTextTheme;
+ static const notoSerifHentaiganaTextTheme = PartN.notoSerifHentaiganaTextTheme;
/// See [PartN.notoSerifJp].
static const notoSerifJp = PartN.notoSerifJp;
@@ -11318,8 +11240,7 @@
static const notoSerifKhitanSmallScript = PartN.notoSerifKhitanSmallScript;
/// See [PartN.notoSerifKhitanSmallScriptTextTheme].
- static const notoSerifKhitanSmallScriptTextTheme =
- PartN.notoSerifKhitanSmallScriptTextTheme;
+ static const notoSerifKhitanSmallScriptTextTheme = PartN.notoSerifKhitanSmallScriptTextTheme;
/// See [PartN.notoSerifKhmer].
static const notoSerifKhmer = PartN.notoSerifKhmer;
@@ -11379,8 +11300,7 @@
static const notoSerifOttomanSiyaq = PartN.notoSerifOttomanSiyaq;
/// See [PartN.notoSerifOttomanSiyaqTextTheme].
- static const notoSerifOttomanSiyaqTextTheme =
- PartN.notoSerifOttomanSiyaqTextTheme;
+ static const notoSerifOttomanSiyaqTextTheme = PartN.notoSerifOttomanSiyaqTextTheme;
/// See [PartN.notoSerifSc].
static const notoSerifSc = PartN.notoSerifSc;
@@ -11458,15 +11378,13 @@
static const notoTraditionalNushu = PartN.notoTraditionalNushu;
/// See [PartN.notoTraditionalNushuTextTheme].
- static const notoTraditionalNushuTextTheme =
- PartN.notoTraditionalNushuTextTheme;
+ static const notoTraditionalNushuTextTheme = PartN.notoTraditionalNushuTextTheme;
/// See [PartN.notoZnamennyMusicalNotation].
static const notoZnamennyMusicalNotation = PartN.notoZnamennyMusicalNotation;
/// See [PartN.notoZnamennyMusicalNotationTextTheme].
- static const notoZnamennyMusicalNotationTextTheme =
- PartN.notoZnamennyMusicalNotationTextTheme;
+ static const notoZnamennyMusicalNotationTextTheme = PartN.notoZnamennyMusicalNotationTextTheme;
/// See [PartN.novaCut].
static const novaCut = PartN.novaCut;
@@ -11598,8 +11516,7 @@
static const oleoScriptSwashCaps = PartO.oleoScriptSwashCaps;
/// See [PartO.oleoScriptSwashCapsTextTheme].
- static const oleoScriptSwashCapsTextTheme =
- PartO.oleoScriptSwashCapsTextTheme;
+ static const oleoScriptSwashCapsTextTheme = PartO.oleoScriptSwashCapsTextTheme;
/// See [PartO.onest].
static const onest = PartO.onest;
@@ -11779,8 +11696,7 @@
static const padyakkeExpandedOne = PartP.padyakkeExpandedOne;
/// See [PartP.padyakkeExpandedOneTextTheme].
- static const padyakkeExpandedOneTextTheme =
- PartP.padyakkeExpandedOneTextTheme;
+ static const padyakkeExpandedOneTextTheme = PartP.padyakkeExpandedOneTextTheme;
/// See [PartP.palanquin].
static const palanquin = PartP.palanquin;
@@ -12086,8 +12002,7 @@
static const playwriteAuNswGuides = PartP.playwriteAuNswGuides;
/// See [PartP.playwriteAuNswGuidesTextTheme].
- static const playwriteAuNswGuidesTextTheme =
- PartP.playwriteAuNswGuidesTextTheme;
+ static const playwriteAuNswGuidesTextTheme = PartP.playwriteAuNswGuidesTextTheme;
/// See [PartP.playwriteAuQld].
static const playwriteAuQld = PartP.playwriteAuQld;
@@ -12099,8 +12014,7 @@
static const playwriteAuQldGuides = PartP.playwriteAuQldGuides;
/// See [PartP.playwriteAuQldGuidesTextTheme].
- static const playwriteAuQldGuidesTextTheme =
- PartP.playwriteAuQldGuidesTextTheme;
+ static const playwriteAuQldGuidesTextTheme = PartP.playwriteAuQldGuidesTextTheme;
/// See [PartP.playwriteAuSa].
static const playwriteAuSa = PartP.playwriteAuSa;
@@ -12112,8 +12026,7 @@
static const playwriteAuSaGuides = PartP.playwriteAuSaGuides;
/// See [PartP.playwriteAuSaGuidesTextTheme].
- static const playwriteAuSaGuidesTextTheme =
- PartP.playwriteAuSaGuidesTextTheme;
+ static const playwriteAuSaGuidesTextTheme = PartP.playwriteAuSaGuidesTextTheme;
/// See [PartP.playwriteAuTas].
static const playwriteAuTas = PartP.playwriteAuTas;
@@ -12125,8 +12038,7 @@
static const playwriteAuTasGuides = PartP.playwriteAuTasGuides;
/// See [PartP.playwriteAuTasGuidesTextTheme].
- static const playwriteAuTasGuidesTextTheme =
- PartP.playwriteAuTasGuidesTextTheme;
+ static const playwriteAuTasGuidesTextTheme = PartP.playwriteAuTasGuidesTextTheme;
/// See [PartP.playwriteAuVic].
static const playwriteAuVic = PartP.playwriteAuVic;
@@ -12138,8 +12050,7 @@
static const playwriteAuVicGuides = PartP.playwriteAuVicGuides;
/// See [PartP.playwriteAuVicGuidesTextTheme].
- static const playwriteAuVicGuidesTextTheme =
- PartP.playwriteAuVicGuidesTextTheme;
+ static const playwriteAuVicGuidesTextTheme = PartP.playwriteAuVicGuidesTextTheme;
/// See [PartP.playwriteBeVlg].
static const playwriteBeVlg = PartP.playwriteBeVlg;
@@ -12151,8 +12062,7 @@
static const playwriteBeVlgGuides = PartP.playwriteBeVlgGuides;
/// See [PartP.playwriteBeVlgGuidesTextTheme].
- static const playwriteBeVlgGuidesTextTheme =
- PartP.playwriteBeVlgGuidesTextTheme;
+ static const playwriteBeVlgGuidesTextTheme = PartP.playwriteBeVlgGuidesTextTheme;
/// See [PartP.playwriteBeWal].
static const playwriteBeWal = PartP.playwriteBeWal;
@@ -12164,8 +12074,7 @@
static const playwriteBeWalGuides = PartP.playwriteBeWalGuides;
/// See [PartP.playwriteBeWalGuidesTextTheme].
- static const playwriteBeWalGuidesTextTheme =
- PartP.playwriteBeWalGuidesTextTheme;
+ static const playwriteBeWalGuidesTextTheme = PartP.playwriteBeWalGuidesTextTheme;
/// See [PartP.playwriteBr].
static const playwriteBr = PartP.playwriteBr;
@@ -12249,8 +12158,7 @@
static const playwriteDeGrundGuides = PartP.playwriteDeGrundGuides;
/// See [PartP.playwriteDeGrundGuidesTextTheme].
- static const playwriteDeGrundGuidesTextTheme =
- PartP.playwriteDeGrundGuidesTextTheme;
+ static const playwriteDeGrundGuidesTextTheme = PartP.playwriteDeGrundGuidesTextTheme;
/// See [PartP.playwriteDeLa].
static const playwriteDeLa = PartP.playwriteDeLa;
@@ -12262,8 +12170,7 @@
static const playwriteDeLaGuides = PartP.playwriteDeLaGuides;
/// See [PartP.playwriteDeLaGuidesTextTheme].
- static const playwriteDeLaGuidesTextTheme =
- PartP.playwriteDeLaGuidesTextTheme;
+ static const playwriteDeLaGuidesTextTheme = PartP.playwriteDeLaGuidesTextTheme;
/// See [PartP.playwriteDeSas].
static const playwriteDeSas = PartP.playwriteDeSas;
@@ -12275,8 +12182,7 @@
static const playwriteDeSasGuides = PartP.playwriteDeSasGuides;
/// See [PartP.playwriteDeSasGuidesTextTheme].
- static const playwriteDeSasGuidesTextTheme =
- PartP.playwriteDeSasGuidesTextTheme;
+ static const playwriteDeSasGuidesTextTheme = PartP.playwriteDeSasGuidesTextTheme;
/// See [PartP.playwriteDeVa].
static const playwriteDeVa = PartP.playwriteDeVa;
@@ -12288,8 +12194,7 @@
static const playwriteDeVaGuides = PartP.playwriteDeVaGuides;
/// See [PartP.playwriteDeVaGuidesTextTheme].
- static const playwriteDeVaGuidesTextTheme =
- PartP.playwriteDeVaGuidesTextTheme;
+ static const playwriteDeVaGuidesTextTheme = PartP.playwriteDeVaGuidesTextTheme;
/// See [PartP.playwriteDkLoopet].
static const playwriteDkLoopet = PartP.playwriteDkLoopet;
@@ -12301,8 +12206,7 @@
static const playwriteDkLoopetGuides = PartP.playwriteDkLoopetGuides;
/// See [PartP.playwriteDkLoopetGuidesTextTheme].
- static const playwriteDkLoopetGuidesTextTheme =
- PartP.playwriteDkLoopetGuidesTextTheme;
+ static const playwriteDkLoopetGuidesTextTheme = PartP.playwriteDkLoopetGuidesTextTheme;
/// See [PartP.playwriteDkUloopet].
static const playwriteDkUloopet = PartP.playwriteDkUloopet;
@@ -12314,8 +12218,7 @@
static const playwriteDkUloopetGuides = PartP.playwriteDkUloopetGuides;
/// See [PartP.playwriteDkUloopetGuidesTextTheme].
- static const playwriteDkUloopetGuidesTextTheme =
- PartP.playwriteDkUloopetGuidesTextTheme;
+ static const playwriteDkUloopetGuidesTextTheme = PartP.playwriteDkUloopetGuidesTextTheme;
/// See [PartP.playwriteEs].
static const playwriteEs = PartP.playwriteEs;
@@ -12333,8 +12236,7 @@
static const playwriteEsDecoGuides = PartP.playwriteEsDecoGuides;
/// See [PartP.playwriteEsDecoGuidesTextTheme].
- static const playwriteEsDecoGuidesTextTheme =
- PartP.playwriteEsDecoGuidesTextTheme;
+ static const playwriteEsDecoGuidesTextTheme = PartP.playwriteEsDecoGuidesTextTheme;
/// See [PartP.playwriteEsGuides].
static const playwriteEsGuides = PartP.playwriteEsGuides;
@@ -12352,8 +12254,7 @@
static const playwriteFrModerneGuides = PartP.playwriteFrModerneGuides;
/// See [PartP.playwriteFrModerneGuidesTextTheme].
- static const playwriteFrModerneGuidesTextTheme =
- PartP.playwriteFrModerneGuidesTextTheme;
+ static const playwriteFrModerneGuidesTextTheme = PartP.playwriteFrModerneGuidesTextTheme;
/// See [PartP.playwriteFrTrad].
static const playwriteFrTrad = PartP.playwriteFrTrad;
@@ -12365,8 +12266,7 @@
static const playwriteFrTradGuides = PartP.playwriteFrTradGuides;
/// See [PartP.playwriteFrTradGuidesTextTheme].
- static const playwriteFrTradGuidesTextTheme =
- PartP.playwriteFrTradGuidesTextTheme;
+ static const playwriteFrTradGuidesTextTheme = PartP.playwriteFrTradGuidesTextTheme;
/// See [PartP.playwriteGbJ].
static const playwriteGbJ = PartP.playwriteGbJ;
@@ -12414,8 +12314,7 @@
static const playwriteHrLijevaGuides = PartP.playwriteHrLijevaGuides;
/// See [PartP.playwriteHrLijevaGuidesTextTheme].
- static const playwriteHrLijevaGuidesTextTheme =
- PartP.playwriteHrLijevaGuidesTextTheme;
+ static const playwriteHrLijevaGuidesTextTheme = PartP.playwriteHrLijevaGuidesTextTheme;
/// See [PartP.playwriteHu].
static const playwriteHu = PartP.playwriteHu;
@@ -12487,8 +12386,7 @@
static const playwriteItModernaGuides = PartP.playwriteItModernaGuides;
/// See [PartP.playwriteItModernaGuidesTextTheme].
- static const playwriteItModernaGuidesTextTheme =
- PartP.playwriteItModernaGuidesTextTheme;
+ static const playwriteItModernaGuidesTextTheme = PartP.playwriteItModernaGuidesTextTheme;
/// See [PartP.playwriteItTrad].
static const playwriteItTrad = PartP.playwriteItTrad;
@@ -12500,8 +12398,7 @@
static const playwriteItTradGuides = PartP.playwriteItTradGuides;
/// See [PartP.playwriteItTradGuidesTextTheme].
- static const playwriteItTradGuidesTextTheme =
- PartP.playwriteItTradGuidesTextTheme;
+ static const playwriteItTradGuidesTextTheme = PartP.playwriteItTradGuidesTextTheme;
/// See [PartP.playwriteMx].
static const playwriteMx = PartP.playwriteMx;
@@ -12525,8 +12422,7 @@
static const playwriteNgModernGuides = PartP.playwriteNgModernGuides;
/// See [PartP.playwriteNgModernGuidesTextTheme].
- static const playwriteNgModernGuidesTextTheme =
- PartP.playwriteNgModernGuidesTextTheme;
+ static const playwriteNgModernGuidesTextTheme = PartP.playwriteNgModernGuidesTextTheme;
/// See [PartP.playwriteNl].
static const playwriteNl = PartP.playwriteNl;
@@ -12646,8 +12542,7 @@
static const playwriteUsModernGuides = PartP.playwriteUsModernGuides;
/// See [PartP.playwriteUsModernGuidesTextTheme].
- static const playwriteUsModernGuidesTextTheme =
- PartP.playwriteUsModernGuidesTextTheme;
+ static const playwriteUsModernGuidesTextTheme = PartP.playwriteUsModernGuidesTextTheme;
/// See [PartP.playwriteUsTrad].
static const playwriteUsTrad = PartP.playwriteUsTrad;
@@ -12659,8 +12554,7 @@
static const playwriteUsTradGuides = PartP.playwriteUsTradGuides;
/// See [PartP.playwriteUsTradGuidesTextTheme].
- static const playwriteUsTradGuidesTextTheme =
- PartP.playwriteUsTradGuidesTextTheme;
+ static const playwriteUsTradGuidesTextTheme = PartP.playwriteUsTradGuidesTextTheme;
/// See [PartP.playwriteVn].
static const playwriteVn = PartP.playwriteVn;
@@ -13146,8 +13040,7 @@
static const redditSansCondensed = PartR.redditSansCondensed;
/// See [PartR.redditSansCondensedTextTheme].
- static const redditSansCondensedTextTheme =
- PartR.redditSansCondensedTextTheme;
+ static const redditSansCondensedTextTheme = PartR.redditSansCondensedTextTheme;
/// See [PartR.redressed].
static const redressed = PartR.redressed;
@@ -13393,8 +13286,7 @@
static const rubikDoodleTriangles = PartR.rubikDoodleTriangles;
/// See [PartR.rubikDoodleTrianglesTextTheme].
- static const rubikDoodleTrianglesTextTheme =
- PartR.rubikDoodleTrianglesTextTheme;
+ static const rubikDoodleTrianglesTextTheme = PartR.rubikDoodleTrianglesTextTheme;
/// See [PartR.rubikGemstones].
static const rubikGemstones = PartR.rubikGemstones;
@@ -13820,8 +13712,7 @@
static const shadowsIntoLightTwo = PartS.shadowsIntoLightTwo;
/// See [PartS.shadowsIntoLightTwoTextTheme].
- static const shadowsIntoLightTwoTextTheme =
- PartS.shadowsIntoLightTwoTextTheme;
+ static const shadowsIntoLightTwoTextTheme = PartS.shadowsIntoLightTwoTextTheme;
/// See [PartS.shafarik].
static const shafarik = PartS.shafarik;
@@ -13995,8 +13886,7 @@
static const sixtyfourConvergence = PartS.sixtyfourConvergence;
/// See [PartS.sixtyfourConvergenceTextTheme].
- static const sixtyfourConvergenceTextTheme =
- PartS.sixtyfourConvergenceTextTheme;
+ static const sixtyfourConvergenceTextTheme = PartS.sixtyfourConvergenceTextTheme;
/// See [PartS.skranji].
static const skranji = PartS.skranji;
@@ -14098,15 +13988,13 @@
static const sofiaSansExtraCondensed = PartS.sofiaSansExtraCondensed;
/// See [PartS.sofiaSansExtraCondensedTextTheme].
- static const sofiaSansExtraCondensedTextTheme =
- PartS.sofiaSansExtraCondensedTextTheme;
+ static const sofiaSansExtraCondensedTextTheme = PartS.sofiaSansExtraCondensedTextTheme;
/// See [PartS.sofiaSansSemiCondensed].
static const sofiaSansSemiCondensed = PartS.sofiaSansSemiCondensed;
/// See [PartS.sofiaSansSemiCondensedTextTheme].
- static const sofiaSansSemiCondensedTextTheme =
- PartS.sofiaSansSemiCondensedTextTheme;
+ static const sofiaSansSemiCondensedTextTheme = PartS.sofiaSansSemiCondensedTextTheme;
/// See [PartS.solitreo].
static const solitreo = PartS.solitreo;
@@ -14208,15 +14096,13 @@
static const specialGothicCondensedOne = PartS.specialGothicCondensedOne;
/// See [PartS.specialGothicCondensedOneTextTheme].
- static const specialGothicCondensedOneTextTheme =
- PartS.specialGothicCondensedOneTextTheme;
+ static const specialGothicCondensedOneTextTheme = PartS.specialGothicCondensedOneTextTheme;
/// See [PartS.specialGothicExpandedOne].
static const specialGothicExpandedOne = PartS.specialGothicExpandedOne;
/// See [PartS.specialGothicExpandedOneTextTheme].
- static const specialGothicExpandedOneTextTheme =
- PartS.specialGothicExpandedOneTextTheme;
+ static const specialGothicExpandedOneTextTheme = PartS.specialGothicExpandedOneTextTheme;
/// See [PartS.spectral].
static const spectral = PartS.spectral;
@@ -14282,8 +14168,7 @@
static const sreeKrushnadevaraya = PartS.sreeKrushnadevaraya;
/// See [PartS.sreeKrushnadevarayaTextTheme].
- static const sreeKrushnadevarayaTextTheme =
- PartS.sreeKrushnadevarayaTextTheme;
+ static const sreeKrushnadevarayaTextTheme = PartS.sreeKrushnadevarayaTextTheme;
/// See [PartS.sriracha].
static const sriracha = PartS.sriracha;
@@ -14355,8 +14240,7 @@
static const stintUltraCondensed = PartS.stintUltraCondensed;
/// See [PartS.stintUltraCondensedTextTheme].
- static const stintUltraCondensedTextTheme =
- PartS.stintUltraCondensedTextTheme;
+ static const stintUltraCondensedTextTheme = PartS.stintUltraCondensedTextTheme;
/// See [PartS.stintUltraExpanded].
static const stintUltraExpanded = PartS.stintUltraExpanded;
@@ -14686,22 +14570,19 @@
static const tiroDevanagariHindi = PartT.tiroDevanagariHindi;
/// See [PartT.tiroDevanagariHindiTextTheme].
- static const tiroDevanagariHindiTextTheme =
- PartT.tiroDevanagariHindiTextTheme;
+ static const tiroDevanagariHindiTextTheme = PartT.tiroDevanagariHindiTextTheme;
/// See [PartT.tiroDevanagariMarathi].
static const tiroDevanagariMarathi = PartT.tiroDevanagariMarathi;
/// See [PartT.tiroDevanagariMarathiTextTheme].
- static const tiroDevanagariMarathiTextTheme =
- PartT.tiroDevanagariMarathiTextTheme;
+ static const tiroDevanagariMarathiTextTheme = PartT.tiroDevanagariMarathiTextTheme;
/// See [PartT.tiroDevanagariSanskrit].
static const tiroDevanagariSanskrit = PartT.tiroDevanagariSanskrit;
/// See [PartT.tiroDevanagariSanskritTextTheme].
- static const tiroDevanagariSanskritTextTheme =
- PartT.tiroDevanagariSanskritTextTheme;
+ static const tiroDevanagariSanskritTextTheme = PartT.tiroDevanagariSanskritTextTheme;
/// See [PartT.tiroGurmukhi].
static const tiroGurmukhi = PartT.tiroGurmukhi;
@@ -15109,8 +14990,7 @@
static const waitingForTheSunrise = PartW.waitingForTheSunrise;
/// See [PartW.waitingForTheSunriseTextTheme].
- static const waitingForTheSunriseTextTheme =
- PartW.waitingForTheSunriseTextTheme;
+ static const waitingForTheSunriseTextTheme = PartW.waitingForTheSunriseTextTheme;
/// See [PartW.wallpoet].
static const wallpoet = PartW.wallpoet;
@@ -15350,15 +15230,13 @@
static const yujiHentaiganaAkari = PartY.yujiHentaiganaAkari;
/// See [PartY.yujiHentaiganaAkariTextTheme].
- static const yujiHentaiganaAkariTextTheme =
- PartY.yujiHentaiganaAkariTextTheme;
+ static const yujiHentaiganaAkariTextTheme = PartY.yujiHentaiganaAkariTextTheme;
/// See [PartY.yujiHentaiganaAkebono].
static const yujiHentaiganaAkebono = PartY.yujiHentaiganaAkebono;
/// See [PartY.yujiHentaiganaAkebonoTextTheme].
- static const yujiHentaiganaAkebonoTextTheme =
- PartY.yujiHentaiganaAkebonoTextTheme;
+ static const yujiHentaiganaAkebonoTextTheme = PartY.yujiHentaiganaAkebonoTextTheme;
/// See [PartY.yujiMai].
static const yujiMai = PartY.yujiMai;
@@ -15388,8 +15266,7 @@
static const zcoolQingKeHuangYou = PartZ.zcoolQingKeHuangYou;
/// See [PartZ.zcoolQingKeHuangYouTextTheme].
- static const zcoolQingKeHuangYouTextTheme =
- PartZ.zcoolQingKeHuangYouTextTheme;
+ static const zcoolQingKeHuangYouTextTheme = PartZ.zcoolQingKeHuangYouTextTheme;
/// See [PartZ.zcoolXiaoWei].
static const zcoolXiaoWei = PartZ.zcoolXiaoWei;
@@ -15413,15 +15290,13 @@
static const zalandoSansExpanded = PartZ.zalandoSansExpanded;
/// See [PartZ.zalandoSansExpandedTextTheme].
- static const zalandoSansExpandedTextTheme =
- PartZ.zalandoSansExpandedTextTheme;
+ static const zalandoSansExpandedTextTheme = PartZ.zalandoSansExpandedTextTheme;
/// See [PartZ.zalandoSansSemiExpanded].
static const zalandoSansSemiExpanded = PartZ.zalandoSansSemiExpanded;
/// See [PartZ.zalandoSansSemiExpandedTextTheme].
- static const zalandoSansSemiExpandedTextTheme =
- PartZ.zalandoSansSemiExpandedTextTheme;
+ static const zalandoSansSemiExpandedTextTheme = PartZ.zalandoSansSemiExpandedTextTheme;
/// See [PartZ.zenAntique].
static const zenAntique = PartZ.zenAntique;
@@ -15445,8 +15320,7 @@
static const zenKakuGothicAntique = PartZ.zenKakuGothicAntique;
/// See [PartZ.zenKakuGothicAntiqueTextTheme].
- static const zenKakuGothicAntiqueTextTheme =
- PartZ.zenKakuGothicAntiqueTextTheme;
+ static const zenKakuGothicAntiqueTextTheme = PartZ.zenKakuGothicAntiqueTextTheme;
/// See [PartZ.zenKakuGothicNew].
static const zenKakuGothicNew = PartZ.zenKakuGothicNew;
diff --git a/packages/google_fonts/lib/src/google_fonts_base.dart b/packages/google_fonts/lib/src/google_fonts_base.dart
index d7827e4..a2a403f 100755
--- a/packages/google_fonts/lib/src/google_fonts_base.dart
+++ b/packages/google_fonts/lib/src/google_fonts_base.dart
@@ -165,10 +165,7 @@
// Attempt to load this font via http, unless disallowed.
if (GoogleFonts.config.allowRuntimeFetching) {
- byteData = _httpFetchFontAndSaveToDevice(
- familyWithVariantString,
- descriptor.file,
- );
+ byteData = _httpFetchFontAndSaveToDevice(familyWithVariantString, descriptor.file);
if (await byteData != null) {
return await loadFontByteData(familyWithVariantString, byteData);
}
@@ -206,10 +203,7 @@
/// Loads a font with [FontLoader], given its name and byte-representation.
@visibleForTesting
-Future<void> loadFontByteData(
- String familyWithVariantString,
- Future<ByteData?>? byteData,
-) async {
+Future<void> loadFontByteData(String familyWithVariantString, Future<ByteData?>? byteData) async {
if (byteData == null) {
return;
}
@@ -249,10 +243,7 @@
/// it is the first time it is being loaded.
///
/// This function can return `null` if the font fails to load from the URL.
-Future<ByteData> _httpFetchFontAndSaveToDevice(
- String fontName,
- GoogleFontsFile file,
-) async {
+Future<ByteData> _httpFetchFontAndSaveToDevice(String fontName, GoogleFontsFile file) async {
final Uri? uri = Uri.tryParse(file.url);
if (uri == null) {
throw Exception('Invalid fontUrl: ${file.url}');
@@ -267,9 +258,7 @@
}
if (response.statusCode == 200) {
if (!_isFileSecure(file, response.bodyBytes)) {
- throw Exception(
- 'File from ${file.url} did not match expected length and checksum.',
- );
+ throw Exception('File from ${file.url} did not match expected length and checksum.');
}
_unawaited(
@@ -314,18 +303,13 @@
}
final String apiFilenamePrefix = familyWithVariant.toApiFilenamePrefix();
- final fileTypes = isWeb
- ? ['.woff2', '.woff', '.ttf', '.otf']
- : ['.ttf', '.otf'];
+ final fileTypes = isWeb ? ['.woff2', '.woff', '.ttf', '.otf'] : ['.ttf', '.otf'];
// Iterate by file type priority, ensuring preferred formats are selected.
for (final fileType in fileTypes) {
for (final String asset in manifestValues) {
if (asset.endsWith(fileType)) {
- final String assetWithoutExtension = asset.substring(
- 0,
- asset.length - fileType.length,
- );
+ final String assetWithoutExtension = asset.substring(0, asset.length - fileType.length);
if (assetWithoutExtension.endsWith(apiFilenamePrefix)) {
return asset;
}
@@ -339,8 +323,7 @@
bool _isFileSecure(GoogleFontsFile file, Uint8List bytes) {
final int actualFileLength = bytes.length;
final actualFileHash = sha256.convert(bytes).toString();
- return file.expectedLength == actualFileLength &&
- file.expectedFileHash == actualFileHash;
+ return file.expectedLength == actualFileLength && file.expectedFileHash == actualFileHash;
}
void _unawaited(Future<void> future) {}
diff --git a/packages/google_fonts/lib/src/google_fonts_descriptor.dart b/packages/google_fonts/lib/src/google_fonts_descriptor.dart
index 126ef9f..62769eb 100644
--- a/packages/google_fonts/lib/src/google_fonts_descriptor.dart
+++ b/packages/google_fonts/lib/src/google_fonts_descriptor.dart
@@ -14,10 +14,7 @@
/// The [familyWithVariant] describes the font family and variant, while
/// the [file] contains information about the font file such as its hash and
/// expected length.
- const GoogleFontsDescriptor({
- required this.familyWithVariant,
- required this.file,
- });
+ const GoogleFontsDescriptor({required this.familyWithVariant, required this.file});
/// The font family and variant information.
///
diff --git a/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart b/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart
index 949e9cb..aa9cdf2 100644
--- a/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart
+++ b/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart
@@ -7,10 +7,7 @@
/// Represents a Google Fonts API variant in Flutter-specific types.
class GoogleFontsFamilyWithVariant {
/// Creates a representation of a Google Fonts family with a specific variant.
- const GoogleFontsFamilyWithVariant({
- required this.family,
- required this.googleFontsVariant,
- });
+ const GoogleFontsFamilyWithVariant({required this.family, required this.googleFontsVariant});
/// The name of the Google Fonts family.
///
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart
index 1f74da8..909c861 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart
@@ -5991,19 +5991,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: alumniSansCollegiateOne(textStyle: textTheme.displayLarge),
- displayMedium: alumniSansCollegiateOne(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: alumniSansCollegiateOne(textStyle: textTheme.displayMedium),
displaySmall: alumniSansCollegiateOne(textStyle: textTheme.displaySmall),
- headlineLarge: alumniSansCollegiateOne(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: alumniSansCollegiateOne(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: alumniSansCollegiateOne(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: alumniSansCollegiateOne(textStyle: textTheme.headlineLarge),
+ headlineMedium: alumniSansCollegiateOne(textStyle: textTheme.headlineMedium),
+ headlineSmall: alumniSansCollegiateOne(textStyle: textTheme.headlineSmall),
titleLarge: alumniSansCollegiateOne(textStyle: textTheme.titleLarge),
titleMedium: alumniSansCollegiateOne(textStyle: textTheme.titleMedium),
titleSmall: alumniSansCollegiateOne(textStyle: textTheme.titleSmall),
@@ -9725,9 +9717,7 @@
displayMedium: annieUseYourTelescope(textStyle: textTheme.displayMedium),
displaySmall: annieUseYourTelescope(textStyle: textTheme.displaySmall),
headlineLarge: annieUseYourTelescope(textStyle: textTheme.headlineLarge),
- headlineMedium: annieUseYourTelescope(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: annieUseYourTelescope(textStyle: textTheme.headlineMedium),
headlineSmall: annieUseYourTelescope(textStyle: textTheme.headlineSmall),
titleLarge: annieUseYourTelescope(textStyle: textTheme.titleLarge),
titleMedium: annieUseYourTelescope(textStyle: textTheme.titleMedium),
@@ -14222,19 +14212,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: atkinsonHyperlegibleMono(textStyle: textTheme.displayLarge),
- displayMedium: atkinsonHyperlegibleMono(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: atkinsonHyperlegibleMono(textStyle: textTheme.displayMedium),
displaySmall: atkinsonHyperlegibleMono(textStyle: textTheme.displaySmall),
- headlineLarge: atkinsonHyperlegibleMono(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: atkinsonHyperlegibleMono(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: atkinsonHyperlegibleMono(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: atkinsonHyperlegibleMono(textStyle: textTheme.headlineLarge),
+ headlineMedium: atkinsonHyperlegibleMono(textStyle: textTheme.headlineMedium),
+ headlineSmall: atkinsonHyperlegibleMono(textStyle: textTheme.headlineSmall),
titleLarge: atkinsonHyperlegibleMono(textStyle: textTheme.titleLarge),
titleMedium: atkinsonHyperlegibleMono(textStyle: textTheme.titleMedium),
titleSmall: atkinsonHyperlegibleMono(textStyle: textTheme.titleSmall),
@@ -14408,19 +14390,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: atkinsonHyperlegibleNext(textStyle: textTheme.displayLarge),
- displayMedium: atkinsonHyperlegibleNext(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: atkinsonHyperlegibleNext(textStyle: textTheme.displayMedium),
displaySmall: atkinsonHyperlegibleNext(textStyle: textTheme.displaySmall),
- headlineLarge: atkinsonHyperlegibleNext(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: atkinsonHyperlegibleNext(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: atkinsonHyperlegibleNext(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: atkinsonHyperlegibleNext(textStyle: textTheme.headlineLarge),
+ headlineMedium: atkinsonHyperlegibleNext(textStyle: textTheme.headlineMedium),
+ headlineSmall: atkinsonHyperlegibleNext(textStyle: textTheme.headlineSmall),
titleLarge: atkinsonHyperlegibleNext(textStyle: textTheme.titleLarge),
titleMedium: atkinsonHyperlegibleNext(textStyle: textTheme.titleMedium),
titleSmall: atkinsonHyperlegibleNext(textStyle: textTheme.titleSmall),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart
index b949b17..a742952 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart
@@ -8203,9 +8203,7 @@
displayMedium: bitcountGridDoubleInk(textStyle: textTheme.displayMedium),
displaySmall: bitcountGridDoubleInk(textStyle: textTheme.displaySmall),
headlineLarge: bitcountGridDoubleInk(textStyle: textTheme.headlineLarge),
- headlineMedium: bitcountGridDoubleInk(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: bitcountGridDoubleInk(textStyle: textTheme.headlineMedium),
headlineSmall: bitcountGridDoubleInk(textStyle: textTheme.headlineSmall),
titleLarge: bitcountGridDoubleInk(textStyle: textTheme.titleLarge),
titleMedium: bitcountGridDoubleInk(textStyle: textTheme.titleMedium),
@@ -8491,9 +8489,7 @@
displayMedium: bitcountGridSingleInk(textStyle: textTheme.displayMedium),
displaySmall: bitcountGridSingleInk(textStyle: textTheme.displaySmall),
headlineLarge: bitcountGridSingleInk(textStyle: textTheme.headlineLarge),
- headlineMedium: bitcountGridSingleInk(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: bitcountGridSingleInk(textStyle: textTheme.headlineMedium),
headlineSmall: bitcountGridSingleInk(textStyle: textTheme.headlineSmall),
titleLarge: bitcountGridSingleInk(textStyle: textTheme.titleLarge),
titleMedium: bitcountGridSingleInk(textStyle: textTheme.titleMedium),
@@ -8922,9 +8918,7 @@
displayMedium: bitcountPropDoubleInk(textStyle: textTheme.displayMedium),
displaySmall: bitcountPropDoubleInk(textStyle: textTheme.displaySmall),
headlineLarge: bitcountPropDoubleInk(textStyle: textTheme.headlineLarge),
- headlineMedium: bitcountPropDoubleInk(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: bitcountPropDoubleInk(textStyle: textTheme.headlineMedium),
headlineSmall: bitcountPropDoubleInk(textStyle: textTheme.headlineSmall),
titleLarge: bitcountPropDoubleInk(textStyle: textTheme.titleLarge),
titleMedium: bitcountPropDoubleInk(textStyle: textTheme.titleMedium),
@@ -9210,9 +9204,7 @@
displayMedium: bitcountPropSingleInk(textStyle: textTheme.displayMedium),
displaySmall: bitcountPropSingleInk(textStyle: textTheme.displaySmall),
headlineLarge: bitcountPropSingleInk(textStyle: textTheme.headlineLarge),
- headlineMedium: bitcountPropSingleInk(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: bitcountPropSingleInk(textStyle: textTheme.headlineMedium),
headlineSmall: bitcountPropSingleInk(textStyle: textTheme.headlineSmall),
titleLarge: bitcountPropSingleInk(textStyle: textTheme.titleLarge),
titleMedium: bitcountPropSingleInk(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart
index efbfd5c..4b9acf7 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart
@@ -6404,9 +6404,7 @@
displayMedium: chocolateClassicalSans(textStyle: textTheme.displayMedium),
displaySmall: chocolateClassicalSans(textStyle: textTheme.displaySmall),
headlineLarge: chocolateClassicalSans(textStyle: textTheme.headlineLarge),
- headlineMedium: chocolateClassicalSans(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: chocolateClassicalSans(textStyle: textTheme.headlineMedium),
headlineSmall: chocolateClassicalSans(textStyle: textTheme.headlineSmall),
titleLarge: chocolateClassicalSans(textStyle: textTheme.titleLarge),
titleMedium: chocolateClassicalSans(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart
index c4a7608..0e5e4a8 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart
@@ -2943,9 +2943,7 @@
displayMedium: firaSansExtraCondensed(textStyle: textTheme.displayMedium),
displaySmall: firaSansExtraCondensed(textStyle: textTheme.displaySmall),
headlineLarge: firaSansExtraCondensed(textStyle: textTheme.headlineLarge),
- headlineMedium: firaSansExtraCondensed(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: firaSansExtraCondensed(textStyle: textTheme.headlineMedium),
headlineSmall: firaSansExtraCondensed(textStyle: textTheme.headlineSmall),
titleLarge: firaSansExtraCondensed(textStyle: textTheme.titleLarge),
titleMedium: firaSansExtraCondensed(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart
index c263314..69edbe8 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart
@@ -612,9 +612,7 @@
displayMedium: ibmPlexSansDevanagari(textStyle: textTheme.displayMedium),
displaySmall: ibmPlexSansDevanagari(textStyle: textTheme.displaySmall),
headlineLarge: ibmPlexSansDevanagari(textStyle: textTheme.headlineLarge),
- headlineMedium: ibmPlexSansDevanagari(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: ibmPlexSansDevanagari(textStyle: textTheme.headlineMedium),
headlineSmall: ibmPlexSansDevanagari(textStyle: textTheme.headlineSmall),
titleLarge: ibmPlexSansDevanagari(textStyle: textTheme.titleLarge),
titleMedium: ibmPlexSansDevanagari(textStyle: textTheme.titleMedium),
@@ -1259,9 +1257,7 @@
displayMedium: ibmPlexSansThaiLooped(textStyle: textTheme.displayMedium),
displaySmall: ibmPlexSansThaiLooped(textStyle: textTheme.displaySmall),
headlineLarge: ibmPlexSansThaiLooped(textStyle: textTheme.headlineLarge),
- headlineMedium: ibmPlexSansThaiLooped(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: ibmPlexSansThaiLooped(textStyle: textTheme.headlineMedium),
headlineSmall: ibmPlexSansThaiLooped(textStyle: textTheme.headlineSmall),
titleLarge: ibmPlexSansThaiLooped(textStyle: textTheme.titleLarge),
titleMedium: ibmPlexSansThaiLooped(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart
index 5fd34e9..14bdb48 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart
@@ -516,24 +516,12 @@
static TextTheme jacquardaBastarda9ChartedTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: jacquardaBastarda9Charted(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: jacquardaBastarda9Charted(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: jacquardaBastarda9Charted(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: jacquardaBastarda9Charted(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: jacquardaBastarda9Charted(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: jacquardaBastarda9Charted(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: jacquardaBastarda9Charted(textStyle: textTheme.displayLarge),
+ displayMedium: jacquardaBastarda9Charted(textStyle: textTheme.displayMedium),
+ displaySmall: jacquardaBastarda9Charted(textStyle: textTheme.displaySmall),
+ headlineLarge: jacquardaBastarda9Charted(textStyle: textTheme.headlineLarge),
+ headlineMedium: jacquardaBastarda9Charted(textStyle: textTheme.headlineMedium),
+ headlineSmall: jacquardaBastarda9Charted(textStyle: textTheme.headlineSmall),
titleLarge: jacquardaBastarda9Charted(textStyle: textTheme.titleLarge),
titleMedium: jacquardaBastarda9Charted(textStyle: textTheme.titleMedium),
titleSmall: jacquardaBastarda9Charted(textStyle: textTheme.titleSmall),
@@ -706,9 +694,7 @@
displayMedium: jacquesFrancoisShadow(textStyle: textTheme.displayMedium),
displaySmall: jacquesFrancoisShadow(textStyle: textTheme.displaySmall),
headlineLarge: jacquesFrancoisShadow(textStyle: textTheme.headlineLarge),
- headlineMedium: jacquesFrancoisShadow(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: jacquesFrancoisShadow(textStyle: textTheme.headlineMedium),
headlineSmall: jacquesFrancoisShadow(textStyle: textTheme.headlineSmall),
titleLarge: jacquesFrancoisShadow(textStyle: textTheme.titleLarge),
titleMedium: jacquesFrancoisShadow(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart
index 1d63527..5186f5f 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart
@@ -4005,9 +4005,7 @@
displayMedium: libertinusSerifDisplay(textStyle: textTheme.displayMedium),
displaySmall: libertinusSerifDisplay(textStyle: textTheme.displaySmall),
headlineLarge: libertinusSerifDisplay(textStyle: textTheme.headlineLarge),
- headlineMedium: libertinusSerifDisplay(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: libertinusSerifDisplay(textStyle: textTheme.headlineMedium),
headlineSmall: libertinusSerifDisplay(textStyle: textTheme.headlineSmall),
titleLarge: libertinusSerifDisplay(textStyle: textTheme.titleLarge),
titleMedium: libertinusSerifDisplay(textStyle: textTheme.titleMedium),
@@ -4222,13 +4220,8 @@
double? decorationThickness,
}) {
final fonts = <GoogleFontsVariant, GoogleFontsFile>{
- const GoogleFontsVariant(
- fontWeight: FontWeight.w400,
- fontStyle: FontStyle.normal,
- ): GoogleFontsFile(
- 'a25d156d437de61fd0000652114599b4d454496b7c82a255a6c2ae7fce3052ab',
- 7628,
- ),
+ const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal):
+ GoogleFontsFile('a25d156d437de61fd0000652114599b4d454496b7c82a255a6c2ae7fce3052ab', 7628),
};
return googleFontsTextStyle(
@@ -4355,9 +4348,7 @@
displayMedium: libreBarcode39Extended(textStyle: textTheme.displayMedium),
displaySmall: libreBarcode39Extended(textStyle: textTheme.displaySmall),
headlineLarge: libreBarcode39Extended(textStyle: textTheme.headlineLarge),
- headlineMedium: libreBarcode39Extended(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: libreBarcode39Extended(textStyle: textTheme.headlineMedium),
headlineSmall: libreBarcode39Extended(textStyle: textTheme.headlineSmall),
titleLarge: libreBarcode39Extended(textStyle: textTheme.titleLarge),
titleMedium: libreBarcode39Extended(textStyle: textTheme.titleMedium),
@@ -4440,24 +4431,12 @@
static TextTheme libreBarcode39ExtendedTextTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: libreBarcode39ExtendedText(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: libreBarcode39ExtendedText(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: libreBarcode39ExtendedText(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: libreBarcode39ExtendedText(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: libreBarcode39ExtendedText(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: libreBarcode39ExtendedText(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: libreBarcode39ExtendedText(textStyle: textTheme.displayLarge),
+ displayMedium: libreBarcode39ExtendedText(textStyle: textTheme.displayMedium),
+ displaySmall: libreBarcode39ExtendedText(textStyle: textTheme.displaySmall),
+ headlineLarge: libreBarcode39ExtendedText(textStyle: textTheme.headlineLarge),
+ headlineMedium: libreBarcode39ExtendedText(textStyle: textTheme.headlineMedium),
+ headlineSmall: libreBarcode39ExtendedText(textStyle: textTheme.headlineSmall),
titleLarge: libreBarcode39ExtendedText(textStyle: textTheme.titleLarge),
titleMedium: libreBarcode39ExtendedText(textStyle: textTheme.titleMedium),
titleSmall: libreBarcode39ExtendedText(textStyle: textTheme.titleSmall),
@@ -4630,9 +4609,7 @@
displayMedium: libreBarcodeEan13Text(textStyle: textTheme.displayMedium),
displaySmall: libreBarcodeEan13Text(textStyle: textTheme.displaySmall),
headlineLarge: libreBarcodeEan13Text(textStyle: textTheme.headlineLarge),
- headlineMedium: libreBarcodeEan13Text(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: libreBarcodeEan13Text(textStyle: textTheme.headlineMedium),
headlineSmall: libreBarcodeEan13Text(textStyle: textTheme.headlineSmall),
titleLarge: libreBarcodeEan13Text(textStyle: textTheme.titleLarge),
titleMedium: libreBarcodeEan13Text(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart
index 0eaeb66..194b71a 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart
@@ -4332,9 +4332,7 @@
displayMedium: notoSansAdlamUnjoined(textStyle: textTheme.displayMedium),
displaySmall: notoSansAdlamUnjoined(textStyle: textTheme.displaySmall),
headlineLarge: notoSansAdlamUnjoined(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSansAdlamUnjoined(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSansAdlamUnjoined(textStyle: textTheme.headlineMedium),
headlineSmall: notoSansAdlamUnjoined(textStyle: textTheme.headlineSmall),
titleLarge: notoSansAdlamUnjoined(textStyle: textTheme.titleLarge),
titleMedium: notoSansAdlamUnjoined(textStyle: textTheme.titleMedium),
@@ -4414,41 +4412,23 @@
///
/// See:
/// * https://fonts.google.com/specimen/Noto+Sans+Anatolian+Hieroglyphs
- static TextTheme notoSansAnatolianHieroglyphsTextTheme([
- TextTheme? textTheme,
- ]) {
+ static TextTheme notoSansAnatolianHieroglyphsTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.headlineSmall),
titleLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.titleLarge),
- titleMedium: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.titleMedium,
- ),
+ titleMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.titleMedium),
titleSmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.titleSmall),
bodyLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.bodyLarge),
bodyMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.bodyMedium),
bodySmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.bodySmall),
labelLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.labelLarge),
- labelMedium: notoSansAnatolianHieroglyphs(
- textStyle: textTheme.labelMedium,
- ),
+ labelMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.labelMedium),
labelSmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.labelSmall),
);
}
@@ -5853,24 +5833,12 @@
static TextTheme notoSansCanadianAboriginalTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansCanadianAboriginal(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansCanadianAboriginal(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansCanadianAboriginal(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansCanadianAboriginal(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansCanadianAboriginal(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansCanadianAboriginal(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSansCanadianAboriginal(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansCanadianAboriginal(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansCanadianAboriginal(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansCanadianAboriginal(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansCanadianAboriginal(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansCanadianAboriginal(textStyle: textTheme.headlineSmall),
titleLarge: notoSansCanadianAboriginal(textStyle: textTheme.titleLarge),
titleMedium: notoSansCanadianAboriginal(textStyle: textTheme.titleMedium),
titleSmall: notoSansCanadianAboriginal(textStyle: textTheme.titleSmall),
@@ -6039,24 +6007,12 @@
static TextTheme notoSansCaucasianAlbanianTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansCaucasianAlbanian(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansCaucasianAlbanian(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansCaucasianAlbanian(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansCaucasianAlbanian(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansCaucasianAlbanian(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansCaucasianAlbanian(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSansCaucasianAlbanian(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansCaucasianAlbanian(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansCaucasianAlbanian(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansCaucasianAlbanian(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansCaucasianAlbanian(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansCaucasianAlbanian(textStyle: textTheme.headlineSmall),
titleLarge: notoSansCaucasianAlbanian(textStyle: textTheme.titleLarge),
titleMedium: notoSansCaucasianAlbanian(textStyle: textTheme.titleMedium),
titleSmall: notoSansCaucasianAlbanian(textStyle: textTheme.titleSmall),
@@ -7473,41 +7429,23 @@
///
/// See:
/// * https://fonts.google.com/specimen/Noto+Sans+Egyptian+Hieroglyphs
- static TextTheme notoSansEgyptianHieroglyphsTextTheme([
- TextTheme? textTheme,
- ]) {
+ static TextTheme notoSansEgyptianHieroglyphsTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.headlineSmall),
titleLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.titleLarge),
- titleMedium: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.titleMedium,
- ),
+ titleMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.titleMedium),
titleSmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.titleSmall),
bodyLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.bodyLarge),
bodyMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.bodyMedium),
bodySmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.bodySmall),
labelLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.labelLarge),
- labelMedium: notoSansEgyptianHieroglyphs(
- textStyle: textTheme.labelMedium,
- ),
+ labelMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.labelMedium),
labelSmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.labelSmall),
);
}
@@ -8864,9 +8802,7 @@
displayMedium: notoSansHanifiRohingya(textStyle: textTheme.displayMedium),
displaySmall: notoSansHanifiRohingya(textStyle: textTheme.displaySmall),
headlineLarge: notoSansHanifiRohingya(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSansHanifiRohingya(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSansHanifiRohingya(textStyle: textTheme.headlineMedium),
headlineSmall: notoSansHanifiRohingya(textStyle: textTheme.headlineSmall),
titleLarge: notoSansHanifiRohingya(textStyle: textTheme.titleLarge),
titleMedium: notoSansHanifiRohingya(textStyle: textTheme.titleMedium),
@@ -9267,19 +9203,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: notoSansImperialAramaic(textStyle: textTheme.displayLarge),
- displayMedium: notoSansImperialAramaic(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: notoSansImperialAramaic(textStyle: textTheme.displayMedium),
displaySmall: notoSansImperialAramaic(textStyle: textTheme.displaySmall),
- headlineLarge: notoSansImperialAramaic(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansImperialAramaic(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansImperialAramaic(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: notoSansImperialAramaic(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansImperialAramaic(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansImperialAramaic(textStyle: textTheme.headlineSmall),
titleLarge: notoSansImperialAramaic(textStyle: textTheme.titleLarge),
titleMedium: notoSansImperialAramaic(textStyle: textTheme.titleMedium),
titleSmall: notoSansImperialAramaic(textStyle: textTheme.titleSmall),
@@ -9361,24 +9289,12 @@
static TextTheme notoSansIndicSiyaqNumbersTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansIndicSiyaqNumbers(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansIndicSiyaqNumbers(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansIndicSiyaqNumbers(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansIndicSiyaqNumbers(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansIndicSiyaqNumbers(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansIndicSiyaqNumbers(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSansIndicSiyaqNumbers(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansIndicSiyaqNumbers(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansIndicSiyaqNumbers(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansIndicSiyaqNumbers(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansIndicSiyaqNumbers(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansIndicSiyaqNumbers(textStyle: textTheme.headlineSmall),
titleLarge: notoSansIndicSiyaqNumbers(textStyle: textTheme.titleLarge),
titleMedium: notoSansIndicSiyaqNumbers(textStyle: textTheme.titleMedium),
titleSmall: notoSansIndicSiyaqNumbers(textStyle: textTheme.titleSmall),
@@ -9457,41 +9373,23 @@
///
/// See:
/// * https://fonts.google.com/specimen/Noto+Sans+Inscriptional+Pahlavi
- static TextTheme notoSansInscriptionalPahlaviTextTheme([
- TextTheme? textTheme,
- ]) {
+ static TextTheme notoSansInscriptionalPahlaviTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansInscriptionalPahlavi(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansInscriptionalPahlavi(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansInscriptionalPahlavi(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansInscriptionalPahlavi(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansInscriptionalPahlavi(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansInscriptionalPahlavi(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansInscriptionalPahlavi(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansInscriptionalPahlavi(textStyle: textTheme.headlineSmall),
titleLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.titleLarge),
- titleMedium: notoSansInscriptionalPahlavi(
- textStyle: textTheme.titleMedium,
- ),
+ titleMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.titleMedium),
titleSmall: notoSansInscriptionalPahlavi(textStyle: textTheme.titleSmall),
bodyLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.bodyLarge),
bodyMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.bodyMedium),
bodySmall: notoSansInscriptionalPahlavi(textStyle: textTheme.bodySmall),
labelLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.labelLarge),
- labelMedium: notoSansInscriptionalPahlavi(
- textStyle: textTheme.labelMedium,
- ),
+ labelMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.labelMedium),
labelSmall: notoSansInscriptionalPahlavi(textStyle: textTheme.labelSmall),
);
}
@@ -9562,52 +9460,24 @@
///
/// See:
/// * https://fonts.google.com/specimen/Noto+Sans+Inscriptional+Parthian
- static TextTheme notoSansInscriptionalParthianTextTheme([
- TextTheme? textTheme,
- ]) {
+ static TextTheme notoSansInscriptionalParthianTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSansInscriptionalParthian(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSansInscriptionalParthian(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSansInscriptionalParthian(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSansInscriptionalParthian(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansInscriptionalParthian(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansInscriptionalParthian(
- textStyle: textTheme.headlineSmall,
- ),
- titleLarge: notoSansInscriptionalParthian(
- textStyle: textTheme.titleLarge,
- ),
- titleMedium: notoSansInscriptionalParthian(
- textStyle: textTheme.titleMedium,
- ),
- titleSmall: notoSansInscriptionalParthian(
- textStyle: textTheme.titleSmall,
- ),
+ displayLarge: notoSansInscriptionalParthian(textStyle: textTheme.displayLarge),
+ displayMedium: notoSansInscriptionalParthian(textStyle: textTheme.displayMedium),
+ displaySmall: notoSansInscriptionalParthian(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSansInscriptionalParthian(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansInscriptionalParthian(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansInscriptionalParthian(textStyle: textTheme.headlineSmall),
+ titleLarge: notoSansInscriptionalParthian(textStyle: textTheme.titleLarge),
+ titleMedium: notoSansInscriptionalParthian(textStyle: textTheme.titleMedium),
+ titleSmall: notoSansInscriptionalParthian(textStyle: textTheme.titleSmall),
bodyLarge: notoSansInscriptionalParthian(textStyle: textTheme.bodyLarge),
- bodyMedium: notoSansInscriptionalParthian(
- textStyle: textTheme.bodyMedium,
- ),
+ bodyMedium: notoSansInscriptionalParthian(textStyle: textTheme.bodyMedium),
bodySmall: notoSansInscriptionalParthian(textStyle: textTheme.bodySmall),
- labelLarge: notoSansInscriptionalParthian(
- textStyle: textTheme.labelLarge,
- ),
- labelMedium: notoSansInscriptionalParthian(
- textStyle: textTheme.labelMedium,
- ),
- labelSmall: notoSansInscriptionalParthian(
- textStyle: textTheme.labelSmall,
- ),
+ labelLarge: notoSansInscriptionalParthian(textStyle: textTheme.labelLarge),
+ labelMedium: notoSansInscriptionalParthian(textStyle: textTheme.labelMedium),
+ labelSmall: notoSansInscriptionalParthian(textStyle: textTheme.labelSmall),
);
}
@@ -11624,13 +11494,8 @@
double? decorationThickness,
}) {
final fonts = <GoogleFontsVariant, GoogleFontsFile>{
- const GoogleFontsVariant(
- fontWeight: FontWeight.w400,
- fontStyle: FontStyle.normal,
- ): GoogleFontsFile(
- '75575abbe344a6327d36709c771ce18f37609a7875a1486bf4e9eda959d814ee',
- 3380,
- ),
+ const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal):
+ GoogleFontsFile('75575abbe344a6327d36709c771ce18f37609a7875a1486bf4e9eda959d814ee', 3380),
};
return googleFontsTextStyle(
@@ -12509,9 +12374,7 @@
displayMedium: notoSansMayanNumerals(textStyle: textTheme.displayMedium),
displaySmall: notoSansMayanNumerals(textStyle: textTheme.displaySmall),
headlineLarge: notoSansMayanNumerals(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSansMayanNumerals(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSansMayanNumerals(textStyle: textTheme.headlineMedium),
headlineSmall: notoSansMayanNumerals(textStyle: textTheme.headlineSmall),
titleLarge: notoSansMayanNumerals(textStyle: textTheme.titleLarge),
titleMedium: notoSansMayanNumerals(textStyle: textTheme.titleMedium),
@@ -14869,19 +14732,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: notoSansOldNorthArabian(textStyle: textTheme.displayLarge),
- displayMedium: notoSansOldNorthArabian(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: notoSansOldNorthArabian(textStyle: textTheme.displayMedium),
displaySmall: notoSansOldNorthArabian(textStyle: textTheme.displaySmall),
- headlineLarge: notoSansOldNorthArabian(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansOldNorthArabian(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansOldNorthArabian(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: notoSansOldNorthArabian(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansOldNorthArabian(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansOldNorthArabian(textStyle: textTheme.headlineSmall),
titleLarge: notoSansOldNorthArabian(textStyle: textTheme.titleLarge),
titleMedium: notoSansOldNorthArabian(textStyle: textTheme.titleMedium),
titleSmall: notoSansOldNorthArabian(textStyle: textTheme.titleSmall),
@@ -15225,19 +15080,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: notoSansOldSouthArabian(textStyle: textTheme.displayLarge),
- displayMedium: notoSansOldSouthArabian(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: notoSansOldSouthArabian(textStyle: textTheme.displayMedium),
displaySmall: notoSansOldSouthArabian(textStyle: textTheme.displaySmall),
- headlineLarge: notoSansOldSouthArabian(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansOldSouthArabian(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansOldSouthArabian(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: notoSansOldSouthArabian(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansOldSouthArabian(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansOldSouthArabian(textStyle: textTheme.headlineSmall),
titleLarge: notoSansOldSouthArabian(textStyle: textTheme.titleLarge),
titleMedium: notoSansOldSouthArabian(textStyle: textTheme.titleMedium),
titleSmall: notoSansOldSouthArabian(textStyle: textTheme.titleSmall),
@@ -16162,9 +16009,7 @@
displayMedium: notoSansPsalterPahlavi(textStyle: textTheme.displayMedium),
displaySmall: notoSansPsalterPahlavi(textStyle: textTheme.displaySmall),
headlineLarge: notoSansPsalterPahlavi(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSansPsalterPahlavi(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSansPsalterPahlavi(textStyle: textTheme.headlineMedium),
headlineSmall: notoSansPsalterPahlavi(textStyle: textTheme.headlineSmall),
titleLarge: notoSansPsalterPahlavi(textStyle: textTheme.titleLarge),
titleMedium: notoSansPsalterPahlavi(textStyle: textTheme.titleMedium),
@@ -18226,9 +18071,7 @@
displayMedium: notoSansSyriacEastern(textStyle: textTheme.displayMedium),
displaySmall: notoSansSyriacEastern(textStyle: textTheme.displaySmall),
headlineLarge: notoSansSyriacEastern(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSansSyriacEastern(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSansSyriacEastern(textStyle: textTheme.headlineMedium),
headlineSmall: notoSansSyriacEastern(textStyle: textTheme.headlineSmall),
titleLarge: notoSansSyriacEastern(textStyle: textTheme.titleLarge),
titleMedium: notoSansSyriacEastern(textStyle: textTheme.titleMedium),
@@ -18371,9 +18214,7 @@
displayMedium: notoSansSyriacWestern(textStyle: textTheme.displayMedium),
displaySmall: notoSansSyriacWestern(textStyle: textTheme.displaySmall),
headlineLarge: notoSansSyriacWestern(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSansSyriacWestern(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSansSyriacWestern(textStyle: textTheme.headlineMedium),
headlineSmall: notoSansSyriacWestern(textStyle: textTheme.headlineSmall),
titleLarge: notoSansSyriacWestern(textStyle: textTheme.titleLarge),
titleMedium: notoSansSyriacWestern(textStyle: textTheme.titleMedium),
@@ -19286,19 +19127,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: notoSansTamilSupplement(textStyle: textTheme.displayLarge),
- displayMedium: notoSansTamilSupplement(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: notoSansTamilSupplement(textStyle: textTheme.displayMedium),
displaySmall: notoSansTamilSupplement(textStyle: textTheme.displaySmall),
- headlineLarge: notoSansTamilSupplement(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansTamilSupplement(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansTamilSupplement(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: notoSansTamilSupplement(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansTamilSupplement(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansTamilSupplement(textStyle: textTheme.headlineSmall),
titleLarge: notoSansTamilSupplement(textStyle: textTheme.titleLarge),
titleMedium: notoSansTamilSupplement(textStyle: textTheme.titleMedium),
titleSmall: notoSansTamilSupplement(textStyle: textTheme.titleSmall),
@@ -20778,19 +20611,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: notoSansZanabazarSquare(textStyle: textTheme.displayLarge),
- displayMedium: notoSansZanabazarSquare(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: notoSansZanabazarSquare(textStyle: textTheme.displayMedium),
displaySmall: notoSansZanabazarSquare(textStyle: textTheme.displaySmall),
- headlineLarge: notoSansZanabazarSquare(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSansZanabazarSquare(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSansZanabazarSquare(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: notoSansZanabazarSquare(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSansZanabazarSquare(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSansZanabazarSquare(textStyle: textTheme.headlineSmall),
titleLarge: notoSansZanabazarSquare(textStyle: textTheme.titleLarge),
titleMedium: notoSansZanabazarSquare(textStyle: textTheme.titleMedium),
titleSmall: notoSansZanabazarSquare(textStyle: textTheme.titleSmall),
@@ -23550,24 +23375,12 @@
static TextTheme notoSerifKhitanSmallScriptTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoSerifKhitanSmallScript(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoSerifKhitanSmallScript(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoSerifKhitanSmallScript(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoSerifKhitanSmallScript(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoSerifKhitanSmallScript(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoSerifKhitanSmallScript(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoSerifKhitanSmallScript(textStyle: textTheme.displayLarge),
+ displayMedium: notoSerifKhitanSmallScript(textStyle: textTheme.displayMedium),
+ displaySmall: notoSerifKhitanSmallScript(textStyle: textTheme.displaySmall),
+ headlineLarge: notoSerifKhitanSmallScript(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoSerifKhitanSmallScript(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoSerifKhitanSmallScript(textStyle: textTheme.headlineSmall),
titleLarge: notoSerifKhitanSmallScript(textStyle: textTheme.titleLarge),
titleMedium: notoSerifKhitanSmallScript(textStyle: textTheme.titleMedium),
titleSmall: notoSerifKhitanSmallScript(textStyle: textTheme.titleSmall),
@@ -24723,9 +24536,7 @@
displayMedium: notoSerifOttomanSiyaq(textStyle: textTheme.displayMedium),
displaySmall: notoSerifOttomanSiyaq(textStyle: textTheme.displaySmall),
headlineLarge: notoSerifOttomanSiyaq(textStyle: textTheme.headlineLarge),
- headlineMedium: notoSerifOttomanSiyaq(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: notoSerifOttomanSiyaq(textStyle: textTheme.headlineMedium),
headlineSmall: notoSerifOttomanSiyaq(textStyle: textTheme.headlineSmall),
titleLarge: notoSerifOttomanSiyaq(textStyle: textTheme.titleLarge),
titleMedium: notoSerifOttomanSiyaq(textStyle: textTheme.titleMedium),
@@ -26468,41 +26279,23 @@
///
/// See:
/// * https://fonts.google.com/specimen/Noto+Znamenny+Musical+Notation
- static TextTheme notoZnamennyMusicalNotationTextTheme([
- TextTheme? textTheme,
- ]) {
+ static TextTheme notoZnamennyMusicalNotationTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: notoZnamennyMusicalNotation(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: notoZnamennyMusicalNotation(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: notoZnamennyMusicalNotation(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: notoZnamennyMusicalNotation(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: notoZnamennyMusicalNotation(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: notoZnamennyMusicalNotation(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: notoZnamennyMusicalNotation(textStyle: textTheme.displayLarge),
+ displayMedium: notoZnamennyMusicalNotation(textStyle: textTheme.displayMedium),
+ displaySmall: notoZnamennyMusicalNotation(textStyle: textTheme.displaySmall),
+ headlineLarge: notoZnamennyMusicalNotation(textStyle: textTheme.headlineLarge),
+ headlineMedium: notoZnamennyMusicalNotation(textStyle: textTheme.headlineMedium),
+ headlineSmall: notoZnamennyMusicalNotation(textStyle: textTheme.headlineSmall),
titleLarge: notoZnamennyMusicalNotation(textStyle: textTheme.titleLarge),
- titleMedium: notoZnamennyMusicalNotation(
- textStyle: textTheme.titleMedium,
- ),
+ titleMedium: notoZnamennyMusicalNotation(textStyle: textTheme.titleMedium),
titleSmall: notoZnamennyMusicalNotation(textStyle: textTheme.titleSmall),
bodyLarge: notoZnamennyMusicalNotation(textStyle: textTheme.bodyLarge),
bodyMedium: notoZnamennyMusicalNotation(textStyle: textTheme.bodyMedium),
bodySmall: notoZnamennyMusicalNotation(textStyle: textTheme.bodySmall),
labelLarge: notoZnamennyMusicalNotation(textStyle: textTheme.labelLarge),
- labelMedium: notoZnamennyMusicalNotation(
- textStyle: textTheme.labelMedium,
- ),
+ labelMedium: notoZnamennyMusicalNotation(textStyle: textTheme.labelMedium),
labelSmall: notoZnamennyMusicalNotation(textStyle: textTheme.labelSmall),
);
}
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart
index 9f1ddca..f32788f 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart
@@ -9034,9 +9034,7 @@
displayMedium: playwriteDeGrundGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteDeGrundGuides(textStyle: textTheme.displaySmall),
headlineLarge: playwriteDeGrundGuides(textStyle: textTheme.headlineLarge),
- headlineMedium: playwriteDeGrundGuides(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: playwriteDeGrundGuides(textStyle: textTheme.headlineMedium),
headlineSmall: playwriteDeGrundGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteDeGrundGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteDeGrundGuides(textStyle: textTheme.titleMedium),
@@ -9813,19 +9811,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteDkLoopetGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteDkLoopetGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteDkLoopetGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteDkLoopetGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteDkLoopetGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteDkLoopetGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteDkLoopetGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteDkLoopetGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteDkLoopetGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteDkLoopetGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteDkLoopetGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteDkLoopetGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteDkLoopetGuides(textStyle: textTheme.titleSmall),
@@ -10016,19 +10006,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteDkUloopetGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteDkUloopetGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteDkUloopetGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteDkUloopetGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteDkUloopetGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteDkUloopetGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteDkUloopetGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteDkUloopetGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteDkUloopetGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteDkUloopetGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteDkUloopetGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteDkUloopetGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteDkUloopetGuides(textStyle: textTheme.titleSmall),
@@ -10330,9 +10312,7 @@
displayMedium: playwriteEsDecoGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteEsDecoGuides(textStyle: textTheme.displaySmall),
headlineLarge: playwriteEsDecoGuides(textStyle: textTheme.headlineLarge),
- headlineMedium: playwriteEsDecoGuides(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: playwriteEsDecoGuides(textStyle: textTheme.headlineMedium),
headlineSmall: playwriteEsDecoGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteEsDecoGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteEsDecoGuides(textStyle: textTheme.titleMedium),
@@ -10611,19 +10591,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteFrModerneGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteFrModerneGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteFrModerneGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteFrModerneGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteFrModerneGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteFrModerneGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteFrModerneGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteFrModerneGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteFrModerneGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteFrModerneGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteFrModerneGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteFrModerneGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteFrModerneGuides(textStyle: textTheme.titleSmall),
@@ -10817,9 +10789,7 @@
displayMedium: playwriteFrTradGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteFrTradGuides(textStyle: textTheme.displaySmall),
headlineLarge: playwriteFrTradGuides(textStyle: textTheme.headlineLarge),
- headlineMedium: playwriteFrTradGuides(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: playwriteFrTradGuides(textStyle: textTheme.headlineMedium),
headlineSmall: playwriteFrTradGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteFrTradGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteFrTradGuides(textStyle: textTheme.titleMedium),
@@ -11666,19 +11636,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteHrLijevaGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteHrLijevaGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteHrLijevaGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteHrLijevaGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteHrLijevaGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteHrLijevaGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteHrLijevaGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteHrLijevaGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteHrLijevaGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteHrLijevaGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteHrLijevaGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteHrLijevaGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteHrLijevaGuides(textStyle: textTheme.titleSmall),
@@ -12844,19 +12806,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteItModernaGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteItModernaGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteItModernaGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteItModernaGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteItModernaGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteItModernaGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteItModernaGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteItModernaGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteItModernaGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteItModernaGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteItModernaGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteItModernaGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteItModernaGuides(textStyle: textTheme.titleSmall),
@@ -13050,9 +13004,7 @@
displayMedium: playwriteItTradGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteItTradGuides(textStyle: textTheme.displaySmall),
headlineLarge: playwriteItTradGuides(textStyle: textTheme.headlineLarge),
- headlineMedium: playwriteItTradGuides(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: playwriteItTradGuides(textStyle: textTheme.headlineMedium),
headlineSmall: playwriteItTradGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteItTradGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteItTradGuides(textStyle: textTheme.titleMedium),
@@ -13439,19 +13391,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteNgModernGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteNgModernGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteNgModernGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteNgModernGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteNgModernGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteNgModernGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteNgModernGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteNgModernGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteNgModernGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteNgModernGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteNgModernGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteNgModernGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteNgModernGuides(textStyle: textTheme.titleSmall),
@@ -15397,19 +15341,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: playwriteUsModernGuides(textStyle: textTheme.displayLarge),
- displayMedium: playwriteUsModernGuides(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: playwriteUsModernGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteUsModernGuides(textStyle: textTheme.displaySmall),
- headlineLarge: playwriteUsModernGuides(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: playwriteUsModernGuides(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: playwriteUsModernGuides(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: playwriteUsModernGuides(textStyle: textTheme.headlineLarge),
+ headlineMedium: playwriteUsModernGuides(textStyle: textTheme.headlineMedium),
+ headlineSmall: playwriteUsModernGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteUsModernGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteUsModernGuides(textStyle: textTheme.titleMedium),
titleSmall: playwriteUsModernGuides(textStyle: textTheme.titleSmall),
@@ -15603,9 +15539,7 @@
displayMedium: playwriteUsTradGuides(textStyle: textTheme.displayMedium),
displaySmall: playwriteUsTradGuides(textStyle: textTheme.displaySmall),
headlineLarge: playwriteUsTradGuides(textStyle: textTheme.headlineLarge),
- headlineMedium: playwriteUsTradGuides(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: playwriteUsTradGuides(textStyle: textTheme.headlineMedium),
headlineSmall: playwriteUsTradGuides(textStyle: textTheme.headlineSmall),
titleLarge: playwriteUsTradGuides(textStyle: textTheme.titleLarge),
titleMedium: playwriteUsTradGuides(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart
index 91bedca..b791137 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart
@@ -9404,19 +9404,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: sofiaSansExtraCondensed(textStyle: textTheme.displayLarge),
- displayMedium: sofiaSansExtraCondensed(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: sofiaSansExtraCondensed(textStyle: textTheme.displayMedium),
displaySmall: sofiaSansExtraCondensed(textStyle: textTheme.displaySmall),
- headlineLarge: sofiaSansExtraCondensed(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: sofiaSansExtraCondensed(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: sofiaSansExtraCondensed(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: sofiaSansExtraCondensed(textStyle: textTheme.headlineLarge),
+ headlineMedium: sofiaSansExtraCondensed(textStyle: textTheme.headlineMedium),
+ headlineSmall: sofiaSansExtraCondensed(textStyle: textTheme.headlineSmall),
titleLarge: sofiaSansExtraCondensed(textStyle: textTheme.titleLarge),
titleMedium: sofiaSansExtraCondensed(textStyle: textTheme.titleMedium),
titleSmall: sofiaSansExtraCondensed(textStyle: textTheme.titleSmall),
@@ -9621,9 +9613,7 @@
displayMedium: sofiaSansSemiCondensed(textStyle: textTheme.displayMedium),
displaySmall: sofiaSansSemiCondensed(textStyle: textTheme.displaySmall),
headlineLarge: sofiaSansSemiCondensed(textStyle: textTheme.headlineLarge),
- headlineMedium: sofiaSansSemiCondensed(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: sofiaSansSemiCondensed(textStyle: textTheme.headlineMedium),
headlineSmall: sofiaSansSemiCondensed(textStyle: textTheme.headlineSmall),
titleLarge: sofiaSansSemiCondensed(textStyle: textTheme.titleLarge),
titleMedium: sofiaSansSemiCondensed(textStyle: textTheme.titleMedium),
@@ -11777,24 +11767,12 @@
static TextTheme specialGothicCondensedOneTextTheme([TextTheme? textTheme]) {
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
- displayLarge: specialGothicCondensedOne(
- textStyle: textTheme.displayLarge,
- ),
- displayMedium: specialGothicCondensedOne(
- textStyle: textTheme.displayMedium,
- ),
- displaySmall: specialGothicCondensedOne(
- textStyle: textTheme.displaySmall,
- ),
- headlineLarge: specialGothicCondensedOne(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: specialGothicCondensedOne(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: specialGothicCondensedOne(
- textStyle: textTheme.headlineSmall,
- ),
+ displayLarge: specialGothicCondensedOne(textStyle: textTheme.displayLarge),
+ displayMedium: specialGothicCondensedOne(textStyle: textTheme.displayMedium),
+ displaySmall: specialGothicCondensedOne(textStyle: textTheme.displaySmall),
+ headlineLarge: specialGothicCondensedOne(textStyle: textTheme.headlineLarge),
+ headlineMedium: specialGothicCondensedOne(textStyle: textTheme.headlineMedium),
+ headlineSmall: specialGothicCondensedOne(textStyle: textTheme.headlineSmall),
titleLarge: specialGothicCondensedOne(textStyle: textTheme.titleLarge),
titleMedium: specialGothicCondensedOne(textStyle: textTheme.titleMedium),
titleSmall: specialGothicCondensedOne(textStyle: textTheme.titleSmall),
@@ -11877,19 +11855,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: specialGothicExpandedOne(textStyle: textTheme.displayLarge),
- displayMedium: specialGothicExpandedOne(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: specialGothicExpandedOne(textStyle: textTheme.displayMedium),
displaySmall: specialGothicExpandedOne(textStyle: textTheme.displaySmall),
- headlineLarge: specialGothicExpandedOne(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: specialGothicExpandedOne(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: specialGothicExpandedOne(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: specialGothicExpandedOne(textStyle: textTheme.headlineLarge),
+ headlineMedium: specialGothicExpandedOne(textStyle: textTheme.headlineMedium),
+ headlineSmall: specialGothicExpandedOne(textStyle: textTheme.headlineSmall),
titleLarge: specialGothicExpandedOne(textStyle: textTheme.titleLarge),
titleMedium: specialGothicExpandedOne(textStyle: textTheme.titleMedium),
titleSmall: specialGothicExpandedOne(textStyle: textTheme.titleSmall),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart
index c08be3f..a966d64 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart
@@ -3586,9 +3586,7 @@
displayMedium: tiroDevanagariMarathi(textStyle: textTheme.displayMedium),
displaySmall: tiroDevanagariMarathi(textStyle: textTheme.displaySmall),
headlineLarge: tiroDevanagariMarathi(textStyle: textTheme.headlineLarge),
- headlineMedium: tiroDevanagariMarathi(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: tiroDevanagariMarathi(textStyle: textTheme.headlineMedium),
headlineSmall: tiroDevanagariMarathi(textStyle: textTheme.headlineSmall),
titleLarge: tiroDevanagariMarathi(textStyle: textTheme.titleLarge),
titleMedium: tiroDevanagariMarathi(textStyle: textTheme.titleMedium),
@@ -3682,9 +3680,7 @@
displayMedium: tiroDevanagariSanskrit(textStyle: textTheme.displayMedium),
displaySmall: tiroDevanagariSanskrit(textStyle: textTheme.displaySmall),
headlineLarge: tiroDevanagariSanskrit(textStyle: textTheme.headlineLarge),
- headlineMedium: tiroDevanagariSanskrit(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: tiroDevanagariSanskrit(textStyle: textTheme.headlineMedium),
headlineSmall: tiroDevanagariSanskrit(textStyle: textTheme.headlineSmall),
titleLarge: tiroDevanagariSanskrit(textStyle: textTheme.titleLarge),
titleMedium: tiroDevanagariSanskrit(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart
index e0f87da..5f6c4a0 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart
@@ -2493,9 +2493,7 @@
displayMedium: yujiHentaiganaAkebono(textStyle: textTheme.displayMedium),
displaySmall: yujiHentaiganaAkebono(textStyle: textTheme.displaySmall),
headlineLarge: yujiHentaiganaAkebono(textStyle: textTheme.headlineLarge),
- headlineMedium: yujiHentaiganaAkebono(
- textStyle: textTheme.headlineMedium,
- ),
+ headlineMedium: yujiHentaiganaAkebono(textStyle: textTheme.headlineMedium),
headlineSmall: yujiHentaiganaAkebono(textStyle: textTheme.headlineSmall),
titleLarge: yujiHentaiganaAkebono(textStyle: textTheme.titleLarge),
titleMedium: yujiHentaiganaAkebono(textStyle: textTheme.titleMedium),
diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart
index 78e606a..48938c0 100644
--- a/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart
+++ b/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart
@@ -968,19 +968,11 @@
textTheme ??= ThemeData.light().textTheme;
return TextTheme(
displayLarge: zalandoSansSemiExpanded(textStyle: textTheme.displayLarge),
- displayMedium: zalandoSansSemiExpanded(
- textStyle: textTheme.displayMedium,
- ),
+ displayMedium: zalandoSansSemiExpanded(textStyle: textTheme.displayMedium),
displaySmall: zalandoSansSemiExpanded(textStyle: textTheme.displaySmall),
- headlineLarge: zalandoSansSemiExpanded(
- textStyle: textTheme.headlineLarge,
- ),
- headlineMedium: zalandoSansSemiExpanded(
- textStyle: textTheme.headlineMedium,
- ),
- headlineSmall: zalandoSansSemiExpanded(
- textStyle: textTheme.headlineSmall,
- ),
+ headlineLarge: zalandoSansSemiExpanded(textStyle: textTheme.headlineLarge),
+ headlineMedium: zalandoSansSemiExpanded(textStyle: textTheme.headlineMedium),
+ headlineSmall: zalandoSansSemiExpanded(textStyle: textTheme.headlineSmall),
titleLarge: zalandoSansSemiExpanded(textStyle: textTheme.titleLarge),
titleMedium: zalandoSansSemiExpanded(textStyle: textTheme.titleMedium),
titleSmall: zalandoSansSemiExpanded(textStyle: textTheme.titleSmall),
diff --git a/packages/google_fonts/lib/src/google_fonts_variant.dart b/packages/google_fonts/lib/src/google_fonts_variant.dart
index d1ed5f0..3ed1551 100644
--- a/packages/google_fonts/lib/src/google_fonts_variant.dart
+++ b/packages/google_fonts/lib/src/google_fonts_variant.dart
@@ -42,13 +42,10 @@
/// See [GoogleFontsVariant.toString] for the inverse function.
GoogleFontsVariant.fromString(String variantString)
: fontWeight =
- FontWeight.values[variantString == _regular ||
- variantString == _italic
+ FontWeight.values[variantString == _regular || variantString == _italic
? 3
: (int.parse(variantString.replaceAll(_italic, '')) ~/ 100) - 1],
- fontStyle = variantString.contains(_italic)
- ? FontStyle.italic
- : FontStyle.normal;
+ fontStyle = variantString.contains(_italic) ? FontStyle.italic : FontStyle.normal;
/// The fon