text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:animations/animations.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('transitions in a new child.', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerOne, color: const Color(0x00000000)), ), ); 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)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerTwo, color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 40)); 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)); // Primary is running for incoming widget. expect(primaryAnimation[containerTwo], moreOrLessEquals(0.4)); expect(secondaryAnimation[containerTwo], equals(0.0)); // Container one is underneath container two final Container container = tester.firstWidget(find.byType(Container)); expect(container.key, containerOne); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerThree, color: const Color(0xffff0000)), ), ); await tester.pump(const Duration(milliseconds: 20)); primaryAnimation = _getPrimaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); secondaryAnimation = _getSecondaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerOne], equals(0.6)); expect(primaryAnimation[containerTwo], equals(0.6)); expect(secondaryAnimation[containerTwo], moreOrLessEquals(0.2)); expect(primaryAnimation[containerThree], moreOrLessEquals(0.2)); expect(secondaryAnimation[containerThree], equals(0.0)); await tester.pumpAndSettle(); }); testWidgets('transitions in a new child in reverse.', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, reverse: true, child: Container(key: containerOne, color: const Color(0x00000000)), ), ); 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)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, reverse: true, child: Container(key: containerTwo, color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 40)); 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)); // Secondary is running forward for incoming widget. expect(primaryAnimation[containerTwo], equals(1.0)); expect(secondaryAnimation[containerTwo], moreOrLessEquals(0.6)); // Container two two is underneath container one. final Container container = tester.firstWidget(find.byType(Container)); expect(container.key, containerTwo); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, reverse: true, child: Container(key: containerThree, color: const Color(0xffff0000)), ), ); await tester.pump(const Duration(milliseconds: 20)); primaryAnimation = _getPrimaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); secondaryAnimation = _getSecondaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); expect(primaryAnimation[containerOne], equals(0.4)); expect(secondaryAnimation[containerOne], equals(0.0)); expect(primaryAnimation[containerTwo], equals(0.8)); expect(secondaryAnimation[containerTwo], equals(0.4)); expect(primaryAnimation[containerThree], equals(1.0)); expect(secondaryAnimation[containerThree], equals(0.8)); await tester.pumpAndSettle(); }); testWidgets('switch from forward to reverse', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerOne, color: const Color(0x00000000)), ), ); 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)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerTwo, color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 40)); 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)); expect(primaryAnimation[containerTwo], moreOrLessEquals(0.4)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, reverse: true, child: Container(key: containerThree, color: const Color(0xffff0000)), ), ); await tester.pump(const Duration(milliseconds: 20)); primaryAnimation = _getPrimaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); secondaryAnimation = _getSecondaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); expect(secondaryAnimation[containerOne], equals(0.6)); expect(primaryAnimation[containerOne], equals(1.0)); expect(secondaryAnimation[containerTwo], equals(0.0)); expect(primaryAnimation[containerTwo], moreOrLessEquals(0.2)); expect(secondaryAnimation[containerThree], equals(0.8)); expect(primaryAnimation[containerThree], equals(1.0)); await tester.pumpAndSettle(); }); testWidgets('switch from reverse to forward.', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, reverse: true, child: Container(key: containerOne, color: const Color(0x00000000)), ), ); 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)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, reverse: true, child: Container(key: containerTwo, color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 40)); 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)); // Secondary is running in reverse for incoming widget. expect(primaryAnimation[containerTwo], equals(1.0)); expect(secondaryAnimation[containerTwo], moreOrLessEquals(0.6)); // Container two is underneath container one. final Container container = tester.firstWidget(find.byType(Container)); expect(container.key, containerTwo); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerThree, color: const Color(0xffff0000)), ), ); await tester.pump(const Duration(milliseconds: 20)); // Container one is expected to continue running its primary animation in // reverse since it is exiting. Container two's secondary animation switches // from running its secondary animation in reverse to running forwards since // it should now be exiting underneath container three. Container three's // primary animation should be running forwards since it is entering above // container two. primaryAnimation = _getPrimaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); secondaryAnimation = _getSecondaryAnimation( <Key>[containerOne, containerTwo, containerThree], tester); expect(primaryAnimation[containerOne], equals(0.4)); expect(secondaryAnimation[containerOne], equals(0.0)); expect(primaryAnimation[containerTwo], equals(1.0)); expect(secondaryAnimation[containerTwo], equals(0.8)); expect(primaryAnimation[containerThree], moreOrLessEquals(0.2)); expect(secondaryAnimation[containerThree], equals(0.0)); await tester.pumpAndSettle(); }); testWidgets('using custom layout', (WidgetTester tester) async { Widget newLayoutBuilder(List<Widget> activeEntries) { return Column( children: activeEntries, ); } await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, layoutBuilder: newLayoutBuilder, child: Container(color: const Color(0x00000000)), ), ); expect(find.byType(Column), findsOneWidget); }); testWidgets("doesn't transition in a new child of the same type.", (WidgetTester tester) async { await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(color: const Color(0x00000000)), ), ); expect(find.byType(FadeTransition), findsOneWidget); expect(find.byType(ScaleTransition), findsOneWidget); FadeTransition fade = tester.firstWidget(find.byType(FadeTransition)); ScaleTransition scale = tester.firstWidget(find.byType(ScaleTransition)); expect(fade.opacity.value, equals(1.0)); expect(scale.scale.value, equals(1.0)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(FadeTransition), findsOneWidget); expect(find.byType(ScaleTransition), findsOneWidget); fade = tester.firstWidget(find.byType(FadeTransition)); scale = tester.firstWidget(find.byType(ScaleTransition)); expect(fade.opacity.value, equals(1.0)); expect(scale.scale.value, equals(1.0)); await tester.pumpAndSettle(); }); testWidgets('handles null children.', (WidgetTester tester) async { await tester.pumpWidget( const PageTransitionSwitcher( duration: Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, ), ); expect(find.byType(FadeTransition), findsNothing); expect(find.byType(ScaleTransition), findsNothing); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 40)); expect(find.byType(FadeTransition), findsOneWidget); expect(find.byType(ScaleTransition), findsOneWidget); FadeTransition fade = tester.firstWidget(find.byType(FadeTransition)); ScaleTransition scale = tester.firstWidget(find.byType(ScaleTransition)); expect(fade.opacity.value, equals(1.0)); expect(scale.scale.value, moreOrLessEquals(0.4)); await tester.pumpAndSettle(); // finish transitions. await tester.pumpWidget( const PageTransitionSwitcher( duration: Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, ), ); await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(FadeTransition), findsOneWidget); expect(find.byType(ScaleTransition), findsOneWidget); fade = tester.firstWidget(find.byType(FadeTransition)); scale = tester.firstWidget(find.byType(ScaleTransition)); expect(fade.opacity.value, equals(0.5)); expect(scale.scale.value, equals(1.0)); await tester.pumpAndSettle(); }); testWidgets("doesn't start any animations after dispose.", (WidgetTester tester) async { await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: UniqueKey(), color: const Color(0xff000000)), ), ); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: UniqueKey(), color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 50)); 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)); expect(fade.opacity.value, equals(0.5)); expect(scale.scale.value, equals(1.0)); // Change the widget tree in the middle of the animation. await tester.pumpWidget(Container(color: const Color(0xffff0000))); expect(await tester.pumpAndSettle(), equals(1)); }); testWidgets("doesn't reset state of the children in transitions.", (WidgetTester tester) async { final UniqueKey statefulOne = UniqueKey(); final UniqueKey statefulTwo = UniqueKey(); final UniqueKey statefulThree = UniqueKey(); StatefulTestWidgetState.generation = 0; await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: StatefulTestWidget(key: statefulOne), ), ); 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)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: StatefulTestWidget(key: statefulTwo), ), ); 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); expect(primaryAnimation[statefulTwo], equals(0.5)); expect(secondaryAnimation[statefulTwo], equals(0.0)); expect(StatefulTestWidgetState.generation, equals(2)); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: StatefulTestWidget(key: statefulThree), ), ); await tester.pump(const Duration(milliseconds: 10)); expect(StatefulTestWidgetState.generation, equals(3)); await tester.pumpAndSettle(); expect(StatefulTestWidgetState.generation, equals(3)); }); testWidgets('updates widgets without animating if they are isomorphic.', (WidgetTester tester) async { Future<void> pumpChild(Widget child) async { return tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: child, ), ), ); } await pumpChild(const Text('1')); await tester.pump(const Duration(milliseconds: 10)); FadeTransition fade = tester.widget(find.byType(FadeTransition)); ScaleTransition scale = tester.widget(find.byType(ScaleTransition)); expect(fade.opacity.value, equals(1.0)); expect(scale.scale.value, equals(1.0)); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); await pumpChild(const Text('2')); fade = tester.widget(find.byType(FadeTransition)); scale = tester.widget(find.byType(ScaleTransition)); await tester.pump(const Duration(milliseconds: 20)); expect(fade.opacity.value, equals(1.0)); expect(scale.scale.value, equals(1.0)); expect(find.text('1'), findsNothing); expect(find.text('2'), findsOneWidget); }); testWidgets( 'updates previous child transitions if the transitionBuilder changes.', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); // Insert three unique children so that we have some previous children. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PageTransitionSwitcher( duration: const Duration(milliseconds: 100), transitionBuilder: _transitionBuilder, child: Container(key: containerOne, color: const Color(0xFFFF0000)), ), ), ); 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, ), ); } // 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)); }); } class StatefulTestWidget extends StatefulWidget { const StatefulTestWidget({super.key}); @override StatefulTestWidgetState createState() => StatefulTestWidgetState(); } class StatefulTestWidgetState extends State<StatefulTestWidget> { StatefulTestWidgetState(); static int generation = 0; @override void initState() { super.initState(); generation++; } @override Widget build(BuildContext context) => Container(); } 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( opacity: Tween<double>(begin: 1.0, end: 0.0).animate(secondary), child: child, ), ); } Map<Key, double> _getSecondaryAnimation(List<Key> keys, WidgetTester tester) { expect(find.byType(FadeTransition), findsNWidgets(keys.length)); final Map<Key, double> result = <Key, double>{}; for (final Key key in keys) { final FadeTransition transition = tester.firstWidget( find.ancestor( of: find.byKey(key), matching: find.byType(FadeTransition), ), ); result[key] = 1.0 - transition.opacity.value; } return result; } Map<Key, double> _getPrimaryAnimation(List<Key> keys, WidgetTester tester) { expect(find.byType(ScaleTransition), findsNWidgets(keys.length)); final Map<Key, double> result = <Key, double>{}; for (final Key key in keys) { final ScaleTransition transition = tester.firstWidget( find.ancestor( of: find.byKey(key), matching: find.byType(ScaleTransition), ), ); result[key] = transition.scale.value; } return result; }
packages/packages/animations/test/page_transition_switcher_test.dart/0
{ "file_path": "packages/packages/animations/test/page_transition_switcher_test.dart", "repo_id": "packages", "token_count": 8629 }
912
## 0.10.8+17 * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates compileSdk version to 34. * Updates `README.md` to encourage developers to opt into `camera_android_camerax`. ## 0.10.8+16 * Fixes new lint warnings. ## 0.10.8+15 * Updates example app to use non-deprecated video_player method. ## 0.10.8+14 * Fixes `pausePreview` null pointer error. `pausePreview` should not be called when camera is closed or not configured. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 0.10.8+13 * Updates annotations lib to 1.7.0. ## 0.10.8+12 * Fixes handling of autofocus state when taking a picture. ## 0.10.8+11 * Downgrades AGP version for compatibility with legacy projects. ## 0.10.8+10 * Sets android.defaults.buildfeatures.buildconfig to true for compatibility with AGP 8.0+. ## 0.10.8+9 * Removes usage of `_ambiguate` method in example. ## 0.10.8+8 * Adds pub topics to package metadata. ## 0.10.8+7 * Fixes video record crash on Android versions lower than 12. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.10.8+6 * Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters. ## 0.10.8+5 * Provides a default exposure point if null. ## 0.10.8+4 * Adjusts SDK checks for better testability. ## 0.10.8+3 * Fixes unawaited_futures violations. * Removes duplicate line in `MediaRecorderBuilder.java`. * Adds support for concurrently capturing images and image streaming/recording. ## 0.10.8+2 * Removes obsolete null checks on non-nullable values. ## 0.10.8+1 * Fixes lint errors. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 0.10.8 * Updates gradle, AGP and fixes some lint errors. ## 0.10.7 * Adds support for NV21 as a new streaming format in Android which includes correct handling of image padding when present. ## 0.10.6+2 * Fixes compatibility with AGP versions older than 4.2. ## 0.10.6+1 * Adds a namespace for compatibility with AGP 8.0. ## 0.10.6 * Fixes Java warnings. ## 0.10.5 * Allows camera to be switched while video recording. ## 0.10.4+3 * Clarifies explanation of endorsement in README. ## 0.10.4+2 * Aligns Dart and Flutter SDK constraints. * Updates compileSdkVersion to 33. * Fixes false positive for CamcorderProfile deprecation warning that was already fixed. * Changes the severity of `javac` warnings so that they are treated as errors and fixes the violations. ## 0.10.4+1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 0.10.4 * Temporarily fixes issue with requested video profiles being null by falling back to deprecated behavior in that case. ## 0.10.3 * Adds back use of Optional type. * Updates minimum Flutter version to 3.0. ## 0.10.2+3 * Updates code for stricter lint checks. ## 0.10.2+2 * Fixes zoom computation for virtual cameras hiding physical cameras in Android 11+. * Removes the unused CameraZoom class from the codebase. ## 0.10.2+1 * Updates code for stricter lint checks. ## 0.10.2 * Remove usage of deprecated quiver Optional type. ## 0.10.1 * Implements an option to also stream when recording a video. ## 0.10.0+5 * Fixes `ArrayIndexOutOfBoundsException` when the permission request is interrupted. ## 0.10.0+4 * Upgrades `androidx.annotation` version to 1.5.0. ## 0.10.0+3 * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 0.10.0+2 * Removes call to `join` on the camera's background `HandlerThread`. * Updates minimum Flutter version to 2.10. ## 0.10.0+1 * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 0.10.0 * **Breaking Change** Updates Android camera access permission error codes to be consistent with other platforms. If your app still handles the legacy `cameraPermission` exception, please update it to handle the new permission exception codes that are noted in the README. * Ignores missing return warnings in preparation for [upcoming analysis changes](https://github.com/flutter/flutter/issues/105750). ## 0.9.8+3 * Skips duplicate calls to stop background thread and removes unnecessary closings of camera capture sessions on Android. ## 0.9.8+2 * Fixes exception in registerWith caused by the switch to an in-package method channel. ## 0.9.8+1 * Ignores deprecation warnings for upcoming styleFrom button API changes. ## 0.9.8 * Switches to internal method channel implementation. ## 0.9.7+1 * Splits from `camera` as a federated implementation.
packages/packages/camera/camera_android/CHANGELOG.md/0
{ "file_path": "packages/packages/camera/camera_android/CHANGELOG.md", "repo_id": "packages", "token_count": 1421 }
913
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features.exposurepoint; import android.annotation.SuppressLint; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.MeteringRectangle; import android.util.Size; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.CameraRegionUtils; import io.flutter.plugins.camera.features.CameraFeature; import io.flutter.plugins.camera.features.Point; import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature; /** Exposure point controls where in the frame exposure metering will come from. */ public class ExposurePointFeature extends CameraFeature<Point> { private Size cameraBoundaries; @Nullable private Point exposurePoint; private MeteringRectangle exposureRectangle; @NonNull private final SensorOrientationFeature sensorOrientationFeature; private boolean defaultRegionsHasBeenSet = false; @VisibleForTesting @Nullable public MeteringRectangle[] defaultRegions; /** * Creates a new instance of the {@link ExposurePointFeature}. * * @param cameraProperties Collection of the characteristics for the current camera device. */ public ExposurePointFeature( @NonNull CameraProperties cameraProperties, @NonNull SensorOrientationFeature sensorOrientationFeature) { super(cameraProperties); this.sensorOrientationFeature = sensorOrientationFeature; } /** * Sets the camera boundaries that are required for the exposure point feature to function. * * @param cameraBoundaries - The camera boundaries to set. */ public void setCameraBoundaries(@NonNull Size cameraBoundaries) { this.cameraBoundaries = cameraBoundaries; this.buildExposureRectangle(); } @NonNull @Override public String getDebugName() { return "ExposurePointFeature"; } @SuppressLint("KotlinPropertyAccess") @Nullable @Override public Point getValue() { return exposurePoint; } @Override public void setValue(@Nullable Point value) { this.exposurePoint = (value == null || value.x == null || value.y == null) ? null : value; this.buildExposureRectangle(); } // Whether or not this camera can set the exposure point. @Override public boolean checkIsSupported() { Integer supportedRegions = cameraProperties.getControlMaxRegionsAutoExposure(); return supportedRegions != null && supportedRegions > 0; } @Override public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) { if (!checkIsSupported()) { return; } if (!defaultRegionsHasBeenSet) { defaultRegions = requestBuilder.get(CaptureRequest.CONTROL_AE_REGIONS); defaultRegionsHasBeenSet = true; } if (exposureRectangle != null) { requestBuilder.set( CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[] {exposureRectangle}); } else { requestBuilder.set(CaptureRequest.CONTROL_AE_REGIONS, defaultRegions); } } private void buildExposureRectangle() { if (this.cameraBoundaries == null) { throw new AssertionError( "The cameraBoundaries should be set (using `ExposurePointFeature.setCameraBoundaries(Size)`) before updating the exposure point."); } if (this.exposurePoint == null) { this.exposureRectangle = null; } else { PlatformChannel.DeviceOrientation orientation = this.sensorOrientationFeature.getLockedCaptureOrientation(); if (orientation == null) { orientation = this.sensorOrientationFeature.getDeviceOrientationManager().getLastUIOrientation(); } this.exposureRectangle = CameraRegionUtils.convertPointToMeteringRectangle( this.cameraBoundaries, this.exposurePoint.x, this.exposurePoint.y, orientation); } } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurepoint/ExposurePointFeature.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurepoint/ExposurePointFeature.java", "repo_id": "packages", "token_count": 1313 }
914
# camera\_android\_camerax An Android implementation of [`camera`][1] that uses the [CameraX library][2]. *Note*: This implementation will become the default implementation of `camera` on Android by May 2024, so **we strongly encourage you to opt into it** by using [the instructions](#usage) below. If any of [the limitations](#limitations) prevent you from using `camera_android_camerax` or if you run into any problems, please report these issues under [`flutter/flutter`][5] with `[camerax]` in the title. ## Usage To use this plugin instead of [`camera_android`][4], run ```sh $ flutter pub add camera_android_camerax ``` from your project's root directory. ## Limitations ### 240p resolution configuration for video recording 240p resolution configuration for video recording is unsupported by CameraX, and thus, the plugin will fall back to 480p if configured with a `ResolutionPreset`. ### Setting maximum duration and stream options for video capture Calling `startVideoCapturing` with `VideoCaptureOptions` configured with `maxVideoDuration` and `streamOptions` is currently unsupported do to the limitations of the CameraX library and the platform interface, respectively, and thus, those parameters will silently be ignored. ## Contributing For more information on contributing to this plugin, see [`CONTRIBUTING.md`](CONTRIBUTING.md). <!-- Links --> [1]: https://pub.dev/packages/camera [2]: https://developer.android.com/training/camerax [3]: https://docs.flutter.dev/packages-and-plugins/developing-packages#non-endorsed-federated-plugin [4]: https://pub.dev/packages/camera_android [5]: https://github.com/flutter/flutter/issues/new/choose [120462]: https://github.com/flutter/flutter/issues/120462 [125915]: https://github.com/flutter/flutter/issues/125915 [120715]: https://github.com/flutter/flutter/issues/120715 [120468]: https://github.com/flutter/flutter/issues/120468 [120467]: https://github.com/flutter/flutter/issues/120467 [125371]: https://github.com/flutter/flutter/issues/125371 [126477]: https://github.com/flutter/flutter/issues/126477 [127896]: https://github.com/flutter/flutter/issues/127896
packages/packages/camera/camera_android_camerax/README.md/0
{ "file_path": "packages/packages/camera/camera_android_camerax/README.md", "repo_id": "packages", "token_count": 649 }
915
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.camera.core.ImageCapture; import androidx.camera.core.ImageCaptureException; import androidx.camera.core.resolutionselector.ResolutionSelector; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageCaptureHostApi; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.concurrent.Executors; public class ImageCaptureHostApiImpl implements ImageCaptureHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; @Nullable private Context context; private SystemServicesFlutterApiImpl systemServicesFlutterApiImpl; public static final String TEMPORARY_FILE_NAME = "CAP"; public static final String JPG_FILE_TYPE = ".jpg"; @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); public ImageCaptureHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull Context context) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; this.context = context; } /** * Sets the context that the {@link ImageCapture} will use to find a location to save a captured * image. */ public void setContext(@NonNull Context context) { this.context = context; } /** * Creates an {@link ImageCapture} with the requested flash mode and target resolution if * specified. */ @Override public void create( @NonNull Long identifier, @Nullable Long rotation, @Nullable Long flashMode, @Nullable Long resolutionSelectorId) { ImageCapture.Builder imageCaptureBuilder = cameraXProxy.createImageCaptureBuilder(); if (rotation != null) { imageCaptureBuilder.setTargetRotation(rotation.intValue()); } if (flashMode != null) { // This sets the requested flash mode, but may fail silently. imageCaptureBuilder.setFlashMode(flashMode.intValue()); } if (resolutionSelectorId != null) { ResolutionSelector resolutionSelector = Objects.requireNonNull(instanceManager.getInstance(resolutionSelectorId)); imageCaptureBuilder.setResolutionSelector(resolutionSelector); } ImageCapture imageCapture = imageCaptureBuilder.build(); instanceManager.addDartCreatedInstance(imageCapture, identifier); } /** Sets the flash mode of the {@link ImageCapture} instance with the specified identifier. */ @Override public void setFlashMode(@NonNull Long identifier, @NonNull Long flashMode) { ImageCapture imageCapture = getImageCaptureInstance(identifier); imageCapture.setFlashMode(flashMode.intValue()); } /** Captures a still image and uses the result to return its absolute path in memory. */ @Override public void takePicture( @NonNull Long identifier, @NonNull GeneratedCameraXLibrary.Result<String> result) { if (context == null) { throw new IllegalStateException("Context must be set to take picture."); } ImageCapture imageCapture = getImageCaptureInstance(identifier); final File outputDir = context.getCacheDir(); File temporaryCaptureFile; try { temporaryCaptureFile = File.createTempFile(TEMPORARY_FILE_NAME, JPG_FILE_TYPE, outputDir); } catch (IOException | SecurityException e) { result.error(e); return; } ImageCapture.OutputFileOptions outputFileOptions = cameraXProxy.createImageCaptureOutputFileOptions(temporaryCaptureFile); ImageCapture.OnImageSavedCallback onImageSavedCallback = createOnImageSavedCallback(temporaryCaptureFile, result); imageCapture.takePicture( outputFileOptions, Executors.newSingleThreadExecutor(), onImageSavedCallback); } /** Creates a callback used when saving a captured image. */ @VisibleForTesting public @NonNull ImageCapture.OnImageSavedCallback createOnImageSavedCallback( @NonNull File file, @NonNull GeneratedCameraXLibrary.Result<String> result) { return new ImageCapture.OnImageSavedCallback() { @Override public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) { result.success(file.getAbsolutePath()); } @Override public void onError(@NonNull ImageCaptureException exception) { result.error(exception); } }; } /** Dynamically sets the target rotation of the {@link ImageCapture}. */ @Override public void setTargetRotation(@NonNull Long identifier, @NonNull Long rotation) { ImageCapture imageCapture = getImageCaptureInstance(identifier); imageCapture.setTargetRotation(rotation.intValue()); } /** * Retrieves the {@link ImageCapture} instance associated with the specified {@code identifier}. */ private ImageCapture getImageCaptureInstance(@NonNull Long identifier) { return Objects.requireNonNull(instanceManager.getInstance(identifier)); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureHostApiImpl.java", "repo_id": "packages", "token_count": 1614 }
916
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import android.app.Activity; import android.app.Application.ActivityLifecycleCallbacks; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.Lifecycle.Event; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LifecycleRegistry; /** * This class provides a custom {@link LifecycleOwner} for the activity driven by {@link * ActivityLifecycleCallbacks}. * * <p>This is used in the case where a direct {@link LifecycleOwner} is not available. */ public class ProxyLifecycleProvider implements ActivityLifecycleCallbacks, LifecycleOwner { @VisibleForTesting @NonNull public LifecycleRegistry lifecycle = new LifecycleRegistry(this); private final int registrarActivityHashCode; ProxyLifecycleProvider(@NonNull Activity activity) { this.registrarActivityHashCode = activity.hashCode(); activity.getApplication().registerActivityLifecycleCallbacks(this); } @Override public void onActivityCreated(@NonNull Activity activity, @NonNull Bundle savedInstanceState) { if (activity.hashCode() != registrarActivityHashCode) { return; } lifecycle.handleLifecycleEvent(Event.ON_CREATE); } @Override public void onActivityStarted(@NonNull Activity activity) { if (activity.hashCode() != registrarActivityHashCode) { return; } lifecycle.handleLifecycleEvent(Event.ON_START); } @Override public void onActivityResumed(@NonNull Activity activity) { if (activity.hashCode() != registrarActivityHashCode) { return; } lifecycle.handleLifecycleEvent(Event.ON_RESUME); } @Override public void onActivityPaused(@NonNull Activity activity) { if (activity.hashCode() != registrarActivityHashCode) { return; } lifecycle.handleLifecycleEvent(Event.ON_PAUSE); } @Override public void onActivityStopped(@NonNull Activity activity) { if (activity.hashCode() != registrarActivityHashCode) { return; } lifecycle.handleLifecycleEvent(Event.ON_STOP); } @Override public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {} @Override public void onActivityDestroyed(@NonNull Activity activity) { if (activity.hashCode() != registrarActivityHashCode) { return; } activity.getApplication().unregisterActivityLifecycleCallbacks(this); lifecycle.handleLifecycleEvent(Event.ON_DESTROY); } @NonNull @Override public Lifecycle getLifecycle() { return lifecycle; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyLifecycleProvider.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyLifecycleProvider.java", "repo_id": "packages", "token_count": 879 }
917
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import android.app.Activity; import android.app.Application; import android.content.Context; import androidx.lifecycle.LifecycleOwner; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class CameraAndroidCameraxPluginTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock ActivityPluginBinding activityPluginBinding; @Mock FlutterPluginBinding flutterPluginBinding; @Test public void onAttachedToActivity_setsLifecycleOwnerAsActivityIfLifecycleOwnerAsNeeded() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); doNothing().when(plugin).setUp(any(), any(), any()); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onAttachedToActivity(activityPluginBinding); verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); } @Test public void onAttachedToActivity_setsLifecycleOwnerAsProxyLifecycleProviderIfActivityNotLifecycleOwnerAsNeeded() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); doNothing().when(plugin).setUp(any(), any(), any()); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); when(mockActivity.getApplication()).thenReturn(mock(Application.class)); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onAttachedToActivity(activityPluginBinding); verify(mockProcessCameraProviderHostApiImpl) .setLifecycleOwner(any(ProxyLifecycleProvider.class)); verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(ProxyLifecycleProvider.class)); } @Test public void onAttachedToActivity_setsActivityAsNeededAndPermissionsRegistry() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class); final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = mock(MeteringPointHostApiImpl.class); final ArgumentCaptor<PermissionsRegistry> permissionsRegistryCaptor = ArgumentCaptor.forClass(PermissionsRegistry.class); doNothing().when(plugin).setUp(any(), any(), any()); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); when(mockActivity.getApplication()).thenReturn(mock(Application.class)); plugin.processCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; plugin.onAttachedToEngine(flutterPluginBinding); plugin.onAttachedToActivity(activityPluginBinding); // Check Activity references are set. verify(mockSystemServicesHostApiImpl).setActivity(mockActivity); verify(mockDeviceOrientationManagerHostApiImpl).setActivity(mockActivity); verify(mockMeteringPointHostApiImpl).setActivity(mockActivity); // Check permissions registry reference is set. verify(mockSystemServicesHostApiImpl) .setPermissionsRegistry(permissionsRegistryCaptor.capture()); assertNotNull(permissionsRegistryCaptor.getValue()); assertTrue(permissionsRegistryCaptor.getValue() instanceof PermissionsRegistry); } @Test public void onDetachedFromActivityForConfigChanges_removesReferencesToActivityPluginBindingAndActivity() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = mock(MeteringPointHostApiImpl.class); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; plugin.onAttachedToEngine(flutterPluginBinding); plugin.onDetachedFromActivityForConfigChanges(); verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(null); verify(mockLiveDataHostApiImpl).setLifecycleOwner(null); verify(mockSystemServicesHostApiImpl).setActivity(null); verify(mockDeviceOrientationManagerHostApiImpl).setActivity(null); verify(mockMeteringPointHostApiImpl).setActivity(null); } @Test public void onDetachedFromActivityForConfigChanges_setsContextReferencesBasedOnFlutterPluginBinding() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Context mockContext = mock(Context.class); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final RecorderHostApiImpl mockRecorderHostApiImpl = mock(RecorderHostApiImpl.class); final PendingRecordingHostApiImpl mockPendingRecordingHostApiImpl = mock(PendingRecordingHostApiImpl.class); final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); final ImageCaptureHostApiImpl mockImageCaptureHostApiImpl = mock(ImageCaptureHostApiImpl.class); final ImageAnalysisHostApiImpl mockImageAnalysisHostApiImpl = mock(ImageAnalysisHostApiImpl.class); final CameraControlHostApiImpl mockCameraControlHostApiImpl = mock(CameraControlHostApiImpl.class); final Camera2CameraControlHostApiImpl mockCamera2CameraControlHostApiImpl = mock(Camera2CameraControlHostApiImpl.class); when(flutterPluginBinding.getApplicationContext()).thenReturn(mockContext); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.recorderHostApiImpl = mockRecorderHostApiImpl; plugin.pendingRecordingHostApiImpl = mockPendingRecordingHostApiImpl; plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; plugin.imageCaptureHostApiImpl = mockImageCaptureHostApiImpl; plugin.imageAnalysisHostApiImpl = mockImageAnalysisHostApiImpl; plugin.cameraControlHostApiImpl = mockCameraControlHostApiImpl; plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); plugin.camera2CameraControlHostApiImpl = mockCamera2CameraControlHostApiImpl; plugin.onAttachedToEngine(flutterPluginBinding); plugin.onDetachedFromActivityForConfigChanges(); verify(mockProcessCameraProviderHostApiImpl).setContext(mockContext); verify(mockRecorderHostApiImpl).setContext(mockContext); verify(mockPendingRecordingHostApiImpl).setContext(mockContext); verify(mockSystemServicesHostApiImpl).setContext(mockContext); verify(mockImageCaptureHostApiImpl).setContext(mockContext); verify(mockImageAnalysisHostApiImpl).setContext(mockContext); verify(mockCameraControlHostApiImpl).setContext(mockContext); verify(mockCamera2CameraControlHostApiImpl).setContext(mockContext); } @Test public void onReattachedToActivityForConfigChanges_setsLifecycleOwnerAsActivityIfLifecycleOwnerAsNeeded() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); plugin.onReattachedToActivityForConfigChanges(activityPluginBinding); verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); } @Test public void onReattachedToActivityForConfigChanges_setsLifecycleOwnerAsProxyLifecycleProviderIfActivityNotLifecycleOwnerAsNeeded() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); when(mockActivity.getApplication()).thenReturn(mock(Application.class)); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onReattachedToActivityForConfigChanges(activityPluginBinding); verify(mockProcessCameraProviderHostApiImpl) .setLifecycleOwner(any(ProxyLifecycleProvider.class)); verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(ProxyLifecycleProvider.class)); } @Test public void onReattachedToActivityForConfigChanges_setsActivityAndPermissionsRegistryAsNeeded() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final RecorderHostApiImpl mockRecorderHostApiImpl = mock(RecorderHostApiImpl.class); final PendingRecordingHostApiImpl mockPendingRecordingHostApiImpl = mock(PendingRecordingHostApiImpl.class); final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); final ImageAnalysisHostApiImpl mockImageAnalysisHostApiImpl = mock(ImageAnalysisHostApiImpl.class); final ImageCaptureHostApiImpl mockImageCaptureHostApiImpl = mock(ImageCaptureHostApiImpl.class); final CameraControlHostApiImpl mockCameraControlHostApiImpl = mock(CameraControlHostApiImpl.class); final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); final Camera2CameraControlHostApiImpl mockCamera2CameraControlHostApiImpl = mock(Camera2CameraControlHostApiImpl.class); final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = mock(MeteringPointHostApiImpl.class); final ArgumentCaptor<PermissionsRegistry> permissionsRegistryCaptor = ArgumentCaptor.forClass(PermissionsRegistry.class); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); when(mockActivity.getApplication()).thenReturn(mock(Application.class)); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.recorderHostApiImpl = mockRecorderHostApiImpl; plugin.pendingRecordingHostApiImpl = mockPendingRecordingHostApiImpl; plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; plugin.imageCaptureHostApiImpl = mockImageCaptureHostApiImpl; plugin.imageAnalysisHostApiImpl = mockImageAnalysisHostApiImpl; plugin.cameraControlHostApiImpl = mockCameraControlHostApiImpl; plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); plugin.camera2CameraControlHostApiImpl = mockCamera2CameraControlHostApiImpl; plugin.onAttachedToEngine(flutterPluginBinding); plugin.onReattachedToActivityForConfigChanges(activityPluginBinding); // Check Activity references are set. verify(mockSystemServicesHostApiImpl).setActivity(mockActivity); verify(mockDeviceOrientationManagerHostApiImpl).setActivity(mockActivity); verify(mockMeteringPointHostApiImpl).setActivity(mockActivity); // Check Activity as Context references are set. verify(mockProcessCameraProviderHostApiImpl).setContext(mockActivity); verify(mockRecorderHostApiImpl).setContext(mockActivity); verify(mockPendingRecordingHostApiImpl).setContext(mockActivity); verify(mockSystemServicesHostApiImpl).setContext(mockActivity); verify(mockImageCaptureHostApiImpl).setContext(mockActivity); verify(mockImageAnalysisHostApiImpl).setContext(mockActivity); verify(mockCameraControlHostApiImpl).setContext(mockActivity); verify(mockCamera2CameraControlHostApiImpl).setContext(mockActivity); // Check permissions registry reference is set. verify(mockSystemServicesHostApiImpl) .setPermissionsRegistry(permissionsRegistryCaptor.capture()); assertNotNull(permissionsRegistryCaptor.getValue()); assertTrue(permissionsRegistryCaptor.getValue() instanceof PermissionsRegistry); } @Test public void onDetachedFromActivity_removesReferencesToActivityPluginBindingAndActivity() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = mock(MeteringPointHostApiImpl.class); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; plugin.onAttachedToEngine(flutterPluginBinding); plugin.onDetachedFromActivityForConfigChanges(); verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(null); verify(mockLiveDataHostApiImpl).setLifecycleOwner(null); verify(mockSystemServicesHostApiImpl).setActivity(null); verify(mockDeviceOrientationManagerHostApiImpl).setActivity(null); verify(mockMeteringPointHostApiImpl).setActivity(null); } @Test public void onDetachedFromActivity_setsContextReferencesBasedOnFlutterPluginBinding() { final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Context mockContext = mock(Context.class); final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); final RecorderHostApiImpl mockRecorderHostApiImpl = mock(RecorderHostApiImpl.class); final PendingRecordingHostApiImpl mockPendingRecordingHostApiImpl = mock(PendingRecordingHostApiImpl.class); final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); final ImageAnalysisHostApiImpl mockImageAnalysisHostApiImpl = mock(ImageAnalysisHostApiImpl.class); final ImageCaptureHostApiImpl mockImageCaptureHostApiImpl = mock(ImageCaptureHostApiImpl.class); final CameraControlHostApiImpl mockCameraControlHostApiImpl = mock(CameraControlHostApiImpl.class); final Camera2CameraControlHostApiImpl mockCamera2CameraControlHostApiImpl = mock(Camera2CameraControlHostApiImpl.class); final ArgumentCaptor<PermissionsRegistry> permissionsRegistryCaptor = ArgumentCaptor.forClass(PermissionsRegistry.class); when(flutterPluginBinding.getApplicationContext()).thenReturn(mockContext); plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; plugin.recorderHostApiImpl = mockRecorderHostApiImpl; plugin.pendingRecordingHostApiImpl = mockPendingRecordingHostApiImpl; plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; plugin.imageCaptureHostApiImpl = mockImageCaptureHostApiImpl; plugin.imageAnalysisHostApiImpl = mockImageAnalysisHostApiImpl; plugin.cameraControlHostApiImpl = mockCameraControlHostApiImpl; plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); plugin.camera2CameraControlHostApiImpl = mockCamera2CameraControlHostApiImpl; plugin.onAttachedToEngine(flutterPluginBinding); plugin.onDetachedFromActivity(); verify(mockProcessCameraProviderHostApiImpl).setContext(mockContext); verify(mockRecorderHostApiImpl).setContext(mockContext); verify(mockPendingRecordingHostApiImpl).setContext(mockContext); verify(mockSystemServicesHostApiImpl).setContext(mockContext); verify(mockImageCaptureHostApiImpl).setContext(mockContext); verify(mockImageAnalysisHostApiImpl).setContext(mockContext); verify(mockCameraControlHostApiImpl).setContext(mockContext); verify(mockCamera2CameraControlHostApiImpl).setContext(mockContext); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraAndroidCameraxPluginTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraAndroidCameraxPluginTest.java", "repo_id": "packages", "token_count": 6592 }
918
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import android.view.Surface; import androidx.camera.core.ImageCapture; import androidx.camera.core.ImageCaptureException; import androidx.camera.core.resolutionselector.ResolutionSelector; import io.flutter.plugin.common.BinaryMessenger; import java.io.File; import java.io.IOException; import java.util.concurrent.Executor; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ImageCaptureTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public ImageCapture mockImageCapture; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public CameraXProxy mockCameraXProxy; InstanceManager testInstanceManager; private Context context; private MockedStatic<File> mockedStaticFile; @Before public void setUp() throws Exception { testInstanceManager = spy(InstanceManager.create(identifier -> {})); context = mock(Context.class); mockedStaticFile = mockStatic(File.class); } @After public void tearDown() { testInstanceManager.stopFinalizationListener(); mockedStaticFile.close(); } @Test public void create_createsImageCaptureWithCorrectConfiguration() { final ImageCaptureHostApiImpl imageCaptureHostApiImpl = new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final ImageCapture.Builder mockImageCaptureBuilder = mock(ImageCapture.Builder.class); final Long imageCaptureIdentifier = 74L; final int flashMode = ImageCapture.FLASH_MODE_ON; final ResolutionSelector mockResolutionSelector = mock(ResolutionSelector.class); final long mockResolutionSelectorId = 77; final int targetRotation = Surface.ROTATION_270; imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; testInstanceManager.addDartCreatedInstance(mockResolutionSelector, mockResolutionSelectorId); when(mockCameraXProxy.createImageCaptureBuilder()).thenReturn(mockImageCaptureBuilder); when(mockImageCaptureBuilder.build()).thenReturn(mockImageCapture); imageCaptureHostApiImpl.create( imageCaptureIdentifier, Long.valueOf(targetRotation), Long.valueOf(flashMode), mockResolutionSelectorId); verify(mockImageCaptureBuilder).setTargetRotation(targetRotation); verify(mockImageCaptureBuilder).setFlashMode(flashMode); verify(mockImageCaptureBuilder).setResolutionSelector(mockResolutionSelector); verify(mockImageCaptureBuilder).build(); verify(testInstanceManager).addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); } @Test public void setFlashMode_setsFlashModeOfImageCaptureInstance() { final ImageCaptureHostApiImpl imageCaptureHostApiImpl = new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final Long imageCaptureIdentifier = 85L; final Long flashMode = Long.valueOf(ImageCapture.FLASH_MODE_AUTO); testInstanceManager.addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); imageCaptureHostApiImpl.setFlashMode(imageCaptureIdentifier, flashMode); verify(mockImageCapture).setFlashMode(flashMode.intValue()); } @Test public void takePicture_sendsRequestToTakePictureWithExpectedConfigurationWhenTemporaryFileCanBeCreated() { final ImageCaptureHostApiImpl imageCaptureHostApiImpl = spy(new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context)); final Long imageCaptureIdentifier = 6L; final File mockOutputDir = mock(File.class); final File mockFile = mock(File.class); final ImageCapture.OutputFileOptions mockOutputFileOptions = mock(ImageCapture.OutputFileOptions.class); final ImageCapture.OnImageSavedCallback mockOnImageSavedCallback = mock(ImageCapture.OnImageSavedCallback.class); @SuppressWarnings("unchecked") final GeneratedCameraXLibrary.Result<String> mockResult = mock(GeneratedCameraXLibrary.Result.class); testInstanceManager.addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); when(context.getCacheDir()).thenReturn(mockOutputDir); imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; mockedStaticFile .when( () -> File.createTempFile( ImageCaptureHostApiImpl.TEMPORARY_FILE_NAME, ImageCaptureHostApiImpl.JPG_FILE_TYPE, mockOutputDir)) .thenReturn(mockFile); when(mockCameraXProxy.createImageCaptureOutputFileOptions(mockFile)) .thenReturn(mockOutputFileOptions); when(imageCaptureHostApiImpl.createOnImageSavedCallback(mockFile, mockResult)) .thenReturn(mockOnImageSavedCallback); imageCaptureHostApiImpl.takePicture(imageCaptureIdentifier, mockResult); verify(mockImageCapture) .takePicture(eq(mockOutputFileOptions), any(Executor.class), eq(mockOnImageSavedCallback)); } @Test public void takePicture_sendsErrorWhenTemporaryFileCannotBeCreated() { final ImageCaptureHostApiImpl imageCaptureHostApiImpl = new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final Long imageCaptureIdentifier = 6L; final File mockOutputDir = mock(File.class); final File mockTemporaryCaptureFile = mock(File.class); @SuppressWarnings("unchecked") final GeneratedCameraXLibrary.Result<String> mockResult = mock(GeneratedCameraXLibrary.Result.class); final IOException fileCreationException = new IOException(); testInstanceManager.addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; when(context.getCacheDir()).thenReturn(mockOutputDir); mockedStaticFile .when( () -> File.createTempFile( ImageCaptureHostApiImpl.TEMPORARY_FILE_NAME, ImageCaptureHostApiImpl.JPG_FILE_TYPE, mockOutputDir)) .thenThrow(fileCreationException); imageCaptureHostApiImpl.takePicture(imageCaptureIdentifier, mockResult); verify(mockResult).error(fileCreationException); verify(mockImageCapture, times(0)) .takePicture( any(ImageCapture.OutputFileOptions.class), any(Executor.class), any(ImageCapture.OnImageSavedCallback.class)); } @Test public void takePicture_usesExpectedOnImageSavedCallback() { final ImageCaptureHostApiImpl imageCaptureHostApiImpl = new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final SystemServicesFlutterApiImpl mockSystemServicesFlutterApiImpl = mock(SystemServicesFlutterApiImpl.class); final File mockFile = mock(File.class); @SuppressWarnings("unchecked") final GeneratedCameraXLibrary.Result<String> mockResult = mock(GeneratedCameraXLibrary.Result.class); final ImageCapture.OutputFileResults mockOutputFileResults = mock(ImageCapture.OutputFileResults.class); final String mockFileAbsolutePath = "absolute/path/to/captured/image"; final ImageCaptureException mockException = mock(ImageCaptureException.class); imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; when(mockFile.getAbsolutePath()).thenReturn(mockFileAbsolutePath); ImageCapture.OnImageSavedCallback onImageSavedCallback = imageCaptureHostApiImpl.createOnImageSavedCallback(mockFile, mockResult); // Test success case. onImageSavedCallback.onImageSaved(mockOutputFileResults); verify(mockResult).success(mockFileAbsolutePath); // Test error case. onImageSavedCallback.onError(mockException); verify(mockResult).error(mockException); } @Test public void setTargetRotation_makesCallToSetTargetRotation() { final ImageCaptureHostApiImpl hostApi = new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final long instanceIdentifier = 42; final int targetRotation = Surface.ROTATION_90; testInstanceManager.addDartCreatedInstance(mockImageCapture, instanceIdentifier); hostApi.setTargetRotation(instanceIdentifier, Long.valueOf(targetRotation)); verify(mockImageCapture).setTargetRotation(targetRotation); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageCaptureTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageCaptureTest.java", "repo_id": "packages", "token_count": 3069 }
919
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import android.util.Size; import androidx.camera.core.resolutionselector.ResolutionStrategy; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class ResolutionStrategyTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public ResolutionStrategy mockResolutionStrategy; @Mock public ResolutionStrategyHostApiImpl.ResolutionStrategyProxy mockProxy; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void hostApiCreate_createsExpectedResolutionStrategyInstanceWhenArgumentsValid() { final GeneratedCameraXLibrary.ResolutionInfo boundSize = new GeneratedCameraXLibrary.ResolutionInfo.Builder().setWidth(50L).setHeight(30L).build(); final Long fallbackRule = 0L; when(mockProxy.create(any(Size.class), eq(fallbackRule))).thenReturn(mockResolutionStrategy); final ResolutionStrategyHostApiImpl hostApi = new ResolutionStrategyHostApiImpl(instanceManager, mockProxy); final long instanceIdentifier = 0; hostApi.create(instanceIdentifier, boundSize, fallbackRule); assertEquals(instanceManager.getInstance(instanceIdentifier), mockResolutionStrategy); } @Test public void hostApiCreate_throwsAssertionErrorWhenArgumentsInvalid() { final Long fallbackRule = 8L; final long instanceIdentifier = 0; final ResolutionStrategyHostApiImpl hostApi = new ResolutionStrategyHostApiImpl(instanceManager, mockProxy); // We expect an exception to be thrown if fallback rule is specified but bound size is not. assertThrows( IllegalArgumentException.class, () -> hostApi.create(instanceIdentifier, null, fallbackRule)); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionStrategyTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionStrategyTest.java", "repo_id": "packages", "token_count": 767 }
920
name: camera_android_camerax_example description: Demonstrates how to use the camera_android_camerax plugin. publish_to: 'none' environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: camera_android_camerax: # When depending on this package from a real application you should use: # camera_android_camerax: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ camera_platform_interface: ^2.2.0 flutter: sdk: flutter video_player: ^2.7.0 dev_dependencies: espresso: ^0.2.0 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/camera/camera_android_camerax/example/pubspec.yaml/0
{ "file_path": "packages/packages/camera/camera_android_camerax/example/pubspec.yaml", "repo_id": "packages", "token_count": 294 }
921
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show Size; import 'analyzer.dart'; import 'camera2_camera_control.dart'; import 'camera_control.dart'; import 'camera_info.dart'; import 'camera_selector.dart'; import 'camera_state.dart'; import 'camerax_library.g.dart'; import 'capture_request_options.dart'; import 'device_orientation_manager.dart'; import 'fallback_strategy.dart'; import 'focus_metering_action.dart'; import 'image_analysis.dart'; import 'image_capture.dart'; import 'image_proxy.dart'; import 'metering_point.dart'; import 'observer.dart'; import 'preview.dart'; import 'process_camera_provider.dart'; import 'quality_selector.dart'; import 'recorder.dart'; import 'resolution_selector.dart'; import 'resolution_strategy.dart'; import 'system_services.dart'; import 'video_capture.dart'; /// Handles `JavaObject` creation and calling their methods that require /// testing. /// /// By default, each function will create `JavaObject`s attached to an /// `InstanceManager` and call through to the appropriate method. class CameraXProxy { /// Constructs a [CameraXProxy]. CameraXProxy({ this.getProcessCameraProvider = _getProcessCameraProvider, this.createCameraSelector = _createAttachedCameraSelector, this.createPreview = _createAttachedPreview, this.createImageCapture = _createAttachedImageCapture, this.createRecorder = _createAttachedRecorder, this.createVideoCapture = _createAttachedVideoCapture, this.createImageAnalysis = _createAttachedImageAnalysis, this.createAnalyzer = _createAttachedAnalyzer, this.createCameraStateObserver = _createAttachedCameraStateObserver, this.createResolutionStrategy = _createAttachedResolutionStrategy, this.createResolutionSelector = _createAttachedResolutionSelector, this.createFallbackStrategy = _createAttachedFallbackStrategy, this.createQualitySelector = _createAttachedQualitySelector, this.requestCameraPermissions = _requestCameraPermissions, this.startListeningForDeviceOrientationChange = _startListeningForDeviceOrientationChange, this.setPreviewSurfaceProvider = _setPreviewSurfaceProvider, this.getDefaultDisplayRotation = _getDefaultDisplayRotation, this.getCamera2CameraControl = _getCamera2CameraControl, this.createCaptureRequestOptions = _createAttachedCaptureRequestOptions, this.createMeteringPoint = _createAttachedMeteringPoint, this.createFocusMeteringAction = _createAttachedFocusMeteringAction, }); /// Returns a [ProcessCameraProvider] instance. Future<ProcessCameraProvider> Function() getProcessCameraProvider; /// Returns a [CameraSelector] based on the specified camera lens direction. CameraSelector Function(int cameraSelectorLensDirection) createCameraSelector; /// Returns a [Preview] configured with the specified target rotation and /// specified [ResolutionSelector]. Preview Function( ResolutionSelector? resolutionSelector, int? targetRotation, ) createPreview; /// Returns an [ImageCapture] configured with specified flash mode and /// the specified [ResolutionSelector]. ImageCapture Function( ResolutionSelector? resolutionSelector, int? targetRotation) createImageCapture; /// Returns a [Recorder] for use in video capture configured with the /// specified [QualitySelector]. Recorder Function(QualitySelector? qualitySelector) createRecorder; /// Returns a [VideoCapture] associated with the provided [Recorder]. Future<VideoCapture> Function(Recorder recorder) createVideoCapture; /// Returns an [ImageAnalysis] configured with the specified /// [ResolutionSelector]. ImageAnalysis Function( ResolutionSelector? resolutionSelector, int? targetRotation) createImageAnalysis; /// Returns an [Analyzer] configured with the specified callback for /// analyzing [ImageProxy]s. Analyzer Function(Future<void> Function(ImageProxy imageProxy) analyze) createAnalyzer; /// Returns an [Observer] of the [CameraState] with the specified callback /// for handling changes in that state. Observer<CameraState> Function(void Function(Object stateAsObject) onChanged) createCameraStateObserver; /// Returns a [ResolutionStrategy] configured with the specified bounds for /// choosing a resolution and a fallback rule if achieving a resolution within /// those bounds is not possible. /// /// [highestAvailable] is used to specify whether or not the highest available /// [ResolutionStrategy] should be returned. ResolutionStrategy Function( {bool highestAvailable, Size? boundSize, int? fallbackRule}) createResolutionStrategy; /// Returns a [ResolutionSelector] configured with the specified /// [ResolutionStrategy]. ResolutionSelector Function(ResolutionStrategy resolutionStrategy) createResolutionSelector; /// Returns a [FallbackStrategy] configured with the specified [VideoQuality] /// and [VideoResolutionFallbackRule]. FallbackStrategy Function( {required VideoQuality quality, required VideoResolutionFallbackRule fallbackRule}) createFallbackStrategy; /// Returns a [QualitySelector] configured with the specified [VideoQuality] /// and [FallbackStrategy]. QualitySelector Function( {required VideoQuality videoQuality, required FallbackStrategy fallbackStrategy}) createQualitySelector; /// Requests camera permissions. Future<void> Function(bool enableAudio) requestCameraPermissions; /// Subscribes the plugin as a listener to changes in device orientation. void Function(bool cameraIsFrontFacing, int sensorOrientation) startListeningForDeviceOrientationChange; /// Sets the surface provider of the specified [Preview] instance and returns /// the ID corresponding to the surface it will provide. Future<int> Function(Preview preview) setPreviewSurfaceProvider; /// Returns default rotation for [UseCase]s in terms of one of the [Surface] /// rotation constants. Future<int> Function() getDefaultDisplayRotation; /// Get [Camera2CameraControl] instance from [cameraControl]. Camera2CameraControl Function(CameraControl cameraControl) getCamera2CameraControl; /// Create [CapureRequestOptions] with specified options. CaptureRequestOptions Function( List<(CaptureRequestKeySupportedType, Object?)> options) createCaptureRequestOptions; /// Returns a [MeteringPoint] with the specified coordinates based on /// [cameraInfo]. MeteringPoint Function( double x, double y, double? size, CameraInfo cameraInfo) createMeteringPoint; /// Returns a [FocusMeteringAction] based on the specified metering points /// and their modes. FocusMeteringAction Function(List<(MeteringPoint, int?)> meteringPointInfos, bool? disableAutoCancel) createFocusMeteringAction; static Future<ProcessCameraProvider> _getProcessCameraProvider() { return ProcessCameraProvider.getInstance(); } static CameraSelector _createAttachedCameraSelector( int cameraSelectorLensDirection) { switch (cameraSelectorLensDirection) { case CameraSelector.lensFacingFront: return CameraSelector.getDefaultFrontCamera(); case CameraSelector.lensFacingBack: return CameraSelector.getDefaultBackCamera(); default: return CameraSelector(lensFacing: cameraSelectorLensDirection); } } static Preview _createAttachedPreview( ResolutionSelector? resolutionSelector, int? targetRotation) { return Preview( initialTargetRotation: targetRotation, resolutionSelector: resolutionSelector); } static ImageCapture _createAttachedImageCapture( ResolutionSelector? resolutionSelector, int? targetRotation) { return ImageCapture( resolutionSelector: resolutionSelector, initialTargetRotation: targetRotation); } static Recorder _createAttachedRecorder(QualitySelector? qualitySelector) { return Recorder(qualitySelector: qualitySelector); } static Future<VideoCapture> _createAttachedVideoCapture( Recorder recorder) async { return VideoCapture.withOutput(recorder); } static ImageAnalysis _createAttachedImageAnalysis( ResolutionSelector? resolutionSelector, int? targetRotation) { return ImageAnalysis( resolutionSelector: resolutionSelector, initialTargetRotation: targetRotation); } static Analyzer _createAttachedAnalyzer( Future<void> Function(ImageProxy imageProxy) analyze) { return Analyzer(analyze: analyze); } static Observer<CameraState> _createAttachedCameraStateObserver( void Function(Object stateAsObject) onChanged) { return Observer<CameraState>(onChanged: onChanged); } static ResolutionStrategy _createAttachedResolutionStrategy( {bool highestAvailable = false, Size? boundSize, int? fallbackRule}) { if (highestAvailable) { return ResolutionStrategy.highestAvailableStrategy(); } return ResolutionStrategy( boundSize: boundSize!, fallbackRule: fallbackRule); } static ResolutionSelector _createAttachedResolutionSelector( ResolutionStrategy resolutionStrategy) { return ResolutionSelector(resolutionStrategy: resolutionStrategy); } static FallbackStrategy _createAttachedFallbackStrategy( {required VideoQuality quality, required VideoResolutionFallbackRule fallbackRule}) { return FallbackStrategy(quality: quality, fallbackRule: fallbackRule); } static QualitySelector _createAttachedQualitySelector( {required VideoQuality videoQuality, required FallbackStrategy fallbackStrategy}) { return QualitySelector.from( quality: VideoQualityData(quality: videoQuality), fallbackStrategy: fallbackStrategy); } static Future<void> _requestCameraPermissions(bool enableAudio) async { await SystemServices.requestCameraPermissions(enableAudio); } static void _startListeningForDeviceOrientationChange( bool cameraIsFrontFacing, int sensorOrientation) { DeviceOrientationManager.startListeningForDeviceOrientationChange( cameraIsFrontFacing, sensorOrientation); } static Future<int> _setPreviewSurfaceProvider(Preview preview) async { return preview.setSurfaceProvider(); } static Future<int> _getDefaultDisplayRotation() async { return DeviceOrientationManager.getDefaultDisplayRotation(); } static Camera2CameraControl _getCamera2CameraControl( CameraControl cameraControl) { return Camera2CameraControl(cameraControl: cameraControl); } static CaptureRequestOptions _createAttachedCaptureRequestOptions( List<(CaptureRequestKeySupportedType, Object?)> options) { return CaptureRequestOptions(requestedOptions: options); } static MeteringPoint _createAttachedMeteringPoint( double x, double y, double? size, CameraInfo cameraInfo) { return MeteringPoint(x: x, y: y, size: size, cameraInfo: cameraInfo); } static FocusMeteringAction _createAttachedFocusMeteringAction( List<(MeteringPoint, int?)> meteringPointInfos, bool? disableAutoCancel) { return FocusMeteringAction( meteringPointInfos: meteringPointInfos, disableAutoCancel: disableAutoCancel); } }
packages/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart", "repo_id": "packages", "token_count": 3340 }
922
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:flutter/services.dart' show BinaryMessenger; import 'package:meta/meta.dart' show immutable, protected; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; /// A single color plane of image data. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageProxy.PlaneProxy. @immutable class PlaneProxy extends JavaObject { /// Constructs a [PlaneProxy] that is not automatically attached to a native object. PlaneProxy.detached( {super.binaryMessenger, super.instanceManager, required this.buffer, required this.pixelStride, required this.rowStride}) : super.detached() { AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } /// Returns the pixels buffer containing frame data. final Uint8List buffer; /// Returns the pixel stride, the distance between adjacent pixel samples, in /// bytes. final int pixelStride; /// Returns the row stride, the distance between the start of two consecutive /// rows of pixels in the image, in bytes. final int rowStride; } /// Flutter API implementation for [PlaneProxy]. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. @protected class PlaneProxyFlutterApiImpl implements PlaneProxyFlutterApi { /// Constructs an [PlaneProxyFlutterApiImpl]. /// /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, /// which routes to the host platform. /// /// An [instanceManager] is typically passed when a copy of an instance /// contained by an [InstanceManager] is being created. If left null, it /// will default to the global instance defined in [JavaObject]. PlaneProxyFlutterApiImpl({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? _binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager _instanceManager; @override void create( int identifier, Uint8List buffer, int pixelStride, int rowStride, ) { _instanceManager.addHostCreatedInstance( PlaneProxy.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, buffer: buffer, pixelStride: pixelStride, rowStride: rowStride, ), identifier, onCopy: (PlaneProxy original) => PlaneProxy.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, buffer: buffer, pixelStride: pixelStride, rowStride: rowStride), ); } }
packages/packages/camera/camera_android_camerax/lib/src/plane_proxy.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/plane_proxy.dart", "repo_id": "packages", "token_count": 992 }
923
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/image_analysis_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:camera_android_camerax/src/resolution_selector.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [TestImageAnalysisHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestImageAnalysisHostApi extends _i1.Mock implements _i2.TestImageAnalysisHostApi { MockTestImageAnalysisHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, int? targetRotation, int? resolutionSelectorId, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, targetRotation, resolutionSelectorId, ], ), returnValueForMissingStub: null, ); @override void setAnalyzer( int? identifier, int? analyzerIdentifier, ) => super.noSuchMethod( Invocation.method( #setAnalyzer, [ identifier, analyzerIdentifier, ], ), returnValueForMissingStub: null, ); @override void clearAnalyzer(int? identifier) => super.noSuchMethod( Invocation.method( #clearAnalyzer, [identifier], ), returnValueForMissingStub: null, ); @override void setTargetRotation( int? identifier, int? rotation, ) => super.noSuchMethod( Invocation.method( #setTargetRotation, [ identifier, rotation, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [ResolutionSelector]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockResolutionSelector extends _i1.Mock implements _i3.ResolutionSelector { MockResolutionSelector() { _i1.throwOnMissingStub(this); } }
packages/packages/camera/camera_android_camerax/test/image_analysis_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/image_analysis_test.mocks.dart", "repo_id": "packages", "token_count": 1300 }
924
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/preview.dart'; import 'package:camera_android_camerax/src/resolution_selector.dart'; import 'package:camera_android_camerax/src/surface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'preview_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks( <Type>[TestInstanceManagerHostApi, TestPreviewHostApi, ResolutionSelector]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); group('Preview', () { tearDown(() => TestPreviewHostApi.setup(null)); test('detached create does not call create on the Java side', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); Preview.detached( instanceManager: instanceManager, initialTargetRotation: Surface.ROTATION_90, resolutionSelector: MockResolutionSelector(), ); verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<int>()), argThat(isA<ResolutionSelector>()))); }); test('create calls create on the Java side', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int targetRotation = Surface.ROTATION_90; final MockResolutionSelector mockResolutionSelector = MockResolutionSelector(); const int mockResolutionSelectorId = 24; instanceManager.addHostCreatedInstance( mockResolutionSelector, mockResolutionSelectorId, onCopy: (ResolutionSelector original) { return MockResolutionSelector(); }); Preview( instanceManager: instanceManager, initialTargetRotation: targetRotation, resolutionSelector: mockResolutionSelector, ); verify(mockApi.create( argThat(isA<int>()), argThat(equals(targetRotation)), argThat(equals(mockResolutionSelectorId)))); }); test( 'setTargetRotation makes call to set target rotation for Preview instance', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int targetRotation = Surface.ROTATION_180; final Preview preview = Preview.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( preview, 0, onCopy: (_) => Preview.detached(instanceManager: instanceManager), ); await preview.setTargetRotation(targetRotation); verify(mockApi.setTargetRotation( instanceManager.getIdentifier(preview), targetRotation)); }); test( 'setSurfaceProvider makes call to set surface provider for preview instance', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int textureId = 8; final Preview preview = Preview.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( preview, 0, onCopy: (_) => Preview.detached(), ); when(mockApi.setSurfaceProvider(instanceManager.getIdentifier(preview))) .thenReturn(textureId); expect(await preview.setSurfaceProvider(), equals(textureId)); verify( mockApi.setSurfaceProvider(instanceManager.getIdentifier(preview))); }); test( 'releaseFlutterSurfaceTexture makes call to release flutter surface texture entry', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final Preview preview = Preview.detached(); preview.releaseFlutterSurfaceTexture(); verify(mockApi.releaseFlutterSurfaceTexture()); }); test( 'getResolutionInfo makes call to get resolution information for preview instance', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Preview preview = Preview.detached( instanceManager: instanceManager, ); const int resolutionWidth = 10; const int resolutionHeight = 60; final ResolutionInfo testResolutionInfo = ResolutionInfo(width: resolutionWidth, height: resolutionHeight); instanceManager.addHostCreatedInstance( preview, 0, onCopy: (_) => Preview.detached(), ); when(mockApi.getResolutionInfo(instanceManager.getIdentifier(preview))) .thenReturn(testResolutionInfo); final ResolutionInfo previewResolutionInfo = await preview.getResolutionInfo(); expect(previewResolutionInfo.width, equals(resolutionWidth)); expect(previewResolutionInfo.height, equals(resolutionHeight)); verify(mockApi.getResolutionInfo(instanceManager.getIdentifier(preview))); }); }); }
packages/packages/camera/camera_android_camerax/test/preview_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/preview_test.dart", "repo_id": "packages", "token_count": 2227 }
925
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v9.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:camera_android_camerax/src/camerax_library.g.dart'; abstract class TestInstanceManagerHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Clear the native `InstanceManager`. /// /// This is typically only used after a hot restart. void clear(); static void setup(TestInstanceManagerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.InstanceManagerHostApi.clear', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message api.clear(); return <Object?>[]; }); } } } } abstract class TestJavaObjectHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void dispose(int identifier); static void setup(TestJavaObjectHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.JavaObjectHostApi.dispose', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.JavaObjectHostApi.dispose was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.JavaObjectHostApi.dispose was null, expected non-null int.'); api.dispose(arg_identifier!); return <Object?>[]; }); } } } } abstract class TestCameraInfoHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); int getSensorRotationDegrees(int identifier); int getCameraState(int identifier); int getExposureState(int identifier); int getZoomState(int identifier); static void setup(TestCameraInfoHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees was null, expected non-null int.'); final int output = api.getSensorRotationDegrees(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraInfoHostApi.getCameraState', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getCameraState was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getCameraState was null, expected non-null int.'); final int output = api.getCameraState(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraInfoHostApi.getExposureState', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getExposureState was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getExposureState was null, expected non-null int.'); final int output = api.getExposureState(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraInfoHostApi.getZoomState', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getZoomState was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getZoomState was null, expected non-null int.'); final int output = api.getZoomState(arg_identifier!); return <Object?>[output]; }); } } } } abstract class TestCameraSelectorHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, int? lensFacing); List<int?> filter(int identifier, List<int?> cameraInfoIds); static void setup(TestCameraSelectorHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraSelectorHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.create was null, expected non-null int.'); final int? arg_lensFacing = (args[1] as int?); api.create(arg_identifier!, arg_lensFacing); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraSelectorHostApi.filter', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null, expected non-null int.'); final List<int?>? arg_cameraInfoIds = (args[1] as List<Object?>?)?.cast<int?>(); assert(arg_cameraInfoIds != null, 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null, expected non-null List<int?>.'); final List<int?> output = api.filter(arg_identifier!, arg_cameraInfoIds!); return <Object?>[output]; }); } } } } abstract class TestProcessCameraProviderHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<int> getInstance(); List<int?> getAvailableCameraInfos(int identifier); int bindToLifecycle( int identifier, int cameraSelectorIdentifier, List<int?> useCaseIds); bool isBound(int identifier, int useCaseIdentifier); void unbind(int identifier, List<int?> useCaseIds); void unbindAll(int identifier); static void setup(TestProcessCameraProviderHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ProcessCameraProviderHostApi.getInstance', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message final int output = await api.getInstance(); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos was null, expected non-null int.'); final List<int?> output = api.getAvailableCameraInfos(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null int.'); final int? arg_cameraSelectorIdentifier = (args[1] as int?); assert(arg_cameraSelectorIdentifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null int.'); final List<int?>? arg_useCaseIds = (args[2] as List<Object?>?)?.cast<int?>(); assert(arg_useCaseIds != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null List<int?>.'); final int output = api.bindToLifecycle( arg_identifier!, arg_cameraSelectorIdentifier!, arg_useCaseIds!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound was null, expected non-null int.'); final int? arg_useCaseIdentifier = (args[1] as int?); assert(arg_useCaseIdentifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound was null, expected non-null int.'); final bool output = api.isBound(arg_identifier!, arg_useCaseIdentifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null, expected non-null int.'); final List<int?>? arg_useCaseIds = (args[1] as List<Object?>?)?.cast<int?>(); assert(arg_useCaseIds != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null, expected non-null List<int?>.'); api.unbind(arg_identifier!, arg_useCaseIds!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll was null, expected non-null int.'); api.unbindAll(arg_identifier!); return <Object?>[]; }); } } } } abstract class TestCameraHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); int getCameraInfo(int identifier); int getCameraControl(int identifier); static void setup(TestCameraHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraHostApi.getCameraInfo', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraInfo was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraInfo was null, expected non-null int.'); final int output = api.getCameraInfo(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraHostApi.getCameraControl', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraControl was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraControl was null, expected non-null int.'); final int output = api.getCameraControl(arg_identifier!); return <Object?>[output]; }); } } } } class _TestSystemServicesHostApiCodec extends StandardMessageCodec { const _TestSystemServicesHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is CameraPermissionsErrorData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return CameraPermissionsErrorData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestSystemServicesHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestSystemServicesHostApiCodec(); Future<CameraPermissionsErrorData?> requestCameraPermissions( bool enableAudio); String getTempFilePath(String prefix, String suffix); static void setup(TestSystemServicesHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions was null.'); final List<Object?> args = (message as List<Object?>?)!; final bool? arg_enableAudio = (args[0] as bool?); assert(arg_enableAudio != null, 'Argument for dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions was null, expected non-null bool.'); final CameraPermissionsErrorData? output = await api.requestCameraPermissions(arg_enableAudio!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_prefix = (args[0] as String?); assert(arg_prefix != null, 'Argument for dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath was null, expected non-null String.'); final String? arg_suffix = (args[1] as String?); assert(arg_suffix != null, 'Argument for dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath was null, expected non-null String.'); final String output = api.getTempFilePath(arg_prefix!, arg_suffix!); return <Object?>[output]; }); } } } } abstract class TestDeviceOrientationManagerHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void startListeningForDeviceOrientationChange( bool isFrontFacing, int sensorOrientation); void stopListeningForDeviceOrientationChange(); int getDefaultDisplayRotation(); static void setup(TestDeviceOrientationManagerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange was null.'); final List<Object?> args = (message as List<Object?>?)!; final bool? arg_isFrontFacing = (args[0] as bool?); assert(arg_isFrontFacing != null, 'Argument for dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange was null, expected non-null bool.'); final int? arg_sensorOrientation = (args[1] as int?); assert(arg_sensorOrientation != null, 'Argument for dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange was null, expected non-null int.'); api.startListeningForDeviceOrientationChange( arg_isFrontFacing!, arg_sensorOrientation!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.stopListeningForDeviceOrientationChange', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message api.stopListeningForDeviceOrientationChange(); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.getDefaultDisplayRotation', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message final int output = api.getDefaultDisplayRotation(); return <Object?>[output]; }); } } } } class _TestPreviewHostApiCodec extends StandardMessageCodec { const _TestPreviewHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is ResolutionInfo) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return ResolutionInfo.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestPreviewHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestPreviewHostApiCodec(); void create(int identifier, int? rotation, int? resolutionSelectorId); int setSurfaceProvider(int identifier); void releaseFlutterSurfaceTexture(); ResolutionInfo getResolutionInfo(int identifier); void setTargetRotation(int identifier, int rotation); static void setup(TestPreviewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PreviewHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.create was null, expected non-null int.'); final int? arg_rotation = (args[1] as int?); final int? arg_resolutionSelectorId = (args[2] as int?); api.create(arg_identifier!, arg_rotation, arg_resolutionSelectorId); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider was null, expected non-null int.'); final int output = api.setSurfaceProvider(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PreviewHostApi.releaseFlutterSurfaceTexture', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message api.releaseFlutterSurfaceTexture(); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PreviewHostApi.getResolutionInfo', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.getResolutionInfo was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.getResolutionInfo was null, expected non-null int.'); final ResolutionInfo output = api.getResolutionInfo(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PreviewHostApi.setTargetRotation', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.setTargetRotation was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.setTargetRotation was null, expected non-null int.'); final int? arg_rotation = (args[1] as int?); assert(arg_rotation != null, 'Argument for dev.flutter.pigeon.PreviewHostApi.setTargetRotation was null, expected non-null int.'); api.setTargetRotation(arg_identifier!, arg_rotation!); return <Object?>[]; }); } } } } abstract class TestVideoCaptureHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); int withOutput(int videoOutputId); int getOutput(int identifier); void setTargetRotation(int identifier, int rotation); static void setup(TestVideoCaptureHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.VideoCaptureHostApi.withOutput', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.withOutput was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_videoOutputId = (args[0] as int?); assert(arg_videoOutputId != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.withOutput was null, expected non-null int.'); final int output = api.withOutput(arg_videoOutputId!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.VideoCaptureHostApi.getOutput', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.getOutput was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.getOutput was null, expected non-null int.'); final int output = api.getOutput(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation was null, expected non-null int.'); final int? arg_rotation = (args[1] as int?); assert(arg_rotation != null, 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation was null, expected non-null int.'); api.setTargetRotation(arg_identifier!, arg_rotation!); return <Object?>[]; }); } } } } abstract class TestRecorderHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create( int identifier, int? aspectRatio, int? bitRate, int? qualitySelectorId); int getAspectRatio(int identifier); int getTargetVideoEncodingBitRate(int identifier); int prepareRecording(int identifier, String path); static void setup(TestRecorderHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecorderHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.create was null, expected non-null int.'); final int? arg_aspectRatio = (args[1] as int?); final int? arg_bitRate = (args[2] as int?); final int? arg_qualitySelectorId = (args[3] as int?); api.create(arg_identifier!, arg_aspectRatio, arg_bitRate, arg_qualitySelectorId); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecorderHostApi.getAspectRatio', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.getAspectRatio was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.getAspectRatio was null, expected non-null int.'); final int output = api.getAspectRatio(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate was null, expected non-null int.'); final int output = api.getTargetVideoEncodingBitRate(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecorderHostApi.prepareRecording', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.prepareRecording was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.prepareRecording was null, expected non-null int.'); final String? arg_path = (args[1] as String?); assert(arg_path != null, 'Argument for dev.flutter.pigeon.RecorderHostApi.prepareRecording was null, expected non-null String.'); final int output = api.prepareRecording(arg_identifier!, arg_path!); return <Object?>[output]; }); } } } } abstract class TestPendingRecordingHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); int start(int identifier); static void setup(TestPendingRecordingHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PendingRecordingHostApi.start', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PendingRecordingHostApi.start was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.PendingRecordingHostApi.start was null, expected non-null int.'); final int output = api.start(arg_identifier!); return <Object?>[output]; }); } } } } abstract class TestRecordingHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void close(int identifier); void pause(int identifier); void resume(int identifier); void stop(int identifier); static void setup(TestRecordingHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecordingHostApi.close', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.close was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.close was null, expected non-null int.'); api.close(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecordingHostApi.pause', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.pause was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.pause was null, expected non-null int.'); api.pause(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecordingHostApi.resume', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.resume was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.resume was null, expected non-null int.'); api.resume(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.RecordingHostApi.stop', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.stop was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.RecordingHostApi.stop was null, expected non-null int.'); api.stop(arg_identifier!); return <Object?>[]; }); } } } } abstract class TestImageCaptureHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, int? targetRotation, int? flashMode, int? resolutionSelectorId); void setFlashMode(int identifier, int flashMode); Future<String> takePicture(int identifier); void setTargetRotation(int identifier, int rotation); static void setup(TestImageCaptureHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageCaptureHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.create was null, expected non-null int.'); final int? arg_targetRotation = (args[1] as int?); final int? arg_flashMode = (args[2] as int?); final int? arg_resolutionSelectorId = (args[3] as int?); api.create(arg_identifier!, arg_targetRotation, arg_flashMode, arg_resolutionSelectorId); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode was null, expected non-null int.'); final int? arg_flashMode = (args[1] as int?); assert(arg_flashMode != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode was null, expected non-null int.'); api.setFlashMode(arg_identifier!, arg_flashMode!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageCaptureHostApi.takePicture', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.takePicture was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.takePicture was null, expected non-null int.'); final String output = await api.takePicture(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation was null, expected non-null int.'); final int? arg_rotation = (args[1] as int?); assert(arg_rotation != null, 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation was null, expected non-null int.'); api.setTargetRotation(arg_identifier!, arg_rotation!); return <Object?>[]; }); } } } } class _TestResolutionStrategyHostApiCodec extends StandardMessageCodec { const _TestResolutionStrategyHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is ResolutionInfo) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return ResolutionInfo.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestResolutionStrategyHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestResolutionStrategyHostApiCodec(); void create(int identifier, ResolutionInfo? boundSize, int? fallbackRule); static void setup(TestResolutionStrategyHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ResolutionStrategyHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ResolutionStrategyHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ResolutionStrategyHostApi.create was null, expected non-null int.'); final ResolutionInfo? arg_boundSize = (args[1] as ResolutionInfo?); final int? arg_fallbackRule = (args[2] as int?); api.create(arg_identifier!, arg_boundSize, arg_fallbackRule); return <Object?>[]; }); } } } } abstract class TestResolutionSelectorHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, int? resolutionStrategyIdentifier, int? aspectRatioStrategyIdentifier); static void setup(TestResolutionSelectorHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ResolutionSelectorHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ResolutionSelectorHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ResolutionSelectorHostApi.create was null, expected non-null int.'); final int? arg_resolutionStrategyIdentifier = (args[1] as int?); final int? arg_aspectRatioStrategyIdentifier = (args[2] as int?); api.create(arg_identifier!, arg_resolutionStrategyIdentifier, arg_aspectRatioStrategyIdentifier); return <Object?>[]; }); } } } } abstract class TestAspectRatioStrategyHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, int preferredAspectRatio, int fallbackRule); static void setup(TestAspectRatioStrategyHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.AspectRatioStrategyHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null, expected non-null int.'); final int? arg_preferredAspectRatio = (args[1] as int?); assert(arg_preferredAspectRatio != null, 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null, expected non-null int.'); final int? arg_fallbackRule = (args[2] as int?); assert(arg_fallbackRule != null, 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null, expected non-null int.'); api.create( arg_identifier!, arg_preferredAspectRatio!, arg_fallbackRule!); return <Object?>[]; }); } } } } abstract class TestImageAnalysisHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, int? targetRotation, int? resolutionSelectorId); void setAnalyzer(int identifier, int analyzerIdentifier); void clearAnalyzer(int identifier); void setTargetRotation(int identifier, int rotation); static void setup(TestImageAnalysisHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageAnalysisHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.create was null, expected non-null int.'); final int? arg_targetRotation = (args[1] as int?); final int? arg_resolutionSelectorId = (args[2] as int?); api.create( arg_identifier!, arg_targetRotation, arg_resolutionSelectorId); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer was null, expected non-null int.'); final int? arg_analyzerIdentifier = (args[1] as int?); assert(arg_analyzerIdentifier != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer was null, expected non-null int.'); api.setAnalyzer(arg_identifier!, arg_analyzerIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer was null, expected non-null int.'); api.clearAnalyzer(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation was null, expected non-null int.'); final int? arg_rotation = (args[1] as int?); assert(arg_rotation != null, 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation was null, expected non-null int.'); api.setTargetRotation(arg_identifier!, arg_rotation!); return <Object?>[]; }); } } } } abstract class TestAnalyzerHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestAnalyzerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.AnalyzerHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.AnalyzerHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.AnalyzerHostApi.create was null, expected non-null int.'); api.create(arg_identifier!); return <Object?>[]; }); } } } } abstract class TestObserverHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestObserverHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ObserverHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ObserverHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ObserverHostApi.create was null, expected non-null int.'); api.create(arg_identifier!); return <Object?>[]; }); } } } } class _TestLiveDataHostApiCodec extends StandardMessageCodec { const _TestLiveDataHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is LiveDataSupportedTypeData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return LiveDataSupportedTypeData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestLiveDataHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestLiveDataHostApiCodec(); void observe(int identifier, int observerIdentifier); void removeObservers(int identifier); int? getValue(int identifier, LiveDataSupportedTypeData type); static void setup(TestLiveDataHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.LiveDataHostApi.observe', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.observe was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.observe was null, expected non-null int.'); final int? arg_observerIdentifier = (args[1] as int?); assert(arg_observerIdentifier != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.observe was null, expected non-null int.'); api.observe(arg_identifier!, arg_observerIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.LiveDataHostApi.removeObservers', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.removeObservers was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.removeObservers was null, expected non-null int.'); api.removeObservers(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.LiveDataHostApi.getValue', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.getValue was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.getValue was null, expected non-null int.'); final LiveDataSupportedTypeData? arg_type = (args[1] as LiveDataSupportedTypeData?); assert(arg_type != null, 'Argument for dev.flutter.pigeon.LiveDataHostApi.getValue was null, expected non-null LiveDataSupportedTypeData.'); final int? output = api.getValue(arg_identifier!, arg_type!); return <Object?>[output]; }); } } } } abstract class TestImageProxyHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); List<int?> getPlanes(int identifier); void close(int identifier); static void setup(TestImageProxyHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageProxyHostApi.getPlanes', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageProxyHostApi.getPlanes was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageProxyHostApi.getPlanes was null, expected non-null int.'); final List<int?> output = api.getPlanes(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImageProxyHostApi.close', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.ImageProxyHostApi.close was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.ImageProxyHostApi.close was null, expected non-null int.'); api.close(arg_identifier!); return <Object?>[]; }); } } } } class _TestQualitySelectorHostApiCodec extends StandardMessageCodec { const _TestQualitySelectorHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is ResolutionInfo) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is VideoQualityData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return ResolutionInfo.decode(readValue(buffer)!); case 129: return VideoQualityData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestQualitySelectorHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestQualitySelectorHostApiCodec(); void create(int identifier, List<VideoQualityData?> videoQualityDataList, int? fallbackStrategyId); ResolutionInfo getResolution(int cameraInfoId, VideoQuality quality); static void setup(TestQualitySelectorHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.QualitySelectorHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.create was null, expected non-null int.'); final List<VideoQualityData?>? arg_videoQualityDataList = (args[1] as List<Object?>?)?.cast<VideoQualityData?>(); assert(arg_videoQualityDataList != null, 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.create was null, expected non-null List<VideoQualityData?>.'); final int? arg_fallbackStrategyId = (args[2] as int?); api.create(arg_identifier!, arg_videoQualityDataList!, arg_fallbackStrategyId); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.QualitySelectorHostApi.getResolution', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.getResolution was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_cameraInfoId = (args[0] as int?); assert(arg_cameraInfoId != null, 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.getResolution was null, expected non-null int.'); final VideoQuality? arg_quality = args[1] == null ? null : VideoQuality.values[args[1] as int]; assert(arg_quality != null, 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.getResolution was null, expected non-null VideoQuality.'); final ResolutionInfo output = api.getResolution(arg_cameraInfoId!, arg_quality!); return <Object?>[output]; }); } } } } abstract class TestFallbackStrategyHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, VideoQuality quality, VideoResolutionFallbackRule fallbackRule); static void setup(TestFallbackStrategyHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FallbackStrategyHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null, expected non-null int.'); final VideoQuality? arg_quality = args[1] == null ? null : VideoQuality.values[args[1] as int]; assert(arg_quality != null, 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null, expected non-null VideoQuality.'); final VideoResolutionFallbackRule? arg_fallbackRule = args[2] == null ? null : VideoResolutionFallbackRule.values[args[2] as int]; assert(arg_fallbackRule != null, 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null, expected non-null VideoResolutionFallbackRule.'); api.create(arg_identifier!, arg_quality!, arg_fallbackRule!); return <Object?>[]; }); } } } } abstract class TestCameraControlHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> enableTorch(int identifier, bool torch); Future<void> setZoomRatio(int identifier, double ratio); Future<int?> startFocusAndMetering(int identifier, int focusMeteringActionId); Future<void> cancelFocusAndMetering(int identifier); Future<int?> setExposureCompensationIndex(int identifier, int index); static void setup(TestCameraControlHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraControlHostApi.enableTorch', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.enableTorch was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.enableTorch was null, expected non-null int.'); final bool? arg_torch = (args[1] as bool?); assert(arg_torch != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.enableTorch was null, expected non-null bool.'); await api.enableTorch(arg_identifier!, arg_torch!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraControlHostApi.setZoomRatio', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.setZoomRatio was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.setZoomRatio was null, expected non-null int.'); final double? arg_ratio = (args[1] as double?); assert(arg_ratio != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.setZoomRatio was null, expected non-null double.'); await api.setZoomRatio(arg_identifier!, arg_ratio!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering was null, expected non-null int.'); final int? arg_focusMeteringActionId = (args[1] as int?); assert(arg_focusMeteringActionId != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering was null, expected non-null int.'); final int? output = await api.startFocusAndMetering( arg_identifier!, arg_focusMeteringActionId!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering was null, expected non-null int.'); await api.cancelFocusAndMetering(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex was null, expected non-null int.'); final int? arg_index = (args[1] as int?); assert(arg_index != null, 'Argument for dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex was null, expected non-null int.'); final int? output = await api.setExposureCompensationIndex( arg_identifier!, arg_index!); return <Object?>[output]; }); } } } } class _TestFocusMeteringActionHostApiCodec extends StandardMessageCodec { const _TestFocusMeteringActionHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MeteringPointInfo) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MeteringPointInfo.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestFocusMeteringActionHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestFocusMeteringActionHostApiCodec(); void create(int identifier, List<MeteringPointInfo?> meteringPointInfos, bool? disableAutoCancel); static void setup(TestFocusMeteringActionHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FocusMeteringActionHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.FocusMeteringActionHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.FocusMeteringActionHostApi.create was null, expected non-null int.'); final List<MeteringPointInfo?>? arg_meteringPointInfos = (args[1] as List<Object?>?)?.cast<MeteringPointInfo?>(); assert(arg_meteringPointInfos != null, 'Argument for dev.flutter.pigeon.FocusMeteringActionHostApi.create was null, expected non-null List<MeteringPointInfo?>.'); final bool? arg_disableAutoCancel = (args[2] as bool?); api.create( arg_identifier!, arg_meteringPointInfos!, arg_disableAutoCancel); return <Object?>[]; }); } } } } abstract class TestFocusMeteringResultHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); bool isFocusSuccessful(int identifier); static void setup(TestFocusMeteringResultHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful was null, expected non-null int.'); final bool output = api.isFocusSuccessful(arg_identifier!); return <Object?>[output]; }); } } } } abstract class TestMeteringPointHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create( int identifier, double x, double y, double? size, int cameraInfoId); double getDefaultPointSize(); static void setup(TestMeteringPointHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.MeteringPointHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null int.'); final double? arg_x = (args[1] as double?); assert(arg_x != null, 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null double.'); final double? arg_y = (args[2] as double?); assert(arg_y != null, 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null double.'); final double? arg_size = (args[3] as double?); final int? arg_cameraInfoId = (args[4] as int?); assert(arg_cameraInfoId != null, 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null int.'); api.create( arg_identifier!, arg_x!, arg_y!, arg_size, arg_cameraInfoId!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.MeteringPointHostApi.getDefaultPointSize', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message final double output = api.getDefaultPointSize(); return <Object?>[output]; }); } } } } class _TestCaptureRequestOptionsHostApiCodec extends StandardMessageCodec { const _TestCaptureRequestOptionsHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is CameraPermissionsErrorData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is CameraStateTypeData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is ExposureCompensationRange) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is LiveDataSupportedTypeData) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is MeteringPointInfo) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is ResolutionInfo) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is VideoQualityData) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return CameraPermissionsErrorData.decode(readValue(buffer)!); case 129: return CameraStateTypeData.decode(readValue(buffer)!); case 130: return ExposureCompensationRange.decode(readValue(buffer)!); case 131: return LiveDataSupportedTypeData.decode(readValue(buffer)!); case 132: return MeteringPointInfo.decode(readValue(buffer)!); case 133: return ResolutionInfo.decode(readValue(buffer)!); case 134: return VideoQualityData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestCaptureRequestOptionsHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestCaptureRequestOptionsHostApiCodec(); void create(int identifier, Map<int?, Object?> options); static void setup(TestCaptureRequestOptionsHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.CaptureRequestOptionsHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.CaptureRequestOptionsHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.CaptureRequestOptionsHostApi.create was null, expected non-null int.'); final Map<int?, Object?>? arg_options = (args[1] as Map<Object?, Object?>?)?.cast<int?, Object?>(); assert(arg_options != null, 'Argument for dev.flutter.pigeon.CaptureRequestOptionsHostApi.create was null, expected non-null Map<int?, Object?>.'); api.create(arg_identifier!, arg_options!); return <Object?>[]; }); } } } } abstract class TestCamera2CameraControlHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier, int cameraControlIdentifier); Future<void> addCaptureRequestOptions( int identifier, int captureRequestOptionsIdentifier); static void setup(TestCamera2CameraControlHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.Camera2CameraControlHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.create was null, expected non-null int.'); final int? arg_cameraControlIdentifier = (args[1] as int?); assert(arg_cameraControlIdentifier != null, 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.create was null, expected non-null int.'); api.create(arg_identifier!, arg_cameraControlIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions was null, expected non-null int.'); final int? arg_captureRequestOptionsIdentifier = (args[1] as int?); assert(arg_captureRequestOptionsIdentifier != null, 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions was null, expected non-null int.'); await api.addCaptureRequestOptions( arg_identifier!, arg_captureRequestOptionsIdentifier!); return <Object?>[]; }); } } } }
packages/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart", "repo_id": "packages", "token_count": 43215 }
926
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// The format in which images should be returned from the camera. enum ImageFileFormat { /// The JPEG format. jpeg, /// The HEIF format. /// /// HEIF is a file format name that refers to High Efficiency Image Format /// (HEIF). For iOS, this is only supported on versions 11+. heif, }
packages/packages/camera/camera_platform_interface/lib/src/types/image_file_format.dart/0
{ "file_path": "packages/packages/camera/camera_platform_interface/lib/src/types/image_file_format.dart", "repo_id": "packages", "token_count": 127 }
927
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/dynamic_layouts/example/android/gradle.properties/0
{ "file_path": "packages/packages/dynamic_layouts/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
928
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:dynamic_layouts/dynamic_layouts.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('DynamicGridView', () { testWidgets( 'DynamicGridView works when using DynamicSliverGridDelegateWithFixedCrossAxisCount', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 100); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView( gridDelegate: const DynamicSliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, ), children: List<Widget>.generate( 50, (int index) => SizedBox( height: index % 2 * 20 + 20, child: Text('Index $index'), ), ), ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 0')), Offset.zero); expect(find.text('Index 1'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 1')), const Offset(100.0, 0.0)); expect(find.text('Index 2'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 2')), const Offset(200.0, 0.0)); expect(find.text('Index 3'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 3')), const Offset(300.0, 0.0)); expect(find.text('Index 4'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 4')), const Offset(0.0, 20.0)); expect(find.text('Index 14'), findsNothing); expect(find.text('Index 47'), findsNothing); expect(find.text('Index 48'), findsNothing); expect(find.text('Index 49'), findsNothing); }); testWidgets( 'DynamicGridView works when using DynamicSliverGridDelegateWithMaxCrossAxisExtent', (WidgetTester tester) async { tester.view.physicalSize = const Size(440, 100); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView( gridDelegate: const DynamicSliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 100, ), children: List<Widget>.generate( 50, (int index) => SizedBox( height: index % 2 * 20 + 20, child: Text('Index $index'), ), ), ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 0')), Offset.zero); expect(find.text('Index 1'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 1')), const Offset(88.0, 0.0)); expect(find.text('Index 2'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 2')), const Offset(176.0, 0.0)); expect(find.text('Index 3'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 3')), const Offset(264.0, 0.0)); expect(find.text('Index 4'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 4')), const Offset(352.0, 0.0)); expect(find.text('Index 47'), findsNothing); expect(find.text('Index 48'), findsNothing); expect(find.text('Index 49'), findsNothing); }); }); group('DynamicGridView.staggered', () { testWidgets('DynamicGridView.staggered works with simple layout', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 100); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView.staggered( crossAxisCount: 4, children: List<Widget>.generate( 50, (int index) => SizedBox( height: index % 2 * 50 + 20, child: Text('Index $index'), ), ), ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 0')), Offset.zero); expect(find.text('Index 1'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 1')), const Offset(100.0, 0.0)); expect(find.text('Index 2'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 2')), const Offset(200.0, 0.0)); expect(find.text('Index 3'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 3')), const Offset(300.0, 0.0)); expect(find.text('Index 4'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 4')), const Offset(0.0, 20.0)); expect(find.text('Index 5'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 5')), const Offset(200.0, 20.0), ); expect(find.text('Index 6'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 6')), const Offset(0.0, 40.0)); expect(find.text('Index 7'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 7')), const Offset(0.0, 60.0)); expect(find.text('Index 12'), findsNothing); // 100 - 120 expect(find.text('Index 47'), findsNothing); expect(find.text('Index 48'), findsNothing); expect(find.text('Index 49'), findsNothing); }); testWidgets('DynamicGridView.staggered works with a horizontal grid', (WidgetTester tester) async { tester.view.physicalSize = const Size(100, 500); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView.staggered( crossAxisCount: 4, scrollDirection: Axis.horizontal, children: List<Widget>.generate( 50, (int index) => SizedBox( width: index % 3 * 50 + 20, child: Text('Index $index'), ), ), ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 0')), Offset.zero); expect(find.text('Index 1'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 1')), const Offset(0.0, 125.0)); expect(find.text('Index 2'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 2')), const Offset(0.0, 250.0)); expect(find.text('Index 3'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 3')), const Offset(0.0, 375.0)); expect(find.text('Index 4'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 4')), const Offset(20.0, 0.0)); expect(find.text('Index 5'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 5')), const Offset(20.0, 375.0), ); expect(find.text('Index 6'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 6')), const Offset(70.0, 125.0), ); expect(find.text('Index 7'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 7')), const Offset(90.0, 0.0), ); expect(find.text('Index 47'), findsNothing); expect(find.text('Index 48'), findsNothing); expect(find.text('Index 49'), findsNothing); }); testWidgets('DynamicGridView.staggered works with a reversed grid', (WidgetTester tester) async { tester.view.physicalSize = const Size(600, 200); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView.staggered( crossAxisCount: 4, reverse: true, children: List<Widget>.generate( 50, (int index) => SizedBox( height: index % 3 * 50 + 20, child: Text('Index $index'), ), ), ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 0')), const Offset(0.0, 200.0), ); expect(find.text('Index 1'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 1')), const Offset(150.0, 200.0), ); expect(find.text('Index 2'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 2')), const Offset(300.0, 200.0), ); expect(find.text('Index 3'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 3')), const Offset(450.0, 200.0), ); expect(find.text('Index 4'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 4')), const Offset(0.0, 180.0), ); expect(find.text('Index 5'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 5')), const Offset(450.0, 180.0), ); expect(find.text('Index 6'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 6')), const Offset(150.0, 130.0), ); expect(find.text('Index 7'), findsOneWidget); expect( tester.getBottomLeft(find.text('Index 7')), const Offset(0.0, 110.0), ); expect(find.text('Index 47'), findsNothing); expect(find.text('Index 48'), findsNothing); expect(find.text('Index 49'), findsNothing); }); testWidgets('DynamicGridView.staggered deletes children appropriately', (WidgetTester tester) async { tester.view.physicalSize = const Size(600, 1000); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); final List<Widget> children = List<Widget>.generate( 50, (int index) => SizedBox( height: index % 3 * 50 + 20, child: Text('Index $index'), ), ); late StateSetter stateSetter; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { stateSetter = setState; return DynamicGridView.staggered( maxCrossAxisExtent: 150, children: <Widget>[...children], ); }), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 0')), Offset.zero); expect(find.text('Index 7'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 7')), const Offset(0.0, 90.0)); expect(find.text('Index 8'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 8')), const Offset(150.0, 90.0), ); expect(find.text('Index 27'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 27')), const Offset(300.0, 420.0), ); expect(find.text('Index 28'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 28')), const Offset(300.0, 440.0), ); expect(find.text('Index 32'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 32')), const Offset(300.0, 510.0), ); expect(find.text('Index 33'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 33')), const Offset(150.0, 540.0), ); stateSetter(() { children.removeAt(0); }); await tester.pump(); expect(find.text('Index 0'), findsNothing); expect( tester.getTopLeft(find.text('Index 8')), const Offset(0.0, 90.0), ); expect( tester.getTopLeft(find.text('Index 28')), const Offset(150.0, 440.0), ); expect( tester.getTopLeft(find.text('Index 33')), const Offset(0.0, 540.0), ); }); }); group('DynamicGridView.builder', () { testWidgets('DynamicGridView.builder works with a staggered layout', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 100); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView.builder( gridDelegate: const DynamicSliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, ), itemBuilder: (BuildContext context, int index) => SizedBox( height: index % 2 * 50 + 20, child: Text('Index $index'), ), itemCount: 50, ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 0')), Offset.zero); expect(find.text('Index 1'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 1')), const Offset(100.0, 0.0)); expect(find.text('Index 2'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 2')), const Offset(200.0, 0.0)); expect(find.text('Index 3'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 3')), const Offset(300.0, 0.0)); expect(find.text('Index 4'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 4')), const Offset(0.0, 20.0)); expect(find.text('Index 5'), findsOneWidget); expect( tester.getTopLeft(find.text('Index 5')), const Offset(200.0, 20.0), ); expect(find.text('Index 6'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 6')), const Offset(0.0, 40.0)); expect(find.text('Index 7'), findsOneWidget); expect(tester.getTopLeft(find.text('Index 7')), const Offset(0.0, 60.0)); expect(find.text('Index 12'), findsNothing); // 100 - 120 expect(find.text('Index 47'), findsNothing); expect(find.text('Index 48'), findsNothing); expect(find.text('Index 49'), findsNothing); }); testWidgets( 'DynamicGridView.builder works with an infinite grid using a staggered layout', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 100); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: DynamicGridView.builder( gridDelegate: const DynamicSliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, ), itemBuilder: (BuildContext context, int index) => SizedBox( height: index % 2 * 50 + 20, child: Text('Index $index'), ), ), ), ), ); expect(find.text('Index 0'), findsOneWidget); expect(find.text('Index 1'), findsOneWidget); expect(find.text('Index 2'), findsOneWidget); await tester.scrollUntilVisible(find.text('Index 500'), 500.0); await tester.pumpAndSettle(); expect(find.text('Index 501'), findsOneWidget); expect(find.text('Index 502'), findsOneWidget); }); }); }
packages/packages/dynamic_layouts/test/staggered_layout_test.dart/0
{ "file_path": "packages/packages/dynamic_layouts/test/staggered_layout_test.dart", "repo_id": "packages", "token_count": 7278 }
929
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Generated file. // // If you wish to remove Flutter's multidex support, delete this entire file. // // Modifications to this file should be done in a copy under a different name // as this file may be regenerated. package io.flutter.app; import android.app.Application; import android.content.Context; import androidx.annotation.CallSuper; import androidx.multidex.MultiDex; /** Extension of {@link android.app.Application}, adding multidex support. */ public class FlutterMultiDexApplication extends Application { @Override @CallSuper protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
packages/packages/espresso/example/android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java/0
{ "file_path": "packages/packages/espresso/example/android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java", "repo_id": "packages", "token_count": 230 }
930
# Copyright 2013 The Flutter Authors # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd name: extension_google_sign_in_as_googleapis_auth description: A bridge package between google_sign_in and googleapis_auth, to create Authenticated Clients from google_sign_in user credentials. repository: https://github.com/flutter/packages/tree/main/packages/extension_google_sign_in_as_googleapis_auth issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+extension_google_sign_in_as_googleapis_auth%22 version: 2.0.12 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter google_sign_in: ">=5.0.0 <7.0.0" googleapis_auth: ^1.1.0 http: ">=0.13.0 <2.0.0" meta: ^1.3.0 dev_dependencies: flutter_test: sdk: flutter topics: - authentication - google-sign-in false_secrets: - example/android/app/google-services.json - example/ios/Runner/GoogleService-Info.plist
packages/packages/extension_google_sign_in_as_googleapis_auth/pubspec.yaml/0
{ "file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/pubspec.yaml", "repo_id": "packages", "token_count": 410 }
931
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v9.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon package dev.flutter.packages.file_selector_android; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class GeneratedFileSelectorApi { /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { /** The error code. */ public final String code; /** The error details. Must be a datatype supported by the api codec. */ public final Object details; public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { super(message); this.code = code; this.details = details; } } @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { ArrayList<Object> errorList = new ArrayList<Object>(3); if (exception instanceof FlutterError) { FlutterError error = (FlutterError) exception; errorList.add(error.code); errorList.add(error.getMessage()); errorList.add(error.details); } else { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); } return errorList; } /** Generated class from Pigeon that represents data sent in messages. */ public static final class FileResponse { private @NonNull String path; public @NonNull String getPath() { return path; } public void setPath(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"path\" is null."); } this.path = setterArg; } private @Nullable String mimeType; public @Nullable String getMimeType() { return mimeType; } public void setMimeType(@Nullable String setterArg) { this.mimeType = setterArg; } private @Nullable String name; public @Nullable String getName() { return name; } public void setName(@Nullable String setterArg) { this.name = setterArg; } private @NonNull Long size; public @NonNull Long getSize() { return size; } public void setSize(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"size\" is null."); } this.size = setterArg; } private @NonNull byte[] bytes; public @NonNull byte[] getBytes() { return bytes; } public void setBytes(@NonNull byte[] setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"bytes\" is null."); } this.bytes = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ FileResponse() {} public static final class Builder { private @Nullable String path; public @NonNull Builder setPath(@NonNull String setterArg) { this.path = setterArg; return this; } private @Nullable String mimeType; public @NonNull Builder setMimeType(@Nullable String setterArg) { this.mimeType = setterArg; return this; } private @Nullable String name; public @NonNull Builder setName(@Nullable String setterArg) { this.name = setterArg; return this; } private @Nullable Long size; public @NonNull Builder setSize(@NonNull Long setterArg) { this.size = setterArg; return this; } private @Nullable byte[] bytes; public @NonNull Builder setBytes(@NonNull byte[] setterArg) { this.bytes = setterArg; return this; } public @NonNull FileResponse build() { FileResponse pigeonReturn = new FileResponse(); pigeonReturn.setPath(path); pigeonReturn.setMimeType(mimeType); pigeonReturn.setName(name); pigeonReturn.setSize(size); pigeonReturn.setBytes(bytes); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(5); toListResult.add(path); toListResult.add(mimeType); toListResult.add(name); toListResult.add(size); toListResult.add(bytes); return toListResult; } static @NonNull FileResponse fromList(@NonNull ArrayList<Object> list) { FileResponse pigeonResult = new FileResponse(); Object path = list.get(0); pigeonResult.setPath((String) path); Object mimeType = list.get(1); pigeonResult.setMimeType((String) mimeType); Object name = list.get(2); pigeonResult.setName((String) name); Object size = list.get(3); pigeonResult.setSize( (size == null) ? null : ((size instanceof Integer) ? (Integer) size : (Long) size)); Object bytes = list.get(4); pigeonResult.setBytes((byte[]) bytes); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class FileTypes { private @NonNull List<String> mimeTypes; public @NonNull List<String> getMimeTypes() { return mimeTypes; } public void setMimeTypes(@NonNull List<String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"mimeTypes\" is null."); } this.mimeTypes = setterArg; } private @NonNull List<String> extensions; public @NonNull List<String> getExtensions() { return extensions; } public void setExtensions(@NonNull List<String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"extensions\" is null."); } this.extensions = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ FileTypes() {} public static final class Builder { private @Nullable List<String> mimeTypes; public @NonNull Builder setMimeTypes(@NonNull List<String> setterArg) { this.mimeTypes = setterArg; return this; } private @Nullable List<String> extensions; public @NonNull Builder setExtensions(@NonNull List<String> setterArg) { this.extensions = setterArg; return this; } public @NonNull FileTypes build() { FileTypes pigeonReturn = new FileTypes(); pigeonReturn.setMimeTypes(mimeTypes); pigeonReturn.setExtensions(extensions); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(mimeTypes); toListResult.add(extensions); return toListResult; } static @NonNull FileTypes fromList(@NonNull ArrayList<Object> list) { FileTypes pigeonResult = new FileTypes(); Object mimeTypes = list.get(0); pigeonResult.setMimeTypes((List<String>) mimeTypes); Object extensions = list.get(1); pigeonResult.setExtensions((List<String>) extensions); return pigeonResult; } } public interface Result<T> { @SuppressWarnings("UnknownNullness") void success(T result); void error(@NonNull Throwable error); } private static class FileSelectorApiCodec extends StandardMessageCodec { public static final FileSelectorApiCodec INSTANCE = new FileSelectorApiCodec(); private FileSelectorApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return FileResponse.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return FileTypes.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof FileResponse) { stream.write(128); writeValue(stream, ((FileResponse) value).toList()); } else if (value instanceof FileTypes) { stream.write(129); writeValue(stream, ((FileTypes) value).toList()); } else { super.writeValue(stream, value); } } } /** * An API to call to native code to select files or directories. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FileSelectorApi { /** * Opens a file dialog for loading files and returns a file path. * * <p>Returns `null` if user cancels the operation. */ void openFile( @Nullable String initialDirectory, @NonNull FileTypes allowedTypes, @NonNull Result<FileResponse> result); /** * Opens a file dialog for loading files and returns a list of file responses chosen by the * user. */ void openFiles( @Nullable String initialDirectory, @NonNull FileTypes allowedTypes, @NonNull Result<List<FileResponse>> result); /** * Opens a file dialog for loading directories and returns a directory path. * * <p>Returns `null` if user cancels the operation. */ void getDirectoryPath(@Nullable String initialDirectory, @NonNull Result<String> result); /** The codec used by FileSelectorApi. */ static @NonNull MessageCodec<Object> getCodec() { return FileSelectorApiCodec.INSTANCE; } /** * Sets up an instance of `FileSelectorApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable FileSelectorApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.FileSelectorApi.openFile", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String initialDirectoryArg = (String) args.get(0); FileTypes allowedTypesArg = (FileTypes) args.get(1); Result<FileResponse> resultCallback = new Result<FileResponse>() { public void success(FileResponse result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.openFile(initialDirectoryArg, allowedTypesArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.FileSelectorApi.openFiles", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String initialDirectoryArg = (String) args.get(0); FileTypes allowedTypesArg = (FileTypes) args.get(1); Result<List<FileResponse>> resultCallback = new Result<List<FileResponse>>() { public void success(List<FileResponse> result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.openFiles(initialDirectoryArg, allowedTypesArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.FileSelectorApi.getDirectoryPath", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String initialDirectoryArg = (String) args.get(0); Result<String> resultCallback = new Result<String>() { public void success(String result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.getDirectoryPath(initialDirectoryArg, resultCallback); }); } else { channel.setMessageHandler(null); } } } } }
packages/packages/file_selector/file_selector_android/android/src/main/java/dev/flutter/packages/file_selector_android/GeneratedFileSelectorApi.java/0
{ "file_path": "packages/packages/file_selector/file_selector_android/android/src/main/java/dev/flutter/packages/file_selector_android/GeneratedFileSelectorApi.java", "repo_id": "packages", "token_count": 5861 }
932
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v13.0.0), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } class FileSelectorConfig { FileSelectorConfig({ required this.utis, required this.allowMultiSelection, }); List<String?> utis; bool allowMultiSelection; Object encode() { return <Object?>[ utis, allowMultiSelection, ]; } static FileSelectorConfig decode(Object result) { result as List<Object?>; return FileSelectorConfig( utis: (result[0] as List<Object?>?)!.cast<String?>(), allowMultiSelection: result[1]! as bool, ); } } class _FileSelectorApiCodec extends StandardMessageCodec { const _FileSelectorApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is FileSelectorConfig) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return FileSelectorConfig.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. FileSelectorApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _FileSelectorApiCodec(); Future<List<String?>> openFile(FileSelectorConfig arg_config) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_config]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)!.cast<String?>(); } } }
packages/packages/file_selector/file_selector_ios/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_ios/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 1267 }
933
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/material.dart'; /// Screen that allows the user to select one or more directories using `getDirectoryPaths`, /// then displays the selected directories in a dialog. class GetMultipleDirectoriesPage extends StatelessWidget { /// Default Constructor const GetMultipleDirectoriesPage({super.key}); Future<void> _getDirectoryPaths(BuildContext context) async { const String confirmButtonText = 'Choose'; final List<String> directoryPaths = await FileSelectorPlatform.instance.getDirectoryPaths( confirmButtonText: confirmButtonText, ); if (directoryPaths.isEmpty) { // Operation was canceled by the user. return; } if (context.mounted) { await showDialog<void>( context: context, builder: (BuildContext context) => TextDisplay(directoryPaths.join('\n')), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Select multiple directories'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.white, ), child: const Text( 'Press to ask user to choose multiple directories'), onPressed: () => _getDirectoryPaths(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog. class TextDisplay extends StatelessWidget { /// Creates a `TextDisplay`. const TextDisplay(this.directoriesPaths, {super.key}); /// The path selected in the dialog. final String directoriesPaths; @override Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directories'), content: Scrollbar( child: SingleChildScrollView( child: Text(directoriesPaths), ), ), actions: <Widget>[ TextButton( child: const Text('Close'), onPressed: () => Navigator.pop(context), ), ], ); } }
packages/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart", "repo_id": "packages", "token_count": 965 }
934
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_platform_interface/src/method_channel/method_channel_file_selector.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { // Store the initial instance before any tests change it. final FileSelectorPlatform initialInstance = FileSelectorPlatform.instance; group('FileSelectorPlatform', () { test('$MethodChannelFileSelector() is the default instance', () { expect(initialInstance, isInstanceOf<MethodChannelFileSelector>()); }); test('Can be extended', () { FileSelectorPlatform.instance = ExtendsFileSelectorPlatform(); }); }); group('getDirectoryPaths', () { test('Should throw unimplemented exception', () async { final FileSelectorPlatform fileSelector = ExtendsFileSelectorPlatform(); await expectLater(() async { return fileSelector.getDirectoryPaths(); }, throwsA(isA<UnimplementedError>())); }); }); test('getSaveLocation falls back to getSavePath by default', () async { final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation(); final FileSaveLocation? result = await fileSelector.getSaveLocation(); expect(result?.path, OldFileSelectorPlatformImplementation.savePath); expect(result?.activeFilter, null); }); } class ExtendsFileSelectorPlatform extends FileSelectorPlatform {} class OldFileSelectorPlatformImplementation extends FileSelectorPlatform { static const String savePath = '/a/path'; // Only implement the deprecated getSavePath. @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async { return savePath; } }
packages/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart", "repo_id": "packages", "token_count": 603 }
935
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart'; import 'package:flutter_adaptive_scaffold_example/adaptive_layout_demo.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { const Color navigationRailThemeBgColor = Colors.white; const IconThemeData selectedIconThemeData = IconThemeData( color: Colors.red, size: 32.0, ); const IconThemeData unSelectedIconThemeData = IconThemeData( color: Colors.black, size: 24.0, ); final Finder body = find.byKey(const Key('Body Small')); final Finder bottomNavigation = find.byKey( const Key('Bottom Navigation Small'), ); Future<void> updateScreen(double width, WidgetTester tester) async { await tester.binding.setSurfaceSize(Size(width, 800)); await tester.pumpWidget( MaterialApp( theme: ThemeData.light().copyWith( navigationRailTheme: const NavigationRailThemeData( backgroundColor: navigationRailThemeBgColor, selectedIconTheme: selectedIconThemeData, unselectedIconTheme: unSelectedIconThemeData, ), ), home: MediaQuery( data: MediaQueryData(size: Size(width, 800)), child: const example.MyHomePage(), ), ), ); await tester.pumpAndSettle(); } testWidgets( 'displays correct item of config based on screen width', (WidgetTester tester) async { await updateScreen(300, tester); expect(find.byKey(const Key('Body Small')), findsOneWidget); expect(find.byKey(const Key('Primary Navigation Medium')), findsNothing); expect(find.byKey(const Key('Bottom Navigation Small')), findsOneWidget); expect(find.byKey(const Key('Body Medium')), findsNothing); expect(find.byKey(const Key('Primary Navigation Large')), findsNothing); await updateScreen(700, tester); expect(find.byKey(const Key('Body')), findsNothing); expect(find.byKey(const Key('Bottom Navigation Small')), findsNothing); expect(find.byKey(const Key('Body Medium')), findsOneWidget); expect( find.byKey(const Key('Primary Navigation Medium')), findsOneWidget); expect(find.byKey(const Key('Primary Navigation Large')), findsNothing); }, ); testWidgets( 'adaptive layout bottom navigation displays with correct properties', (WidgetTester tester) async { await updateScreen(400, tester); final BuildContext context = tester.element(find.byType(MaterialApp)); // Bottom Navigation Bar final Finder findKey = find.byKey(const Key('Bottom Navigation Small')); final SlotLayoutConfig slotLayoutConfig = tester.firstWidget<SlotLayoutConfig>(findKey); final WidgetBuilder? widgetBuilder = slotLayoutConfig.builder; final Widget Function(BuildContext) widgetFunction = (widgetBuilder ?? () => Container()) as Widget Function(BuildContext); final Builder builderWidget = widgetFunction(context) as Builder; expect(builderWidget, isNotNull); }, ); testWidgets( 'adaptive layout navigation rail displays with correct properties', (WidgetTester tester) async { await updateScreen(620, tester); final BuildContext context = tester.element(find.byType(AdaptiveLayout)); final Finder findKey = find.byKey(const Key('Primary Navigation Medium')); final SlotLayoutConfig slotLayoutConfig = tester.firstWidget<SlotLayoutConfig>(findKey); final WidgetBuilder? widgetBuilder = slotLayoutConfig.builder; final Widget Function(BuildContext) widgetFunction = (widgetBuilder ?? () => Container()) as Widget Function(BuildContext); final SizedBox sizedBox = (((widgetFunction(context) as Builder).builder(context) as Padding) .child ?? () => const SizedBox()) as SizedBox; expect(sizedBox.width, 72); }, ); testWidgets( 'adaptive layout displays children in correct places', (WidgetTester tester) async { await updateScreen(400, tester); expect(tester.getBottomLeft(bottomNavigation), const Offset(0, 800)); expect(tester.getBottomRight(bottomNavigation), const Offset(400, 800)); expect(tester.getTopRight(body), const Offset(400, 0)); expect(tester.getTopLeft(body), Offset.zero); }, ); testWidgets( 'adaptive layout does not animate when animations off', (WidgetTester tester) async { final Finder bodyMedium = find.byKey(const Key('Body Medium')); await updateScreen(690, tester); expect(tester.getTopLeft(bodyMedium), const Offset(88, 0)); expect(tester.getBottomRight(bodyMedium), const Offset(690, 800)); }, ); testWidgets( 'when view in medium screen, navigation rail must be visible as per theme data values.', (WidgetTester tester) async { final Finder primaryNavigationMedium = find.byKey( const Key('Primary Navigation Medium'), ); await updateScreen(690, tester); expect(primaryNavigationMedium, findsOneWidget); final Finder navigationRailFinder = find.descendant( of: primaryNavigationMedium, matching: find.byType(NavigationRail), ); expect(navigationRailFinder, findsOneWidget); final NavigationRail navigationRailView = tester.firstWidget( navigationRailFinder, ); expect(navigationRailView, isNotNull); expect( navigationRailView.backgroundColor, navigationRailThemeBgColor, ); expect( navigationRailView.selectedIconTheme?.size, selectedIconThemeData.size, ); expect( navigationRailView.selectedIconTheme?.color, selectedIconThemeData.color, ); expect( navigationRailView.unselectedIconTheme?.size, unSelectedIconThemeData.size, ); expect( navigationRailView.unselectedIconTheme?.color, unSelectedIconThemeData.color, ); }, ); testWidgets( 'when view in large screen, navigation rail must be visible as per theme data values.', (WidgetTester tester) async { final Finder primaryNavigationLarge = find.byKey( const Key('Primary Navigation Large'), ); await updateScreen(860, tester); expect(primaryNavigationLarge, findsOneWidget); final Finder navigationRailFinder = find.descendant( of: primaryNavigationLarge, matching: find.byType(NavigationRail), ); expect(navigationRailFinder, findsOneWidget); final NavigationRail navigationRailView = tester.firstWidget( navigationRailFinder, ); expect(navigationRailView, isNotNull); expect( navigationRailView.backgroundColor, navigationRailThemeBgColor, ); expect( navigationRailView.selectedIconTheme?.size, selectedIconThemeData.size, ); expect( navigationRailView.selectedIconTheme?.color, selectedIconThemeData.color, ); expect( navigationRailView.unselectedIconTheme?.size, unSelectedIconThemeData.size, ); expect( navigationRailView.unselectedIconTheme?.color, unSelectedIconThemeData.color, ); }, ); }
packages/packages/flutter_adaptive_scaffold/example/test/adaptive_layout_demo_test.dart/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/test/adaptive_layout_demo_test.dart", "repo_id": "packages", "token_count": 2744 }
936
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_adaptive_scaffold/src/adaptive_layout.dart'; import 'package:flutter_adaptive_scaffold/src/breakpoints.dart'; import 'package:flutter_adaptive_scaffold/src/slot_layout.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( 'slot layout displays correct item of config based on screen width', (WidgetTester tester) async { MediaQuery slot(double width) { return MediaQuery( data: MediaQueryData.fromView(tester.view) .copyWith(size: Size(width, 800)), child: Directionality( textDirection: TextDirection.ltr, child: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( key: const Key('0'), builder: (_) => const SizedBox()), TestBreakpoint400(): SlotLayout.from( key: const Key('400'), builder: (_) => const SizedBox()), TestBreakpoint800(): SlotLayout.from( key: const Key('800'), builder: (_) => const SizedBox()), }, ), ), ); } await tester.pumpWidget(slot(300)); expect(find.byKey(const Key('0')), findsOneWidget); expect(find.byKey(const Key('400')), findsNothing); expect(find.byKey(const Key('800')), findsNothing); await tester.pumpWidget(slot(500)); expect(find.byKey(const Key('0')), findsNothing); expect(find.byKey(const Key('400')), findsOneWidget); expect(find.byKey(const Key('800')), findsNothing); await tester.pumpWidget(slot(1000)); expect(find.byKey(const Key('0')), findsNothing); expect(find.byKey(const Key('400')), findsNothing); expect(find.byKey(const Key('800')), findsOneWidget); }); testWidgets('adaptive layout displays children in correct places', (WidgetTester tester) async { await tester.pumpWidget(await layout(width: 400, tester: tester)); await tester.pumpAndSettle(); expect(tester.getTopLeft(topNavigation), Offset.zero); expect(tester.getTopLeft(secondaryNavigation), const Offset(390, 10)); expect(tester.getTopLeft(primaryNavigation), const Offset(0, 10)); expect(tester.getTopLeft(bottomNavigation), const Offset(0, 790)); expect(tester.getTopLeft(testBreakpoint), const Offset(10, 10)); expect(tester.getBottomRight(testBreakpoint), const Offset(200, 790)); expect(tester.getTopLeft(secondaryTestBreakpoint), const Offset(200, 10)); expect( tester.getBottomRight(secondaryTestBreakpoint), const Offset(390, 790)); }); testWidgets('adaptive layout correct layout when body vertical', (WidgetTester tester) async { await tester.pumpWidget( await layout(width: 400, tester: tester, orientation: Axis.vertical)); await tester.pumpAndSettle(); expect(tester.getTopLeft(topNavigation), Offset.zero); expect(tester.getTopLeft(secondaryNavigation), const Offset(390, 10)); expect(tester.getTopLeft(primaryNavigation), const Offset(0, 10)); expect(tester.getTopLeft(bottomNavigation), const Offset(0, 790)); expect(tester.getTopLeft(testBreakpoint), const Offset(10, 10)); expect(tester.getBottomRight(testBreakpoint), const Offset(390, 400)); expect(tester.getTopLeft(secondaryTestBreakpoint), const Offset(10, 400)); expect( tester.getBottomRight(secondaryTestBreakpoint), const Offset(390, 790)); }); testWidgets('adaptive layout correct layout when rtl', (WidgetTester tester) async { await tester.pumpWidget(await layout( width: 400, tester: tester, directionality: TextDirection.rtl)); await tester.pumpAndSettle(); expect(tester.getTopLeft(topNavigation), Offset.zero); expect(tester.getTopLeft(secondaryNavigation), const Offset(0, 10)); expect(tester.getTopLeft(primaryNavigation), const Offset(390, 10)); expect(tester.getTopLeft(bottomNavigation), const Offset(0, 790)); expect(tester.getTopLeft(testBreakpoint), const Offset(200, 10)); expect(tester.getBottomRight(testBreakpoint), const Offset(390, 790)); expect(tester.getTopLeft(secondaryTestBreakpoint), const Offset(10, 10)); expect( tester.getBottomRight(secondaryTestBreakpoint), const Offset(200, 790)); }); testWidgets('adaptive layout correct layout when body ratio not default', (WidgetTester tester) async { await tester .pumpWidget(await layout(width: 400, tester: tester, bodyRatio: 1 / 3)); await tester.pumpAndSettle(); expect(tester.getTopLeft(topNavigation), Offset.zero); expect(tester.getTopLeft(secondaryNavigation), const Offset(390, 10)); expect(tester.getTopLeft(primaryNavigation), const Offset(0, 10)); expect(tester.getTopLeft(bottomNavigation), const Offset(0, 790)); expect(tester.getTopLeft(testBreakpoint), const Offset(10, 10)); expect(tester.getBottomRight(testBreakpoint), offsetMoreOrLessEquals(const Offset(136.7, 790), epsilon: 1.0)); expect(tester.getTopLeft(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(136.7, 10), epsilon: 1.0)); expect( tester.getBottomRight(secondaryTestBreakpoint), const Offset(390, 790)); }); final Finder begin = find.byKey(const Key('0')); final Finder end = find.byKey(const Key('400')); Finder slideIn(String key) => find.byKey(Key('in-${Key(key)}')); Finder slideOut(String key) => find.byKey(Key('out-${Key(key)}')); testWidgets( 'slot layout properly switches between items with the appropriate animation', (WidgetTester tester) async { await tester.pumpWidget(slot(300, tester)); expect(begin, findsOneWidget); expect(end, findsNothing); await tester.pumpWidget(slot(500, tester)); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(tester.widget<SlideTransition>(slideOut('0')).position.value, const Offset(-0.5, 0)); expect(tester.widget<SlideTransition>(slideIn('400')).position.value, const Offset(-0.5, 0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(tester.widget<SlideTransition>(slideOut('0')).position.value, const Offset(-1.0, 0)); expect(tester.widget<SlideTransition>(slideIn('400')).position.value, Offset.zero); await tester.pumpAndSettle(); expect(begin, findsNothing); expect(end, findsOneWidget); }); testWidgets('AnimatedSwitcher does not spawn duplicate keys on rapid resize', (WidgetTester tester) async { // Populate the smaller slot layout and let the animation settle. await tester.pumpWidget(slot(300, tester)); await tester.pumpAndSettle(); expect(begin, findsOneWidget); expect(end, findsNothing); // Jumping back between two layouts before allowing an animation to complete. // Produces a chain of widgets in AnimatedSwitcher that includes duplicate // widgets with the same global key. for (int i = 0; i < 2; i++) { // Resize between the two slot layouts, but do not pump the animation // until completion. await tester.pumpWidget(slot(500, tester)); await tester.pump(const Duration(milliseconds: 100)); expect(begin, findsOneWidget); expect(end, findsOneWidget); await tester.pumpWidget(slot(300, tester)); await tester.pump(const Duration(milliseconds: 100)); expect(begin, findsOneWidget); expect(end, findsOneWidget); } }); testWidgets('slot layout can tolerate rapid changes in breakpoints', (WidgetTester tester) async { await tester.pumpWidget(slot(300, tester)); expect(begin, findsOneWidget); expect(end, findsNothing); await tester.pumpWidget(slot(500, tester)); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(tester.widget<SlideTransition>(slideOut('0')).position.value, offsetMoreOrLessEquals(const Offset(-0.1, 0), epsilon: 0.05)); expect(tester.widget<SlideTransition>(slideIn('400')).position.value, offsetMoreOrLessEquals(const Offset(-0.9, 0), epsilon: 0.05)); await tester.pumpWidget(slot(300, tester)); await tester.pumpAndSettle(); expect(begin, findsOneWidget); expect(end, findsNothing); }); // This test reflects the behavior of the internal animations of both the body // and secondary body and also the navigational items. This is reflected in // the changes in LTRB offsets from all sides instead of just LR for the body // animations. testWidgets('adaptive layout handles internal animations correctly', (WidgetTester tester) async { final Finder testBreakpoint = find.byKey(const Key('Test Breakpoint')); final Finder secondaryTestBreakpoint = find.byKey(const Key('Secondary Test Breakpoint')); await tester.pumpWidget(await layout(width: 400, tester: tester)); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(tester.getTopLeft(testBreakpoint), const Offset(1, 1)); expect(tester.getBottomRight(testBreakpoint), offsetMoreOrLessEquals(const Offset(395.8, 799), epsilon: 1.0)); expect(tester.getTopLeft(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(395.8, 1.0), epsilon: 1.0)); expect(tester.getBottomRight(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(594.8, 799.0), epsilon: 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); expect(tester.getTopLeft(testBreakpoint), const Offset(5, 5)); expect(tester.getBottomRight(testBreakpoint), offsetMoreOrLessEquals(const Offset(294.2, 795), epsilon: 1.0)); expect(tester.getTopLeft(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(294.2, 5.0), epsilon: 1.0)); expect(tester.getBottomRight(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(489.2, 795.0), epsilon: 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); expect(tester.getTopLeft(testBreakpoint), const Offset(9, 9)); expect(tester.getBottomRight(testBreakpoint), offsetMoreOrLessEquals(const Offset(201.7, 791), epsilon: 1.0)); expect(tester.getTopLeft(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(201.7, 9.0), epsilon: 1.0)); expect(tester.getBottomRight(secondaryTestBreakpoint), offsetMoreOrLessEquals(const Offset(392.7, 791), epsilon: 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(tester.getTopLeft(testBreakpoint), const Offset(10, 10)); expect(tester.getBottomRight(testBreakpoint), const Offset(200, 790)); expect(tester.getTopLeft(secondaryTestBreakpoint), const Offset(200, 10)); expect( tester.getBottomRight(secondaryTestBreakpoint), const Offset(390, 790)); }); testWidgets('adaptive layout does not animate when animations off', (WidgetTester tester) async { final Finder testBreakpoint = find.byKey(const Key('Test Breakpoint')); final Finder secondaryTestBreakpoint = find.byKey(const Key('Secondary Test Breakpoint')); await tester.pumpWidget( await layout(width: 400, tester: tester, animations: false)); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(tester.getTopLeft(testBreakpoint), const Offset(10, 10)); expect(tester.getBottomRight(testBreakpoint), const Offset(200, 790)); expect(tester.getTopLeft(secondaryTestBreakpoint), const Offset(200, 10)); expect( tester.getBottomRight(secondaryTestBreakpoint), const Offset(390, 790)); }); } class TestBreakpoint0 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width >= 0; } } class TestBreakpoint400 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width > 400; } } class TestBreakpoint800 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width > 800; } } final Finder topNavigation = find.byKey(const Key('Top Navigation')); final Finder secondaryNavigation = find.byKey(const Key('Secondary Navigation Small')); final Finder primaryNavigation = find.byKey(const Key('Primary Navigation Small')); final Finder bottomNavigation = find.byKey(const Key('Bottom Navigation Small')); final Finder testBreakpoint = find.byKey(const Key('Test Breakpoint')); final Finder secondaryTestBreakpoint = find.byKey(const Key('Secondary Test Breakpoint')); Widget on(BuildContext _) { return const SizedBox(width: 10, height: 10); } Future<MediaQuery> layout({ required double width, required WidgetTester tester, Axis orientation = Axis.horizontal, TextDirection directionality = TextDirection.ltr, double? bodyRatio, bool animations = true, }) async { await tester.binding.setSurfaceSize(Size(width, 800)); return MediaQuery( data: MediaQueryData(size: Size(width, 800)), child: Directionality( textDirection: directionality, child: AdaptiveLayout( bodyOrientation: orientation, bodyRatio: bodyRatio, internalAnimations: animations, primaryNavigation: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( key: const Key('Primary Navigation Small'), builder: on), TestBreakpoint400(): SlotLayout.from( key: const Key('Primary Navigation Medium'), builder: on), TestBreakpoint800(): SlotLayout.from( key: const Key('Primary Navigation Large'), builder: on), }, ), secondaryNavigation: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( key: const Key('Secondary Navigation Small'), builder: on), TestBreakpoint400(): SlotLayout.from( key: const Key('Secondary Navigation Medium'), builder: on), TestBreakpoint800(): SlotLayout.from( key: const Key('Secondary Navigation Large'), builder: on), }, ), topNavigation: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from(key: const Key('Top Navigation'), builder: on), TestBreakpoint400(): SlotLayout.from(key: const Key('Top Navigation1'), builder: on), TestBreakpoint800(): SlotLayout.from(key: const Key('Top Navigation2'), builder: on), }, ), bottomNavigation: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( key: const Key('Bottom Navigation Small'), builder: on), TestBreakpoint400(): SlotLayout.from(key: const Key('bnav1'), builder: on), TestBreakpoint800(): SlotLayout.from(key: const Key('bnav2'), builder: on), }, ), body: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( key: const Key('Test Breakpoint'), builder: (_) => Container(color: Colors.red), ), TestBreakpoint400(): SlotLayout.from( key: const Key('Test Breakpoint 1'), builder: (_) => Container(color: Colors.red), ), TestBreakpoint800(): SlotLayout.from( key: const Key('Test Breakpoint 2'), builder: (_) => Container(color: Colors.red), ), }, ), secondaryBody: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( key: const Key('Secondary Test Breakpoint'), builder: (_) => Container(color: Colors.blue), ), TestBreakpoint400(): SlotLayout.from( key: const Key('Secondary Test Breakpoint 1'), builder: (_) => Container(color: Colors.blue), ), TestBreakpoint800(): SlotLayout.from( key: const Key('Secondary Test Breakpoint 2'), builder: (_) => Container(color: Colors.blue), ), }, ), ), ), ); } AnimatedWidget leftOutIn(Widget child, Animation<double> animation) { return SlideTransition( key: Key('in-${child.key}'), position: Tween<Offset>( begin: const Offset(-1, 0), end: Offset.zero, ).animate(animation), child: child, ); } AnimatedWidget leftInOut(Widget child, Animation<double> animation) { return SlideTransition( key: Key('out-${child.key}'), position: Tween<Offset>( begin: Offset.zero, end: const Offset(-1, 0), ).animate(animation), child: child, ); } MediaQuery slot(double width, WidgetTester tester) { return MediaQuery( data: MediaQueryData.fromView(tester.view).copyWith(size: Size(width, 800)), child: Directionality( textDirection: TextDirection.ltr, child: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ TestBreakpoint0(): SlotLayout.from( inAnimation: leftOutIn, outAnimation: leftInOut, key: const Key('0'), builder: (_) => const SizedBox(width: 10, height: 10), ), TestBreakpoint400(): SlotLayout.from( inAnimation: leftOutIn, outAnimation: leftInOut, key: const Key('400'), builder: (_) => const SizedBox(width: 10, height: 10), ), }, ), ), ); }
packages/packages/flutter_adaptive_scaffold/test/adaptive_layout_test.dart/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/test/adaptive_layout_test.dart", "repo_id": "packages", "token_count": 6952 }
937
An example project that showcases how to enable the lint set from `package:flutter_lints`, which contains recommended lints for Flutter apps, packages, and plugins. The `flutter_lints` packages is listed as a dev_dependency in the `pubspec.yaml` file. The lint set provided by the package is activated in the `analysis_options.yaml` file. The lints enforced for this project can be further customized in that file. The Dart code in this project (e.g. `lib/main.dart`) is analyzed using the lint configuration provided by `package:flutter_lints`. The issues identified by the analyzer are surfaced in IDEs with Dart support or by invoking `flutter analyze` from the command line.
packages/packages/flutter_lints/example/README.md/0
{ "file_path": "packages/packages/flutter_lints/example/README.md", "repo_id": "packages", "token_count": 184 }
938
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/flutter_markdown/example/android/gradle.properties/0
{ "file_path": "packages/packages/flutter_markdown/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
939
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(goderbauer): Restructure the examples to avoid this ignore, https://github.com/flutter/flutter/issues/110208. // ignore_for_file: avoid_implementing_value_types import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import '../shared/markdown_demo_widget.dart'; // ignore_for_file: public_member_api_docs const String _data = ''' # Minimal Markdown Test --- This is a simple Markdown test. Provide a text string with Markdown tags to the Markdown widget and it will display the formatted output in a scrollable widget. ## Section 1 Maecenas eget **arcu egestas**, mollis ex vitae, posuere magna. Nunc eget aliquam tortor. Vestibulum porta sodales efficitur. Mauris interdum turpis eget est condimentum, vitae porttitor diam ornare. ### Subsection A Sed et massa finibus, blandit massa vel, vulputate velit. Vestibulum vitae venenatis libero. ***Curabitur sem lectus, feugiat eu justo in, eleifend accumsan ante.*** Sed a fermentum elit. Curabitur sodales metus id mi ornare, in ullamcorper magna congue. '''; const String _notes = """ # Minimal Markdown Demo --- ## Overview The simplest use case that illustrates how to make use of the flutter_markdown package is to include a Markdown widget in a widget tree and supply it with a character string of text containing Markdown formatting syntax. Here is a simple Flutter app that creates a Markdown widget that formats and displays the text in the string _markdownData. The resulting Flutter app demonstrates the use of headers, rules, and emphasis text from plain text Markdown syntax. ## Usage The code sample below demonstrates a simple Flutter app with a Markdown widget. ``` import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; const String _markdownData = \""" # Minimal Markdown Test --- This is a simple Markdown test. Provide a text string with Markdown tags to the Markdown widget and it will display the formatted output in a scrollable widget. ## Section 1 Maecenas eget **arcu egestas**, mollis ex vitae, posuere magna. Nunc eget aliquam tortor. Vestibulum porta sodales efficitur. Mauris interdum turpis eget est condimentum, vitae porttitor diam ornare. ### Subsection A Sed et massa finibus, blandit massa vel, vulputate velit. Vestibulum vitae venenatis libero. **__Curabitur sem lectus, feugiat eu justo in, eleifend accumsan ante.__** Sed a fermentum elit. Curabitur sodales metus id mi ornare, in ullamcorper magna congue. \"""; void main() { runApp( MaterialApp( title: "Markdown Demo", home: Scaffold( appBar: AppBar( title: const Text('Simple Markdown Demo'), ), body: SafeArea( child: Markdown( data: _markdownData, ), ), ), ), ); } ``` """; class MinimalMarkdownDemo extends StatelessWidget implements MarkdownDemoWidget { const MinimalMarkdownDemo({super.key}); static const String _title = 'Minimal Markdown Demo'; @override String get title => MinimalMarkdownDemo._title; @override String get description => 'A minimal example of how to use the Markdown ' 'widget in a Flutter app.'; @override Future<String> get data => Future<String>.value(_data); @override Future<String> get notes => Future<String>.value(_notes); @override Widget build(BuildContext context) { return const Markdown( data: _data, ); } }
packages/packages/flutter_markdown/example/lib/demos/minimal_markdown_demo.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/demos/minimal_markdown_demo.dart", "repo_id": "packages", "token_count": 1198 }
940
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Blockquote', () { testWidgets( 'simple one word blockquote', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( const MarkdownBody(data: '> quote'), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>['quote']); }, ); testWidgets( 'should work with styling', (WidgetTester tester) async { final ThemeData theme = ThemeData.light().copyWith( textTheme: textTheme, ); final MarkdownStyleSheet styleSheet = MarkdownStyleSheet.fromTheme( theme, ); const String data = '> this is a link: [Markdown guide](https://www.markdownguide.org) and this is **bold** and *italic*'; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, styleSheet: styleSheet, ), ), ); final Iterable<Widget> widgets = tester.allWidgets; final DecoratedBox blockQuoteContainer = tester.widget( find.byType(DecoratedBox), ); final Text qouteText = tester.widget(find.byType(Text)); final List<TextSpan> styledTextParts = (qouteText.textSpan! as TextSpan).children!.cast<TextSpan>(); expectTextStrings( widgets, <String>[ 'this is a link: Markdown guide and this is bold and italic' ], ); expect( (blockQuoteContainer.decoration as BoxDecoration).color, (styleSheet.blockquoteDecoration as BoxDecoration?)!.color, ); expect( (blockQuoteContainer.decoration as BoxDecoration).borderRadius, (styleSheet.blockquoteDecoration as BoxDecoration?)!.borderRadius, ); /// this is a link expect(styledTextParts[0].text, 'this is a link: '); expect( styledTextParts[0].style!.color, theme.textTheme.bodyMedium!.color, ); /// Markdown guide expect(styledTextParts[1].text, 'Markdown guide'); expect(styledTextParts[1].style!.color, Colors.blue); /// and this is expect(styledTextParts[2].text, ' and this is '); expect( styledTextParts[2].style!.color, theme.textTheme.bodyMedium!.color, ); /// bold expect(styledTextParts[3].text, 'bold'); expect(styledTextParts[3].style!.fontWeight, FontWeight.bold); /// and expect(styledTextParts[4].text, ' and '); expect( styledTextParts[4].style!.color, theme.textTheme.bodyMedium!.color, ); /// italic expect(styledTextParts[5].text, 'italic'); expect(styledTextParts[5].style!.fontStyle, FontStyle.italic); }, ); }); }
packages/packages/flutter_markdown/test/blockquote_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/blockquote_test.dart", "repo_id": "packages", "token_count": 1474 }
941
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; void main() => defineTests(); void defineTests() { group('Compatible with SelectionArea when selectable is default to false', () { testWidgets( 'Text can be selected', (WidgetTester tester) async { SelectedContent? content; const String data = 'How are you?'; await tester.pumpWidget(MaterialApp( home: SelectionArea( child: const Markdown( data: data, ), onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, ))); final TestGesture gesture = await tester.startGesture( tester.getTopLeft(find.text('How are you?')), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(tester.getBottomRight(find.text('How are you?'))); await gesture.up(); await tester.pump(); expect(content, isNotNull); expect(content!.plainText, 'How are you?'); }, ); testWidgets( 'List can be selected', (WidgetTester tester) async { SelectedContent? content; const String data = '- Item 1\n- Item 2\n- Item 3'; await tester.pumpWidget(MaterialApp( home: SelectionArea( child: const Markdown( data: data, ), onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, ))); final TestGesture gesture = await tester.startGesture( tester.getTopLeft(find.byType(Markdown)), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(tester.getBottomRight(find.byType(Markdown))); await gesture.up(); await tester.pump(); expect(content, isNotNull); expect(content!.plainText, '•Item 1•Item 2•Item 3'); }, ); }); }
packages/packages/flutter_markdown/test/selection_area_compatibility_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/selection_area_compatibility_test.dart", "repo_id": "packages", "token_count": 1011 }
942
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'src/base/command.dart'; import 'src/base/file_system.dart'; import 'src/base_dependencies.dart'; import 'src/commands/abandon.dart'; import 'src/commands/apply.dart'; import 'src/commands/start.dart'; import 'src/commands/status.dart'; Future<void> main(List<String> args) async { final bool veryVerbose = args.contains('-vv'); final bool verbose = args.contains('-v') || args.contains('--verbose') || veryVerbose; final MigrateBaseDependencies baseDependencies = MigrateBaseDependencies(); final List<MigrateCommand> commands = <MigrateCommand>[ MigrateStartCommand( verbose: verbose, logger: baseDependencies.logger, fileSystem: baseDependencies.fileSystem, processManager: baseDependencies.processManager, ), MigrateStatusCommand( verbose: verbose, logger: baseDependencies.logger, fileSystem: baseDependencies.fileSystem, processManager: baseDependencies.processManager, ), MigrateAbandonCommand( logger: baseDependencies.logger, fileSystem: baseDependencies.fileSystem, terminal: baseDependencies.terminal, processManager: baseDependencies.processManager), MigrateApplyCommand( verbose: verbose, logger: baseDependencies.logger, fileSystem: baseDependencies.fileSystem, terminal: baseDependencies.terminal, processManager: baseDependencies.processManager), ]; final MigrateCommandRunner runner = MigrateCommandRunner(); commands.forEach(runner.addCommand); await runner.run(args); await _exit(0, baseDependencies, shutdownHooks: baseDependencies.fileSystem.shutdownHooks); await baseDependencies.fileSystem.dispose(); } /// Simple extension of a CommandRunner to provide migrate specific global flags. class MigrateCommandRunner extends CommandRunner<void> { MigrateCommandRunner() : super( 'flutter', 'Migrates legacy flutter projects to modern versions.', ) { argParser.addFlag('verbose', abbr: 'v', negatable: false, help: 'Noisy logging, including all shell commands executed.'); } @override ArgParser get argParser => _argParser; final ArgParser _argParser = ArgParser(); } Future<int> _exit(int code, MigrateBaseDependencies baseDependencies, {required ShutdownHooks shutdownHooks}) async { // Run shutdown hooks before flushing logs await shutdownHooks.runShutdownHooks(baseDependencies.logger); final Completer<void> completer = Completer<void>(); // Give the task / timer queue one cycle through before we hard exit. Timer.run(() { io.exit(code); }); await completer.future; return code; }
packages/packages/flutter_migrate/lib/executable.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/executable.dart", "repo_id": "packages", "token_count": 1044 }
943
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'base/file_system.dart'; import 'base/logger.dart'; import 'flutter_project_metadata.dart'; import 'utils.dart'; /// Handles the custom/manual merging of one file at `localPath`. /// /// The `merge` method should be overridden to implement custom merging. abstract class CustomMerge { CustomMerge({ required this.logger, required this.localPath, }); /// The local path (with the project root as the root directory) of the file to merge. final String localPath; final Logger logger; /// Called to perform a custom three way merge between the current, /// base, and target files. MergeResult merge(File current, File base, File target); } /// Manually merges a flutter .metadata file. /// /// See `FlutterProjectMetadata`. class MetadataCustomMerge extends CustomMerge { MetadataCustomMerge({ required super.logger, }) : super(localPath: '.metadata'); @override MergeResult merge(File current, File base, File target) { final FlutterProjectMetadata result = computeMerge( FlutterProjectMetadata(current, logger), FlutterProjectMetadata(base, logger), FlutterProjectMetadata(target, logger), logger, ); return StringMergeResult.explicit( mergedString: result.toString(), hasConflict: false, exitCode: 0, localPath: localPath, ); } FlutterProjectMetadata computeMerge( FlutterProjectMetadata current, FlutterProjectMetadata base, FlutterProjectMetadata target, Logger logger) { // Prefer to update the version revision and channel to latest version. final String? versionRevision = target.versionRevision ?? current.versionRevision ?? base.versionRevision; final String? versionChannel = target.versionChannel ?? current.versionChannel ?? base.versionChannel; // Prefer to leave the project type untouched as it is non-trivial to change project type. final FlutterProjectType? projectType = current.projectType ?? base.projectType ?? target.projectType; final MigrateConfig migrateConfig = mergeMigrateConfig( current.migrateConfig, target.migrateConfig, ); final FlutterProjectMetadata output = FlutterProjectMetadata.explicit( file: current.file, versionRevision: versionRevision, versionChannel: versionChannel, projectType: projectType, migrateConfig: migrateConfig, logger: logger, ); return output; } MigrateConfig mergeMigrateConfig( MigrateConfig current, MigrateConfig target) { // Create the superset of current and target platforms with baseRevision updated to be that of target. final Map<FlutterProjectComponent, MigratePlatformConfig> projectComponentConfigs = <FlutterProjectComponent, MigratePlatformConfig>{}; for (final MapEntry<FlutterProjectComponent, MigratePlatformConfig> entry in current.platformConfigs.entries) { if (target.platformConfigs.containsKey(entry.key)) { projectComponentConfigs[entry.key] = MigratePlatformConfig( component: entry.value.component, createRevision: entry.value.createRevision, baseRevision: target.platformConfigs[entry.key]?.baseRevision); } else { projectComponentConfigs[entry.key] = entry.value; } } for (final MapEntry<FlutterProjectComponent, MigratePlatformConfig> entry in target.platformConfigs.entries) { if (!projectComponentConfigs.containsKey(entry.key)) { projectComponentConfigs[entry.key] = entry.value; } } // Ignore the base file list. final List<String> unmanagedFiles = List<String>.from(current.unmanagedFiles); for (final String path in target.unmanagedFiles) { if (!unmanagedFiles.contains(path) && !MigrateConfig.kDefaultUnmanagedFiles.contains(path)) { unmanagedFiles.add(path); } } return MigrateConfig( platformConfigs: projectComponentConfigs, unmanagedFiles: unmanagedFiles, ); } }
packages/packages/flutter_migrate/lib/src/custom_merge.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/custom_merge.dart", "repo_id": "packages", "token_count": 1432 }
944
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_migrate/src/base/io.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:flutter_migrate/src/base/terminal.dart'; import 'package:test/fake.dart'; import '../src/common.dart'; void main() { group('output preferences', () { testWithoutContext('can wrap output', () async { final BufferLogger bufferLogger = BufferLogger( outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40), terminal: TestTerminal(), ); bufferLogger.printStatus('0123456789' * 8); expect(bufferLogger.statusText, equals(('${'0123456789' * 4}\n') * 2)); }); testWithoutContext('can turn off wrapping', () async { final BufferLogger bufferLogger = BufferLogger( outputPreferences: OutputPreferences.test(), terminal: TestTerminal(), ); final String testString = '0123456789' * 20; bufferLogger.printStatus(testString); expect(bufferLogger.statusText, equals('$testString\n')); }); }); group('ANSI coloring and bold', () { late AnsiTerminal terminal; setUp(() { terminal = AnsiTerminal( stdio: Stdio(), // Danger, using real stdio. supportsColor: true, ); }); testWithoutContext('adding colors works', () { for (final TerminalColor color in TerminalColor.values) { expect( terminal.color('output', color), equals( '${AnsiTerminal.colorCode(color)}output${AnsiTerminal.resetColor}'), ); } }); testWithoutContext('adding bold works', () { expect( terminal.bolden('output'), equals('${AnsiTerminal.bold}output${AnsiTerminal.resetBold}'), ); }); testWithoutContext('nesting bold within color works', () { expect( terminal.color(terminal.bolden('output'), TerminalColor.blue), equals( '${AnsiTerminal.blue}${AnsiTerminal.bold}output${AnsiTerminal.resetBold}${AnsiTerminal.resetColor}'), ); expect( terminal.color('non-bold ${terminal.bolden('output')} also non-bold', TerminalColor.blue), equals( '${AnsiTerminal.blue}non-bold ${AnsiTerminal.bold}output${AnsiTerminal.resetBold} also non-bold${AnsiTerminal.resetColor}'), ); }); testWithoutContext('nesting color within bold works', () { expect( terminal.bolden(terminal.color('output', TerminalColor.blue)), equals( '${AnsiTerminal.bold}${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.resetBold}'), ); expect( terminal.bolden( 'non-color ${terminal.color('output', TerminalColor.blue)} also non-color'), equals( '${AnsiTerminal.bold}non-color ${AnsiTerminal.blue}output${AnsiTerminal.resetColor} also non-color${AnsiTerminal.resetBold}'), ); }); testWithoutContext('nesting color within color works', () { expect( terminal.color(terminal.color('output', TerminalColor.blue), TerminalColor.magenta), equals( '${AnsiTerminal.magenta}${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.magenta}${AnsiTerminal.resetColor}'), ); expect( terminal.color( 'magenta ${terminal.color('output', TerminalColor.blue)} also magenta', TerminalColor.magenta), equals( '${AnsiTerminal.magenta}magenta ${AnsiTerminal.blue}output${AnsiTerminal.resetColor}${AnsiTerminal.magenta} also magenta${AnsiTerminal.resetColor}'), ); }); testWithoutContext('nesting bold within bold works', () { expect( terminal.bolden(terminal.bolden('output')), equals('${AnsiTerminal.bold}output${AnsiTerminal.resetBold}'), ); expect( terminal.bolden('bold ${terminal.bolden('output')} still bold'), equals( '${AnsiTerminal.bold}bold output still bold${AnsiTerminal.resetBold}'), ); }); }); group('character input prompt', () { late AnsiTerminal terminalUnderTest; setUp(() { terminalUnderTest = TestTerminal(stdio: FakeStdio()); }); testWithoutContext('character prompt throws if usesTerminalUi is false', () async { expect( terminalUnderTest.promptForCharInput( <String>['a', 'b', 'c'], prompt: 'Please choose something', logger: BufferLogger.test(), ), throwsStateError); }); testWithoutContext('character prompt', () async { final BufferLogger bufferLogger = BufferLogger( terminal: terminalUnderTest, outputPreferences: OutputPreferences.test(), ); terminalUnderTest.usesTerminalUi = true; mockStdInStream = Stream<String>.fromFutures(<Future<String>>[ Future<String>.value('d'), // Not in accepted list. Future<String>.value('\n'), // Not in accepted list Future<String>.value('b'), ]).asBroadcastStream(); final String choice = await terminalUnderTest.promptForCharInput( <String>['a', 'b', 'c'], prompt: 'Please choose something', logger: bufferLogger, ); expect(choice, 'b'); expect( bufferLogger.statusText, 'Please choose something [a|b|c]: d\n' 'Please choose something [a|b|c]: \n' 'Please choose something [a|b|c]: b\n'); }); testWithoutContext( 'default character choice without displayAcceptedCharacters', () async { final BufferLogger bufferLogger = BufferLogger( terminal: terminalUnderTest, outputPreferences: OutputPreferences.test(), ); terminalUnderTest.usesTerminalUi = true; mockStdInStream = Stream<String>.fromFutures(<Future<String>>[ Future<String>.value('\n'), // Not in accepted list ]).asBroadcastStream(); final String choice = await terminalUnderTest.promptForCharInput( <String>['a', 'b', 'c'], prompt: 'Please choose something', displayAcceptedCharacters: false, defaultChoiceIndex: 1, // which is b. logger: bufferLogger, ); expect(choice, 'b'); expect(bufferLogger.statusText, 'Please choose something: \n'); }); testWithoutContext( 'Does not set single char mode when a terminal is not attached', () { final Stdio stdio = FakeStdio()..stdinHasTerminal = false; final AnsiTerminal ansiTerminal = AnsiTerminal( stdio: stdio, ); expect(() => ansiTerminal.singleCharMode = true, returnsNormally); }); }); testWithoutContext('AnsiTerminal.preferredStyle', () { final Stdio stdio = FakeStdio(); expect(AnsiTerminal(stdio: stdio).preferredStyle, 0); // Defaults to 0 for backwards compatibility. expect(AnsiTerminal(stdio: stdio, now: DateTime(2018)).preferredStyle, 0); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2)).preferredStyle, 1); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3)).preferredStyle, 2); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4)).preferredStyle, 3); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5)).preferredStyle, 4); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6)).preferredStyle, 5); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7)).preferredStyle, 5); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8)).preferredStyle, 0); expect(AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9)).preferredStyle, 1); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10)).preferredStyle, 2); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11)).preferredStyle, 3); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 1, 1)).preferredStyle, 0); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2, 1)).preferredStyle, 1); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3, 1)).preferredStyle, 2); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4, 1)).preferredStyle, 3); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5, 1)).preferredStyle, 4); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6, 1)).preferredStyle, 6); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7, 1)).preferredStyle, 6); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8, 1)).preferredStyle, 0); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9, 1)).preferredStyle, 1); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10, 1)) .preferredStyle, 2); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11, 1)) .preferredStyle, 3); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 1, 23)) .preferredStyle, 0); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 2, 23)) .preferredStyle, 1); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 3, 23)) .preferredStyle, 2); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 4, 23)) .preferredStyle, 3); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 5, 23)) .preferredStyle, 4); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 6, 23)) .preferredStyle, 28); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 7, 23)) .preferredStyle, 28); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 8, 23)) .preferredStyle, 0); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 9, 23)) .preferredStyle, 1); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 10, 23)) .preferredStyle, 2); expect( AnsiTerminal(stdio: stdio, now: DateTime(2018, 1, 11, 23)) .preferredStyle, 3); }); } late Stream<String> mockStdInStream; class TestTerminal extends AnsiTerminal { TestTerminal({ Stdio? stdio, DateTime? now, }) : super(stdio: stdio ?? Stdio(), now: now ?? DateTime(2018)); @override Stream<String> get keystrokes { return mockStdInStream; } @override bool singleCharMode = false; @override int get preferredStyle => 0; } class FakeStdio extends Fake implements Stdio { @override bool stdinHasTerminal = false; }
packages/packages/flutter_migrate/test/base/terminal_test.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/base/terminal_test.dart", "repo_id": "packages", "token_count": 4797 }
945
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import '../src/test_utils.dart'; const String _kDefaultHtml = ''' <html> <head> <title>Hello, World</title> </head> <body> <script src="main.dart.js"></script> </body> </html> '''; abstract class Project { late Directory dir; String get pubspec; String? get main => null; String? get test => null; String? get generatedFile => null; Uri get mainDart => Uri.parse('package:test/main.dart'); Future<void> setUpIn(Directory dir) async { this.dir = dir; writeFile(fileSystem.path.join(dir.path, 'pubspec.yaml'), pubspec); final String? main = this.main; if (main != null) { writeFile(fileSystem.path.join(dir.path, 'lib', 'main.dart'), main); } final String? test = this.test; if (test != null) { writeFile(fileSystem.path.join(dir.path, 'test', 'test.dart'), test); } final String? generatedFile = this.generatedFile; if (generatedFile != null) { writeFile( fileSystem.path .join(dir.path, '.dart_tool', 'flutter_gen', 'flutter_gen.dart'), generatedFile); } writeFile( fileSystem.path.join(dir.path, 'web', 'index.html'), _kDefaultHtml); writePackages(dir.path); await getPackages(dir.path); } int lineContaining(String contents, String search) { final int index = contents.split('\n').indexWhere((String l) => l.contains(search)); if (index == -1) { throw Exception("Did not find '$search' inside the file"); } return index + 1; // first line is line 1, not line 0 } }
packages/packages/flutter_migrate/test/test_data/project.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/test_data/project.dart", "repo_id": "packages", "token_count": 689 }
946
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.plugins.lifecycle; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import androidx.lifecycle.Lifecycle; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class FlutterLifecycleAdapterTest { @Mock Lifecycle lifecycle; @Mock ActivityPluginBinding mockActivityPluginBinding; AutoCloseable mockCloseable; @Before public void setUp() { mockCloseable = MockitoAnnotations.openMocks(this); } @After public void tearDown() throws Exception { mockCloseable.close(); } @Test public void getActivityLifecycle() { when(mockActivityPluginBinding.getLifecycle()) .thenReturn(new HiddenLifecycleReference(lifecycle)); when(mockActivityPluginBinding.getActivity()).thenReturn(null); Lifecycle parsedLifecycle = FlutterLifecycleAdapter.getActivityLifecycle(mockActivityPluginBinding); assertEquals(lifecycle, parsedLifecycle); } }
packages/packages/flutter_plugin_android_lifecycle/android/src/test/java/io/flutter/embedding/engine/plugins/lifecycle/FlutterLifecycleAdapterTest.java/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/android/src/test/java/io/flutter/embedding/engine/plugins/lifecycle/FlutterLifecycleAdapterTest.java", "repo_id": "packages", "token_count": 420 }
947
name: flutter_template_images description: Image files for use in flutter_tools templates without adding binary files to flutter/flutter. repository: https://github.com/flutter/packages/tree/main/packages/flutter_template_images issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+flutter_template_images%22 version: 4.2.1 environment: sdk: ^3.1.0 topics: - assets - image
packages/packages/flutter_template_images/pubspec.yaml/0
{ "file_path": "packages/packages/flutter_template_images/pubspec.yaml", "repo_id": "packages", "token_count": 150 }
948
Redirection changes the location to a new one based on application state. For example, redirection can be used to display a sign-in screen if the user is not logged in. A redirect is a callback of the type [GoRouterRedirect](https://pub.dev/documentation/go_router/latest/go_router/GoRouterRedirect.html). To change incoming location based on some application state, add a callback to either the GoRouter or GoRoute constructor: ```dart redirect: (BuildContext context, GoRouterState state) { if (AuthState.of(context).isSignedIn) { return '/signin'; } else { return null; } }, ``` To display the intended route without redirecting, return `null` or the original route path. ## Top-level vs route-level redirection There are two types of redirection: - Top-level redirection: Defined on the `GoRouter` constructor. Called before any navigation event. - Route-level redirection: Defined on the `GoRoute` constructor. Called when a navigation event is about to display the route. ## Named routes You can also redirect using [Named routes]. ## Considerations - You can specify a `redirectLimit` to configure the maximum number of redirects that are expected to occur in your app. By default, this value is set to 5. GoRouter will display the error screen if this redirect limit is exceeded (See the [Error handling][] topic for more information on the error screen.) [Named routes]: https://pub.dev/documentation/go_router/latest/topics/Named%20routes-topic.html [Error handling]: https://pub.dev/documentation/go_router/topics/Error%20handling-topic.html
packages/packages/go_router/doc/redirection.md/0
{ "file_path": "packages/packages/go_router/doc/redirection.md", "repo_id": "packages", "token_count": 452 }
949
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Credential data class. class Credentials { /// Creates a credential data object. Credentials(this.username, this.password); /// The username of the credentials. final String username; /// The password of the credentials. final String password; } /// The sign-in screen. class SignInScreen extends StatefulWidget { /// Creates a sign-in screen. const SignInScreen({ required this.onSignIn, super.key, }); /// Called when users sign in with [Credentials]. final ValueChanged<Credentials> onSignIn; @override State<SignInScreen> createState() => _SignInScreenState(); } class _SignInScreenState extends State<SignInScreen> { final TextEditingController _usernameController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); @override Widget build(BuildContext context) => Scaffold( body: Center( child: Card( child: Container( constraints: BoxConstraints.loose(const Size(600, 600)), padding: const EdgeInsets.all(8), child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('Sign in', style: Theme.of(context).textTheme.headlineMedium), TextField( decoration: const InputDecoration(labelText: 'Username'), controller: _usernameController, ), TextField( decoration: const InputDecoration(labelText: 'Password'), obscureText: true, controller: _passwordController, ), Padding( padding: const EdgeInsets.all(16), child: TextButton( onPressed: () async { widget.onSignIn(Credentials( _usernameController.value.text, _passwordController.value.text)); }, child: const Text('Sign in'), ), ), ], ), ), ), ), ); }
packages/packages/go_router/example/lib/books/src/screens/sign_in.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/screens/sign_in.dart", "repo_id": "packages", "token_count": 1164 }
950
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; void main() => runApp(RestorableStatefulShellRouteExampleApp()); /// An example demonstrating how to use StatefulShellRoute with state /// restoration. class RestorableStatefulShellRouteExampleApp extends StatelessWidget { /// Creates a NestedTabNavigationExampleApp RestorableStatefulShellRouteExampleApp({super.key}); final GoRouter _router = GoRouter( initialLocation: '/a', restorationScopeId: 'router', routes: <RouteBase>[ StatefulShellRoute.indexedStack( restorationScopeId: 'shell1', pageBuilder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { return MaterialPage<void>( restorationId: 'shellWidget1', child: ScaffoldWithNavBar(navigationShell: navigationShell)); }, branches: <StatefulShellBranch>[ // The route branch for the first tab of the bottom navigation bar. StatefulShellBranch( restorationScopeId: 'branchA', routes: <RouteBase>[ GoRoute( // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', pageBuilder: (BuildContext context, GoRouterState state) => const MaterialPage<void>( restorationId: 'screenA', child: RootScreen(label: 'A', detailsPath: '/a/details')), routes: <RouteBase>[ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', pageBuilder: (BuildContext context, GoRouterState state) => const MaterialPage<void>( restorationId: 'screenADetail', child: DetailsScreen(label: 'A')), ), ], ), ], ), // The route branch for the second tab of the bottom navigation bar. StatefulShellBranch( restorationScopeId: 'branchB', routes: <RouteBase>[ GoRoute( // The screen to display as the root in the second tab of the // bottom navigation bar. path: '/b', pageBuilder: (BuildContext context, GoRouterState state) => const MaterialPage<void>( restorationId: 'screenB', child: RootScreen(label: 'B', detailsPath: '/b/details')), routes: <RouteBase>[ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', pageBuilder: (BuildContext context, GoRouterState state) => const MaterialPage<void>( restorationId: 'screenBDetail', child: DetailsScreen(label: 'B')), ), ], ), ], ), ], ), ], ); @override Widget build(BuildContext context) { return MaterialApp.router( restorationScopeId: 'app', title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), routerConfig: _router, ); } } /// Builds the "shell" for the app by building a Scaffold with a /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. const ScaffoldWithNavBar({ required this.navigationShell, Key? key, }) : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; @override Widget build(BuildContext context) { return Scaffold( body: navigationShell, bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Section A'), BottomNavigationBarItem(icon: Icon(Icons.work), label: 'Section B'), ], currentIndex: navigationShell.currentIndex, onTap: (int tappedIndex) => navigationShell.goBranch(tappedIndex), ), ); } } /// Widget for the root/initial pages in the bottom navigation bar. class RootScreen extends StatelessWidget { /// Creates a RootScreen const RootScreen({ required this.label, required this.detailsPath, super.key, }); /// The label final String label; /// The path to the detail page final String detailsPath; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Root of section $label'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('Screen $label', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { GoRouter.of(context).go(detailsPath); }, child: const Text('View details'), ), ], ), ), ); } } /// The details screen for either the A or B screen. class DetailsScreen extends StatefulWidget { /// Constructs a [DetailsScreen]. const DetailsScreen({ required this.label, super.key, }); /// The label to display in the center of the screen. final String label; @override State<StatefulWidget> createState() => DetailsScreenState(); } /// The state for DetailsScreen class DetailsScreenState extends State<DetailsScreen> with RestorationMixin { final RestorableInt _counter = RestorableInt(0); @override String? get restorationId => 'DetailsScreen-${widget.label}'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_counter, 'counter'); } @override void dispose() { super.dispose(); _counter.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Details Screen - ${widget.label}'), ), body: _build(context), ); } Widget _build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('Details for ${widget.label} - Counter: ${_counter.value}', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { setState(() { _counter.value++; }); }, child: const Text('Increment counter'), ), const Padding(padding: EdgeInsets.all(8)), ], ), ); } }
packages/packages/go_router/example/lib/others/stateful_shell_state_restoration.dart/0
{ "file_path": "packages/packages/go_router/example/lib/others/stateful_shell_state_restoration.dart", "repo_id": "packages", "token_count": 3339 }
951
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import '../router.dart'; /// GoRouter implementation of InheritedWidget. /// /// Used for to find the current GoRouter in the widget tree. This is useful /// 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, }); /// The [GoRouter] that is made available to the widget tree. final GoRouter goRouter; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<GoRouter>('goRouter', goRouter)); } @override bool updateShouldNotify(covariant InheritedWidget oldWidget) => false; }
packages/packages/go_router/lib/src/misc/inherited_router.dart/0
{ "file_path": "packages/packages/go_router/lib/src/misc/inherited_router.dart", "repo_id": "packages", "token_count": 306 }
952
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:go_router/src/misc/error_screen.dart'; import 'test_helpers.dart'; Future<GoRouter> createGoRouter( WidgetTester tester, { Listenable? refreshListenable, bool dispose = true, }) async { final GoRouter router = GoRouter( initialLocation: '/', routes: <GoRoute>[ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), GoRoute(path: '/a', builder: (_, __) => const DummyStatefulWidget()), GoRoute( path: '/error', builder: (_, __) => const ErrorScreen(null), ), ], refreshListenable: refreshListenable, ); if (dispose) { addTearDown(router.dispose); } await tester.pumpWidget(MaterialApp.router( routerConfig: router, )); return router; } Future<GoRouter> createGoRouterWithStatefulShellRoute( WidgetTester tester) async { final GoRouter router = GoRouter( initialLocation: '/', routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), GoRoute(path: '/a', builder: (_, __) => const DummyStatefulWidget()), StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <RouteBase>[ GoRoute( path: '/c', builder: (_, __) => const DummyStatefulWidget(), routes: <RouteBase>[ GoRoute( path: 'c1', builder: (_, __) => const DummyStatefulWidget()), GoRoute( path: 'c2', builder: (_, __) => const DummyStatefulWidget()), ]), ]), StatefulShellBranch(routes: <RouteBase>[ GoRoute( path: '/d', builder: (_, __) => const DummyStatefulWidget(), routes: <RouteBase>[ GoRoute( path: 'd1', builder: (_, __) => const DummyStatefulWidget()), ]), ]), ], builder: mockStackedShellBuilder), ], ); addTearDown(router.dispose); await tester.pumpWidget(MaterialApp.router( routerConfig: router, )); return router; } void main() { group('pop', () { testWidgets('removes the last element', (WidgetTester tester) async { final GoRouter goRouter = await createGoRouter(tester) ..push('/error'); await tester.pumpAndSettle(); expect(find.byType(ErrorScreen), findsOneWidget); 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); }); testWidgets('pops more than matches count should return false', (WidgetTester tester) async { final GoRouter goRouter = await createGoRouter(tester) ..push('/error'); await tester.pumpAndSettle(); await goRouter.routerDelegate.popRoute(); expect(await goRouter.routerDelegate.popRoute(), isFalse); }); testWidgets('throw if nothing to pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>(); final GoRouter goRouter = await createRouter( <RouteBase>[ ShellRoute( navigatorKey: rootKey, builder: (_, __, Widget child) => child, routes: <RouteBase>[ ShellRoute( parentNavigatorKey: rootKey, navigatorKey: navKey, builder: (_, __, Widget child) => child, routes: <RouteBase>[ GoRoute( path: '/', parentNavigatorKey: navKey, builder: (_, __) => const Text('Home'), ), ], ), ], ), ], tester, ); await tester.pumpAndSettle(); expect(find.text('Home'), findsOneWidget); String? message; try { goRouter.pop(); } on GoError catch (e) { message = e.message; } expect(message, 'There is nothing to pop'); }); testWidgets('poproute return false if nothing to pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>(); final GoRouter goRouter = await createRouter( <RouteBase>[ ShellRoute( navigatorKey: rootKey, builder: (_, __, Widget child) => child, routes: <RouteBase>[ ShellRoute( parentNavigatorKey: rootKey, navigatorKey: navKey, builder: (_, __, Widget child) => child, routes: <RouteBase>[ GoRoute( path: '/', parentNavigatorKey: navKey, builder: (_, __) => const Text('Home'), ), ], ), ], ), ], tester, ); expect(await goRouter.routerDelegate.popRoute(), isFalse); }); }); group('push', () { testWidgets( 'It should return different pageKey when push is called', (WidgetTester tester) async { final GoRouter goRouter = await createGoRouter(tester); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); goRouter.push('/a'); await tester.pumpAndSettle(); goRouter.push('/a'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); expect( goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, isNot(equals( goRouter.routerDelegate.currentConfiguration.matches[2].pageKey)), ); }, ); 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(); goRouter.push('/c/c2'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ShellRouteMatch 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(); goRouter.push('/c'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ShellRouteMatch 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); 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); }, ); }); group('pushReplacement', () { testWidgets('It should replace the last match with the given one', (WidgetTester tester) async { final GoRouter goRouter = GoRouter( initialLocation: '/', routes: <GoRoute>[ GoRoute(path: '/', builder: (_, __) => const SizedBox()), GoRoute(path: '/page-0', builder: (_, __) => const SizedBox()), GoRoute(path: '/page-1', builder: (_, __) => const SizedBox()), ], ); addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: goRouter, ), ); goRouter.push('/page-0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); 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); expect( goRouter.routerDelegate.currentConfiguration.matches.first, first, reason: 'The first match should still be in the list of matches', ); expect( goRouter.routerDelegate.currentConfiguration.last, isNot(last), reason: 'The last match should have been removed', ); expect( (goRouter.routerDelegate.currentConfiguration.last 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, ); goRouter.push('/a'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ValueKey<String> prev = goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; goRouter.pushReplacement('/a'); await tester.pumpAndSettle(); 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 { final GoRouter 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()), ], ); addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: goRouter, ), ); goRouter.pushNamed('page0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first; final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; goRouter.pushReplacementNamed('page1'); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); expect( goRouter.routerDelegate.currentConfiguration.matches.first, first, reason: 'The first match should still be in the list of matches', ); expect( goRouter.routerDelegate.currentConfiguration.last, isNot(last), reason: 'The last match should have been removed', ); expect( goRouter.routerDelegate.currentConfiguration.last, isA<RouteMatch>().having( (RouteMatch match) => match.route.name, 'match.route.name', 'page1', ), reason: 'The new location should have been pushed', ); }, ); }); group('replace', () { testWidgets('It should replace the last match with the given one', (WidgetTester tester) async { final GoRouter goRouter = GoRouter( initialLocation: '/', routes: <GoRoute>[ GoRoute(path: '/', builder: (_, __) => const SizedBox()), GoRoute(path: '/page-0', builder: (_, __) => const SizedBox()), GoRoute(path: '/page-1', builder: (_, __) => const SizedBox()), ], ); addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: goRouter, ), ); goRouter.push('/page-0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); 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); expect( goRouter.routerDelegate.currentConfiguration.matches.first, first, reason: 'The first match should still be in the list of matches', ); expect( goRouter.routerDelegate.currentConfiguration.last, isNot(last), reason: 'The last match should have been removed', ); expect( (goRouter.routerDelegate.currentConfiguration.last 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, ); goRouter.push('/a'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ValueKey<String> prev = goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; goRouter.replace<void>('/a'); await tester.pumpAndSettle(); 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, ); goRouter.push('/a'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ValueKey<String> prev = goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; goRouter.replace<void>('/'); await tester.pumpAndSettle(); 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 { final GoRouter 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(), ), ], ); addTearDown(router.dispose); await tester.pumpWidget(MaterialApp.router( routerConfig: router, )); return router; } 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 RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; goRouter.replaceNamed<void>('page1'); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); expect( goRouter.routerDelegate.currentConfiguration.matches.first, first, reason: 'The first match should still be in the list of matches', ); expect( goRouter.routerDelegate.currentConfiguration.last, isNot(last), reason: 'The last match should have been removed', ); expect( (goRouter.routerDelegate.currentConfiguration.last 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, ); goRouter.pushNamed('page0'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ValueKey<String> prev = goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; goRouter.replaceNamed<void>('page0'); await tester.pumpAndSettle(); 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, ); goRouter.pushNamed('page0'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); final ValueKey<String> prev = goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; goRouter.replaceNamed<void>('home'); await tester.pumpAndSettle(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); expect( goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev, ); }, ); }); testWidgets('dispose unsubscribes from refreshListenable', (WidgetTester tester) async { final FakeRefreshListenable refreshListenable = FakeRefreshListenable(); addTearDown(refreshListenable.dispose); final GoRouter goRouter = await createGoRouter( tester, refreshListenable: refreshListenable, dispose: false, ); await tester.pumpWidget(Container()); goRouter.dispose(); expect(refreshListenable.unsubscribed, true); }); } class FakeRefreshListenable extends ChangeNotifier { bool unsubscribed = false; @override void removeListener(VoidCallback listener) { unsubscribed = true; super.removeListener(listener); } } class DummyStatefulWidget extends StatefulWidget { const DummyStatefulWidget({super.key}); @override State<DummyStatefulWidget> createState() => _DummyStatefulWidgetState(); } class _DummyStatefulWidgetState extends State<DummyStatefulWidget> { @override Widget build(BuildContext context) => Container(); }
packages/packages/go_router/test/delegate_test.dart/0
{ "file_path": "packages/packages/go_router/test/delegate_test.dart", "repo_id": "packages", "token_count": 10066 }
953
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; void main() { testWidgets( 'Route names are case sensitive', (WidgetTester tester) async { // config router with 2 routes with the same name but different case (Name, name) final GoRouter router = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', name: 'Name', builder: (_, __) => const ScreenA(), ), GoRoute( path: '/path', name: 'name', builder: (_, __) => const ScreenB(), ), ], ); addTearDown(router.dispose); // run MaterialApp, initial screen path is '/' -> ScreenA await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Testcase', ), ); // go to ScreenB router.goNamed('name'); await tester.pumpAndSettle(); expect(find.byType(ScreenB), findsOneWidget); // go to ScreenA router.goNamed('Name'); await tester.pumpAndSettle(); expect(find.byType(ScreenA), findsOneWidget); }, ); } class ScreenA extends StatelessWidget { const ScreenA({super.key}); @override Widget build(BuildContext context) { return Container(); } } class ScreenB extends StatelessWidget { const ScreenB({super.key}); @override Widget build(BuildContext context) { return Container(); } }
packages/packages/go_router/test/name_case_test.dart/0
{ "file_path": "packages/packages/go_router/test/name_case_test.dart", "repo_id": "packages", "token_count": 702 }
954
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates dependencies to require `analyzer` 5.2.0 or later. ## 2.4.1 * Fixes new lint warnings. ## 2.4.0 * Adds support for passing observers to the ShellRoute for the nested Navigator. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.3.4 * Fixes a bug of typeArguments losing NullabilitySuffix ## 2.3.3 * Adds `initialLocation` for `StatefulShellBranchConfig` ## 2.3.2 * Supports the latest `package:analyzer`. ## 2.3.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.3.0 * Adds Support for StatefulShellRoute ## 2.2.5 * Fixes a bug where shell routes without const constructor were not generated correctly. ## 2.2.4 * Bumps example go_router version to v10.0.0 and migrate example code. ## 2.2.3 * Removes `path_to_regexp` from the dependencies. ## 2.2.2 * Bumps example go_router version and migrate example code. ## 2.2.1 * Cleans up go_router_builder code. ## 2.2.0 * Adds replace methods to the generated routes. ## 2.1.1 * Fixes a bug that the required/positional parameters are not added to query parameters correctly. ## 2.1.0 * Supports required/positional parameters that are not in the path. ## 2.0.2 * Fixes unawaited_futures violations. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.0.1 * Supports name parameter for `TypedGoRoute`. ## 2.0.0 * Updates the documentation to go_router v7.0.0. * Bumps go_router version in example folder to v7.0.0. ## 1.2.2 * Supports returning value in generated `push` method. [go_router CHANGELOG](https://github.com/flutter/packages/blob/main/packages/go_router/CHANGELOG.md#650) ## 1.2.1 * Supports opt-in required extra parameters. [#117261](https://github.com/flutter/flutter/issues/117261) ## 1.2.0 * Adds Support for ShellRoute ## 1.1.7 * Supports default values for `Set`, `List` and `Iterable` route parameters. ## 1.1.6 * Generates the const enum map for enums used in `List`, `Set` and `Iterable`. ## 1.1.5 * Replaces unnecessary Flutter SDK constraint with corresponding Dart SDK constraint. ## 1.1.4 * Fixes the example for the default values in the README. ## 1.1.3 * Updates router_config to not passing itself as `extra`. ## 1.1.2 * Adds support for Iterables, Lists and Sets in query params for TypedGoRoute. [#108437](https://github.com/flutter/flutter/issues/108437). ## 1.1.1 * Support for the generation of the pushReplacement method has been added. ## 1.1.0 * Supports default value for the route parameters. ## 1.0.16 * Update the documentation to go_router v6.0.0. * Bumps go_router version in example folder to v6.0.0. ## 1.0.15 * Avoids using deprecated DartType.element2. ## 1.0.14 * Bumps go_router version in example folder to v5.0.0. * Bumps flutter version to 3.3.0. ## 1.0.13 * Supports the latest `package:analyzer`. ## 1.0.12 * Adds support for enhanced enums. [#105876](https://github.com/flutter/flutter/issues/105876). ## 1.0.11 * Replace mentions of the deprecated `GoRouteData.buildPage` with `GoRouteData.buildPageWithState`. ## 1.0.10 * Adds a lint ignore for deprecated member in the example. ## 1.0.9 * Fixes lint warnings. ## 1.0.8 * Updates `analyzer` to 4.4.0. * Removes the usage of deprecated API in `analyzer`. ## 1.0.7 * Supports newer versions of `analyzer`. ## 1.0.6 * Uses path-based deps in example. ## 1.0.5 * Update example to avoid using `push()` to push the same page since is not supported. [#105150](https://github.com/flutter/flutter/issues/105150) ## 1.0.4 * Adds `push` method to generated GoRouteData's extension. [#103025](https://github.com/flutter/flutter/issues/103025) ## 1.0.3 * Fixes incorrect separator at location path on Windows. [#102710](https://github.com/flutter/flutter/issues/102710) ## 1.0.2 * Changes the parameter name of the auto-generated `go` method from `buildContext` to `context`. ## 1.0.1 * Documentation fixes. [#102713](https://github.com/flutter/flutter/issues/102713). ## 1.0.0 * First release.
packages/packages/go_router_builder/CHANGELOG.md/0
{ "file_path": "packages/packages/go_router_builder/CHANGELOG.md", "repo_id": "packages", "token_count": 1437 }
955
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs, unreachable_from_main import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; part 'shell_route_example.g.dart'; void main() => runApp(App()); class App extends StatelessWidget { App({super.key}); @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, ); final GoRouter _router = GoRouter( routes: $appRoutes, initialLocation: '/foo', ); } class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('foo')), ); } @TypedShellRoute<MyShellRouteData>( routes: <TypedRoute<RouteData>>[ TypedGoRoute<FooRouteData>(path: '/foo'), TypedGoRoute<BarRouteData>(path: '/bar'), ], ) class MyShellRouteData extends ShellRouteData { const MyShellRouteData(); @override Widget builder( BuildContext context, GoRouterState state, Widget navigator, ) { return MyShellRouteScreen(child: navigator); } } class FooRouteData extends GoRouteData { const FooRouteData(); @override Widget build(BuildContext context, GoRouterState state) { return const FooScreen(); } } class BarRouteData extends GoRouteData { const BarRouteData(); @override Widget build(BuildContext context, GoRouterState state) { return const BarScreen(); } } class MyShellRouteScreen extends StatelessWidget { const MyShellRouteScreen({required this.child, super.key}); final Widget child; int getCurrentIndex(BuildContext context) { final String location = GoRouterState.of(context).uri.toString(); if (location == '/bar') { return 1; } return 0; } @override Widget build(BuildContext context) { final int currentIndex = getCurrentIndex(context); return Scaffold( body: child, bottomNavigationBar: BottomNavigationBar( currentIndex: currentIndex, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Foo', ), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'Bar', ), ], onTap: (int index) { switch (index) { case 0: const FooRouteData().go(context); case 1: const BarRouteData().go(context); } }, ), ); } } class FooScreen extends StatelessWidget { const FooScreen({super.key}); @override Widget build(BuildContext context) { return const Text('Foo'); } } class BarScreen extends StatelessWidget { const BarScreen({super.key}); @override Widget build(BuildContext context) { return const Text('Bar'); } } @TypedGoRoute<LoginRoute>(path: '/login') class LoginRoute extends GoRouteData { const LoginRoute(); @override Widget build(BuildContext context, GoRouterState state) => const LoginScreen(); } class LoginScreen extends StatelessWidget { const LoginScreen({super.key}); @override Widget build(BuildContext context) { return const Text('Login'); } }
packages/packages/go_router_builder/example/lib/shell_route_example.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/shell_route_example.dart", "repo_id": "packages", "token_count": 1259 }
956
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:go_router/go_router.dart'; @TypedGoRoute<RequiredExtraValueRoute>(path: '/default-value-route') class RequiredExtraValueRoute extends GoRouteData { RequiredExtraValueRoute({required this.$extra}); final int $extra; }
packages/packages/go_router_builder/test_inputs/required_extra_value.dart/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/required_extra_value.dart", "repo_id": "packages", "token_count": 114 }
957
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:go_router/go_router.dart'; @TypedGoRoute<UnsupportedType>(path: 'bob/:id') class UnsupportedType extends GoRouteData { UnsupportedType({required this.id}); final Stopwatch id; }
packages/packages/go_router_builder/test_inputs/unsupported_type.dart/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/unsupported_type.dart", "repo_id": "packages", "token_count": 111 }
958
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'package:google_identity_services_web/id.dart'; // #docregion use-loader import 'package:google_identity_services_web/loader.dart' as gis; // #enddocregion use-loader import 'src/jwt.dart' as jwt; // #docregion use-loader void main() async { await gis.loadWebSdk(); // Load the GIS SDK // The rest of your code... // #enddocregion use-loader id.setLogLevel('debug'); final IdConfiguration config = IdConfiguration( client_id: 'your-google-client-id-goes-here.apps.googleusercontent.com', callback: onCredentialResponse, use_fedcm_for_prompt: true, ); id.initialize(config); id.prompt(onPromptMoment); // #docregion use-loader } // #enddocregion use-loader /// Handles the ID token returned from the One Tap prompt. /// See: https://developers.google.com/identity/gsi/web/reference/js-reference#callback void onCredentialResponse(CredentialResponse o) { final Map<String, dynamic>? payload = jwt.decodePayload(o.credential); if (payload != null) { print('Hello, ${payload["name"]}'); print(o.select_by); print(payload); } else { print('Could not decode ${o.credential}'); } } /// Handles Prompt UI status notifications. /// See: https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.prompt void onPromptMoment(PromptMomentNotification o) { final MomentType type = o.getMomentType(); print(type.runtimeType); print(type); print(type.index); print(o.getDismissedReason()); print(o.getNotDisplayedReason()); print(o.getSkippedReason()); }
packages/packages/google_identity_services_web/example/lib/main.dart/0
{ "file_path": "packages/packages/google_identity_services_web/example/lib/main.dart", "repo_id": "packages", "token_count": 596 }
959
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; import 'shared.dart'; /// Integration Tests for the Tiles feature. These also use the [GoogleMapsInspectorPlatform]. void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); runTests(); } void runTests() { GoogleMapsFlutterPlatform.instance.enableDebugInspection(); final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; group('Tiles', () { testWidgets( 'set tileOverlay correctly', (WidgetTester tester) async { final Completer<int> mapIdCompleter = Completer<int>(); final TileOverlay tileOverlay1 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 2, transparency: 0.2, ); final TileOverlay tileOverlay2 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_2'), tileProvider: _DebugTileProvider(), zIndex: 1, visible: false, transparency: 0.3, fadeIn: false, ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: kInitialCameraPosition, tileOverlays: <TileOverlay>{tileOverlay1, tileOverlay2}, onMapCreated: (GoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, ), ), ); await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; final TileOverlay tileOverlayInfo1 = (await inspector .getTileOverlayInfo(tileOverlay1.mapsId, mapId: mapId))!; final TileOverlay tileOverlayInfo2 = (await inspector .getTileOverlayInfo(tileOverlay2.mapsId, mapId: mapId))!; expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }, ); testWidgets( 'update tileOverlays correctly', (WidgetTester tester) async { final Completer<int> mapIdCompleter = Completer<int>(); final Key key = GlobalKey(); final TileOverlay tileOverlay1 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 2, transparency: 0.2, ); final TileOverlay tileOverlay2 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_2'), tileProvider: _DebugTileProvider(), zIndex: 3, transparency: 0.5, ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( key: key, initialCameraPosition: kInitialCameraPosition, tileOverlays: <TileOverlay>{tileOverlay1, tileOverlay2}, onMapCreated: (GoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, ), ), ); final int mapId = await mapIdCompleter.future; final TileOverlay tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 1, visible: false, transparency: 0.3, fadeIn: false, ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( key: key, initialCameraPosition: kInitialCameraPosition, tileOverlays: <TileOverlay>{tileOverlay1New}, onMapCreated: (GoogleMapController controller) { fail('update: OnMapCreated should get called only once.'); }, ), ), ); await tester.pumpAndSettle(const Duration(seconds: 3)); final TileOverlay tileOverlayInfo1 = (await inspector .getTileOverlayInfo(tileOverlay1.mapsId, mapId: mapId))!; final TileOverlay? tileOverlayInfo2 = await inspector .getTileOverlayInfo(tileOverlay2.mapsId, mapId: mapId); expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); }, ); testWidgets( 'remove tileOverlays correctly', (WidgetTester tester) async { final Completer<int> mapIdCompleter = Completer<int>(); final Key key = GlobalKey(); final TileOverlay tileOverlay1 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 2, transparency: 0.2, ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( key: key, initialCameraPosition: kInitialCameraPosition, tileOverlays: <TileOverlay>{tileOverlay1}, onMapCreated: (GoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, ), ), ); final int mapId = await mapIdCompleter.future; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( key: key, initialCameraPosition: kInitialCameraPosition, onMapCreated: (GoogleMapController controller) { fail('OnMapCreated should get called only once.'); }, ), ), ); await tester.pumpAndSettle(const Duration(seconds: 3)); final TileOverlay? tileOverlayInfo1 = await inspector .getTileOverlayInfo(tileOverlay1.mapsId, mapId: mapId); expect(tileOverlayInfo1, isNull); }, ); }, skip: isWeb /* Tiles not supported on the web */); } class _DebugTileProvider implements TileProvider { _DebugTileProvider() { boxPaint.isAntiAlias = true; boxPaint.color = Colors.blue; boxPaint.strokeWidth = 2.0; boxPaint.style = PaintingStyle.stroke; } static const int width = 100; static const int height = 100; static final Paint boxPaint = Paint(); static const TextStyle textStyle = TextStyle( color: Colors.red, fontSize: 20, ); @override Future<Tile> getTile(int x, int y, int? zoom) async { final ui.PictureRecorder recorder = ui.PictureRecorder(); final Canvas canvas = Canvas(recorder); final TextSpan textSpan = TextSpan( text: '$x,$y', style: textStyle, ); final TextPainter textPainter = TextPainter( text: textSpan, textDirection: TextDirection.ltr, ); textPainter.layout( maxWidth: width.toDouble(), ); textPainter.paint(canvas, Offset.zero); canvas.drawRect( Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } }
packages/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart", "repo_id": "packages", "token_count": 3787 }
960
# google\_maps\_flutter\_android <?code-excerpt path-base="example/lib"?> The Android implementation of [`google_maps_flutter`][1]. ## Usage This package is [endorsed][2], which means you can simply use `google_maps_flutter` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. ## Display Mode This plugin supports two different [platform view display modes][3]. The default display mode is subject to change in the future, and will not be considered a breaking change, so if you want to ensure a specific mode you can set it explicitly: <?code-excerpt "readme_excerpts.dart (DisplayMode)"?> ```dart import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { // Require Hybrid Composition mode on Android. final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { // Force Hybrid Composition mode. mapsImplementation.useAndroidViewSurface = true; } // ··· } ``` ### Texture Layer Hybrid Composition This is the the current default mode and corresponds to `useAndroidViewSurface = false`. This mode is more performant than Hybrid Composition and we recommend that you use this mode. ### Hybrid Composition This mode is available for backwards compatability and corresponds to `useAndroidViewSurface = true`. We do not recommend its use as it is less performant than Texture Layer Hybrid Composition and certain flutter rendering effects are not supported. If you require this mode for correctness, please file a bug so we can investigate and fix the issue in the TLHC mode. ## Map renderer This plugin supports the option to request a specific [map renderer][5]. The renderer must be requested before creating GoogleMap instances, as the renderer can be initialized only once per application context. <?code-excerpt "readme_excerpts.dart (MapRenderer)"?> ```dart AndroidMapRenderer mapRenderer = AndroidMapRenderer.platformDefault; // ··· final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { WidgetsFlutterBinding.ensureInitialized(); mapRenderer = await mapsImplementation .initializeWithRenderer(AndroidMapRenderer.latest); } ``` `AndroidMapRenderer.platformDefault` corresponds to `AndroidMapRenderer.latest`. You are not guaranteed to get the requested renderer. For example, on emulators without Google Play the latest renderer will not be available and the legacy renderer will always be used. WARNING: `AndroidMapRenderer.legacy` is known to crash apps and is no longer supported by the Google Maps team and therefore cannot be supported by the Flutter team. [1]: https://pub.dev/packages/google_maps_flutter [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://docs.flutter.dev/development/platform-integration/android/platform-views [4]: https://github.com/flutter/flutter/issues/103686 [5]: https://developers.google.com/maps/documentation/android-sdk/renderer
packages/packages/google_maps_flutter/google_maps_flutter_android/README.md/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/README.md", "repo_id": "packages", "token_count": 962 }
961
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=false
packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
962
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object_updates.dart'; /// A trivial TestMapsObject implementation for testing updates with. @immutable class TestMapsObject implements MapsObject<TestMapsObject> { const TestMapsObject(this.mapsId, {this.data = 1}); @override final MapsObjectId<TestMapsObject> mapsId; final int data; @override TestMapsObject clone() { return TestMapsObject(mapsId, data: data); } @override Object toJson() { return <String, Object>{'id': mapsId.value}; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is TestMapsObject && mapsId == other.mapsId && data == other.data; } @override int get hashCode => Object.hash(mapsId, data); } class TestMapsObjectUpdate extends MapsObjectUpdates<TestMapsObject> { TestMapsObjectUpdate.from(super.previous, super.current) : super.from(objectName: 'testObject'); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart", "repo_id": "packages", "token_count": 422 }
963
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'dart:async'; import 'dart:convert' show json; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:http/http.dart' as http; import 'src/sign_in_button.dart'; /// The scopes required by this application. // #docregion Initialize const List<String> scopes = <String>[ 'email', 'https://www.googleapis.com/auth/contacts.readonly', ]; GoogleSignIn _googleSignIn = GoogleSignIn( // Optional clientId // clientId: 'your-client_id.apps.googleusercontent.com', scopes: scopes, ); // #enddocregion Initialize void main() { runApp( const MaterialApp( title: 'Google Sign In', home: SignInDemo(), ), ); } /// The SignInDemo app. class SignInDemo extends StatefulWidget { /// const SignInDemo({super.key}); @override State createState() => _SignInDemoState(); } class _SignInDemoState extends State<SignInDemo> { GoogleSignInAccount? _currentUser; bool _isAuthorized = false; // has granted permissions? String _contactText = ''; @override void initState() { super.initState(); _googleSignIn.onCurrentUserChanged .listen((GoogleSignInAccount? account) async { // #docregion CanAccessScopes // In mobile, being authenticated means being authorized... bool isAuthorized = account != null; // However, on web... if (kIsWeb && account != null) { isAuthorized = await _googleSignIn.canAccessScopes(scopes); } // #enddocregion CanAccessScopes setState(() { _currentUser = account; _isAuthorized = isAuthorized; }); // Now that we know that the user can access the required scopes, the app // can call the REST API. if (isAuthorized) { unawaited(_handleGetContact(account!)); } }); // In the web, _googleSignIn.signInSilently() triggers the One Tap UX. // // It is recommended by Google Identity Services to render both the One Tap UX // and the Google Sign In button together to "reduce friction and improve // sign-in rates" ([docs](https://developers.google.com/identity/gsi/web/guides/display-button#html)). _googleSignIn.signInSilently(); } // Calls the People API REST endpoint for the signed-in user to retrieve information. Future<void> _handleGetContact(GoogleSignInAccount user) async { setState(() { _contactText = 'Loading contact info...'; }); final http.Response response = await http.get( Uri.parse('https://people.googleapis.com/v1/people/me/connections' '?requestMask.includeField=person.names'), headers: await user.authHeaders, ); if (response.statusCode != 200) { setState(() { _contactText = 'People API gave a ${response.statusCode} ' 'response. Check logs for details.'; }); print('People API ${response.statusCode} response: ${response.body}'); return; } final Map<String, dynamic> data = json.decode(response.body) as Map<String, dynamic>; final String? namedContact = _pickFirstNamedContact(data); setState(() { if (namedContact != null) { _contactText = 'I see you know $namedContact!'; } else { _contactText = 'No contacts to display.'; } }); } String? _pickFirstNamedContact(Map<String, dynamic> data) { final List<dynamic>? connections = data['connections'] as List<dynamic>?; final Map<String, dynamic>? contact = connections?.firstWhere( (dynamic contact) => (contact as Map<Object?, dynamic>)['names'] != null, orElse: () => null, ) as Map<String, dynamic>?; if (contact != null) { final List<dynamic> names = contact['names'] as List<dynamic>; final Map<String, dynamic>? name = names.firstWhere( (dynamic name) => (name as Map<Object?, dynamic>)['displayName'] != null, orElse: () => null, ) as Map<String, dynamic>?; if (name != null) { return name['displayName'] as String?; } } return null; } // This is the on-click handler for the Sign In button that is rendered by Flutter. // // On the web, the on-click handler of the Sign In button is owned by the JS // SDK, so this method can be considered mobile only. // #docregion SignIn Future<void> _handleSignIn() async { try { await _googleSignIn.signIn(); } catch (error) { print(error); } } // #enddocregion SignIn // Prompts the user to authorize `scopes`. // // This action is **required** in platforms that don't perform Authentication // and Authorization at the same time (like the web). // // On the web, this must be called from an user interaction (button click). // #docregion RequestScopes Future<void> _handleAuthorizeScopes() async { final bool isAuthorized = await _googleSignIn.requestScopes(scopes); // #enddocregion RequestScopes setState(() { _isAuthorized = isAuthorized; }); // #docregion RequestScopes if (isAuthorized) { unawaited(_handleGetContact(_currentUser!)); } // #enddocregion RequestScopes } Future<void> _handleSignOut() => _googleSignIn.disconnect(); Widget _buildBody() { final GoogleSignInAccount? user = _currentUser; if (user != null) { // The user is Authenticated return Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ ListTile( leading: GoogleUserCircleAvatar( identity: user, ), title: Text(user.displayName ?? ''), subtitle: Text(user.email), ), const Text('Signed in successfully.'), if (_isAuthorized) ...<Widget>[ // The user has Authorized all required scopes Text(_contactText), ElevatedButton( child: const Text('REFRESH'), onPressed: () => _handleGetContact(user), ), ], if (!_isAuthorized) ...<Widget>[ // The user has NOT Authorized all required scopes. // (Mobile users may never see this button!) const Text('Additional permissions needed to read your contacts.'), ElevatedButton( onPressed: _handleAuthorizeScopes, child: const Text('REQUEST PERMISSIONS'), ), ], ElevatedButton( onPressed: _handleSignOut, child: const Text('SIGN OUT'), ), ], ); } else { // The user is NOT Authenticated return Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ const Text('You are not currently signed in.'), // This method is used to separate mobile from web code with conditional exports. // See: src/sign_in_button.dart buildSignInButton( onPressed: _handleSignIn, ), ], ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Google Sign In'), ), body: ConstrainedBox( constraints: const BoxConstraints.expand(), child: _buildBody(), )); } }
packages/packages/google_sign_in/google_sign_in/example/lib/main.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/example/lib/main.dart", "repo_id": "packages", "token_count": 2926 }
964
name: google_sign_in_example description: Example of Google Sign-In plugin. publish_to: none environment: sdk: ^3.2.0 flutter: ">=3.16.0" dependencies: flutter: sdk: flutter google_sign_in: # When depending on this package from a real application you should use: # google_sign_in: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ google_sign_in_web: ^0.12.3 http: ">=0.13.0 <2.0.0" dev_dependencies: espresso: ^0.2.0 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/google_sign_in/google_sign_in/example/pubspec.yaml/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/example/pubspec.yaml", "repo_id": "packages", "token_count": 287 }
965
## 6.1.22 * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates compileSdk version to 34. * Updates play-services-auth version to 21.0.0. ## 6.1.21 * Updates `clearAuthCache` override to match base class declaration. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 6.1.20 * Updates play-services-auth version to 20.7.0. ## 6.1.19 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 6.1.18 * Updates play-services-auth version to 20.6.0. ## 6.1.17 * Converts method channels to Pigeon. ## 6.1.16 * Updates Guava to version 32.0.1. ## 6.1.15 * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. * Updates Guava to version 32.0.0. ## 6.1.14 * Fixes compatibility with AGP versions older than 4.2. ## 6.1.13 * Adds `targetCompatibilty` matching `sourceCompatibility` for older toolchains. ## 6.1.12 * Adds a namespace for compatibility with AGP 8.0. ## 6.1.11 * Fixes Java warnings. ## 6.1.10 * Sets an explicit Java compatibility version. ## 6.1.9 * Updates play-services-auth version to 20.5.0. ## 6.1.8 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. * Updates compileSdkVersion to 33. ## 6.1.7 * Updates links for the merge of flutter/plugins into flutter/packages. ## 6.1.6 * Minor implementation cleanup * Updates minimum Flutter version to 3.0. ## 6.1.5 * Updates play-services-auth version to 20.4.1. ## 6.1.4 * Rolls Guava to version 31.1. ## 6.1.3 * Updates play-services-auth version to 20.4.0. ## 6.1.2 * Fixes passing `serverClientId` via the channelled `init` call ## 6.1.1 * Corrects typos in plugin error logs and removes not actionable warnings. * Updates minimum Flutter version to 2.10. * Updates play-services-auth version to 20.3.0. ## 6.1.0 * Adds override for `GoogleSignIn.initWithParams` to handle new `forceCodeForRefreshToken` parameter. ## 6.0.1 * Updates gradle version to 7.2.1 on Android. ## 6.0.0 * Deprecates `clientId` and adds support for `serverClientId` instead. Historically `clientId` was interpreted as `serverClientId`, but only on Android. On other platforms it was interpreted as the OAuth `clientId` of the app. For backwards-compatibility `clientId` will still be used as a server client ID if `serverClientId` is not provided. * **BREAKING CHANGES**: * Adds `serverClientId` parameter to `IDelegate.init` (Java). ## 5.2.8 * Suppresses `deprecation` warnings (for using Android V1 embedding). ## 5.2.7 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 5.2.6 * Switches to an internal method channel, rather than the default. ## 5.2.5 * Splits from `google_sign_in` as a federated implementation.
packages/packages/google_sign_in/google_sign_in_android/CHANGELOG.md/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/CHANGELOG.md", "repo_id": "packages", "token_count": 967 }
966
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true
packages/packages/google_sign_in/google_sign_in_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 22 }
967
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'src/messages.g.dart'; /// iOS implementation of [GoogleSignInPlatform]. class GoogleSignInIOS extends GoogleSignInPlatform { /// Creates a new plugin implementation instance. GoogleSignInIOS({ @visibleForTesting GoogleSignInApi? api, }) : _api = api ?? GoogleSignInApi(); final GoogleSignInApi _api; /// Registers this class as the default instance of [GoogleSignInPlatform]. static void registerWith() { GoogleSignInPlatform.instance = GoogleSignInIOS(); } @override Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) { return initWithParams(SignInInitParameters( signInOption: signInOption, scopes: scopes, hostedDomain: hostedDomain, clientId: clientId, )); } @override Future<void> initWithParams(SignInInitParameters params) { if (params.signInOption == SignInOption.games) { throw PlatformException( code: 'unsupported-options', message: 'Games sign in is not supported on iOS'); } return _api.init(InitParams( scopes: params.scopes, hostedDomain: params.hostedDomain, clientId: params.clientId, serverClientId: params.serverClientId, )); } @override Future<GoogleSignInUserData?> signInSilently() { return _api.signInSilently().then(_signInUserDataFromChannelData); } @override Future<GoogleSignInUserData?> signIn() { return _api.signIn().then(_signInUserDataFromChannelData); } @override Future<GoogleSignInTokenData> getTokens( {required String email, bool? shouldRecoverAuth = true}) { return _api.getAccessToken().then(_signInTokenDataFromChannelData); } @override Future<void> signOut() { return _api.signOut(); } @override Future<void> disconnect() { return _api.disconnect(); } @override Future<bool> isSignedIn() { return _api.isSignedIn(); } @override Future<void> clearAuthCache({required String token}) async { // There's nothing to be done here on iOS since the expired/invalid // tokens are refreshed automatically by getTokens. } @override Future<bool> requestScopes(List<String> scopes) { return _api.requestScopes(scopes); } GoogleSignInUserData _signInUserDataFromChannelData(UserData data) { return GoogleSignInUserData( email: data.email, id: data.userId, displayName: data.displayName, photoUrl: data.photoUrl, serverAuthCode: data.serverAuthCode, idToken: data.idToken, ); } GoogleSignInTokenData _signInTokenDataFromChannelData(TokenData data) { return GoogleSignInTokenData( idToken: data.idToken, accessToken: data.accessToken, ); } }
packages/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart", "repo_id": "packages", "token_count": 1113 }
968
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:google_sign_in_web/google_sign_in_web.dart' show GoogleSignInPlugin; import 'package:google_sign_in_web/src/gis_client.dart'; import 'package:google_sign_in_web/web_only.dart' as web; import 'package:integration_test/integration_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart' as mockito; import 'web_only_test.mocks.dart'; // Mock GisSdkClient so we can simulate any response from the JS side. @GenerateMocks(<Type>[], customMocks: <MockSpec<dynamic>>[ MockSpec<GisSdkClient>(onMissingStub: OnMissingStub.returnDefault), ]) void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('non-web plugin instance', () { setUp(() { GoogleSignInPlatform.instance = NonWebImplementation(); }); testWidgets('renderButton throws', (WidgetTester _) async { expect(() { web.renderButton(); }, throwsAssertionError); }); testWidgets('requestServerAuthCode throws', (WidgetTester _) async { expect(() async { await web.requestServerAuthCode(); }, throwsAssertionError); }); }); group('web plugin instance', () { const String someAuthCode = '50m3_4u7h_c0d3'; late MockGisSdkClient mockGis; setUp(() { mockGis = MockGisSdkClient(); GoogleSignInPlatform.instance = GoogleSignInPlugin( debugOverrideLoader: true, debugOverrideGisSdkClient: mockGis, )..initWithParams( const SignInInitParameters( clientId: 'does-not-matter', ), ); }); testWidgets('call reaches GIS API', (WidgetTester _) async { mockito .when(mockGis.requestServerAuthCode()) .thenAnswer((_) => Future<String>.value(someAuthCode)); final String? serverAuthCode = await web.requestServerAuthCode(); expect(serverAuthCode, someAuthCode); }); }); } /// Fake non-web implementation used to verify that the web_only methods /// throw when the wrong type of instance is configured. class NonWebImplementation extends GoogleSignInPlatform {}
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart", "repo_id": "packages", "token_count": 878 }
969
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; // #docregion CameraDelegate import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; // #enddocregion CameraDelegate /// Example of a camera delegate // #docregion CameraDelegate class MyCameraDelegate extends ImagePickerCameraDelegate { @override Future<XFile?> takePhoto( {ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions()}) async { return _takeAPhoto(options.preferredCameraDevice); } @override Future<XFile?> takeVideo( {ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions()}) async { return _takeAVideo(options.preferredCameraDevice); } } // #enddocregion CameraDelegate /// Example function for README demonstration of various pick* calls. Future<List<XFile?>> readmePickExample() async { // #docregion Pick final ImagePicker picker = ImagePicker(); // Pick an image. final XFile? image = await picker.pickImage(source: ImageSource.gallery); // Capture a photo. final XFile? photo = await picker.pickImage(source: ImageSource.camera); // Pick a video. final XFile? galleryVideo = await picker.pickVideo(source: ImageSource.gallery); // Capture a video. final XFile? cameraVideo = await picker.pickVideo(source: ImageSource.camera); // Pick multiple images. final List<XFile> images = await picker.pickMultiImage(); // Pick singe image or video. final XFile? media = await picker.pickMedia(); // Pick multiple images and videos. final List<XFile> medias = await picker.pickMultipleMedia(); // #enddocregion Pick // Return everything for the sanity check test. return <XFile?>[ image, photo, galleryVideo, cameraVideo, if (images.isEmpty) null else images.first, media, if (medias.isEmpty) null else medias.first, ]; } /// Example function for README demonstration of getting lost data. // #docregion LostData Future<void> getLostData() async { final ImagePicker picker = ImagePicker(); final LostDataResponse response = await picker.retrieveLostData(); if (response.isEmpty) { return; } final List<XFile>? files = response.files; if (files != null) { _handleLostFiles(files); } else { _handleError(response.exception); } } // #enddocregion LostData /// Example of camera delegate setup. // #docregion CameraDelegate void setUpCameraDelegate() { final ImagePickerPlatform instance = ImagePickerPlatform.instance; if (instance is CameraDelegatingImagePickerPlatform) { instance.cameraDelegate = MyCameraDelegate(); } } // #enddocregion CameraDelegate // Stubs for the getLostData function. void _handleLostFiles(List<XFile> file) {} void _handleError(PlatformException? exception) {} // Stubs for MyCameraDelegate. Future<XFile?> _takeAPhoto(CameraDevice device) async => null; Future<XFile?> _takeAVideo(CameraDevice device) async => null;
packages/packages/image_picker/image_picker/example/lib/readme_excerpts.dart/0
{ "file_path": "packages/packages/image_picker/image_picker/example/lib/readme_excerpts.dart", "repo_id": "packages", "token_count": 982 }
970
## 0.8.9+4 * Minimizes scope of deprecation warning suppression to only the versions where it is required. * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates compileSdk version to 34. ## 0.8.9+3 * Bumps androidx.annotation:annotation from 1.7.0 to 1.7.1. ## 0.8.9+2 * Fixes new lint warnings. ## 0.8.9+1 * Updates plugin and example Gradle versions to 7.6.3. ## 0.8.9 * Fixes resizing bug and updates rounding to be more accurate. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 0.8.8+2 * Updates annotations lib to 1.7.0. ## 0.8.8+1 * Fixes NullPointerException on pre-Android 13 devices when using Android Photo Picker to pick image or video. ## 0.8.8 * Adds additional category II and III exif tags to be copied during photo resize. ## 0.8.7+5 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.8.7+4 * Updates the example to use the latest versions of the platform interface APIs. ## 0.8.7+3 * Bumps androidx.activity:activity from 1.7.1 to 1.7.2. ## 0.8.7+2 * Fixes a crash case when picking an image with a display name that does not contain a period. ## 0.8.7+1 * Bumps org.jetbrains.kotlin:kotlin-bom from 1.8.21 to 1.8.22. ## 0.8.7 * Adds `getMedia` method. ## 0.8.6+20 * Bumps androidx.activity:activity from 1.7.0 to 1.7.1. ## 0.8.6+19 * Bumps androidx.core:core from 1.9.0 to 1.10.1. ## 0.8.6+18 * Bumps org.jetbrains.kotlin:kotlin-bom from 1.8.10 to 1.8.21. ## 0.8.6+17 * Moves disk accesses to background thread. ## 0.8.6+16 * Fixes crashes caused by `SecurityException` when calling `getPathFromUri()`. ## 0.8.6+15 * Bumps androidx.activity:activity from 1.6.1 to 1.7.0. ## 0.8.6+14 * Fixes Java warnings. ## 0.8.6+13 * Fixes `BuildContext` handling in example. ## 0.8.6+12 * Improves image resizing performance by decoding Bitmap only when needed. ## 0.8.6+11 * Updates gradle to 7.6.1. * Updates gradle, AGP and fixes some lint errors. ## 0.8.6+10 * Offloads picker result handling to separate thread. ## 0.8.6+9 * Fixes compatibility with AGP versions older than 4.2. ## 0.8.6+8 * Adds a namespace for compatibility with AGP 8.0. ## 0.8.6+7 * Fixes handling of non-bitmap image types. * Updates minimum Flutter version to 3.3. ## 0.8.6+6 * Bumps androidx.core:core from 1.8.0 to 1.9.0. ## 0.8.6+5 * Fixes case when file extension returned from the OS does not match its real mime type. ## 0.8.6+4 * Bumps androidx.exifinterface:exifinterface from 1.3.3 to 1.3.6. ## 0.8.6+3 * Switches to Pigeon for internal implementation. ## 0.8.6+2 * Fixes null pointer exception in `saveResult`. ## 0.8.6+1 * Refactors code in preparation for adopting Pigeon. ## 0.8.6 * Adds `usePhotoPickerAndroid` options. ## 0.8.5+10 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 0.8.5+9 * Fixes compilation warnings. * Updates compileSdkVersion to 33. ## 0.8.5+8 * Adds Android 13 photo picker functionality if SDK version is at least 33. * Bumps compileSdkVersion from 31 to 33 ## 0.8.5+7 * Updates links for the merge of flutter/plugins into flutter/packages. ## 0.8.5+6 * Updates minimum Flutter version to 3.0. * Fixes names of picked files to match original filenames where possible. ## 0.8.5+5 * Updates code for stricter lint checks. ## 0.8.5+4 * Fixes null cast exception when restoring a cancelled selection. ## 0.8.5+3 * Updates minimum Flutter version to 2.10. * Bumps gradle from 7.1.2 to 7.2.1. ## 0.8.5+2 * Updates `image_picker_platform_interface` constraint to the correct minimum version. ## 0.8.5+1 * Switches to an internal method channel implementation. ## 0.8.5 * Updates gradle to 7.1.2. ## 0.8.4+13 * Minor fixes for new analysis options. ## 0.8.4+12 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.8.4+11 * Splits from `image_picker` as a federated implementation.
packages/packages/image_picker/image_picker_android/CHANGELOG.md/0
{ "file_path": "packages/packages/image_picker/image_picker_android/CHANGELOG.md", "repo_id": "packages", "token_count": 1500 }
971
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v9.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.imagepicker; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class Messages { /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { /** The error code. */ public final String code; /** The error details. Must be a datatype supported by the api codec. */ public final Object details; public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { super(message); this.code = code; this.details = details; } } @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { ArrayList<Object> errorList = new ArrayList<Object>(3); if (exception instanceof FlutterError) { FlutterError error = (FlutterError) exception; errorList.add(error.code); errorList.add(error.getMessage()); errorList.add(error.details); } else { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); } return errorList; } public enum SourceCamera { REAR(0), FRONT(1); final int index; private SourceCamera(final int index) { this.index = index; } } public enum SourceType { CAMERA(0), GALLERY(1); final int index; private SourceType(final int index) { this.index = index; } } public enum CacheRetrievalType { IMAGE(0), VIDEO(1); final int index; private CacheRetrievalType(final int index) { this.index = index; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class GeneralOptions { private @NonNull Boolean allowMultiple; public @NonNull Boolean getAllowMultiple() { return allowMultiple; } public void setAllowMultiple(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"allowMultiple\" is null."); } this.allowMultiple = setterArg; } private @NonNull Boolean usePhotoPicker; public @NonNull Boolean getUsePhotoPicker() { return usePhotoPicker; } public void setUsePhotoPicker(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"usePhotoPicker\" is null."); } this.usePhotoPicker = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ GeneralOptions() {} public static final class Builder { private @Nullable Boolean allowMultiple; public @NonNull Builder setAllowMultiple(@NonNull Boolean setterArg) { this.allowMultiple = setterArg; return this; } private @Nullable Boolean usePhotoPicker; public @NonNull Builder setUsePhotoPicker(@NonNull Boolean setterArg) { this.usePhotoPicker = setterArg; return this; } public @NonNull GeneralOptions build() { GeneralOptions pigeonReturn = new GeneralOptions(); pigeonReturn.setAllowMultiple(allowMultiple); pigeonReturn.setUsePhotoPicker(usePhotoPicker); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(allowMultiple); toListResult.add(usePhotoPicker); return toListResult; } static @NonNull GeneralOptions fromList(@NonNull ArrayList<Object> list) { GeneralOptions pigeonResult = new GeneralOptions(); Object allowMultiple = list.get(0); pigeonResult.setAllowMultiple((Boolean) allowMultiple); Object usePhotoPicker = list.get(1); pigeonResult.setUsePhotoPicker((Boolean) usePhotoPicker); return pigeonResult; } } /** * Options for image selection and output. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class ImageSelectionOptions { /** If set, the max width that the image should be resized to fit in. */ private @Nullable Double maxWidth; public @Nullable Double getMaxWidth() { return maxWidth; } public void setMaxWidth(@Nullable Double setterArg) { this.maxWidth = setterArg; } /** If set, the max height that the image should be resized to fit in. */ private @Nullable Double maxHeight; public @Nullable Double getMaxHeight() { return maxHeight; } public void setMaxHeight(@Nullable Double setterArg) { this.maxHeight = setterArg; } /** * The quality of the output image, from 0-100. * * <p>100 indicates original quality. */ private @NonNull Long quality; public @NonNull Long getQuality() { return quality; } public void setQuality(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"quality\" is null."); } this.quality = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ ImageSelectionOptions() {} public static final class Builder { private @Nullable Double maxWidth; public @NonNull Builder setMaxWidth(@Nullable Double setterArg) { this.maxWidth = setterArg; return this; } private @Nullable Double maxHeight; public @NonNull Builder setMaxHeight(@Nullable Double setterArg) { this.maxHeight = setterArg; return this; } private @Nullable Long quality; public @NonNull Builder setQuality(@NonNull Long setterArg) { this.quality = setterArg; return this; } public @NonNull ImageSelectionOptions build() { ImageSelectionOptions pigeonReturn = new ImageSelectionOptions(); pigeonReturn.setMaxWidth(maxWidth); pigeonReturn.setMaxHeight(maxHeight); pigeonReturn.setQuality(quality); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(3); toListResult.add(maxWidth); toListResult.add(maxHeight); toListResult.add(quality); return toListResult; } static @NonNull ImageSelectionOptions fromList(@NonNull ArrayList<Object> list) { ImageSelectionOptions pigeonResult = new ImageSelectionOptions(); Object maxWidth = list.get(0); pigeonResult.setMaxWidth((Double) maxWidth); Object maxHeight = list.get(1); pigeonResult.setMaxHeight((Double) maxHeight); Object quality = list.get(2); pigeonResult.setQuality( (quality == null) ? null : ((quality instanceof Integer) ? (Integer) quality : (Long) quality)); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class MediaSelectionOptions { private @NonNull ImageSelectionOptions imageSelectionOptions; public @NonNull ImageSelectionOptions getImageSelectionOptions() { return imageSelectionOptions; } public void setImageSelectionOptions(@NonNull ImageSelectionOptions setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"imageSelectionOptions\" is null."); } this.imageSelectionOptions = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ MediaSelectionOptions() {} public static final class Builder { private @Nullable ImageSelectionOptions imageSelectionOptions; public @NonNull Builder setImageSelectionOptions(@NonNull ImageSelectionOptions setterArg) { this.imageSelectionOptions = setterArg; return this; } public @NonNull MediaSelectionOptions build() { MediaSelectionOptions pigeonReturn = new MediaSelectionOptions(); pigeonReturn.setImageSelectionOptions(imageSelectionOptions); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add((imageSelectionOptions == null) ? null : imageSelectionOptions.toList()); return toListResult; } static @NonNull MediaSelectionOptions fromList(@NonNull ArrayList<Object> list) { MediaSelectionOptions pigeonResult = new MediaSelectionOptions(); Object imageSelectionOptions = list.get(0); pigeonResult.setImageSelectionOptions( (imageSelectionOptions == null) ? null : ImageSelectionOptions.fromList((ArrayList<Object>) imageSelectionOptions)); return pigeonResult; } } /** * Options for image selection and output. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class VideoSelectionOptions { /** The maximum desired length for the video, in seconds. */ private @Nullable Long maxDurationSeconds; public @Nullable Long getMaxDurationSeconds() { return maxDurationSeconds; } public void setMaxDurationSeconds(@Nullable Long setterArg) { this.maxDurationSeconds = setterArg; } public static final class Builder { private @Nullable Long maxDurationSeconds; public @NonNull Builder setMaxDurationSeconds(@Nullable Long setterArg) { this.maxDurationSeconds = setterArg; return this; } public @NonNull VideoSelectionOptions build() { VideoSelectionOptions pigeonReturn = new VideoSelectionOptions(); pigeonReturn.setMaxDurationSeconds(maxDurationSeconds); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add(maxDurationSeconds); return toListResult; } static @NonNull VideoSelectionOptions fromList(@NonNull ArrayList<Object> list) { VideoSelectionOptions pigeonResult = new VideoSelectionOptions(); Object maxDurationSeconds = list.get(0); pigeonResult.setMaxDurationSeconds( (maxDurationSeconds == null) ? null : ((maxDurationSeconds instanceof Integer) ? (Integer) maxDurationSeconds : (Long) maxDurationSeconds)); return pigeonResult; } } /** * Specification for the source of an image or video selection. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class SourceSpecification { private @NonNull SourceType type; public @NonNull SourceType getType() { return type; } public void setType(@NonNull SourceType setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"type\" is null."); } this.type = setterArg; } private @Nullable SourceCamera camera; public @Nullable SourceCamera getCamera() { return camera; } public void setCamera(@Nullable SourceCamera setterArg) { this.camera = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ SourceSpecification() {} public static final class Builder { private @Nullable SourceType type; public @NonNull Builder setType(@NonNull SourceType setterArg) { this.type = setterArg; return this; } private @Nullable SourceCamera camera; public @NonNull Builder setCamera(@Nullable SourceCamera setterArg) { this.camera = setterArg; return this; } public @NonNull SourceSpecification build() { SourceSpecification pigeonReturn = new SourceSpecification(); pigeonReturn.setType(type); pigeonReturn.setCamera(camera); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(type == null ? null : type.index); toListResult.add(camera == null ? null : camera.index); return toListResult; } static @NonNull SourceSpecification fromList(@NonNull ArrayList<Object> list) { SourceSpecification pigeonResult = new SourceSpecification(); Object type = list.get(0); pigeonResult.setType(type == null ? null : SourceType.values()[(int) type]); Object camera = list.get(1); pigeonResult.setCamera(camera == null ? null : SourceCamera.values()[(int) camera]); return pigeonResult; } } /** * An error that occurred during lost result retrieval. * * <p>The data here maps to the `PlatformException` that will be created from it. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class CacheRetrievalError { private @NonNull String code; public @NonNull String getCode() { return code; } public void setCode(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"code\" is null."); } this.code = setterArg; } private @Nullable String message; public @Nullable String getMessage() { return message; } public void setMessage(@Nullable String setterArg) { this.message = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ CacheRetrievalError() {} public static final class Builder { private @Nullable String code; public @NonNull Builder setCode(@NonNull String setterArg) { this.code = setterArg; return this; } private @Nullable String message; public @NonNull Builder setMessage(@Nullable String setterArg) { this.message = setterArg; return this; } public @NonNull CacheRetrievalError build() { CacheRetrievalError pigeonReturn = new CacheRetrievalError(); pigeonReturn.setCode(code); pigeonReturn.setMessage(message); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(code); toListResult.add(message); return toListResult; } static @NonNull CacheRetrievalError fromList(@NonNull ArrayList<Object> list) { CacheRetrievalError pigeonResult = new CacheRetrievalError(); Object code = list.get(0); pigeonResult.setCode((String) code); Object message = list.get(1); pigeonResult.setMessage((String) message); return pigeonResult; } } /** * The result of retrieving cached results from a previous run. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class CacheRetrievalResult { /** The type of the retrieved data. */ private @NonNull CacheRetrievalType type; public @NonNull CacheRetrievalType getType() { return type; } public void setType(@NonNull CacheRetrievalType setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"type\" is null."); } this.type = setterArg; } /** The error from the last selection, if any. */ private @Nullable CacheRetrievalError error; public @Nullable CacheRetrievalError getError() { return error; } public void setError(@Nullable CacheRetrievalError setterArg) { this.error = setterArg; } /** * The results from the last selection, if any. * * <p>Elements must not be null, by convention. See * https://github.com/flutter/flutter/issues/97848 */ private @NonNull List<String> paths; public @NonNull List<String> getPaths() { return paths; } public void setPaths(@NonNull List<String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"paths\" is null."); } this.paths = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ CacheRetrievalResult() {} public static final class Builder { private @Nullable CacheRetrievalType type; public @NonNull Builder setType(@NonNull CacheRetrievalType setterArg) { this.type = setterArg; return this; } private @Nullable CacheRetrievalError error; public @NonNull Builder setError(@Nullable CacheRetrievalError setterArg) { this.error = setterArg; return this; } private @Nullable List<String> paths; public @NonNull Builder setPaths(@NonNull List<String> setterArg) { this.paths = setterArg; return this; } public @NonNull CacheRetrievalResult build() { CacheRetrievalResult pigeonReturn = new CacheRetrievalResult(); pigeonReturn.setType(type); pigeonReturn.setError(error); pigeonReturn.setPaths(paths); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(3); toListResult.add(type == null ? null : type.index); toListResult.add((error == null) ? null : error.toList()); toListResult.add(paths); return toListResult; } static @NonNull CacheRetrievalResult fromList(@NonNull ArrayList<Object> list) { CacheRetrievalResult pigeonResult = new CacheRetrievalResult(); Object type = list.get(0); pigeonResult.setType(type == null ? null : CacheRetrievalType.values()[(int) type]); Object error = list.get(1); pigeonResult.setError( (error == null) ? null : CacheRetrievalError.fromList((ArrayList<Object>) error)); Object paths = list.get(2); pigeonResult.setPaths((List<String>) paths); return pigeonResult; } } public interface Result<T> { @SuppressWarnings("UnknownNullness") void success(T result); void error(@NonNull Throwable error); } private static class ImagePickerApiCodec extends StandardMessageCodec { public static final ImagePickerApiCodec INSTANCE = new ImagePickerApiCodec(); private ImagePickerApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return CacheRetrievalError.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return CacheRetrievalResult.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 130: return GeneralOptions.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 131: return ImageSelectionOptions.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 132: return MediaSelectionOptions.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 133: return SourceSpecification.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 134: return VideoSelectionOptions.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof CacheRetrievalError) { stream.write(128); writeValue(stream, ((CacheRetrievalError) value).toList()); } else if (value instanceof CacheRetrievalResult) { stream.write(129); writeValue(stream, ((CacheRetrievalResult) value).toList()); } else if (value instanceof GeneralOptions) { stream.write(130); writeValue(stream, ((GeneralOptions) value).toList()); } else if (value instanceof ImageSelectionOptions) { stream.write(131); writeValue(stream, ((ImageSelectionOptions) value).toList()); } else if (value instanceof MediaSelectionOptions) { stream.write(132); writeValue(stream, ((MediaSelectionOptions) value).toList()); } else if (value instanceof SourceSpecification) { stream.write(133); writeValue(stream, ((SourceSpecification) value).toList()); } else if (value instanceof VideoSelectionOptions) { stream.write(134); writeValue(stream, ((VideoSelectionOptions) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface ImagePickerApi { /** * Selects images and returns their paths. * * <p>Elements must not be null, by convention. See * https://github.com/flutter/flutter/issues/97848 */ void pickImages( @NonNull SourceSpecification source, @NonNull ImageSelectionOptions options, @NonNull GeneralOptions generalOptions, @NonNull Result<List<String>> result); /** * Selects video and returns their paths. * * <p>Elements must not be null, by convention. See * https://github.com/flutter/flutter/issues/97848 */ void pickVideos( @NonNull SourceSpecification source, @NonNull VideoSelectionOptions options, @NonNull GeneralOptions generalOptions, @NonNull Result<List<String>> result); /** * Selects images and videos and returns their paths. * * <p>Elements must not be null, by convention. See * https://github.com/flutter/flutter/issues/97848 */ void pickMedia( @NonNull MediaSelectionOptions mediaSelectionOptions, @NonNull GeneralOptions generalOptions, @NonNull Result<List<String>> result); /** Returns results from a previous app session, if any. */ @Nullable CacheRetrievalResult retrieveLostResults(); /** The codec used by ImagePickerApi. */ static @NonNull MessageCodec<Object> getCodec() { return ImagePickerApiCodec.INSTANCE; } /** Sets up an instance of `ImagePickerApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable ImagePickerApi api) { { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ImagePickerApi.pickImages", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; SourceSpecification sourceArg = (SourceSpecification) args.get(0); ImageSelectionOptions optionsArg = (ImageSelectionOptions) args.get(1); GeneralOptions generalOptionsArg = (GeneralOptions) args.get(2); Result<List<String>> resultCallback = new Result<List<String>>() { public void success(List<String> result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.pickImages(sourceArg, optionsArg, generalOptionsArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ImagePickerApi.pickVideos", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; SourceSpecification sourceArg = (SourceSpecification) args.get(0); VideoSelectionOptions optionsArg = (VideoSelectionOptions) args.get(1); GeneralOptions generalOptionsArg = (GeneralOptions) args.get(2); Result<List<String>> resultCallback = new Result<List<String>>() { public void success(List<String> result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.pickVideos(sourceArg, optionsArg, generalOptionsArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ImagePickerApi.pickMedia", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; MediaSelectionOptions mediaSelectionOptionsArg = (MediaSelectionOptions) args.get(0); GeneralOptions generalOptionsArg = (GeneralOptions) args.get(1); Result<List<String>> resultCallback = new Result<List<String>>() { public void success(List<String> result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.pickMedia(mediaSelectionOptionsArg, generalOptionsArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ImagePickerApi.retrieveLostResults", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { CacheRetrievalResult output = api.retrieveLostResults(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } }
packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/Messages.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/Messages.java", "repo_id": "packages", "token_count": 11198 }
972
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ImagePickerTestImages.h" @import image_picker_ios; @import image_picker_ios.Test; @import XCTest; @interface PhotoAssetUtilTests : XCTestCase @end @implementation PhotoAssetUtilTests - (void)getAssetFromImagePickerInfoShouldReturnNilIfNotAvailable { NSDictionary *mockData = @{}; XCTAssertNil([FLTImagePickerPhotoAssetUtil getAssetFromImagePickerInfo:mockData]); } - (void)testGetAssetFromPHPickerResultShouldReturnNilIfNotAvailable API_AVAILABLE(ios(14)) { if (@available(iOS 14, *)) { PHPickerResult *mockData; [mockData.itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(__kindof id<NSItemProviderReading> _Nullable image, NSError *_Nullable error) { XCTAssertNil([FLTImagePickerPhotoAssetUtil getAssetFromPHPickerResult:mockData]); }]; } } - (void)testSaveImageWithOriginalImageData_ShouldSaveWithTheCorrectExtentionAndMetaData { // test jpg NSData *dataJPG = ImagePickerTestImages.JPGTestData; UIImage *imageJPG = [UIImage imageWithData:dataJPG]; NSString *savedPathJPG = [FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:dataJPG image:imageJPG maxWidth:nil maxHeight:nil imageQuality:nil]; XCTAssertEqualObjects([NSURL URLWithString:savedPathJPG].pathExtension, @"jpg"); NSDictionary *originalMetaDataJPG = [FLTImagePickerMetaDataUtil getMetaDataFromImageData:dataJPG]; NSData *newDataJPG = [NSData dataWithContentsOfFile:savedPathJPG]; NSDictionary *newMetaDataJPG = [FLTImagePickerMetaDataUtil getMetaDataFromImageData:newDataJPG]; XCTAssertEqualObjects(originalMetaDataJPG[@"ProfileName"], newMetaDataJPG[@"ProfileName"]); // test png NSData *dataPNG = ImagePickerTestImages.PNGTestData; UIImage *imagePNG = [UIImage imageWithData:dataPNG]; NSString *savedPathPNG = [FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:dataPNG image:imagePNG maxWidth:nil maxHeight:nil imageQuality:nil]; XCTAssertEqualObjects([NSURL URLWithString:savedPathPNG].pathExtension, @"png"); NSDictionary *originalMetaDataPNG = [FLTImagePickerMetaDataUtil getMetaDataFromImageData:dataPNG]; NSData *newDataPNG = [NSData dataWithContentsOfFile:savedPathPNG]; NSDictionary *newMetaDataPNG = [FLTImagePickerMetaDataUtil getMetaDataFromImageData:newDataPNG]; XCTAssertEqualObjects(originalMetaDataPNG[@"ProfileName"], newMetaDataPNG[@"ProfileName"]); } - (void)testSaveImageWithPickerInfo_ShouldSaveWithDefaultExtention { UIImage *imageJPG = [UIImage imageWithData:ImagePickerTestImages.JPGTestData]; NSString *savedPathJPG = [FLTImagePickerPhotoAssetUtil saveImageWithPickerInfo:nil image:imageJPG imageQuality:nil]; // should be saved as XCTAssertEqualObjects([savedPathJPG substringFromIndex:savedPathJPG.length - 4], kFLTImagePickerDefaultSuffix); } - (void)testSaveImageWithPickerInfo_ShouldSaveWithTheCorrectExtentionAndMetaData { NSDictionary *dummyInfo = @{ UIImagePickerControllerMediaMetadata : @{ (__bridge NSString *)kCGImagePropertyExifDictionary : @{(__bridge NSString *)kCGImagePropertyExifUserComment : @"aNote"} } }; UIImage *imageJPG = [UIImage imageWithData:ImagePickerTestImages.JPGTestData]; NSString *savedPathJPG = [FLTImagePickerPhotoAssetUtil saveImageWithPickerInfo:dummyInfo image:imageJPG imageQuality:nil]; NSData *data = [NSData dataWithContentsOfFile:savedPathJPG]; NSDictionary *meta = [FLTImagePickerMetaDataUtil getMetaDataFromImageData:data]; XCTAssertEqualObjects(meta[(__bridge NSString *)kCGImagePropertyExifDictionary] [(__bridge NSString *)kCGImagePropertyExifUserComment], @"aNote"); } - (void)testSaveImageWithOriginalImageData_ShouldSaveAsGifAnimation { // test gif NSData *dataGIF = ImagePickerTestImages.GIFTestData; UIImage *imageGIF = [UIImage imageWithData:dataGIF]; CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)dataGIF, nil); size_t numberOfFrames = CGImageSourceGetCount(imageSource); NSString *savedPathGIF = [FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:dataGIF image:imageGIF maxWidth:nil maxHeight:nil imageQuality:nil]; XCTAssertEqualObjects([NSURL URLWithString:savedPathGIF].pathExtension, @"gif"); NSData *newDataGIF = [NSData dataWithContentsOfFile:savedPathGIF]; CGImageSourceRef newImageSource = CGImageSourceCreateWithData((__bridge CFDataRef)newDataGIF, nil); size_t newNumberOfFrames = CGImageSourceGetCount(newImageSource); XCTAssertEqual(numberOfFrames, newNumberOfFrames); } - (void)testSaveImageWithOriginalImageData_ShouldSaveAsScalledGifAnimation { // test gif NSData *dataGIF = ImagePickerTestImages.GIFTestData; UIImage *imageGIF = [UIImage imageWithData:dataGIF]; CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)dataGIF, nil); size_t numberOfFrames = CGImageSourceGetCount(imageSource); NSString *savedPathGIF = [FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:dataGIF image:imageGIF maxWidth:@3 maxHeight:@2 imageQuality:nil]; NSData *newDataGIF = [NSData dataWithContentsOfFile:savedPathGIF]; UIImage *newImage = [[UIImage alloc] initWithData:newDataGIF]; XCTAssertEqual(newImage.size.width, 3); XCTAssertEqual(newImage.size.height, 2); CGImageSourceRef newImageSource = CGImageSourceCreateWithData((__bridge CFDataRef)newDataGIF, nil); size_t newNumberOfFrames = CGImageSourceGetCount(newImageSource); XCTAssertEqual(numberOfFrames, newNumberOfFrames); } @end
packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/PhotoAssetUtilTests.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/PhotoAssetUtilTests.m", "repo_id": "packages", "token_count": 3572 }
973
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> #import "FLTPHPickerSaveImageToPathOperation.h" #import <os/log.h> API_AVAILABLE(ios(14)) @interface FLTPHPickerSaveImageToPathOperation () @property(strong, nonatomic) PHPickerResult *result; @property(strong, nonatomic) NSNumber *maxHeight; @property(strong, nonatomic) NSNumber *maxWidth; @property(strong, nonatomic) NSNumber *desiredImageQuality; @property(assign, nonatomic) BOOL requestFullMetadata; @end @implementation FLTPHPickerSaveImageToPathOperation { BOOL executing; BOOL finished; FLTGetSavedPath getSavedPath; } - (instancetype)initWithResult:(PHPickerResult *)result maxHeight:(NSNumber *)maxHeight maxWidth:(NSNumber *)maxWidth desiredImageQuality:(NSNumber *)desiredImageQuality fullMetadata:(BOOL)fullMetadata savedPathBlock:(FLTGetSavedPath)savedPathBlock API_AVAILABLE(ios(14)) { if (self = [super init]) { if (result) { self.result = result; self.maxHeight = maxHeight; self.maxWidth = maxWidth; self.desiredImageQuality = desiredImageQuality; self.requestFullMetadata = fullMetadata; getSavedPath = savedPathBlock; executing = NO; finished = NO; } else { return nil; } return self; } else { return nil; } } - (BOOL)isConcurrent { return YES; } - (BOOL)isExecuting { return executing; } - (BOOL)isFinished { return finished; } - (void)setFinished:(BOOL)isFinished { [self willChangeValueForKey:@"isFinished"]; self->finished = isFinished; [self didChangeValueForKey:@"isFinished"]; } - (void)setExecuting:(BOOL)isExecuting { [self willChangeValueForKey:@"isExecuting"]; self->executing = isExecuting; [self didChangeValueForKey:@"isExecuting"]; } - (void)completeOperationWithPath:(NSString *)savedPath error:(FlutterError *)error { getSavedPath(savedPath, error); [self setExecuting:NO]; [self setFinished:YES]; } - (void)start { if ([self isCancelled]) { [self setFinished:YES]; return; } if (@available(iOS 14, *)) { [self setExecuting:YES]; // This supports uniform types that conform to UTTypeImage. // This includes UTTypeHEIC, UTTypeHEIF, UTTypeLivePhoto, UTTypeICO, UTTypeICNS, UTTypePNG // UTTypeGIF, UTTypeJPEG, UTTypeWebP, UTTypeTIFF, UTTypeBMP, UTTypeSVG, UTTypeRAWImage if ([self.result.itemProvider hasItemConformingToTypeIdentifier:UTTypeImage.identifier]) { [self.result.itemProvider loadDataRepresentationForTypeIdentifier:UTTypeImage.identifier completionHandler:^(NSData *_Nullable data, NSError *_Nullable error) { if (data != nil) { [self processImage:data]; } else { FlutterError *flutterError = [FlutterError errorWithCode:@"invalid_image" message:error.localizedDescription details:error.domain]; [self completeOperationWithPath:nil error:flutterError]; } }]; } else if ([self.result.itemProvider // This supports uniform types that conform to UTTypeMovie. // This includes kUTTypeVideo, kUTTypeMPEG4, public.3gpp, kUTTypeMPEG, // public.3gpp2, public.avi, kUTTypeQuickTimeMovie. hasItemConformingToTypeIdentifier:UTTypeMovie.identifier]) { [self processVideo]; } else { FlutterError *flutterError = [FlutterError errorWithCode:@"invalid_source" message:@"Invalid media source." details:nil]; [self completeOperationWithPath:nil error:flutterError]; } } else { [self setFinished:YES]; } } /// Processes the image. - (void)processImage:(NSData *)pickerImageData API_AVAILABLE(ios(14)) { UIImage *localImage = [[UIImage alloc] initWithData:pickerImageData]; PHAsset *originalAsset; // Only if requested, fetch the full "PHAsset" metadata, which requires "Photo Library Usage" // permissions. if (self.requestFullMetadata) { originalAsset = [FLTImagePickerPhotoAssetUtil getAssetFromPHPickerResult:self.result]; } if (self.maxWidth != nil || self.maxHeight != nil) { localImage = [FLTImagePickerImageUtil scaledImage:localImage maxWidth:self.maxWidth maxHeight:self.maxHeight isMetadataAvailable:YES]; } if (originalAsset) { void (^resultHandler)(NSData *imageData, NSString *dataUTI, NSDictionary *info) = ^(NSData *_Nullable imageData, NSString *_Nullable dataUTI, NSDictionary *_Nullable info) { // maxWidth and maxHeight are used only for GIF images. NSString *savedPath = [FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:imageData image:localImage maxWidth:self.maxWidth maxHeight:self.maxHeight imageQuality:self.desiredImageQuality]; [self completeOperationWithPath:savedPath error:nil]; }; if (@available(iOS 13.0, *)) { [[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:originalAsset options:nil resultHandler:^(NSData *_Nullable imageData, NSString *_Nullable dataUTI, CGImagePropertyOrientation orientation, NSDictionary *_Nullable info) { resultHandler(imageData, dataUTI, info); }]; } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" [[PHImageManager defaultManager] requestImageDataForAsset:originalAsset options:nil resultHandler:^(NSData *_Nullable imageData, NSString *_Nullable dataUTI, UIImageOrientation orientation, NSDictionary *_Nullable info) { resultHandler(imageData, dataUTI, info); }]; #pragma clang diagnostic pop } } else { // Image picked without an original asset (e.g. User pick image without permission) // maxWidth and maxHeight are used only for GIF images. NSString *savedPath = [FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:pickerImageData image:localImage maxWidth:self.maxWidth maxHeight:self.maxHeight imageQuality:self.desiredImageQuality]; [self completeOperationWithPath:savedPath error:nil]; } } /// Processes the video. - (void)processVideo API_AVAILABLE(ios(14)) { NSString *typeIdentifier = self.result.itemProvider.registeredTypeIdentifiers.firstObject; [self.result.itemProvider loadFileRepresentationForTypeIdentifier:typeIdentifier completionHandler:^(NSURL *_Nullable videoURL, NSError *_Nullable error) { if (error != nil) { FlutterError *flutterError = [FlutterError errorWithCode:@"invalid_image" message:error.localizedDescription details:error.domain]; [self completeOperationWithPath:nil error:flutterError]; return; } NSURL *destination = [FLTImagePickerPhotoAssetUtil saveVideoFromURL:videoURL]; if (destination == nil) { [self completeOperationWithPath:nil error:[FlutterError errorWithCode: @"flutter_image_picker_copy_" @"video_error" message:@"Could not cache " @"the video file." details:nil]]; return; } [self completeOperationWithPath:[destination path] error:nil]; }]; } @end
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTPHPickerSaveImageToPathOperation.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTPHPickerSaveImageToPathOperation.m", "repo_id": "packages", "token_count": 5175 }
974
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.inapppurchase; import static io.flutter.plugins.inapppurchase.Translator.fromAlternativeBillingOnlyReportingDetails; import static io.flutter.plugins.inapppurchase.Translator.fromBillingConfig; import static io.flutter.plugins.inapppurchase.Translator.fromBillingResult; import static io.flutter.plugins.inapppurchase.Translator.fromProductDetailsList; import static io.flutter.plugins.inapppurchase.Translator.fromPurchaseHistoryRecordList; import static io.flutter.plugins.inapppurchase.Translator.fromPurchasesList; import static io.flutter.plugins.inapppurchase.Translator.fromUserChoiceDetails; import static io.flutter.plugins.inapppurchase.Translator.toProductList; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.android.billingclient.api.AcknowledgePurchaseParams; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.BillingClientStateListener; import com.android.billingclient.api.BillingFlowParams; import com.android.billingclient.api.BillingResult; import com.android.billingclient.api.ConsumeParams; import com.android.billingclient.api.ConsumeResponseListener; import com.android.billingclient.api.GetBillingConfigParams; import com.android.billingclient.api.ProductDetails; import com.android.billingclient.api.QueryProductDetailsParams; import com.android.billingclient.api.QueryProductDetailsParams.Product; import com.android.billingclient.api.QueryPurchaseHistoryParams; import com.android.billingclient.api.QueryPurchasesParams; import com.android.billingclient.api.UserChoiceBillingListener; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** Handles method channel for the plugin. */ class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler, Application.ActivityLifecycleCallbacks { @VisibleForTesting static final class MethodNames { static final String IS_READY = "BillingClient#isReady()"; static final String START_CONNECTION = "BillingClient#startConnection(BillingClientStateListener)"; static final String END_CONNECTION = "BillingClient#endConnection()"; static final String ON_DISCONNECT = "BillingClientStateListener#onBillingServiceDisconnected()"; static final String QUERY_PRODUCT_DETAILS = "BillingClient#queryProductDetailsAsync(QueryProductDetailsParams, ProductDetailsResponseListener)"; static final String LAUNCH_BILLING_FLOW = "BillingClient#launchBillingFlow(Activity, BillingFlowParams)"; static final String QUERY_PURCHASES_ASYNC = "BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener)"; static final String QUERY_PURCHASE_HISTORY_ASYNC = "BillingClient#queryPurchaseHistoryAsync(QueryPurchaseHistoryParams, PurchaseHistoryResponseListener)"; static final String CONSUME_PURCHASE_ASYNC = "BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)"; static final String ACKNOWLEDGE_PURCHASE = "BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)"; static final String IS_FEATURE_SUPPORTED = "BillingClient#isFeatureSupported(String)"; static final String GET_CONNECTION_STATE = "BillingClient#getConnectionState()"; static final String GET_BILLING_CONFIG = "BillingClient#getBillingConfig()"; static final String IS_ALTERNATIVE_BILLING_ONLY_AVAILABLE = "BillingClient#isAlternativeBillingOnlyAvailable()"; static final String CREATE_ALTERNATIVE_BILLING_ONLY_REPORTING_DETAILS = "BillingClient#createAlternativeBillingOnlyReportingDetails()"; static final String SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG = "BillingClient#showAlternativeBillingOnlyInformationDialog()"; static final String USER_SELECTED_ALTERNATIVE_BILLING = "UserChoiceBillingListener#userSelectedAlternativeBilling(UserChoiceDetails)"; private MethodNames() {} } @VisibleForTesting static final class MethodArgs { // Key for an int argument passed into startConnection static final String HANDLE = "handle"; // Key for a boolean argument passed into startConnection. static final String BILLING_CHOICE_MODE = "billingChoiceMode"; private MethodArgs() {} } /** * Values here must match values used in * in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart */ static final class BillingChoiceMode { static final int PLAY_BILLING_ONLY = 0; static final int ALTERNATIVE_BILLING_ONLY = 1; static final int USER_CHOICE_BILLING = 2; } // TODO(gmackall): Replace uses of deprecated ProrationMode enum values with new // ReplacementMode enum values. // https://github.com/flutter/flutter/issues/128957. @SuppressWarnings(value = "deprecation") private static final int PRORATION_MODE_UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY = com.android.billingclient.api.BillingFlowParams.ProrationMode .UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY; private static final String TAG = "InAppPurchasePlugin"; private static final String LOAD_PRODUCT_DOC_URL = "https://github.com/flutter/packages/blob/main/packages/in_app_purchase/in_app_purchase/README.md#loading-products-for-sale"; @VisibleForTesting static final String ACTIVITY_UNAVAILABLE = "ACTIVITY_UNAVAILABLE"; @Nullable private BillingClient billingClient; private final BillingClientFactory billingClientFactory; @Nullable private Activity activity; private final Context applicationContext; final MethodChannel methodChannel; private final HashMap<String, ProductDetails> cachedProducts = new HashMap<>(); /** Constructs the MethodCallHandlerImpl */ MethodCallHandlerImpl( @Nullable Activity activity, @NonNull Context applicationContext, @NonNull MethodChannel methodChannel, @NonNull BillingClientFactory billingClientFactory) { this.billingClientFactory = billingClientFactory; this.applicationContext = applicationContext; this.activity = activity; this.methodChannel = methodChannel; } /** * Sets the activity. Should be called as soon as the the activity is available. When the activity * becomes unavailable, call this method again with {@code null}. */ void setActivity(@Nullable Activity activity) { this.activity = activity; } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {} @Override public void onActivityStarted(Activity activity) {} @Override public void onActivityResumed(Activity activity) {} @Override public void onActivityPaused(Activity activity) {} @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {} @Override public void onActivityDestroyed(Activity activity) { if (this.activity == activity && this.applicationContext != null) { ((Application) this.applicationContext).unregisterActivityLifecycleCallbacks(this); endBillingClientConnection(); } } @Override public void onActivityStopped(Activity activity) {} void onDetachedFromActivity() { endBillingClientConnection(); } @Override public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { switch (call.method) { case MethodNames.IS_READY: isReady(result); break; case MethodNames.START_CONNECTION: final int handle = (int) call.argument(MethodArgs.HANDLE); int billingChoiceMode = BillingChoiceMode.PLAY_BILLING_ONLY; if (call.hasArgument(MethodArgs.BILLING_CHOICE_MODE)) { billingChoiceMode = call.argument(MethodArgs.BILLING_CHOICE_MODE); } startConnection(handle, result, billingChoiceMode); break; case MethodNames.END_CONNECTION: endConnection(result); break; case MethodNames.QUERY_PRODUCT_DETAILS: List<Product> productList = toProductList(call.argument("productList")); queryProductDetailsAsync(productList, result); break; case MethodNames.LAUNCH_BILLING_FLOW: launchBillingFlow( (String) call.argument("product"), (String) call.argument("offerToken"), (String) call.argument("accountId"), (String) call.argument("obfuscatedProfileId"), (String) call.argument("oldProduct"), (String) call.argument("purchaseToken"), call.hasArgument("prorationMode") ? (int) call.argument("prorationMode") : PRORATION_MODE_UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY, result); break; case MethodNames.QUERY_PURCHASES_ASYNC: queryPurchasesAsync((String) call.argument("productType"), result); break; case MethodNames.QUERY_PURCHASE_HISTORY_ASYNC: queryPurchaseHistoryAsync((String) call.argument("productType"), result); break; case MethodNames.CONSUME_PURCHASE_ASYNC: consumeAsync((String) call.argument("purchaseToken"), result); break; case MethodNames.ACKNOWLEDGE_PURCHASE: acknowledgePurchase((String) call.argument("purchaseToken"), result); break; case MethodNames.IS_FEATURE_SUPPORTED: isFeatureSupported((String) call.argument("feature"), result); break; case MethodNames.GET_CONNECTION_STATE: getConnectionState(result); break; case MethodNames.GET_BILLING_CONFIG: getBillingConfig(result); break; case MethodNames.IS_ALTERNATIVE_BILLING_ONLY_AVAILABLE: isAlternativeBillingOnlyAvailable(result); break; case MethodNames.CREATE_ALTERNATIVE_BILLING_ONLY_REPORTING_DETAILS: createAlternativeBillingOnlyReportingDetails(result); break; case MethodNames.SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG: showAlternativeBillingOnlyInformationDialog(result); break; default: result.notImplemented(); } } private void showAlternativeBillingOnlyInformationDialog(final MethodChannel.Result result) { if (billingClientError(result)) { return; } if (activity == null) { result.error(ACTIVITY_UNAVAILABLE, "Not attempting to show dialog", null); return; } billingClient.showAlternativeBillingOnlyInformationDialog( activity, billingResult -> { result.success(fromBillingResult(billingResult)); }); } private void createAlternativeBillingOnlyReportingDetails(final MethodChannel.Result result) { if (billingClientError(result)) { return; } billingClient.createAlternativeBillingOnlyReportingDetailsAsync( ((billingResult, alternativeBillingOnlyReportingDetails) -> { result.success( fromAlternativeBillingOnlyReportingDetails( billingResult, alternativeBillingOnlyReportingDetails)); })); } private void isAlternativeBillingOnlyAvailable(final MethodChannel.Result result) { if (billingClientError(result)) { return; } billingClient.isAlternativeBillingOnlyAvailableAsync( billingResult -> { result.success(fromBillingResult(billingResult)); }); } private void getBillingConfig(final MethodChannel.Result result) { if (billingClientError(result)) { return; } billingClient.getBillingConfigAsync( GetBillingConfigParams.newBuilder().build(), (billingResult, billingConfig) -> { result.success(fromBillingConfig(billingResult, billingConfig)); }); } private void endConnection(final MethodChannel.Result result) { endBillingClientConnection(); result.success(null); } private void endBillingClientConnection() { if (billingClient != null) { billingClient.endConnection(); billingClient = null; } } private void isReady(MethodChannel.Result result) { if (billingClientError(result)) { return; } result.success(billingClient.isReady()); } private void queryProductDetailsAsync( final List<Product> productList, final MethodChannel.Result result) { if (billingClientError(result)) { return; } QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder().setProductList(productList).build(); billingClient.queryProductDetailsAsync( params, (billingResult, productDetailsList) -> { updateCachedProducts(productDetailsList); final Map<String, Object> productDetailsResponse = new HashMap<>(); productDetailsResponse.put("billingResult", fromBillingResult(billingResult)); productDetailsResponse.put( "productDetailsList", fromProductDetailsList(productDetailsList)); result.success(productDetailsResponse); }); } private void launchBillingFlow( String product, @Nullable String offerToken, @Nullable String accountId, @Nullable String obfuscatedProfileId, @Nullable String oldProduct, @Nullable String purchaseToken, int prorationMode, MethodChannel.Result result) { if (billingClientError(result)) { return; } com.android.billingclient.api.ProductDetails productDetails = cachedProducts.get(product); if (productDetails == null) { result.error( "NOT_FOUND", "Details for product " + product + " are not available. It might because products were not fetched prior to the call. Please fetch the products first. An example of how to fetch the products could be found here: " + LOAD_PRODUCT_DOC_URL, null); return; } @Nullable List<ProductDetails.SubscriptionOfferDetails> subscriptionOfferDetails = productDetails.getSubscriptionOfferDetails(); if (subscriptionOfferDetails != null) { boolean isValidOfferToken = false; for (ProductDetails.SubscriptionOfferDetails offerDetails : subscriptionOfferDetails) { if (offerToken != null && offerToken.equals(offerDetails.getOfferToken())) { isValidOfferToken = true; break; } } if (!isValidOfferToken) { result.error( "INVALID_OFFER_TOKEN", "Offer token " + offerToken + " for product " + product + " is not valid. Make sure to only pass offer tokens that belong to the product. To obtain offer tokens for a product, fetch the products. An example of how to fetch the products could be found here: " + LOAD_PRODUCT_DOC_URL, null); return; } } if (oldProduct == null && prorationMode != PRORATION_MODE_UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY) { result.error( "IN_APP_PURCHASE_REQUIRE_OLD_PRODUCT", "launchBillingFlow failed because oldProduct is null. You must provide a valid oldProduct in order to use a proration mode.", null); return; } else if (oldProduct != null && !cachedProducts.containsKey(oldProduct)) { result.error( "IN_APP_PURCHASE_INVALID_OLD_PRODUCT", "Details for product " + oldProduct + " are not available. It might because products were not fetched prior to the call. Please fetch the products first. An example of how to fetch the products could be found here: " + LOAD_PRODUCT_DOC_URL, null); return; } if (activity == null) { result.error( ACTIVITY_UNAVAILABLE, "Details for product " + product + " are not available. This method must be run with the app in foreground.", null); return; } BillingFlowParams.ProductDetailsParams.Builder productDetailsParamsBuilder = BillingFlowParams.ProductDetailsParams.newBuilder(); productDetailsParamsBuilder.setProductDetails(productDetails); if (offerToken != null) { productDetailsParamsBuilder.setOfferToken(offerToken); } List<BillingFlowParams.ProductDetailsParams> productDetailsParamsList = new ArrayList<>(); productDetailsParamsList.add(productDetailsParamsBuilder.build()); BillingFlowParams.Builder paramsBuilder = BillingFlowParams.newBuilder().setProductDetailsParamsList(productDetailsParamsList); if (accountId != null && !accountId.isEmpty()) { paramsBuilder.setObfuscatedAccountId(accountId); } if (obfuscatedProfileId != null && !obfuscatedProfileId.isEmpty()) { paramsBuilder.setObfuscatedProfileId(obfuscatedProfileId); } BillingFlowParams.SubscriptionUpdateParams.Builder subscriptionUpdateParamsBuilder = BillingFlowParams.SubscriptionUpdateParams.newBuilder(); if (oldProduct != null && !oldProduct.isEmpty() && purchaseToken != null) { subscriptionUpdateParamsBuilder.setOldPurchaseToken(purchaseToken); // Set the prorationMode using a helper to minimize impact of deprecation warning suppression. setReplaceProrationMode(subscriptionUpdateParamsBuilder, prorationMode); paramsBuilder.setSubscriptionUpdateParams(subscriptionUpdateParamsBuilder.build()); } result.success( fromBillingResult(billingClient.launchBillingFlow(activity, paramsBuilder.build()))); } // TODO(gmackall): Replace uses of deprecated setReplaceProrationMode. // https://github.com/flutter/flutter/issues/128957. @SuppressWarnings(value = "deprecation") private void setReplaceProrationMode( BillingFlowParams.SubscriptionUpdateParams.Builder builder, int prorationMode) { // The proration mode value has to match one of the following declared in // https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode builder.setReplaceProrationMode(prorationMode); } private void consumeAsync(String purchaseToken, final MethodChannel.Result result) { if (billingClientError(result)) { return; } ConsumeResponseListener listener = (billingResult, outToken) -> result.success(fromBillingResult(billingResult)); ConsumeParams.Builder paramsBuilder = ConsumeParams.newBuilder().setPurchaseToken(purchaseToken); ConsumeParams params = paramsBuilder.build(); billingClient.consumeAsync(params, listener); } private void queryPurchasesAsync(String productType, MethodChannel.Result result) { if (billingClientError(result)) { return; } // Like in our connect call, consider the billing client responding a "success" here regardless // of status code. QueryPurchasesParams.Builder paramsBuilder = QueryPurchasesParams.newBuilder(); paramsBuilder.setProductType(productType); billingClient.queryPurchasesAsync( paramsBuilder.build(), (billingResult, purchasesList) -> { final Map<String, Object> serialized = new HashMap<>(); // The response code is no longer passed, as part of billing 4.0, so we pass OK here // as success is implied by calling this callback. serialized.put("responseCode", BillingClient.BillingResponseCode.OK); serialized.put("billingResult", fromBillingResult(billingResult)); serialized.put("purchasesList", fromPurchasesList(purchasesList)); result.success(serialized); }); } private void queryPurchaseHistoryAsync(String productType, final MethodChannel.Result result) { if (billingClientError(result)) { return; } billingClient.queryPurchaseHistoryAsync( QueryPurchaseHistoryParams.newBuilder().setProductType(productType).build(), (billingResult, purchasesList) -> { final Map<String, Object> serialized = new HashMap<>(); serialized.put("billingResult", fromBillingResult(billingResult)); serialized.put("purchaseHistoryRecordList", fromPurchaseHistoryRecordList(purchasesList)); result.success(serialized); }); } private void getConnectionState(final MethodChannel.Result result) { if (billingClientError(result)) { return; } final Map<String, Object> serialized = new HashMap<>(); serialized.put("connectionState", billingClient.getConnectionState()); result.success(serialized); } private void startConnection( final int handle, final MethodChannel.Result result, int billingChoiceMode) { if (billingClient == null) { UserChoiceBillingListener listener = getUserChoiceBillingListener(billingChoiceMode); billingClient = billingClientFactory.createBillingClient( applicationContext, methodChannel, billingChoiceMode, listener); } billingClient.startConnection( new BillingClientStateListener() { private boolean alreadyFinished = false; @Override public void onBillingSetupFinished(@NonNull BillingResult billingResult) { if (alreadyFinished) { Log.d(TAG, "Tried to call onBillingSetupFinished multiple times."); return; } alreadyFinished = true; // Consider the fact that we've finished a success, leave it to the Dart side to // validate the responseCode. result.success(fromBillingResult(billingResult)); } @Override public void onBillingServiceDisconnected() { final Map<String, Object> arguments = new HashMap<>(); arguments.put("handle", handle); methodChannel.invokeMethod(MethodNames.ON_DISCONNECT, arguments); } }); } @Nullable private UserChoiceBillingListener getUserChoiceBillingListener(int billingChoiceMode) { UserChoiceBillingListener listener = null; if (billingChoiceMode == BillingChoiceMode.USER_CHOICE_BILLING) { listener = userChoiceDetails -> { final Map<String, Object> arguments = fromUserChoiceDetails(userChoiceDetails); methodChannel.invokeMethod(MethodNames.USER_SELECTED_ALTERNATIVE_BILLING, arguments); }; } return listener; } private void acknowledgePurchase(String purchaseToken, final MethodChannel.Result result) { if (billingClientError(result)) { return; } AcknowledgePurchaseParams params = AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchaseToken).build(); billingClient.acknowledgePurchase( params, billingResult -> result.success(fromBillingResult(billingResult))); } protected void updateCachedProducts(@Nullable List<ProductDetails> productDetailsList) { if (productDetailsList == null) { return; } for (ProductDetails productDetails : productDetailsList) { cachedProducts.put(productDetails.getProductId(), productDetails); } } private boolean billingClientError(MethodChannel.Result result) { if (billingClient != null) { return false; } result.error("UNAVAILABLE", "BillingClient is unset. Try reconnecting.", null); return true; } private void isFeatureSupported(String feature, MethodChannel.Result result) { if (billingClientError(result)) { return; } assert billingClient != null; BillingResult billingResult = billingClient.isFeatureSupported(feature); result.success(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK); } }
packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java", "repo_id": "packages", "token_count": 8398 }
975
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: unused_local_variable import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/in_app_purchase_android.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; // #docregion one-time-purchase-price /// Handles the one time purchase price of a product. void handleOneTimePurchasePrice(ProductDetails productDetails) { if (productDetails is GooglePlayProductDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.inapp) { // Unwrapping is safe because the product is a one time purchase. final OneTimePurchaseOfferDetailsWrapper offer = product.oneTimePurchaseOfferDetails!; final String price = offer.formattedPrice; } } } // #enddocregion one-time-purchase-price // #docregion subscription-free-trial /// Handles the free trial period of a subscription. void handleFreeTrialPeriod(ProductDetails productDetails) { if (productDetails is GooglePlayProductDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.subs) { // Unwrapping is safe because the product is a subscription. final SubscriptionOfferDetailsWrapper offer = product.subscriptionOfferDetails![productDetails.subscriptionIndex!]; final List<PricingPhaseWrapper> pricingPhases = offer.pricingPhases; if (pricingPhases.first.priceAmountMicros == 0) { // Free trial period logic. } } } } // #enddocregion subscription-free-trial // #docregion subscription-introductory-price /// Handles the introductory price period of a subscription. void handleIntroductoryPricePeriod(ProductDetails productDetails) { if (productDetails is GooglePlayProductDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.subs) { // Unwrapping is safe because the product is a subscription. final SubscriptionOfferDetailsWrapper offer = product.subscriptionOfferDetails![productDetails.subscriptionIndex!]; final List<PricingPhaseWrapper> pricingPhases = offer.pricingPhases; if (pricingPhases.length >= 2 && pricingPhases.first.priceAmountMicros < pricingPhases[1].priceAmountMicros) { // Introductory pricing period logic. } } } } // #enddocregion subscription-introductory-price
packages/packages/in_app_purchase/in_app_purchase_android/example/lib/migration_guide_examples.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/example/lib/migration_guide_examples.dart", "repo_id": "packages", "token_count": 848 }
976
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'one_time_purchase_offer_details_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** OneTimePurchaseOfferDetailsWrapper _$OneTimePurchaseOfferDetailsWrapperFromJson( Map json) => OneTimePurchaseOfferDetailsWrapper( formattedPrice: json['formattedPrice'] as String? ?? '', priceAmountMicros: json['priceAmountMicros'] as int? ?? 0, priceCurrencyCode: json['priceCurrencyCode'] as String? ?? '', );
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/one_time_purchase_offer_details_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/one_time_purchase_offer_details_wrapper.g.dart", "repo_id": "packages", "token_count": 180 }
977
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../../billing_client_wrappers.dart'; import '../in_app_purchase_android_platform.dart'; /// The class represents the information of a purchase made using Google Play. class GooglePlayPurchaseDetails extends PurchaseDetails { /// Creates a new Google Play specific purchase details object with the /// provided details. GooglePlayPurchaseDetails({ super.purchaseID, required super.productID, required super.verificationData, required super.transactionDate, required this.billingClientPurchase, required super.status, }) { pendingCompletePurchase = !billingClientPurchase.isAcknowledged; } /// Generates a [List] of [PurchaseDetails] based on an Android [Purchase] object. /// /// The list contains one entry per product. static List<GooglePlayPurchaseDetails> fromPurchase( PurchaseWrapper purchase) { return purchase.products.map((String productId) { final GooglePlayPurchaseDetails purchaseDetails = GooglePlayPurchaseDetails( purchaseID: purchase.orderId, productID: productId, verificationData: PurchaseVerificationData( localVerificationData: purchase.originalJson, serverVerificationData: purchase.purchaseToken, source: kIAPSource), transactionDate: purchase.purchaseTime.toString(), billingClientPurchase: purchase, status: const PurchaseStateConverter() .toPurchaseStatus(purchase.purchaseState), ); if (purchaseDetails.status == PurchaseStatus.error) { purchaseDetails.error = IAPError( source: kIAPSource, code: kPurchaseErrorCode, message: '', ); } return purchaseDetails; }).toList(); } /// Points back to the [PurchaseWrapper] which was used to generate this /// [GooglePlayPurchaseDetails] object. final PurchaseWrapper billingClientPurchase; }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart", "repo_id": "packages", "token_count": 712 }
978
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/src/types/google_play_user_choice_details.dart'; import 'package:in_app_purchase_android/src/types/translator.dart'; import 'package:test/test.dart'; void main() { group('Translator ', () { test('convertToPlayProductType', () { expect(Translator.convertToPlayProductType(ProductType.inapp), GooglePlayProductType.inapp); expect(Translator.convertToPlayProductType(ProductType.subs), GooglePlayProductType.subs); expect(GooglePlayProductType.values.length, ProductType.values.length); }); test('convertToUserChoiceDetailsProduct', () { const GooglePlayUserChoiceDetailsProduct expected = GooglePlayUserChoiceDetailsProduct( id: 'id', offerToken: 'offerToken', productType: GooglePlayProductType.inapp); expect( Translator.convertToUserChoiceDetailsProduct( UserChoiceDetailsProductWrapper( id: expected.id, offerToken: expected.offerToken, productType: ProductType.inapp)), expected); }); test('convertToUserChoiceDetailsProduct', () { const GooglePlayUserChoiceDetailsProduct expectedProduct1 = GooglePlayUserChoiceDetailsProduct( id: 'id1', offerToken: 'offerToken1', productType: GooglePlayProductType.inapp); const GooglePlayUserChoiceDetailsProduct expectedProduct2 = GooglePlayUserChoiceDetailsProduct( id: 'id2', offerToken: 'offerToken2', productType: GooglePlayProductType.subs); const GooglePlayUserChoiceDetails expected = GooglePlayUserChoiceDetails( originalExternalTransactionId: 'originalExternalTransactionId', externalTransactionToken: 'externalTransactionToken', products: <GooglePlayUserChoiceDetailsProduct>[ expectedProduct1, expectedProduct2 ]); expect( Translator.convertToUserChoiceDetails(UserChoiceDetailsWrapper( originalExternalTransactionId: expected.originalExternalTransactionId, externalTransactionToken: expected.externalTransactionToken, products: <UserChoiceDetailsProductWrapper>[ UserChoiceDetailsProductWrapper( id: expectedProduct1.id, offerToken: expectedProduct1.offerToken, productType: ProductType.inapp), UserChoiceDetailsProductWrapper( id: expectedProduct2.id, offerToken: expectedProduct2.offerToken, productType: ProductType.subs), ])), expected); }); }); }
packages/packages/in_app_purchase/in_app_purchase_android/test/types/translator_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/types/translator_test.dart", "repo_id": "packages", "token_count": 1259 }
979
name: local_auth description: Flutter plugin for Android and iOS devices to allow local authentication via fingerprint, touch ID, face ID, passcode, pin, or pattern. repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22 version: 2.2.0 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: platforms: android: default_package: local_auth_android ios: default_package: local_auth_darwin windows: default_package: local_auth_windows dependencies: flutter: sdk: flutter local_auth_android: ^1.0.0 local_auth_darwin: ^1.2.1 local_auth_platform_interface: ^1.0.1 local_auth_windows: ^1.0.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter mockito: 5.4.4 plugin_platform_interface: ^2.1.7 topics: - authentication - biometrics - local-auth
packages/packages/local_auth/local_auth/pubspec.yaml/0
{ "file_path": "packages/packages/local_auth/local_auth/pubspec.yaml", "repo_id": "packages", "token_count": 409 }
980
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.localauth; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Application; import android.content.Context; import androidx.biometric.BiometricPrompt; import androidx.fragment.app.FragmentActivity; import io.flutter.plugins.localauth.AuthenticationHelper.AuthCompletionHandler; import io.flutter.plugins.localauth.Messages.AuthOptions; import io.flutter.plugins.localauth.Messages.AuthResult; import io.flutter.plugins.localauth.Messages.AuthStrings; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; // TODO(stuartmorgan): Add injectable BiometricPrompt factory, and AlertDialog factor, and add // testing of the rest of the flows. @RunWith(RobolectricTestRunner.class) public class AuthenticationHelperTest { static final AuthStrings dummyStrings = new AuthStrings.Builder() .setReason("a reason") .setBiometricHint("a hint") .setBiometricNotRecognized("biometric not recognized") .setBiometricRequiredTitle("biometric required") .setCancelButton("cancel") .setDeviceCredentialsRequiredTitle("credentials required") .setDeviceCredentialsSetupDescription("credentials setup description") .setGoToSettingsButton("go") .setGoToSettingsDescription("go to settings description") .setSignInTitle("sign in") .build(); static final AuthOptions defaultOptions = new AuthOptions.Builder() .setBiometricOnly(false) .setSensitiveTransaction(false) .setSticky(false) .setUseErrorDialgs(false) .build(); @Test public void onAuthenticationError_withoutDialogs_returnsNotAvailableForNoCredential() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL, ""); verify(handler).complete(AuthResult.ERROR_NOT_AVAILABLE); } @Test public void onAuthenticationError_withoutDialogs_returnsNotEnrolledForNoBiometrics() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_NO_BIOMETRICS, ""); verify(handler).complete(AuthResult.ERROR_NOT_ENROLLED); } @Test public void onAuthenticationError_returnsNotAvailableForHardwareUnavailable() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_HW_UNAVAILABLE, ""); verify(handler).complete(AuthResult.ERROR_NOT_AVAILABLE); } @Test public void onAuthenticationError_returnsNotAvailableForHardwareNotPresent() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_HW_NOT_PRESENT, ""); verify(handler).complete(AuthResult.ERROR_NOT_AVAILABLE); } @Test public void onAuthenticationError_returnsTemporaryLockoutForLockout() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_LOCKOUT, ""); verify(handler).complete(AuthResult.ERROR_LOCKED_OUT_TEMPORARILY); } @Test public void onAuthenticationError_returnsPermanentLockoutForLockoutPermanent() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_LOCKOUT_PERMANENT, ""); verify(handler).complete(AuthResult.ERROR_LOCKED_OUT_PERMANENTLY); } @Test public void onAuthenticationError_withoutSticky_returnsFailureForCanceled() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_CANCELED, ""); verify(handler).complete(AuthResult.FAILURE); } @Test public void onAuthenticationError_withoutSticky_returnsFailureForOtherCases() { final AuthCompletionHandler handler = mock(AuthCompletionHandler.class); final AuthenticationHelper helper = new AuthenticationHelper( null, buildMockActivityWithContext(mock(FragmentActivity.class)), defaultOptions, dummyStrings, handler, true); helper.onAuthenticationError(BiometricPrompt.ERROR_VENDOR, ""); verify(handler).complete(AuthResult.FAILURE); } private FragmentActivity buildMockActivityWithContext(FragmentActivity mockActivity) { final Application mockApplication = mock(Application.class); final Context mockContext = mock(Context.class); when(mockActivity.getBaseContext()).thenReturn(mockContext); when(mockActivity.getApplicationContext()).thenReturn(mockContext); when(mockActivity.getApplication()).thenReturn(mockApplication); return mockActivity; } }
packages/packages/local_auth/local_auth_android/android/src/test/java/io/flutter/plugins/localauth/AuthenticationHelperTest.java/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/test/java/io/flutter/plugins/localauth/AuthenticationHelperTest.java", "repo_id": "packages", "token_count": 2552 }
981
## 1.2.2 * Adds compatibility with `intl` 0.19.0. ## 1.2.1 * Renames the Objective-C plugin classes to avoid runtime conflicts with `local_auth_ios` in apps that have transitive dependencies on both. ## 1.2.0 * Renames the package previously published as [`local_auth_ios`](https://pub.dev/packages/local_auth_ios)
packages/packages/local_auth/local_auth_darwin/CHANGELOG.md/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/CHANGELOG.md", "repo_id": "packages", "token_count": 107 }
982
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'src/messages.g.dart'; import 'types/auth_messages_ios.dart'; export 'package:local_auth_darwin/types/auth_messages_ios.dart'; export 'package:local_auth_platform_interface/types/auth_messages.dart'; export 'package:local_auth_platform_interface/types/auth_options.dart'; export 'package:local_auth_platform_interface/types/biometric_type.dart'; /// The implementation of [LocalAuthPlatform] for iOS. class LocalAuthDarwin extends LocalAuthPlatform { /// Creates a new plugin implementation instance. LocalAuthDarwin({ @visibleForTesting LocalAuthApi? api, }) : _api = api ?? LocalAuthApi(); /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { LocalAuthPlatform.instance = LocalAuthDarwin(); } final LocalAuthApi _api; @override Future<bool> authenticate({ required String localizedReason, required Iterable<AuthMessages> authMessages, AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); final AuthResultDetails resultDetails = await _api.authenticate( AuthOptions( biometricOnly: options.biometricOnly, sticky: options.stickyAuth, useErrorDialogs: options.useErrorDialogs), _pigeonStringsFromAuthMessages(localizedReason, authMessages)); // TODO(stuartmorgan): Replace this with structured errors, coordinated // across all platform implementations, per // https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#platform-exception-handling // The PlatformExceptions thrown here are for compatibiilty with the // previous Objective-C implementation. switch (resultDetails.result) { case AuthResult.success: return true; case AuthResult.failure: return false; case AuthResult.errorNotAvailable: throw PlatformException( code: 'NotAvailable', message: resultDetails.errorMessage, details: resultDetails.errorDetails); case AuthResult.errorNotEnrolled: throw PlatformException( code: 'NotEnrolled', message: resultDetails.errorMessage, details: resultDetails.errorDetails); case AuthResult.errorPasscodeNotSet: throw PlatformException( code: 'PasscodeNotSet', message: resultDetails.errorMessage, details: resultDetails.errorDetails); } } @override Future<bool> deviceSupportsBiometrics() async { return _api.deviceCanSupportBiometrics(); } @override Future<List<BiometricType>> getEnrolledBiometrics() async { final List<AuthBiometricWrapper?> result = await _api.getEnrolledBiometrics(); return result .cast<AuthBiometricWrapper>() .map((AuthBiometricWrapper entry) { switch (entry.value) { case AuthBiometric.face: return BiometricType.face; case AuthBiometric.fingerprint: return BiometricType.fingerprint; } }).toList(); } @override Future<bool> isDeviceSupported() async => _api.isDeviceSupported(); /// Always returns false as this method is not supported on iOS. @override Future<bool> stopAuthentication() async => false; AuthStrings _pigeonStringsFromAuthMessages( String localizedReason, Iterable<AuthMessages> messagesList) { IOSAuthMessages? messages; for (final AuthMessages entry in messagesList) { if (entry is IOSAuthMessages) { messages = entry; break; } } return AuthStrings( reason: localizedReason, lockOut: messages?.lockOut ?? iOSLockOut, goToSettingsButton: messages?.goToSettingsButton ?? goToSettings, goToSettingsDescription: messages?.goToSettingsDescription ?? iOSGoToSettingsDescription, // TODO(stuartmorgan): The default's name is confusing here for legacy // reasons; this should be fixed as part of some future breaking change. cancelButton: messages?.cancelButton ?? iOSOkButton, localizedFallbackTitle: messages?.localizedFallbackTitle, ); } }
packages/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart", "repo_id": "packages", "token_count": 1564 }
983
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:fake_async/fake_async.dart'; import 'package:gcloud/storage.dart'; import 'package:googleapis/storage/v1.dart'; import 'package:googleapis_auth/auth_io.dart'; import 'package:metrics_center/src/constants.dart'; import 'package:metrics_center/src/gcs_lock.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'common.dart'; import 'gcs_lock_test.mocks.dart'; import 'utility.dart'; enum TestPhase { run1, run2, } @GenerateMocks(<Type>[ AuthClient, StorageApi ], customMocks: <MockSpec<dynamic>>[ MockSpec<ObjectsResource>(onMissingStub: OnMissingStub.returnDefault) ]) void main() { const Duration kDelayStep = Duration(milliseconds: 10); final Map<String, dynamic>? credentialsJson = getTestGcpCredentialsJson(); test('GcsLock prints warnings for long waits', () { // Capture print to verify error messages. final List<String> prints = <String>[]; final ZoneSpecification spec = ZoneSpecification(print: (_, __, ___, String msg) => prints.add(msg)); Zone.current.fork(specification: spec).run<void>(() { fakeAsync((FakeAsync fakeAsync) { final MockAuthClient mockClient = MockAuthClient(); final GcsLock lock = GcsLock(StorageApi(mockClient), 'mockBucket'); when(mockClient.send(any)).thenThrow(DetailedApiRequestError(412, '')); final Future<void> runFinished = lock.protectedRun('mock.lock', () async {}); fakeAsync.elapse(const Duration(seconds: 10)); when(mockClient.send(any)).thenThrow(AssertionError('Stop!')); runFinished.catchError((dynamic e) { final AssertionError error = e as AssertionError; expect(error.message, 'Stop!'); // TODO(goderbauer): We should not be printing from a test. // ignore: avoid_print print('${error.message}'); }); fakeAsync.elapse(const Duration(seconds: 20)); }); }); const String kExpectedErrorMessage = 'The lock is waiting for a long time: ' '0:00:10.240000. If the lock file mock.lock in bucket mockBucket ' 'seems to be stuck (i.e., it was created a long time ago and no one ' 'seems to be owning it currently), delete it manually to unblock this.'; expect(prints, equals(<String>[kExpectedErrorMessage, 'Stop!'])); }); test('GcsLock integration test: single protectedRun is successful', () async { final AutoRefreshingAuthClient client = await clientViaServiceAccount( ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES); final GcsLock lock = GcsLock(StorageApi(client), kTestBucketName); int testValue = 0; await lock.protectedRun('test.lock', () async { testValue = 1; }); expect(testValue, 1); }, skip: credentialsJson == null); test('GcsLock integration test: protectedRun is exclusive', () async { final AutoRefreshingAuthClient client = await clientViaServiceAccount( ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES); final GcsLock lock1 = GcsLock(StorageApi(client), kTestBucketName); final GcsLock lock2 = GcsLock(StorageApi(client), kTestBucketName); TestPhase phase = TestPhase.run1; final Completer<void> started1 = Completer<void>(); final Future<void> finished1 = lock1.protectedRun('test.lock', () async { started1.complete(); while (phase == TestPhase.run1) { await Future<void>.delayed(kDelayStep); } }); await started1.future; final Completer<void> started2 = Completer<void>(); final Future<void> finished2 = lock2.protectedRun('test.lock', () async { started2.complete(); }); // started2 should not be set even after a long wait because lock1 is // holding the GCS lock file. await Future<void>.delayed(kDelayStep * 10); expect(started2.isCompleted, false); // When phase is switched to run2, lock1 should be released soon and // lock2 should soon be able to proceed its protectedRun. phase = TestPhase.run2; await started2.future; await finished1; await finished2; }, skip: credentialsJson == null); test('GcsLock attempts to unlock again on a DetailedApiRequestError', () async { fakeAsync((FakeAsync fakeAsync) { final StorageApi mockStorageApi = MockStorageApi(); final ObjectsResource mockObjectsResource = MockObjectsResource(); final GcsLock gcsLock = GcsLock(mockStorageApi, kTestBucketName); const String lockFileName = 'test.lock'; when(mockStorageApi.objects).thenReturn(mockObjectsResource); // Simulate a failure to delete a lock file. when(mockObjectsResource.delete(kTestBucketName, lockFileName)) .thenThrow(DetailedApiRequestError(504, '')); gcsLock.protectedRun(lockFileName, () async {}); // Allow time to pass by to ensure deleting the lock file is retried multiple times. fakeAsync.elapse(const Duration(milliseconds: 30)); verify(mockObjectsResource.delete(kTestBucketName, lockFileName)) .called(3); // Simulate a successful deletion of the lock file. when(mockObjectsResource.delete(kTestBucketName, lockFileName)) .thenAnswer((_) => Future<void>( () { return; }, )); // At this point, there should only be one more (successful) attempt to delete the lock file. fakeAsync.elapse(const Duration(minutes: 2)); verify(mockObjectsResource.delete(kTestBucketName, lockFileName)) .called(1); }); }); }
packages/packages/metrics_center/test/gcs_lock_test.dart/0
{ "file_path": "packages/packages/metrics_center/test/gcs_lock_test.dart", "repo_id": "packages", "token_count": 2127 }
984
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'resource_record.dart'; /// Class for maintaining state about pending mDNS requests. base class PendingRequest extends LinkedListEntry<PendingRequest> { /// Creates a new PendingRequest. PendingRequest(this.type, this.domainName, this.controller); /// The [ResourceRecordType] of the request. final int type; /// The domain name to look up via mDNS. /// /// For example, `'_http._tcp.local` to look up HTTP services on the local /// domain. final String domainName; /// A StreamController managing the request. final StreamController<ResourceRecord> controller; /// The timer for the request. Timer? timer; } /// Class for keeping track of pending lookups and processing incoming /// query responses. class LookupResolver { final LinkedList<PendingRequest> _pendingRequests = LinkedList<PendingRequest>(); /// Adds a request and returns a [Stream] of [ResourceRecord] responses. Stream<T> addPendingRequest<T extends ResourceRecord>( int type, String name, Duration timeout) { final StreamController<T> controller = StreamController<T>(); final PendingRequest request = PendingRequest(type, name, controller); final Timer timer = Timer(timeout, () { request.unlink(); controller.close(); }); request.timer = timer; _pendingRequests.add(request); return controller.stream; } /// Parses [ResoureRecord]s received and delivers them to the appropriate /// listener(s) added via [addPendingRequest]. void handleResponse(List<ResourceRecord> response) { for (final ResourceRecord r in response) { final int type = r.resourceRecordType; String name = r.name.toLowerCase(); if (name.endsWith('.')) { name = name.substring(0, name.length - 1); } bool responseMatches(PendingRequest request) { String requestName = request.domainName.toLowerCase(); // make, e.g. "_http" become "_http._tcp.local". if (!requestName.endsWith('local')) { if (!requestName.endsWith('._tcp.local') && !requestName.endsWith('._udp.local') && !requestName.endsWith('._tcp') && !requestName.endsWith('.udp')) { requestName += '._tcp'; } requestName += '.local'; } return requestName == name && request.type == type; } for (final PendingRequest pendingRequest in _pendingRequests) { if (responseMatches(pendingRequest)) { if (pendingRequest.controller.isClosed) { return; } pendingRequest.controller.add(r); } } } } /// Removes any pending requests and ends processing. void clearPendingRequests() { while (_pendingRequests.isNotEmpty) { final PendingRequest request = _pendingRequests.first; request.unlink(); request.timer?.cancel(); request.controller.close(); } } }
packages/packages/multicast_dns/lib/src/lookup_resolver.dart/0
{ "file_path": "packages/packages/multicast_dns/lib/src/lookup_resolver.dart", "repo_id": "packages", "token_count": 1122 }
985
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/palette_generator/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/palette_generator/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
986
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/palette_generator/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/palette_generator/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
987
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/path_provider/path_provider/example/android/gradle.properties/0
{ "file_path": "packages/packages/path_provider/path_provider/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
988
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/path_provider/path_provider/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/path_provider/path_provider/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
989
name: path_provider_platform_interface description: A common platform interface for the path_provider plugin. repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 # NOTE: We strongly prefer non-breaking changes, even at the expense of a # less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes version: 2.1.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter platform: ^3.0.0 plugin_platform_interface: ^2.1.7 dev_dependencies: flutter_test: sdk: flutter topics: - files - path-provider - paths
packages/packages/path_provider/path_provider_platform_interface/pubspec.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider_platform_interface/pubspec.yaml", "repo_id": "packages", "token_count": 277 }
990
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon import android.util.Log import io.flutter.plugin.common.BasicMessageChannel import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MessageCodec import io.flutter.plugin.common.StandardMessageCodec import java.io.ByteArrayOutputStream import java.nio.ByteBuffer private fun wrapResult(result: Any?): List<Any?> { return listOf(result) } private fun wrapError(exception: Throwable): List<Any?> { if (exception is FlutterError) { return listOf(exception.code, exception.message, exception.details) } else { return listOf( exception.javaClass.simpleName, exception.toString(), "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception)) } } private fun createConnectionError(channelName: String): FlutterError { return FlutterError( "channel-error", "Unable to establish connection on channel: '$channelName'.", "") } /** * Error class for passing custom error details to Flutter via a thrown PlatformException. * * @property code The error code. * @property message The error message. * @property details The error details. Must be a datatype supported by the api codec. */ class FlutterError( val code: String, override val message: String? = null, val details: Any? = null ) : Throwable() enum class Code(val raw: Int) { ONE(0), TWO(1); companion object { fun ofRaw(raw: Int): Code? { return values().firstOrNull { it.raw == raw } } } } /** Generated class from Pigeon that represents data sent in messages. */ data class MessageData( val name: String? = null, val description: String? = null, val code: Code, val data: Map<String?, String?> ) { companion object { @Suppress("UNCHECKED_CAST") fun fromList(list: List<Any?>): MessageData { val name = list[0] as String? val description = list[1] as String? val code = Code.ofRaw(list[2] as Int)!! val data = list[3] as Map<String?, String?> return MessageData(name, description, code, data) } } fun toList(): List<Any?> { return listOf<Any?>( name, description, code.raw, data, ) } } @Suppress("UNCHECKED_CAST") private object ExampleHostApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { 128.toByte() -> { return (readValue(buffer) as? List<Any?>)?.let { MessageData.fromList(it) } } else -> super.readValueOfType(type, buffer) } } override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { when (value) { is MessageData -> { stream.write(128) writeValue(stream, value.toList()) } else -> super.writeValue(stream, value) } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface ExampleHostApi { fun getHostLanguage(): String fun add(a: Long, b: Long): Long fun sendMessage(message: MessageData, callback: (Result<Boolean>) -> Unit) companion object { /** The codec used by ExampleHostApi. */ val codec: MessageCodec<Any?> by lazy { ExampleHostApiCodec } /** Sets up an instance of `ExampleHostApi` to handle messages through the `binaryMessenger`. */ @Suppress("UNCHECKED_CAST") fun setUp(binaryMessenger: BinaryMessenger, api: ExampleHostApi?) { run { val channel = BasicMessageChannel<Any?>( binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage", codec) if (api != null) { channel.setMessageHandler { _, reply -> var wrapped: List<Any?> try { wrapped = listOf<Any?>(api.getHostLanguage()) } catch (exception: Throwable) { wrapped = wrapError(exception) } reply.reply(wrapped) } } else { channel.setMessageHandler(null) } } run { val channel = BasicMessageChannel<Any?>( binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add", codec) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List<Any?> val aArg = args[0].let { if (it is Int) it.toLong() else it as Long } val bArg = args[1].let { if (it is Int) it.toLong() else it as Long } var wrapped: List<Any?> try { wrapped = listOf<Any?>(api.add(aArg, bArg)) } catch (exception: Throwable) { wrapped = wrapError(exception) } reply.reply(wrapped) } } else { channel.setMessageHandler(null) } } run { val channel = BasicMessageChannel<Any?>( binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage", codec) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List<Any?> val messageArg = args[0] as MessageData api.sendMessage(messageArg) { result: Result<Boolean> -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) } else { val data = result.getOrNull() reply.reply(wrapResult(data)) } } } } else { channel.setMessageHandler(null) } } } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. */ @Suppress("UNCHECKED_CAST") class MessageFlutterApi(private val binaryMessenger: BinaryMessenger) { companion object { /** The codec used by MessageFlutterApi. */ val codec: MessageCodec<Any?> by lazy { StandardMessageCodec() } } fun flutterMethod(aStringArg: String?, callback: (Result<String>) -> Unit) { val channelName = "dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod" val channel = BasicMessageChannel<Any?>(binaryMessenger, channelName, codec) channel.send(listOf(aStringArg)) { if (it is List<*>) { if (it.size > 1) { callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?))) } else if (it[0] == null) { callback( Result.failure( FlutterError( "null-error", "Flutter api returned null value for non-null return value.", ""))) } else { val output = it[0] as String callback(Result.success(output)) } } else { callback(Result.failure(createConnectionError(channelName))) } } } }
packages/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt/0
{ "file_path": "packages/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt", "repo_id": "packages", "token_count": 3063 }
991
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'ast.dart'; import 'generator_tools.dart'; /// Writes the AST representation of [root] to [sink]. void generateAst(Root root, StringSink sink) { final Indent indent = Indent(sink); final String output = root.toString(); bool isFirst = true; for (final int ch in output.runes) { final String chStr = String.fromCharCode(ch); if (chStr == '(') { if (isFirst) { isFirst = false; } else { indent.inc(); indent.addln(''); indent.write(''); } } else if (chStr == ')') { indent.dec(); } indent.add(chStr); } indent.addln(''); }
packages/packages/pigeon/lib/ast_generator.dart/0
{ "file_path": "packages/packages/pigeon/lib/ast_generator.dart", "repo_id": "packages", "token_count": 305 }
992
group 'com.example.alternate_language_test_plugin' version '1.0' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:8.0.0' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'com.example.alternate_language_test_plugin' } compileSdk 34 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { minSdkVersion 16 } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } dependencies { testImplementation 'junit:junit:4.13.2' testImplementation "org.mockito:mockito-core:5.1.1" } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle", "repo_id": "packages", "token_count": 618 }
993
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "EchoMessenger.h" @interface EchoBinaryMessenger () @property(nonatomic, strong) NSObject<FlutterMessageCodec> *codec; @end @implementation EchoBinaryMessenger { int _count; } - (instancetype)initWithCodec:(NSObject<FlutterMessageCodec> *)codec { self = [super init]; if (self) { _codec = codec; } return self; } - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { } - (void)sendOnChannel:(nonnull NSString *)channel message:(NSData *_Nullable)message { } - (void)sendOnChannel:(nonnull NSString *)channel message:(NSData *_Nullable)message binaryReply:(FlutterBinaryReply _Nullable)callback { NSArray *args = [self.codec decode:message]; callback([self.codec encode:args]); } - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(nonnull NSString *)channel binaryMessageHandler: (FlutterBinaryMessageHandler _Nullable)handler { return ++_count; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/EchoMessenger.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/EchoMessenger.m", "repo_id": "packages", "token_count": 456 }
994
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, FLTAnEnum) { FLTAnEnumOne = 0, FLTAnEnumTwo = 1, FLTAnEnumThree = 2, FLTAnEnumFortyTwo = 3, FLTAnEnumFourHundredTwentyTwo = 4, }; /// Wrapper for FLTAnEnum to allow for nullability. @interface FLTAnEnumBox : NSObject @property(nonatomic, assign) FLTAnEnum value; - (instancetype)initWithValue:(FLTAnEnum)value; @end @class FLTAllTypes; @class FLTAllNullableTypes; @class FLTAllClassesWrapper; @class FLTTestMessage; /// A class containing all supported types. @interface FLTAllTypes : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithABool:(BOOL)aBool anInt:(NSInteger)anInt anInt64:(NSInteger)anInt64 aDouble:(double)aDouble aByteArray:(FlutterStandardTypedData *)aByteArray a4ByteArray:(FlutterStandardTypedData *)a4ByteArray a8ByteArray:(FlutterStandardTypedData *)a8ByteArray aFloatArray:(FlutterStandardTypedData *)aFloatArray aList:(NSArray *)aList aMap:(NSDictionary *)aMap anEnum:(FLTAnEnum)anEnum aString:(NSString *)aString anObject:(id)anObject; @property(nonatomic, assign) BOOL aBool; @property(nonatomic, assign) NSInteger anInt; @property(nonatomic, assign) NSInteger anInt64; @property(nonatomic, assign) double aDouble; @property(nonatomic, strong) FlutterStandardTypedData *aByteArray; @property(nonatomic, strong) FlutterStandardTypedData *a4ByteArray; @property(nonatomic, strong) FlutterStandardTypedData *a8ByteArray; @property(nonatomic, strong) FlutterStandardTypedData *aFloatArray; @property(nonatomic, copy) NSArray *aList; @property(nonatomic, copy) NSDictionary *aMap; @property(nonatomic, assign) FLTAnEnum anEnum; @property(nonatomic, copy) NSString *aString; @property(nonatomic, strong) id anObject; @end /// A class containing all supported nullable types. @interface FLTAllNullableTypes : NSObject + (instancetype)makeWithANullableBool:(nullable NSNumber *)aNullableBool aNullableInt:(nullable NSNumber *)aNullableInt aNullableInt64:(nullable NSNumber *)aNullableInt64 aNullableDouble:(nullable NSNumber *)aNullableDouble aNullableByteArray:(nullable FlutterStandardTypedData *)aNullableByteArray aNullable4ByteArray:(nullable FlutterStandardTypedData *)aNullable4ByteArray aNullable8ByteArray:(nullable FlutterStandardTypedData *)aNullable8ByteArray aNullableFloatArray:(nullable FlutterStandardTypedData *)aNullableFloatArray aNullableList:(nullable NSArray *)aNullableList aNullableMap:(nullable NSDictionary *)aNullableMap nullableNestedList:(nullable NSArray<NSArray<NSNumber *> *> *)nullableNestedList nullableMapWithAnnotations: (nullable NSDictionary<NSString *, NSString *> *)nullableMapWithAnnotations nullableMapWithObject:(nullable NSDictionary<NSString *, id> *)nullableMapWithObject aNullableEnum:(nullable FLTAnEnumBox *)aNullableEnum aNullableString:(nullable NSString *)aNullableString aNullableObject:(nullable id)aNullableObject; @property(nonatomic, strong, nullable) NSNumber *aNullableBool; @property(nonatomic, strong, nullable) NSNumber *aNullableInt; @property(nonatomic, strong, nullable) NSNumber *aNullableInt64; @property(nonatomic, strong, nullable) NSNumber *aNullableDouble; @property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullableByteArray; @property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullable4ByteArray; @property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullable8ByteArray; @property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullableFloatArray; @property(nonatomic, copy, nullable) NSArray *aNullableList; @property(nonatomic, copy, nullable) NSDictionary *aNullableMap; @property(nonatomic, copy, nullable) NSArray<NSArray<NSNumber *> *> *nullableNestedList; @property(nonatomic, copy, nullable) NSDictionary<NSString *, NSString *> *nullableMapWithAnnotations; @property(nonatomic, copy, nullable) NSDictionary<NSString *, id> *nullableMapWithObject; @property(nonatomic, strong, nullable) FLTAnEnumBox *aNullableEnum; @property(nonatomic, copy, nullable) NSString *aNullableString; @property(nonatomic, strong, nullable) id aNullableObject; @end /// A class for testing nested class handling. /// /// This is needed to test nested nullable and non-nullable classes, /// `AllNullableTypes` is non-nullable here as it is easier to instantiate /// than `AllTypes` when testing doesn't require both (ie. testing null classes). @interface FLTAllClassesWrapper : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithAllNullableTypes:(FLTAllNullableTypes *)allNullableTypes allTypes:(nullable FLTAllTypes *)allTypes; @property(nonatomic, strong) FLTAllNullableTypes *allNullableTypes; @property(nonatomic, strong, nullable) FLTAllTypes *allTypes; @end /// A data class containing a List, used in unit tests. @interface FLTTestMessage : NSObject + (instancetype)makeWithTestList:(nullable NSArray *)testList; @property(nonatomic, copy, nullable) NSArray *testList; @end /// The codec used by FLTHostIntegrationCoreApi. NSObject<FlutterMessageCodec> *FLTHostIntegrationCoreApiGetCodec(void); /// The core interface that each host language plugin must implement in /// platform_test integration tests. @protocol FLTHostIntegrationCoreApi /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. - (void)noopWithError:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed object, to test serialization and deserialization. /// /// @return `nil` only when `error != nil`. - (nullable FLTAllTypes *)echoAllTypes:(FLTAllTypes *)everything error:(FlutterError *_Nullable *_Nonnull)error; /// Returns an error, to test error handling. - (nullable id)throwErrorWithError:(FlutterError *_Nullable *_Nonnull)error; /// Returns an error from a void function, to test error handling. - (void)throwErrorFromVoidWithError:(FlutterError *_Nullable *_Nonnull)error; /// Returns a Flutter error, to test error handling. - (nullable id)throwFlutterErrorWithError:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in int. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)echoInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in double. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)echoDouble:(double)aDouble error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in boolean. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)echoBool:(BOOL)aBool error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in string. /// /// @return `nil` only when `error != nil`. - (nullable NSString *)echoString:(NSString *)aString error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in Uint8List. /// /// @return `nil` only when `error != nil`. - (nullable FlutterStandardTypedData *)echoUint8List:(FlutterStandardTypedData *)aUint8List error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in generic Object. /// /// @return `nil` only when `error != nil`. - (nullable id)echoObject:(id)anObject error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed list, to test serialization and deserialization. /// /// @return `nil` only when `error != nil`. - (nullable NSArray<id> *)echoList:(NSArray<id> *)aList error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed map, to test serialization and deserialization. /// /// @return `nil` only when `error != nil`. - (nullable NSDictionary<NSString *, id> *)echoMap:(NSDictionary<NSString *, id> *)aMap error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed map to test nested class serialization and deserialization. /// /// @return `nil` only when `error != nil`. - (nullable FLTAllClassesWrapper *)echoClassWrapper:(FLTAllClassesWrapper *)wrapper error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed enum to test serialization and deserialization. /// /// @return `nil` only when `error != nil`. - (FLTAnEnumBox *_Nullable)echoEnum:(FLTAnEnum)anEnum error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the default string. /// /// @return `nil` only when `error != nil`. - (nullable NSString *)echoNamedDefaultString:(NSString *)aString error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in double. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)echoOptionalDefaultDouble:(double)aDouble error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in int. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)echoRequiredInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed object, to test serialization and deserialization. - (nullable FLTAllNullableTypes *)echoAllNullableTypes:(nullable FLTAllNullableTypes *)everything error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. - (nullable NSString *)extractNestedNullableStringFrom:(FLTAllClassesWrapper *)wrapper error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. /// /// @return `nil` only when `error != nil`. - (nullable FLTAllClassesWrapper *) createNestedObjectWithNullableString:(nullable NSString *)nullableString error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in arguments of multiple types. /// /// @return `nil` only when `error != nil`. - (nullable FLTAllNullableTypes *) sendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool anInt:(nullable NSNumber *)aNullableInt aString:(nullable NSString *)aNullableString error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in int. - (nullable NSNumber *)echoNullableInt:(nullable NSNumber *)aNullableInt error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in double. - (nullable NSNumber *)echoNullableDouble:(nullable NSNumber *)aNullableDouble error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in boolean. - (nullable NSNumber *)echoNullableBool:(nullable NSNumber *)aNullableBool error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in string. - (nullable NSString *)echoNullableString:(nullable NSString *)aNullableString error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in Uint8List. - (nullable FlutterStandardTypedData *) echoNullableUint8List:(nullable FlutterStandardTypedData *)aNullableUint8List error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in generic Object. - (nullable id)echoNullableObject:(nullable id)aNullableObject error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed list, to test serialization and deserialization. - (nullable NSArray<id> *)echoNullableList:(nullable NSArray<id> *)aNullableList error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed map, to test serialization and deserialization. - (nullable NSDictionary<NSString *, id> *)echoNullableMap: (nullable NSDictionary<NSString *, id> *)aNullableMap error:(FlutterError *_Nullable *_Nonnull)error; - (FLTAnEnumBox *_Nullable)echoNullableEnum:(nullable FLTAnEnumBox *)anEnumBoxed error:(FlutterError *_Nullable *_Nonnull)error; /// Returns passed in int. - (nullable NSNumber *)echoOptionalNullableInt:(nullable NSNumber *)aNullableInt error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed in string. - (nullable NSString *)echoNamedNullableString:(nullable NSString *)aNullableString error:(FlutterError *_Nullable *_Nonnull)error; /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. - (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion; /// Returns passed in int asynchronously. - (void)echoAsyncInt:(NSInteger)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns passed in double asynchronously. - (void)echoAsyncDouble:(double)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed in boolean asynchronously. - (void)echoAsyncBool:(BOOL)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed string asynchronously. - (void)echoAsyncString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed in Uint8List asynchronously. - (void)echoAsyncUint8List:(FlutterStandardTypedData *)aUint8List completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed in generic Object asynchronously. - (void)echoAsyncObject:(id)anObject completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; /// Returns the passed list, to test asynchronous serialization and deserialization. - (void)echoAsyncList:(NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed map, to test asynchronous serialization and deserialization. - (void)echoAsyncMap:(NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed enum, to test asynchronous serialization and deserialization. - (void)echoAsyncEnum:(FLTAnEnum)anEnum completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion; /// Responds with an error from an async function returning a value. - (void)throwAsyncErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; /// Responds with an error from an async void function. - (void)throwAsyncErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion; /// Responds with a Flutter error from an async function returning a value. - (void)throwAsyncFlutterErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; /// Returns the passed object, to test async serialization and deserialization. - (void)echoAsyncAllTypes:(FLTAllTypes *)everything completion:(void (^)(FLTAllTypes *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed object, to test serialization and deserialization. - (void)echoAsyncNullableAllNullableTypes:(nullable FLTAllNullableTypes *)everything completion:(void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion; /// Returns passed in int asynchronously. - (void)echoAsyncNullableInt:(nullable NSNumber *)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns passed in double asynchronously. - (void)echoAsyncNullableDouble:(nullable NSNumber *)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed in boolean asynchronously. - (void)echoAsyncNullableBool:(nullable NSNumber *)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed string asynchronously. - (void)echoAsyncNullableString:(nullable NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed in Uint8List asynchronously. - (void)echoAsyncNullableUint8List:(nullable FlutterStandardTypedData *)aUint8List completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed in generic Object asynchronously. - (void)echoAsyncNullableObject:(nullable id)anObject completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; /// Returns the passed list, to test asynchronous serialization and deserialization. - (void)echoAsyncNullableList:(nullable NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed map, to test asynchronous serialization and deserialization. - (void)echoAsyncNullableMap:(nullable NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed enum, to test asynchronous serialization and deserialization. - (void)echoAsyncNullableEnum:(nullable FLTAnEnumBox *)anEnumBoxed completion: (void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterNoopWithCompletion:(void (^)(FlutterError *_Nullable))completion; - (void)callFlutterThrowErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; - (void)callFlutterThrowErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion; - (void)callFlutterEchoAllTypes:(FLTAllTypes *)everything completion: (void (^)(FLTAllTypes *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoAllNullableTypes:(nullable FLTAllNullableTypes *)everything completion:(void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterSendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool anInt:(nullable NSNumber *)aNullableInt aString:(nullable NSString *)aNullableString completion:(void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoBool:(BOOL)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoInt:(NSInteger)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoDouble:(double)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoUint8List:(FlutterStandardTypedData *)aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoList:(NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoMap:(NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoEnum:(FLTAnEnum)anEnum completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableBool:(nullable NSNumber *)aBool completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableInt:(nullable NSNumber *)anInt completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableDouble:(nullable NSNumber *)aDouble completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableString:(nullable NSString *)aString completion: (void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableUint8List:(nullable FlutterStandardTypedData *)aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableList:(nullable NSArray<id> *)aList completion: (void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableMap:(nullable NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion; - (void)callFlutterEchoNullableEnum:(nullable FLTAnEnumBox *)anEnumBoxed completion: (void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion; @end extern void SetUpFLTHostIntegrationCoreApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTHostIntegrationCoreApi> *_Nullable api); /// The codec used by FLTFlutterIntegrationCoreApi. NSObject<FlutterMessageCodec> *FLTFlutterIntegrationCoreApiGetCodec(void); /// The core interface that the Dart platform_test code implements for host /// integration tests to call into. @interface FLTFlutterIntegrationCoreApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. - (void)noopWithCompletion:(void (^)(FlutterError *_Nullable))completion; /// Responds with an error from an async function returning a value. - (void)throwErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; /// Responds with an error from an async void function. - (void)throwErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion; /// Returns the passed object, to test serialization and deserialization. - (void)echoAllTypes:(FLTAllTypes *)everything completion:(void (^)(FLTAllTypes *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed object, to test serialization and deserialization. - (void)echoAllNullableTypes:(nullable FLTAllNullableTypes *)everything completion: (void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion; /// Returns passed in arguments of multiple types. /// /// Tests multiple-arity FlutterApi handling. - (void)sendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool anInt:(nullable NSNumber *)aNullableInt aString:(nullable NSString *)aNullableString completion:(void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed boolean, to test serialization and deserialization. - (void)echoBool:(BOOL)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed int, to test serialization and deserialization. - (void)echoInt:(NSInteger)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed double, to test serialization and deserialization. - (void)echoDouble:(double)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed string, to test serialization and deserialization. - (void)echoString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed byte list, to test serialization and deserialization. - (void)echoUint8List:(FlutterStandardTypedData *)aList completion: (void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed list, to test serialization and deserialization. - (void)echoList:(NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed map, to test serialization and deserialization. - (void)echoMap:(NSDictionary<NSString *, id> *)aMap completion: (void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed enum to test serialization and deserialization. - (void)echoEnum:(FLTAnEnum)anEnum completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed boolean, to test serialization and deserialization. - (void)echoNullableBool:(nullable NSNumber *)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed int, to test serialization and deserialization. - (void)echoNullableInt:(nullable NSNumber *)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed double, to test serialization and deserialization. - (void)echoNullableDouble:(nullable NSNumber *)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed string, to test serialization and deserialization. - (void)echoNullableString:(nullable NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed byte list, to test serialization and deserialization. - (void)echoNullableUint8List:(nullable FlutterStandardTypedData *)aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed list, to test serialization and deserialization. - (void)echoNullableList:(nullable NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed map, to test serialization and deserialization. - (void)echoNullableMap:(nullable NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion; /// Returns the passed enum to test serialization and deserialization. - (void)echoNullableEnum:(nullable FLTAnEnumBox *)anEnumBoxed completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion; /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. - (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion; /// Returns the passed in generic Object asynchronously. - (void)echoAsyncString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; @end /// The codec used by FLTHostTrivialApi. NSObject<FlutterMessageCodec> *FLTHostTrivialApiGetCodec(void); /// An API that can be implemented for minimal, compile-only tests. @protocol FLTHostTrivialApi - (void)noopWithError:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFLTHostTrivialApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTHostTrivialApi> *_Nullable api); /// The codec used by FLTHostSmallApi. NSObject<FlutterMessageCodec> *FLTHostSmallApiGetCodec(void); /// A simple API implemented in some unit tests. @protocol FLTHostSmallApi - (void)echoString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; - (void)voidVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion; @end extern void SetUpFLTHostSmallApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTHostSmallApi> *_Nullable api); /// The codec used by FLTFlutterSmallApi. NSObject<FlutterMessageCodec> *FLTFlutterSmallApiGetCodec(void); /// A simple API called in some unit tests. @interface FLTFlutterSmallApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)echoWrappedList:(FLTTestMessage *)msg completion:(void (^)(FLTTestMessage *_Nullable, FlutterError *_Nullable))completion; - (void)echoString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; @end NS_ASSUME_NONNULL_END
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/Classes/CoreTests.gen.h/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/Classes/CoreTests.gen.h", "repo_id": "packages", "token_count": 12226 }
995
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file specifically tests the test PigeonInstanceManager generated by core_tests. import 'package:flutter_test/flutter_test.dart'; import 'package:shared_test_plugin_code/src/generated/proxy_api_tests.gen.dart'; void main() { group('InstanceManager', () { test('addHostCreatedInstance', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.getIdentifier(object), 0); expect( instanceManager.getInstanceWithWeakReference(0), object, ); }); test('addHostCreatedInstance prevents already used objects and ids', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); expect( () => instanceManager.addHostCreatedInstance(object, 0), throwsAssertionError, ); expect( () => instanceManager.addHostCreatedInstance( CopyableObject(pigeon_instanceManager: instanceManager), 0, ), throwsAssertionError, ); }); test('addFlutterCreatedInstance', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addDartCreatedInstance(object); final int? instanceId = instanceManager.getIdentifier(object); expect(instanceId, isNotNull); expect( instanceManager.getInstanceWithWeakReference(instanceId!), object, ); }); test('removeWeakReference', () { int? weakInstanceId; final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (int instanceId) { weakInstanceId = instanceId; }); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.removeWeakReference(object), 0); expect( instanceManager.getInstanceWithWeakReference(0), isA<CopyableObject>(), ); expect(weakInstanceId, 0); }); test('removeWeakReference removes only weak reference', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.removeWeakReference(object), 0); final CopyableObject copy = instanceManager.getInstanceWithWeakReference( 0, )!; expect(identical(object, copy), isFalse); }); test('removeStrongReference', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); instanceManager.removeWeakReference(object); expect(instanceManager.remove(0), isA<CopyableObject>()); expect(instanceManager.containsIdentifier(0), isFalse); }); test('removeStrongReference removes only strong reference', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.remove(0), isA<CopyableObject>()); expect( instanceManager.getInstanceWithWeakReference(0), object, ); }); test('getInstance can add a new weak reference', () { final PigeonInstanceManager instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final CopyableObject object = CopyableObject( pigeon_instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(object, 0); instanceManager.removeWeakReference(object); final CopyableObject newWeakCopy = instanceManager.getInstanceWithWeakReference( 0, )!; expect(identical(object, newWeakCopy), isFalse); }); }); } class CopyableObject extends PigeonProxyApiBaseClass { // ignore: non_constant_identifier_names CopyableObject({super.pigeon_instanceManager}); @override // ignore: non_constant_identifier_names CopyableObject pigeon_copy() { return CopyableObject(pigeon_instanceManager: pigeon_instanceManager); } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart", "repo_id": "packages", "token_count": 1859 }
996
rootProject.name = 'test_plugin'
packages/packages/pigeon/platform_tests/test_plugin/android/settings.gradle/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/settings.gradle", "repo_id": "packages", "token_count": 11 }
997
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter @testable import test_plugin class MockBinaryMessenger<T>: NSObject, FlutterBinaryMessenger { let codec: FlutterMessageCodec var result: T? private(set) var handlers: [String: FlutterBinaryMessageHandler] = [:] init(codec: FlutterMessageCodec) { self.codec = codec super.init() } func send(onChannel channel: String, message: Data?) {} func send( onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply? = nil ) { if let result = result { callback?(codec.encode([result])) } } func setMessageHandlerOnChannel( _ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler? = nil ) -> FlutterBinaryMessengerConnection { handlers[channel] = handler return .init(handlers.count) } func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) {} }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MockBinaryMessenger.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MockBinaryMessenger.swift", "repo_id": "packages", "token_count": 339 }
998
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PLATFORM_TESTS_TEST_PLUGIN_WINDOWS_TEST_UTILS_ECHO_MESSENGER_H_ #define PLATFORM_TESTS_TEST_PLUGIN_WINDOWS_TEST_UTILS_ECHO_MESSENGER_H_ #include <flutter/binary_messenger.h> #include <flutter/encodable_value.h> #include <flutter/message_codec.h> namespace testing { // A BinaryMessenger that replies with the first argument sent to it. class EchoMessenger : public flutter::BinaryMessenger { public: // Creates an echo messenger that expects MessageCalls encoded with the given // codec. EchoMessenger(const flutter::MessageCodec<flutter::EncodableValue>* codec); virtual ~EchoMessenger(); // flutter::BinaryMessenger: void Send(const std::string& channel, const uint8_t* message, size_t message_size, flutter::BinaryReply reply = nullptr) const override; void SetMessageHandler(const std::string& channel, flutter::BinaryMessageHandler handler) override; private: const flutter::MessageCodec<flutter::EncodableValue>* codec_; }; } // namespace testing #endif // PLATFORM_TESTS_TEST_PLUGIN_WINDOWS_TEST_UTILS_ECHO_MESSENGER_H_
packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/echo_messenger.h/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/echo_messenger.h", "repo_id": "packages", "token_count": 456 }
999
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:pigeon/ast.dart'; import 'package:pigeon/generator_tools.dart'; import 'package:pigeon/pigeon_lib.dart'; import 'package:test/test.dart'; class _ValidatorGeneratorAdapter implements GeneratorAdapter { _ValidatorGeneratorAdapter(this.sink); @override List<FileType> fileTypeList = const <FileType>[FileType.na]; bool didCallValidate = false; final IOSink? sink; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) {} @override IOSink? shouldGenerate(PigeonOptions options, FileType _) => sink; @override List<Error> validate(PigeonOptions options, Root root) { didCallValidate = true; return <Error>[ Error(message: '_ValidatorGenerator'), ]; } } void main() { /// Creates a temporary file named [filename] then calls [callback] with a /// [File] representing that temporary directory. The file will be deleted /// after the [callback] is executed. void withTempFile(String filename, void Function(File) callback) { final Directory dir = Directory.systemTemp.createTempSync(); final String path = '${dir.path}/$filename'; final File file = File(path); file.createSync(); try { callback(file); } finally { dir.deleteSync(recursive: true); } } ParseResults parseSource(String source) { final Pigeon dartle = Pigeon.setup(); ParseResults? results; withTempFile('source.dart', (File file) { file.writeAsStringSync(source); results = dartle.parseFile(file.path); }); return results!; } test('parse args - input', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--input', 'foo.dart']); expect(opts.input, equals('foo.dart')); }); test('parse args - dart_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--dart_out', 'foo.dart']); expect(opts.dartOut, equals('foo.dart')); }); test('parse args - java_package', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--java_package', 'com.google.foo']); expect(opts.javaOptions?.package, equals('com.google.foo')); }); test('parse args - input', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--java_out', 'foo.java']); expect(opts.javaOut, equals('foo.java')); }); test('parse args - objc_header_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--objc_header_out', 'foo.h']); expect(opts.objcHeaderOut, equals('foo.h')); }); test('parse args - objc_source_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--objc_source_out', 'foo.m']); expect(opts.objcSourceOut, equals('foo.m')); }); test('parse args - swift_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--swift_out', 'Foo.swift']); expect(opts.swiftOut, equals('Foo.swift')); }); test('parse args - kotlin_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--kotlin_out', 'Foo.kt']); expect(opts.kotlinOut, equals('Foo.kt')); }); test('parse args - kotlin_package', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--kotlin_package', 'com.google.foo']); expect(opts.kotlinOptions?.package, equals('com.google.foo')); }); test('parse args - cpp_header_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--cpp_header_out', 'foo.h']); expect(opts.cppHeaderOut, equals('foo.h')); }); test('parse args - java_use_generated_annotation', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--java_use_generated_annotation']); expect(opts.javaOptions!.useGeneratedAnnotation, isTrue); }); test('parse args - cpp_source_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--cpp_source_out', 'foo.cpp']); expect(opts.cppSourceOut, equals('foo.cpp')); }); test('parse args - one_language', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--one_language']); expect(opts.oneLanguage, isTrue); }); test('parse args - ast_out', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--ast_out', 'stdout']); expect(opts.astOut, equals('stdout')); }); test('parse args - base_path', () { final PigeonOptions opts = Pigeon.parseArgs(<String>['--base_path', './foo/']); expect(opts.basePath, equals('./foo/')); }); test('simple parse api', () { const String code = ''' class Input1 { String? input; } class Output1 { String? output; } @HostApi() abstract class Api1 { Output1 doit(Input1 input); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); final Root root = parseResult.root; expect(root.classes.length, equals(2)); expect(root.apis.length, equals(1)); expect(root.apis[0].name, equals('Api1')); expect(root.apis[0].methods.length, equals(1)); expect(root.apis[0].methods[0].name, equals('doit')); expect(root.apis[0].methods[0].parameters[0].name, equals('input')); expect( root.apis[0].methods[0].parameters[0].type.baseName, equals('Input1')); expect(root.apis[0].methods[0].returnType.baseName, equals('Output1')); Class? input; Class? output; for (final Class classDefinition in root.classes) { if (classDefinition.name == 'Input1') { input = classDefinition; } else if (classDefinition.name == 'Output1') { output = classDefinition; } } expect(input, isNotNull); expect(output, isNotNull); expect(input?.fields.length, equals(1)); expect(input?.fields[0].name, equals('input')); expect(input?.fields[0].type.baseName, equals('String')); expect(input?.fields[0].type.isNullable, isTrue); expect(output?.fields.length, equals(1)); expect(output?.fields[0].name, equals('output')); expect(output?.fields[0].type.baseName, equals('String')); expect(output?.fields[0].type.isNullable, isTrue); }); test('invalid datatype', () { const String source = ''' class InvalidDatatype { dynamic something; } @HostApi() abstract class Api { InvalidDatatype foo(); } '''; final ParseResults results = parseSource(source); expect(results.errors.length, 1); expect(results.errors[0].message, contains('InvalidDatatype')); expect(results.errors[0].message, contains('dynamic')); }); test('enum in classes', () { const String code = ''' enum Enum1 { one, two, } class ClassWithEnum { Enum1? enum1; } @HostApi abstract class Api { ClassWithEnum foo(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.classes.length, equals(1)); expect(results.root.classes[0].name, equals('ClassWithEnum')); expect(results.root.classes[0].fields.length, equals(1)); expect(results.root.classes[0].fields[0].type.baseName, equals('Enum1')); expect(results.root.classes[0].fields[0].type.isNullable, isTrue); expect(results.root.classes[0].fields[0].name, equals('enum1')); }); test('two methods', () { const String code = ''' class Input1 { String? input; } class Output1 { int? output; } @HostApi() abstract class ApiTwoMethods { Output1 method1(Input1 input); Output1 method2(Input1 input); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(2)); expect(results.root.apis[0].methods[0].name, equals('method1')); expect(results.root.apis[0].methods[1].name, equals('method2')); }); test('nested', () { const String code = ''' class Input1 { String? input; } class Nested { Input1? input; } @HostApi() abstract class Api { Nested foo(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.classes.length, equals(2)); final Class nested = results.root.classes.firstWhere((Class x) => x.name == 'Nested'); expect(nested.fields.length, equals(1)); expect(nested.fields[0].type.baseName, equals('Input1')); expect(nested.fields[0].type.isNullable, isTrue); }); test('flutter api', () { const String code = ''' class Input1 { String? input; } class Output1 { int? output; } @FlutterApi() abstract class AFlutterApi { Output1 doit(Input1 input); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.apis.length, equals(1)); expect(results.root.apis[0].name, equals('AFlutterApi')); expect(results.root.apis[0], isA<AstFlutterApi>()); }); test('void host api', () { const String code = ''' class Input1 { String? input; } @HostApi() abstract class VoidApi { void doit(Input1 input); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.apis.length, equals(1)); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].name, equals('VoidApi')); expect(results.root.apis[0].methods[0].returnType.isVoid, isTrue); }); test('void arg host api', () { const String code = ''' class Output1 { String? output; } @HostApi() abstract class VoidArgApi { Output1 doit(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.apis.length, equals(1)); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].name, equals('VoidArgApi')); expect( results.root.apis[0].methods[0].returnType.baseName, equals('Output1')); expect(results.root.apis[0].methods[0].parameters.isEmpty, isTrue); }); test('mockDartClass', () { const String code = ''' class Output1 { String? output; } @HostApi(dartHostTestHandler: 'ApiWithMockDartClassMock') abstract class ApiWithMockDartClass { Output1 doit(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, equals(0)); expect(results.root.apis.length, equals(1)); expect( (results.root.apis[0] as AstHostApi).dartHostTestHandler, equals('ApiWithMockDartClassMock'), ); }); test('only visible from nesting', () { const String code = ''' class OnlyVisibleFromNesting { String? foo; } class Nestor { OnlyVisibleFromNesting? nested; } @HostApi() abstract class NestorApi { Nestor getit(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); final List<String> classNames = results.root.classes.map((Class x) => x.name).toList(); expect(classNames.length, 2); expect(classNames.contains('Nestor'), true); expect(classNames.contains('OnlyVisibleFromNesting'), true); }); test('copyright flag', () { final PigeonOptions results = Pigeon.parseArgs(<String>['--copyright_header', 'foobar.txt']); expect(results.copyrightHeader, 'foobar.txt'); }); test('Dart generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions(copyrightHeader: './copyright_header.txt'); final DartGeneratorAdapter dartGeneratorAdapter = DartGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); dartGeneratorAdapter.generate(buffer, options, root, FileType.na); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('Java generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions( javaOut: 'Foo.java', copyrightHeader: './copyright_header.txt'); final JavaGeneratorAdapter javaGeneratorAdapter = JavaGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); javaGeneratorAdapter.generate(buffer, options, root, FileType.na); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('Objc header generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions(copyrightHeader: './copyright_header.txt'); final ObjcGeneratorAdapter objcHeaderGeneratorAdapter = ObjcGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); objcHeaderGeneratorAdapter.generate(buffer, options, root, FileType.header); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('Objc source generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions(copyrightHeader: './copyright_header.txt'); final ObjcGeneratorAdapter objcSourceGeneratorAdapter = ObjcGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); objcSourceGeneratorAdapter.generate(buffer, options, root, FileType.source); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('Swift generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions( swiftOut: 'Foo.swift', copyrightHeader: './copyright_header.txt'); final SwiftGeneratorAdapter swiftGeneratorAdapter = SwiftGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); swiftGeneratorAdapter.generate(buffer, options, root, FileType.na); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('C++ header generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions( cppHeaderOut: 'Foo.h', copyrightHeader: './copyright_header.txt'); final CppGeneratorAdapter cppHeaderGeneratorAdapter = CppGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); cppHeaderGeneratorAdapter.generate(buffer, options, root, FileType.header); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('C++ source generator copyright flag', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions(copyrightHeader: './copyright_header.txt'); final CppGeneratorAdapter cppSourceGeneratorAdapter = CppGeneratorAdapter(fileTypeList: <FileType>[FileType.source]); final StringBuffer buffer = StringBuffer(); cppSourceGeneratorAdapter.generate(buffer, options, root, FileType.source); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('nested enum', () { const String code = ''' enum NestedEnum { one, two } class NestedEnum1 { NestedEnum? test; } class NestedEnum2 { NestedEnum1? class1; } class NestedEnum3 { NestedEnum2? class1; int? n; } @HostApi() abstract class NestedEnumApi { void method(NestedEnum3 foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); expect(parseResult.root.apis.length, 1); expect(parseResult.root.classes.length, 3); expect(parseResult.root.enums.length, 1); }); test('test circular references', () { const String code = ''' class Foo { Bar? bar; } class Bar { Foo? foo; } @HostApi() abstract class NotificationsHostApi { void doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.classes.length, 2); final Class foo = results.root.classes.firstWhere((Class aClass) => aClass.name == 'Foo'); expect(foo.fields.length, 1); expect(foo.fields[0].type.baseName, 'Bar'); }); test('test compilation error', () { const String code = 'Hello\n'; final ParseResults results = parseSource(code); expect(results.errors.length, greaterThanOrEqualTo(1)); expect(results.errors[0].lineNumber, 1); }); test('test method in data class error', () { const String code = ''' class Foo { int? x; int? foo() { return x; } } @HostApi() abstract class Api { Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Method')); }); test('test field initialization', () { const String code = ''' class Foo { int? x = 123; } @HostApi() abstract class Api { Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 2); expect(results.errors[0].message, contains('Initialization')); }); test('test field in api error', () { const String code = ''' class Foo { int? x; } @HostApi() abstract class Api { int? x; Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 7); expect(results.errors[0].message, contains('Field')); }); test('constructor in data class', () { const String code = ''' class Foo { int? x; Foo({this.x}); } @HostApi() abstract class Api { Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); }); test('constructor body in data class', () { const String code = ''' class Foo { int? x; Foo({this.x}) { print('hi'); } } @HostApi() abstract class Api { Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Constructor')); }); test('constructor body in data class', () { const String code = ''' class Foo { int? x; Foo() : x = 0; } @HostApi() abstract class Api { Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Constructor')); }); test('constructor in api class', () { const String code = ''' class Foo { int? x; } @HostApi() abstract class Api { Api() { print('hi'); } Foo doit(Foo foo); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 7); expect(results.errors[0].message, contains('Constructor')); }); test('test invalid import', () { const String code = "import 'foo.dart';\n"; final ParseResults results = parseSource(code); expect(results.errors.length, greaterThanOrEqualTo(1)); expect(results.errors[0].lineNumber, 1); }); test('test valid import', () { const String code = "import 'package:pigeon/pigeon.dart';\n"; final ParseResults parseResults = parseSource(code); expect(parseResults.errors.length, 0); }); test('error with static field', () { const String code = ''' class WithStaticField { static int? x; int? y; } @HostApi() abstract class WithStaticFieldApi { void doit(WithStaticField withTemplate); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(1)); expect(parseResult.errors[0].message, contains('static field')); expect(parseResult.errors[0].lineNumber, isNotNull); }); test('parse generics', () { const String code = ''' class Foo { List<int?>? list; } @HostApi() abstract class Api { void doit(Foo foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); final NamedType field = parseResult.root.classes[0].fields[0]; expect(field.type.typeArguments.length, 1); expect(field.type.typeArguments[0].baseName, 'int'); }); test('parse recursive generics', () { const String code = ''' class Foo { List<List<int?>?>? list; } @HostApi() abstract class Api { void doit(Foo foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); final NamedType field = parseResult.root.classes[0].fields[0]; expect(field.type.typeArguments.length, 1); expect(field.type.typeArguments[0].baseName, 'List'); expect(field.type.typeArguments[0].typeArguments[0].baseName, 'int'); }); test('error nonnull type argument', () { const String code = ''' class Foo { List<int> list; } @HostApi() abstract class Api { void doit(Foo foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(1)); expect(parseResult.errors[0].message, contains('Generic type parameters must be nullable')); expect(parseResult.errors[0].message, contains('"list"')); expect(parseResult.errors[0].lineNumber, 2); }); test('enums argument host', () { const String code = ''' enum Foo { one, two, } @HostApi() abstract class Api { void doit(Foo foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); }); test('enums argument flutter', () { const String code = ''' enum Foo { one, two, } @FlutterApi() abstract class Api { void doit(Foo foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); }); test('enums list argument', () { const String code = ''' enum Foo { one, two } @HostApi() abstract class Api { void doit(List<Foo> foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); }); test('enums map argument key', () { const String code = ''' enum Foo { one, two } @HostApi() abstract class Api { void doit(Map<Foo, Object> foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); }); test('enums map argument value', () { const String code = ''' enum Foo { one, two } @HostApi() abstract class Api { void doit(Map<Foo, Object> foo); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); }); test('enums return value', () { const String code = ''' enum Foo { one, two, } @HostApi() abstract class Api { Foo doit(); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); }); test('return type generics', () { const String code = ''' @HostApi() abstract class Api { List<double?> doit(); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.root.apis[0].methods[0].returnType.baseName, 'List'); expect( parseResult .root.apis[0].methods[0].returnType.typeArguments[0].baseName, 'double'); expect( parseResult .root.apis[0].methods[0].returnType.typeArguments[0].isNullable, isTrue); }); test('argument generics', () { const String code = ''' @HostApi() abstract class Api { void doit(int x, List<double?> value); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.root.apis[0].methods[0].parameters[1].type.baseName, 'List'); expect( parseResult.root.apis[0].methods[0].parameters[1].type.typeArguments[0] .baseName, 'double'); expect( parseResult.root.apis[0].methods[0].parameters[1].type.typeArguments[0] .isNullable, isTrue); }); test('map generics', () { const String code = ''' class Foo { Map<String?, int?> map; } @HostApi() abstract class Api { void doit(Foo foo); } '''; final ParseResults parseResult = parseSource(code); final NamedType field = parseResult.root.classes[0].fields[0]; expect(field.type.typeArguments.length, 2); expect(field.type.typeArguments[0].baseName, 'String'); expect(field.type.typeArguments[1].baseName, 'int'); }); test('two parameters', () { const String code = ''' class Input { String? input; } @HostApi() abstract class Api { void method(Input input1, Input input2); } '''; final ParseResults results = parseSource(code); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].methods[0].name, equals('method')); expect(results.root.apis[0].methods[0].parameters.length, 2); }); test('no type name argument', () { const String code = ''' @HostApi() abstract class Api { void method(x); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Parameters must specify their type')); }); test('custom objc selector', () { const String code = ''' @HostApi() abstract class Api { @ObjCSelector('subtractValue:by:') void subtract(int x, int y); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].methods[0].objcSelector, equals('subtractValue:by:')); }); test('custom objc invalid selector', () { const String code = ''' @HostApi() abstract class Api { @ObjCSelector('subtractValue:by:error:') void subtract(int x, int y); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Invalid selector, expected 2 parameters')); }); test('custom objc no parameters', () { const String code = ''' @HostApi() abstract class Api { @ObjCSelector('foobar') void initialize(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].methods[0].objcSelector, equals('foobar')); }); test('custom swift valid function signature', () { const String code = ''' @HostApi() abstract class Api { @SwiftFunction('subtractValue(_:by:)') void subtract(int x, int y); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].methods[0].swiftFunction, equals('subtractValue(_:by:)')); }); test('custom swift invalid function signature', () { const String code = ''' @HostApi() abstract class Api { @SwiftFunction('subtractValue(_:by:error:)') void subtract(int x, int y); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Invalid function signature, expected 2 parameters')); }); test('custom swift function signature no parameters', () { const String code = ''' @HostApi() abstract class Api { @SwiftFunction('foobar()') void initialize(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); expect(results.root.apis[0].methods.length, equals(1)); expect(results.root.apis[0].methods[0].swiftFunction, equals('foobar()')); }); test('dart test has copyright', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); const PigeonOptions options = PigeonOptions( copyrightHeader: './copyright_header.txt', dartTestOut: 'stdout', dartOut: 'stdout', ); final DartTestGeneratorAdapter dartTestGeneratorAdapter = DartTestGeneratorAdapter(); final StringBuffer buffer = StringBuffer(); dartTestGeneratorAdapter.generate(buffer, options, root, FileType.source); expect(buffer.toString(), startsWith('// Copyright 2013')); }); test('only class reference is type argument for return value', () { const String code = ''' class Foo { int? foo; } @HostApi() abstract class Api { List<Foo?> grabAll(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.classes.length, 1); expect(results.root.classes[0].name, 'Foo'); }); test('only class reference is type argument for argument', () { const String code = ''' class Foo { int? foo; } @HostApi() abstract class Api { void storeAll(List<Foo?> foos); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.classes.length, 1); expect(results.root.classes[0].name, 'Foo'); }); test('recurse into type parameters', () { const String code = ''' class Foo { int? foo; List<Bar?> bars; } class Bar { int? bar; } @HostApi() abstract class Api { void storeAll(List<Foo?> foos); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.classes.length, 2); expect( results.root.classes .where((Class element) => element.name == 'Foo') .length, 1); expect( results.root.classes .where((Class element) => element.name == 'Bar') .length, 1); }); test('undeclared class in argument type argument', () { const String code = ''' @HostApi() abstract class Api { void storeAll(List<Foo?> foos); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Unknown type: Foo')); }); test('Object type argument', () { const String code = ''' @HostApi() abstract class Api { void storeAll(List<Object?> foos); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); }); test('Enum key not supported', () { const String code = ''' enum MessageKey { title, subtitle, description, } class Message { int? id; Map<MessageKey?, String?>? additionalProperties; } @HostApi() abstract class HostApiBridge { void sendMessage(Message message); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); }); test('Export unreferenced enums', () { const String code = ''' enum MessageKey { title, subtitle, description, } class Message { int? id; Map<int?, String?>? additionalProperties; } @HostApi() abstract class HostApiBridge { void sendMessage(Message message); } '''; final ParseResults results = parseSource(code); expect(results.root.enums.length, 1); expect(results.root.enums[0].name, 'MessageKey'); }); test('@ConfigurePigeon JavaOptions.copyrightHeader', () { const String code = ''' @ConfigurePigeon(PigeonOptions( javaOptions: JavaOptions(copyrightHeader: <String>['A', 'Header']), )) class Message { int? id; } '''; final ParseResults results = parseSource(code); final PigeonOptions options = PigeonOptions.fromMap(results.pigeonOptions!); expect(options.javaOptions!.copyrightHeader, <String>['A', 'Header']); }); test('@ConfigurePigeon DartOptions.copyrightHeader', () { const String code = ''' @ConfigurePigeon(PigeonOptions( dartOptions: DartOptions(copyrightHeader: <String>['A', 'Header']), )) class Message { int? id; } '''; final ParseResults results = parseSource(code); final PigeonOptions options = PigeonOptions.fromMap(results.pigeonOptions!); expect(options.dartOptions!.copyrightHeader, <String>['A', 'Header']); }); test('@ConfigurePigeon ObjcOptions.copyrightHeader', () { const String code = ''' @ConfigurePigeon(PigeonOptions( objcOptions: ObjcOptions(copyrightHeader: <String>['A', 'Header']), )) class Message { int? id; } '''; final ParseResults results = parseSource(code); final PigeonOptions options = PigeonOptions.fromMap(results.pigeonOptions!); expect(options.objcOptions!.copyrightHeader, <String>['A', 'Header']); }); test('return nullable', () { const String code = ''' @HostApi() abstract class Api { int? calc(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis[0].methods[0].returnType.isNullable, isTrue); }); test('nullable parameters', () { const String code = ''' @HostApi() abstract class Api { void calc(int? value); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect( results.root.apis[0].methods[0].parameters[0].type.isNullable, isTrue); }); test('task queue specified', () { const String code = ''' @HostApi() abstract class Api { @TaskQueue(type: TaskQueueType.serialBackgroundThread) int? calc(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis[0].methods[0].taskQueueType, equals(TaskQueueType.serialBackgroundThread)); }); test('task queue unspecified', () { const String code = ''' @HostApi() abstract class Api { int? calc(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis[0].methods[0].taskQueueType, equals(TaskQueueType.serial)); }); test('unsupported task queue on FlutterApi', () { const String code = ''' @FlutterApi() abstract class Api { @TaskQueue(type: TaskQueueType.serialBackgroundThread) int? calc(); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].message, contains('Unsupported TaskQueue specification')); }); test('generator validation', () async { final Completer<void> completer = Completer<void>(); withTempFile('foo.dart', (File input) async { final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter(stdout); final int result = await Pigeon.run(<String>['--input', input.path], adapters: <GeneratorAdapter>[generator]); expect(generator.didCallValidate, isTrue); expect(result, isNot(0)); completer.complete(); }); await completer.future; }); test('generator validation skipped', () async { final Completer<void> completer = Completer<void>(); withTempFile('foo.dart', (File input) async { final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter(null); final int result = await Pigeon.run( <String>['--input', input.path, '--dart_out', 'foo.dart'], adapters: <GeneratorAdapter>[generator]); expect(generator.didCallValidate, isFalse); expect(result, equals(0)); completer.complete(); }); await completer.future; }); test('run with PigeonOptions', () async { final Completer<void> completer = Completer<void>(); withTempFile('foo.dart', (File input) async { final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter(null); final int result = await Pigeon.runWithOptions( PigeonOptions(input: input.path, dartOut: 'foo.dart'), adapters: <GeneratorAdapter>[generator]); expect(generator.didCallValidate, isFalse); expect(result, equals(0)); completer.complete(); }); await completer.future; }); test('unsupported non-positional parameters on FlutterApi', () { const String code = ''' @FlutterApi() abstract class Api { int? calc({int? anInt}); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].message, contains('FlutterApi method parameters must be positional')); }); test('unsupported optional parameters on FlutterApi', () { const String code = ''' @FlutterApi() abstract class Api { int? calc([int? anInt]); } '''; final ParseResults results = parseSource(code); expect(results.errors.length, 1); expect(results.errors[0].message, contains('FlutterApi method parameters must not be optional')); }); test('simple parse ProxyApi', () { const String code = ''' @ProxyApi() abstract class MyClass { MyClass(); late String aField; late void Function() aCallbackMethod; void aMethod(); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(0)); final Root root = parseResult.root; expect(root.apis.length, equals(1)); final AstProxyApi proxyApi = root.apis.single as AstProxyApi; expect(proxyApi.name, equals('MyClass')); expect(proxyApi.constructors.single.name, equals('')); expect(proxyApi.methods.length, equals(2)); for (final Method method in proxyApi.methods) { if (method.location == ApiLocation.host) { expect(method.name, equals('aMethod')); } else if (method.location == ApiLocation.flutter) { expect(method.name, equals('aCallbackMethod')); } } }); group('ProxyApi validation', () { test('error with using data class', () { const String code = ''' class DataClass { late int input; } @ProxyApi() abstract class MyClass { MyClass(DataClass input); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors.length, equals(1)); expect( parseResult.errors.single.message, contains('ProxyApis do not support data classes'), ); }); test('super class must be proxy api', () { const String code = ''' class DataClass { late int input; } @ProxyApi() abstract class MyClass extends DataClass { void aMethod(); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains('Super class of MyClass is not marked as a @ProxyApi'), ); }); test('interface must be proxy api', () { const String code = ''' class DataClass { late int input; } @ProxyApi() abstract class MyClass implements DataClass { void aMethod(); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains('Interface of MyClass is not marked as a @ProxyApi'), ); }); test('unattached fields can not be inherited', () { const String code = ''' @ProxyApi() abstract class MyClass extends MyOtherClass { } @ProxyApi() abstract class MyOtherClass { late int aField; } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains( 'Unattached fields can not be inherited. Unattached field found for parent class: aField', ), ); }); test( 'api is not used as an attached field while having an unattached field', () { const String code = ''' @ProxyApi() abstract class MyClass { @attached late MyOtherClass anAttachedField; } @ProxyApi() abstract class MyOtherClass { late int aField; } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains( 'ProxyApis with unattached fields can not be used as attached fields: anAttachedField', ), ); }); test( 'api is not used as an attached field while having a required Flutter method', () { const String code = ''' @ProxyApi() abstract class MyClass { @attached late MyOtherClass anAttachedField; } @ProxyApi() abstract class MyOtherClass { late void Function() aCallbackMethod; } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains( 'ProxyApis with required callback methods can not be used as attached fields: anAttachedField', ), ); }); test('interfaces can only have callback methods', () { const String code = ''' @ProxyApi() abstract class MyClass implements MyOtherClass { } @ProxyApi() abstract class MyOtherClass { MyOtherClass(); } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains( 'ProxyApis used as interfaces can only have callback methods: `MyClass` implements `MyOtherClass`', ), ); }); test('attached fields must be a ProxyApi', () { const String code = ''' @ProxyApi() abstract class MyClass { @attached late int aField; } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains('Attached fields must be a ProxyApi: int'), ); }); test('attached fields must not be nullable', () { const String code = ''' @ProxyApi() abstract class MyClass { @attached late MyClass? aField; } '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); expect( parseResult.errors[0].message, contains('Attached fields must not be nullable: MyClass?'), ); }); }); }
packages/packages/pigeon/test/pigeon_lib_test.dart/0
{ "file_path": "packages/packages/pigeon/test/pigeon_lib_test.dart", "repo_id": "packages", "token_count": 15631 }
1,000
name: plaform_example description: Demonstrates how to use the plaform plugin. publish_to: 'none' version: 1.0.0+1 environment: sdk: ^3.1.0 dependencies: flutter: sdk: flutter platform: path: ../ dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
packages/packages/platform/example/pubspec.yaml/0
{ "file_path": "packages/packages/platform/example/pubspec.yaml", "repo_id": "packages", "token_count": 125 }
1,001
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint pointer_interceptor_ios.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = 'pointer_interceptor_ios' s.version = '0.0.1' s.summary = 'Implementation of pointer_interceptor for iOS.' s.description = <<-DESC This Flutter plugin provides means to prevent gestures from being swallowed by PlatformView on iOS. DESC s.homepage = 'https://github.com/flutter/packages' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/pointer_interceptor/pointer_interceptor_ios' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' s.platform = :ios, '12.0' # Flutter.framework does not contain a i386 slice. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } s.swift_version = '5.0' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', 'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift', } s.resource_bundles = {'pointer_interceptor_ios_privacy' => ['Resources/PrivacyInfo.xcprivacy']} end
packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/pointer_interceptor_ios.podspec/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/pointer_interceptor_ios.podspec", "repo_id": "packages", "token_count": 594 }
1,002
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/messages.g.dart', swiftOut: 'ios/Classes/messages.g.swift', copyrightHeader: 'pigeons/copyright.txt', )) /// Home screen quick-action shortcut item. class ShortcutItemMessage { ShortcutItemMessage( this.type, this.localizedTitle, this.icon, ); /// The identifier of this item; should be unique within the app. String type; /// Localized title of the item. String localizedTitle; /// Name of native resource to be displayed as the icon for this item. String? icon; } @HostApi() abstract class IOSQuickActionsApi { /// Sets the dynamic shortcuts for the app. void setShortcutItems(List<ShortcutItemMessage> itemsList); /// Removes all dynamic shortcuts. void clearShortcutItems(); } @FlutterApi() abstract class IOSQuickActionsFlutterApi { /// Sends a string representing a shortcut from the native platform to the app. void launchAction(String action); }
packages/packages/quick_actions/quick_actions_ios/pigeons/messages.dart/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/pigeons/messages.dart", "repo_id": "packages", "token_count": 358 }
1,003
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/hello/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/rfw/example/hello/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,004
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/remote/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/rfw/example/remote/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,005
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -ex clang++ --target=wasm32 -nostdlib "-Wl,--export-all" "-Wl,--no-entry" -o calculator.wasm calculator.cc dart encode.dart calculator.rfwtxt calculator.rfw
packages/packages/rfw/example/wasm/logic/build.sh/0
{ "file_path": "packages/packages/rfw/example/wasm/logic/build.sh", "repo_id": "packages", "token_count": 111 }
1,006
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script is mentioned in the README.md file. # This script is also called from: ../../customer_testing.sh set -e pushd test_coverage; dart pub get; popd set -x dart --enable-asserts test_coverage/bin/test_coverage.dart "$@"
packages/packages/rfw/run_tests.sh/0
{ "file_path": "packages/packages/rfw/run_tests.sh", "repo_id": "packages", "token_count": 129 }
1,007
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates support matrix in README to indicate that iOS 11 is no longer supported. * Clients on versions of Flutter that still support iOS 11 can continue to use this package with iOS 11, but will not receive any further updates to the iOS implementation. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.2.2 * Updates documentation for `containsKey`. ## 2.2.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Fixes the example app to be debuggable on Android. * Deletes deprecated splash screen meta-data element. ## 2.2.0 * Adds `allowList` option to setPrefix. ## 2.1.2 * Fixes singleton initialization race condition introduced during NNBD transition. * Updates minimum supported macOS version to 10.14. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.1.1 * Updates iOS minimum version in README. ## 2.1.0 * Adds `setPrefix` method. ## 2.0.20 * Adds README discussion of `reload()`. ## 2.0.19 * Updates README to use code excerpts. * Aligns Dart and Flutter SDK constraints. ## 2.0.18 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.0.17 * Updates code for stricter lint checks. ## 2.0.16 * Switches to the new `shared_preferences_foundation` implementation package for iOS and macOS. * Updates code for `no_leading_underscores_for_local_identifiers` lint. * Updates minimum Flutter version to 2.10. ## 2.0.15 * Minor fixes for new analysis options. ## 2.0.14 * Adds OS version support information to README. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.0.13 * Updates documentation on README.md. ## 2.0.12 * Removes dependency on `meta`. ## 2.0.11 * Corrects example for mocking in readme. ## 2.0.10 * Removes obsolete manual registration of Windows and Linux implementations. ## 2.0.9 * Fixes newly enabled analyzer options. * Updates example app Android compileSdkVersion to 31. * Moved Android and iOS implementations to federated packages. ## 2.0.8 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 2.0.7 * Add iOS unit test target. * Updated Android lint settings. * Fix string clash with double entries on Android ## 2.0.6 * Migrate maven repository from jcenter to mavenCentral. ## 2.0.5 * Fix missing declaration of windows' default_package ## 2.0.4 * Fix a regression with simultaneous writes on Android. ## 2.0.3 * Android: don't create additional Handler when method channel is called. ## 2.0.2 * Don't create additional thread pools when method channel is called. ## 2.0.1 * Removed deprecated [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask) was deprecated in API level 30 ([#3481](https://github.com/flutter/plugins/pull/3481)) ## 2.0.0 * Migrate to null-safety. **Breaking changes**: * Setters no longer accept null to mean removing values. If you were previously using `set*(key, null)` for removing, use `remove(key)` instead. ## 0.5.13+2 * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) ## 0.5.13+1 * Update Flutter SDK constraint. ## 0.5.13 * Update integration test examples to use `testWidgets` instead of `test`. ## 0.5.12+4 * Remove unused `test` dependency. ## 0.5.12+3 * Check in windows/ directory for example/ ## 0.5.12+2 * Update android compileSdkVersion to 29. ## 0.5.12+1 * Check in linux/ directory for example/ ## 0.5.12 * Keep handling deprecated Android v1 classes for backward compatibility. ## 0.5.11 * Support Windows by default. ## 0.5.10 * Update package:e2e -> package:integration_test ## 0.5.9 * Update package:e2e reference to use the local version in the flutter/plugins repository. ## 0.5.8 * Support Linux by default. ## 0.5.7+3 * Post-v2 Android embedding cleanup. ## 0.5.7+2 * Update lower bound of dart dependency to 2.1.0. ## 0.5.7+1 * Declare API stability and compatibility with `1.0.0` (more details at: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0). ## 0.5.7 * Remove Android dependencies fallback. * Require Flutter SDK 1.12.13+hotfix.5 or greater. * Fix CocoaPods podspec lint warnings. ## 0.5.6+3 * Fix deprecated API usage warning. ## 0.5.6+2 * Make the pedantic dev_dependency explicit. ## 0.5.6+1 * Updated README ## 0.5.6 * Support `web` by default. * Require Flutter SDK 1.12.13+hotfix.4 or greater. ## 0.5.5 * Support macos by default. ## 0.5.4+10 * Adds a `shared_preferences_macos` package. ## 0.5.4+9 * Remove the deprecated `author:` field from pubspec.yaml * Migrate the plugin to the pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 0.5.4+8 * Switch `package:shared_preferences` to `package:shared_preferences_platform_interface`. No code changes are necessary in Flutter apps. This is not a breaking change. ## 0.5.4+7 * Restructure the project for Web support. ## 0.5.4+6 * Add missing documentation and a lint to prevent further undocumented APIs. ## 0.5.4+5 * Update and migrate iOS example project by removing flutter_assets, change "English" to "en", remove extraneous xcconfigs and framework outputs, update to Xcode 11 build settings, and remove ARCHS. ## 0.5.4+4 * `setMockInitialValues` needs to handle non-prefixed keys since that's an implementation detail. ## 0.5.4+3 * Android: Suppress casting warnings. ## 0.5.4+2 * Remove AndroidX warnings. ## 0.5.4+1 * Include lifecycle dependency as a compileOnly one on Android to resolve potential version conflicts with other transitive libraries. ## 0.5.4 * Support the v2 Android embedding. * Update to AndroidX. * Migrate to using the new e2e test binding. ## 0.5.3+5 * Define clang module for iOS. ## 0.5.3+4 * Copy `List` instances when reading and writing values to prevent mutations from propagating. ## 0.5.3+3 * `setMockInitialValues` can now be called multiple times and will `reload()` the singleton if necessary. ## 0.5.3+2 * Fix Gradle version. ## 0.5.3+1 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 0.5.3 * Add reload method. ## 0.5.2+2 * Updated Gradle tooling to match Android Studio 3.4. ## 0.5.2+1 * .commit() calls are now run in an async background task on Android. ## 0.5.2 * Add containsKey method. ## 0.5.1+2 * Add a driver test ## 0.5.1+1 * Log a more detailed warning at build time about the previous AndroidX migration. ## 0.5.1 * Use String to save double in Android. ## 0.5.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 0.4.3 * Prevent strings that match special prefixes from being saved. This is a bugfix that prevents apps from accidentally setting special values that would be interpreted incorrectly. ## 0.4.2 * Updated Gradle tooling to match Android Studio 3.1.2. ## 0.4.1 * Added getKeys method. ## 0.4.0 * **Breaking change**. Set SDK constraints to match the Flutter beta release. ## 0.3.3 * Fixed Dart 2 issues. ## 0.3.2 * Added an getter that can retrieve values of any type ## 0.3.1 * Simplified and upgraded Android project template to Android SDK 27. * Updated package description. ## 0.3.0 * **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1). ## 0.2.6 * Added FLT prefix to iOS types ## 0.2.5+1 * Aligned author name with rest of repo. ## 0.2.5 * Fixed crashes when setting null values. They now cause the key to be removed. * Added remove() method ## 0.2.4+1 * Fixed typo in changelog ## 0.2.4 * Added setMockInitialValues * Added a test * Updated README ## 0.2.3 * Suppress warning about unchecked operations when compiling for Android ## 0.2.2 * BREAKING CHANGE: setStringSet API changed to setStringList and plugin now supports ordered storage. ## 0.2.1 * Support arbitrary length integers for setInt. ## 0.2.0+1 * Updated README ## 0.2.0 * Upgrade to new plugin registration. (https://groups.google.com/forum/#!topic/flutter-dev/zba1Ynf2OKM) ## 0.1.1 * Upgrade Android SDK Build Tools to 25.0.3. ## 0.1.0 * Initial Open Source release.
packages/packages/shared_preferences/shared_preferences/CHANGELOG.md/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/CHANGELOG.md", "repo_id": "packages", "token_count": 2929 }
1,008
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.sharedpreferences; import androidx.annotation.NonNull; import java.util.List; /** * An interface used to provide conversion logic between List<String> and String for * SharedPreferencesPlugin. */ public interface SharedPreferencesListEncoder { /** Converts list to String for storing in shared preferences. */ @NonNull String encode(@NonNull List<String> list); /** Converts stored String representing List<String> to List. */ @NonNull List<String> decode(@NonNull String listString); }
packages/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/SharedPreferencesListEncoder.java/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/SharedPreferencesListEncoder.java", "repo_id": "packages", "token_count": 187 }
1,009
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v9.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; class SharedPreferencesApi { /// Constructor for [SharedPreferencesApi]. 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. SharedPreferencesApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Removes property from shared preferences data set. Future<bool> remove(String arg_key) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.remove', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Adds property to shared preferences data set of type bool. Future<bool> setBool(String arg_key, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.setBool', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Adds property to shared preferences data set of type String. Future<bool> setString(String arg_key, String arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.setString', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Adds property to shared preferences data set of type int. Future<bool> setInt(String arg_key, int arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.setInt', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Adds property to shared preferences data set of type double. Future<bool> setDouble(String arg_key, double arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.setDouble', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Adds property to shared preferences data set of type List<String>. Future<bool> setStringList(String arg_key, List<String?> arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.setStringList', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Removes all properties from shared preferences data set with matching prefix. Future<bool> clear(String arg_prefix, List<String?>? arg_allowList) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.clear', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_prefix, arg_allowList]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Gets all properties from shared preferences data set with matching prefix. Future<Map<String?, Object?>> getAll( String arg_prefix, List<String?>? arg_allowList) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.SharedPreferencesApi.getAll', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_prefix, arg_allowList]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as Map<Object?, Object?>?)!.cast<String?, Object?>(); } } }
packages/packages/shared_preferences/shared_preferences_android/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 3625 }
1,010
# Two Dimensional Scrollables A package that provides widgets that scroll in two dimensions, built on the two-dimensional foundation of the Flutter framework. ## Features This package provides support for a TableView widget that scrolls in both the vertical and horizontal axes. ### TableView `TableView` is a subclass of `TwoDimensionalScrollView`, building its provided children lazily in a `TwoDimensionalViewport`. This widget can - Scroll diagonally, or lock axes - Apply decorations to rows and columns - Handle gestures & custom pointers for rows and columns - Pin rows and columns ## Getting started ### Depend on it Run this command with Flutter: ```sh $ flutter pub add two_dimensional_scrollables ``` ### Import it Now in your Dart code, you can use: ```sh import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; ``` ## Usage ### TableView The code in `example/` shows a `TableView` of initially 400 cells, each varying in sizes with a few `TableSpanDecoration`s like background colors and borders. The `builder` constructor is called on demand for the cells that are visible in the TableView. Additional rows can be added on demand while the vertical position can jump between the first and last row using the buttons at the bottom of the screen. ## Changelog See the [Changelog](https://github.com/flutter/packages/blob/main/packages/two_dimensional_scrollables/CHANGELOG.md) for a list of new features and breaking changes. ## Roadmap See the [GitHub project](https://github.com/orgs/flutter/projects/32/) for a prioritized list of feature requests and known issues. ## Additional information The package uses the two-dimensional foundation from the Flutter framework, meaning most of the core functionality of 2D scrolling is not implemented here. This also means any subclass of the foundation can create different 2D scrolling widgets and be added to the collection. If you want to contribute to this package, you can open a pull request in [Flutter Packages](https://github.com/flutter/packages) and add the tag "p: two_dimensional_scrollables".
packages/packages/two_dimensional_scrollables/README.md/0
{ "file_path": "packages/packages/two_dimensional_scrollables/README.md", "repo_id": "packages", "token_count": 544 }
1,011