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. package io.flutter.plugins.camera; import static org.mockito.ArgumentMatchers.anyFloat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import io.flutter.plugins.camera.types.CameraCaptureProperties; import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class CameraCaptureCallbackTest { private CameraCaptureCallback cameraCaptureCallback; private CameraCaptureProperties mockCaptureProps; @Before public void setUp() { CameraCaptureCallback.CameraCaptureStateListener mockCaptureStateListener = mock(CameraCaptureCallback.CameraCaptureStateListener.class); CaptureTimeoutsWrapper mockCaptureTimeouts = mock(CaptureTimeoutsWrapper.class); mockCaptureProps = mock(CameraCaptureProperties.class); cameraCaptureCallback = CameraCaptureCallback.create( mockCaptureStateListener, mockCaptureTimeouts, mockCaptureProps); } @Test public void onCaptureProgressed_doesNotUpdateCameraCaptureProperties() { CameraCaptureSession mockSession = mock(CameraCaptureSession.class); CaptureRequest mockRequest = mock(CaptureRequest.class); CaptureResult mockResult = mock(CaptureResult.class); cameraCaptureCallback.onCaptureProgressed(mockSession, mockRequest, mockResult); verify(mockCaptureProps, never()).setLastLensAperture(anyFloat()); verify(mockCaptureProps, never()).setLastSensorExposureTime(anyLong()); verify(mockCaptureProps, never()).setLastSensorSensitivity(anyInt()); } @Test public void onCaptureCompleted_updatesCameraCaptureProperties() { CameraCaptureSession mockSession = mock(CameraCaptureSession.class); CaptureRequest mockRequest = mock(CaptureRequest.class); TotalCaptureResult mockResult = mock(TotalCaptureResult.class); when(mockResult.get(CaptureResult.LENS_APERTURE)).thenReturn(1.0f); when(mockResult.get(CaptureResult.SENSOR_EXPOSURE_TIME)).thenReturn(2L); when(mockResult.get(CaptureResult.SENSOR_SENSITIVITY)).thenReturn(3); cameraCaptureCallback.onCaptureCompleted(mockSession, mockRequest, mockResult); verify(mockCaptureProps, times(1)).setLastLensAperture(1.0f); verify(mockCaptureProps, times(1)).setLastSensorExposureTime(2L); verify(mockCaptureProps, times(1)).setLastSensorSensitivity(3); } @Test public void onCaptureCompleted_checksBothAutoFocusAndAutoExposure() { CameraCaptureSession mockSession = mock(CameraCaptureSession.class); CaptureRequest mockRequest = mock(CaptureRequest.class); TotalCaptureResult mockResult = mock(TotalCaptureResult.class); cameraCaptureCallback.onCaptureCompleted(mockSession, mockRequest, mockResult); // This is inherently somewhat fragile since it is testing internal implementation details, // but it is important to test that the code is actually using both of the expected states // since it's easy to typo one of these constants as the other. Ideally this would be tested // via the state machine output (CameraCaptureCallbackStatesTest.java), but testing the state // machine requires overriding the keys, so can't test that the right real keys are used in // production. verify(mockResult, times(1)).get(CaptureResult.CONTROL_AE_STATE); verify(mockResult, times(1)).get(CaptureResult.CONTROL_AF_STATE); } }
packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraCaptureCallbackTest.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraCaptureCallbackTest.java", "repo_id": "packages", "token_count": 1219 }
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. package io.flutter.plugins.camerax; import android.app.Activity; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.lifecycle.LifecycleOwner; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.view.TextureRegistry; /** Platform implementation of the camera_plugin implemented with the CameraX library. */ public final class CameraAndroidCameraxPlugin implements FlutterPlugin, ActivityAware { private InstanceManager instanceManager; private FlutterPluginBinding pluginBinding; @VisibleForTesting @Nullable public PendingRecordingHostApiImpl pendingRecordingHostApiImpl; @VisibleForTesting @Nullable public RecorderHostApiImpl recorderHostApiImpl; @VisibleForTesting @Nullable public VideoCaptureHostApiImpl videoCaptureHostApiImpl; @VisibleForTesting @Nullable public ImageAnalysisHostApiImpl imageAnalysisHostApiImpl; @VisibleForTesting @Nullable public ImageCaptureHostApiImpl imageCaptureHostApiImpl; @VisibleForTesting @Nullable public CameraControlHostApiImpl cameraControlHostApiImpl; @VisibleForTesting @Nullable public SystemServicesHostApiImpl systemServicesHostApiImpl; @VisibleForTesting @Nullable public MeteringPointHostApiImpl meteringPointHostApiImpl; @VisibleForTesting @Nullable public Camera2CameraControlHostApiImpl camera2CameraControlHostApiImpl; @VisibleForTesting public @Nullable DeviceOrientationManagerHostApiImpl deviceOrientationManagerHostApiImpl; @VisibleForTesting public @Nullable ProcessCameraProviderHostApiImpl processCameraProviderHostApiImpl; @VisibleForTesting public @Nullable LiveDataHostApiImpl liveDataHostApiImpl; /** * Initialize this within the {@code #configureFlutterEngine} of a Flutter activity or fragment. * * <p>See {@code io.flutter.plugins.camera.MainActivity} for an example. */ public CameraAndroidCameraxPlugin() {} @VisibleForTesting public void setUp( @NonNull BinaryMessenger binaryMessenger, @NonNull Context context, @NonNull TextureRegistry textureRegistry) { // Set up instance manager. instanceManager = InstanceManager.create( identifier -> { new GeneratedCameraXLibrary.JavaObjectFlutterApi(binaryMessenger) .dispose(identifier, reply -> {}); }); // Set up Host APIs. GeneratedCameraXLibrary.InstanceManagerHostApi.setup( binaryMessenger, () -> instanceManager.clear()); GeneratedCameraXLibrary.CameraHostApi.setup( binaryMessenger, new CameraHostApiImpl(binaryMessenger, instanceManager)); GeneratedCameraXLibrary.CameraInfoHostApi.setup( binaryMessenger, new CameraInfoHostApiImpl(binaryMessenger, instanceManager)); GeneratedCameraXLibrary.CameraSelectorHostApi.setup( binaryMessenger, new CameraSelectorHostApiImpl(binaryMessenger, instanceManager)); GeneratedCameraXLibrary.JavaObjectHostApi.setup( binaryMessenger, new JavaObjectHostApiImpl(instanceManager)); processCameraProviderHostApiImpl = new ProcessCameraProviderHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.ProcessCameraProviderHostApi.setup( binaryMessenger, processCameraProviderHostApiImpl); systemServicesHostApiImpl = new SystemServicesHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.SystemServicesHostApi.setup(binaryMessenger, systemServicesHostApiImpl); deviceOrientationManagerHostApiImpl = new DeviceOrientationManagerHostApiImpl(binaryMessenger, instanceManager); GeneratedCameraXLibrary.DeviceOrientationManagerHostApi.setup( binaryMessenger, deviceOrientationManagerHostApiImpl); GeneratedCameraXLibrary.PreviewHostApi.setup( binaryMessenger, new PreviewHostApiImpl(binaryMessenger, instanceManager, textureRegistry)); imageCaptureHostApiImpl = new ImageCaptureHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.ImageCaptureHostApi.setup(binaryMessenger, imageCaptureHostApiImpl); GeneratedCameraXLibrary.CameraHostApi.setup( binaryMessenger, new CameraHostApiImpl(binaryMessenger, instanceManager)); liveDataHostApiImpl = new LiveDataHostApiImpl(binaryMessenger, instanceManager); GeneratedCameraXLibrary.LiveDataHostApi.setup(binaryMessenger, liveDataHostApiImpl); GeneratedCameraXLibrary.ObserverHostApi.setup( binaryMessenger, new ObserverHostApiImpl(binaryMessenger, instanceManager)); imageAnalysisHostApiImpl = new ImageAnalysisHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.ImageAnalysisHostApi.setup(binaryMessenger, imageAnalysisHostApiImpl); GeneratedCameraXLibrary.AnalyzerHostApi.setup( binaryMessenger, new AnalyzerHostApiImpl(binaryMessenger, instanceManager)); GeneratedCameraXLibrary.ImageProxyHostApi.setup( binaryMessenger, new ImageProxyHostApiImpl(binaryMessenger, instanceManager)); GeneratedCameraXLibrary.RecordingHostApi.setup( binaryMessenger, new RecordingHostApiImpl(binaryMessenger, instanceManager)); recorderHostApiImpl = new RecorderHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.RecorderHostApi.setup(binaryMessenger, recorderHostApiImpl); pendingRecordingHostApiImpl = new PendingRecordingHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.PendingRecordingHostApi.setup( binaryMessenger, pendingRecordingHostApiImpl); videoCaptureHostApiImpl = new VideoCaptureHostApiImpl(binaryMessenger, instanceManager); GeneratedCameraXLibrary.VideoCaptureHostApi.setup(binaryMessenger, videoCaptureHostApiImpl); GeneratedCameraXLibrary.ResolutionSelectorHostApi.setup( binaryMessenger, new ResolutionSelectorHostApiImpl(instanceManager)); GeneratedCameraXLibrary.ResolutionStrategyHostApi.setup( binaryMessenger, new ResolutionStrategyHostApiImpl(instanceManager)); GeneratedCameraXLibrary.AspectRatioStrategyHostApi.setup( binaryMessenger, new AspectRatioStrategyHostApiImpl(instanceManager)); GeneratedCameraXLibrary.FallbackStrategyHostApi.setup( binaryMessenger, new FallbackStrategyHostApiImpl(instanceManager)); GeneratedCameraXLibrary.QualitySelectorHostApi.setup( binaryMessenger, new QualitySelectorHostApiImpl(instanceManager)); cameraControlHostApiImpl = new CameraControlHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.CameraControlHostApi.setup(binaryMessenger, cameraControlHostApiImpl); camera2CameraControlHostApiImpl = new Camera2CameraControlHostApiImpl(instanceManager, context); GeneratedCameraXLibrary.Camera2CameraControlHostApi.setup( binaryMessenger, camera2CameraControlHostApiImpl); GeneratedCameraXLibrary.CaptureRequestOptionsHostApi.setup( binaryMessenger, new CaptureRequestOptionsHostApiImpl(instanceManager)); GeneratedCameraXLibrary.FocusMeteringActionHostApi.setup( binaryMessenger, new FocusMeteringActionHostApiImpl(instanceManager)); GeneratedCameraXLibrary.FocusMeteringResultHostApi.setup( binaryMessenger, new FocusMeteringResultHostApiImpl(instanceManager)); meteringPointHostApiImpl = new MeteringPointHostApiImpl(instanceManager); GeneratedCameraXLibrary.MeteringPointHostApi.setup(binaryMessenger, meteringPointHostApiImpl); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { pluginBinding = flutterPluginBinding; } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { if (instanceManager != null) { instanceManager.stopFinalizationListener(); } } // Activity Lifecycle methods: @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) { Activity activity = activityPluginBinding.getActivity(); // Set up Host API implementations based on the context that `activity` provides. setUp(pluginBinding.getBinaryMessenger(), activity, pluginBinding.getTextureRegistry()); // Set any needed references to `activity` itself. updateLifecycleOwner(activity); updateActivity(activity); // Set permissions registry reference. systemServicesHostApiImpl.setPermissionsRegistry( activityPluginBinding::addRequestPermissionsResultListener); } @Override public void onDetachedFromActivityForConfigChanges() { // Clear any references to previously attached `ActivityPluginBinding`/`Activity`. updateContext(pluginBinding.getApplicationContext()); updateLifecycleOwner(null); updateActivity(null); systemServicesHostApiImpl.setPermissionsRegistry(null); } @Override public void onReattachedToActivityForConfigChanges( @NonNull ActivityPluginBinding activityPluginBinding) { Activity activity = activityPluginBinding.getActivity(); // Set any needed references to `activity` itself or its context. updateContext(activity); updateLifecycleOwner(activity); updateActivity(activity); // Set permissions registry reference. systemServicesHostApiImpl.setPermissionsRegistry( activityPluginBinding::addRequestPermissionsResultListener); } @Override public void onDetachedFromActivity() { // Clear any references to previously attached `ActivityPluginBinding`/`Activity`. updateContext(pluginBinding.getApplicationContext()); updateLifecycleOwner(null); updateActivity(null); systemServicesHostApiImpl.setPermissionsRegistry(null); } /** * Updates context that is used to fetch the corresponding instance of a {@code * ProcessCameraProvider} to each of the relevant camera controls. */ public void updateContext(@NonNull Context context) { if (processCameraProviderHostApiImpl != null) { processCameraProviderHostApiImpl.setContext(context); } if (recorderHostApiImpl != null) { recorderHostApiImpl.setContext(context); } if (pendingRecordingHostApiImpl != null) { pendingRecordingHostApiImpl.setContext(context); } if (systemServicesHostApiImpl != null) { systemServicesHostApiImpl.setContext(context); } if (imageCaptureHostApiImpl != null) { imageCaptureHostApiImpl.setContext(context); } if (imageAnalysisHostApiImpl != null) { imageAnalysisHostApiImpl.setContext(context); } if (cameraControlHostApiImpl != null) { cameraControlHostApiImpl.setContext(context); } if (camera2CameraControlHostApiImpl != null) { camera2CameraControlHostApiImpl.setContext(context); } } /** Sets {@code LifecycleOwner} that is used to control the lifecycle of the camera by CameraX. */ public void updateLifecycleOwner(@Nullable Activity activity) { if (activity == null) { processCameraProviderHostApiImpl.setLifecycleOwner(null); liveDataHostApiImpl.setLifecycleOwner(null); } else if (activity instanceof LifecycleOwner) { processCameraProviderHostApiImpl.setLifecycleOwner((LifecycleOwner) activity); liveDataHostApiImpl.setLifecycleOwner((LifecycleOwner) activity); } else { ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity); processCameraProviderHostApiImpl.setLifecycleOwner(proxyLifecycleProvider); liveDataHostApiImpl.setLifecycleOwner(proxyLifecycleProvider); } } /** * Updates {@code Activity} that is used for requesting camera permissions and tracking the * orientation of the device. */ public void updateActivity(@Nullable Activity activity) { if (systemServicesHostApiImpl != null) { systemServicesHostApiImpl.setActivity(activity); } if (deviceOrientationManagerHostApiImpl != null) { deviceOrientationManagerHostApiImpl.setActivity(activity); } if (meteringPointHostApiImpl != null) { meteringPointHostApiImpl.setActivity(activity); } } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java", "repo_id": "packages", "token_count": 3919 }
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. package io.flutter.plugins.camerax; import android.app.Activity; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.DeviceOrientationManagerHostApi; public class DeviceOrientationManagerHostApiImpl implements DeviceOrientationManagerHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); @VisibleForTesting public @Nullable DeviceOrientationManager deviceOrientationManager; @VisibleForTesting public @NonNull DeviceOrientationManagerFlutterApiImpl deviceOrientationManagerFlutterApiImpl; private Activity activity; private PermissionsRegistry permissionsRegistry; public DeviceOrientationManagerHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; this.deviceOrientationManagerFlutterApiImpl = new DeviceOrientationManagerFlutterApiImpl(binaryMessenger); } public void setActivity(@NonNull Activity activity) { this.activity = activity; } /** * Starts listening for device orientation changes using an instance of a {@link * DeviceOrientationManager}. * * <p>Whenever a change in device orientation is detected by the {@code DeviceOrientationManager}, * the {@link SystemServicesFlutterApi} will be used to notify the Dart side. */ @Override public void startListeningForDeviceOrientationChange( @NonNull Boolean isFrontFacing, @NonNull Long sensorOrientation) { if (activity == null) { throw new IllegalStateException( "Activity must be set to start listening for device orientation changes."); } deviceOrientationManager = cameraXProxy.createDeviceOrientationManager( activity, isFrontFacing, sensorOrientation.intValue(), (DeviceOrientation newOrientation) -> { deviceOrientationManagerFlutterApiImpl.sendDeviceOrientationChangedEvent( serializeDeviceOrientation(newOrientation), reply -> {}); }); deviceOrientationManager.start(); } /** Serializes {@code DeviceOrientation} into a String that the Dart side is able to recognize. */ String serializeDeviceOrientation(DeviceOrientation orientation) { return orientation.toString(); } /** * Tells the {@code deviceOrientationManager} to stop listening for orientation updates. * * <p>Has no effect if the {@code deviceOrientationManager} was never created to listen for device * orientation updates. */ @Override public void stopListeningForDeviceOrientationChange() { if (deviceOrientationManager != null) { deviceOrientationManager.stop(); } } /** * Gets default capture rotation for CameraX {@code UseCase}s. * * <p>The default capture rotation for CameraX is the rotation of default {@code Display} at the * time that a {@code UseCase} is bound, but the default {@code Display} does not change in this * plugin, so this value is {@code Display}-agnostic. * * <p>See * https://developer.android.com/reference/androidx/camera/core/ImageCapture#setTargetRotation(int) * for instance for more information on how this default value is used. */ @Override public @NonNull Long getDefaultDisplayRotation() { int defaultRotation; try { defaultRotation = deviceOrientationManager.getDefaultRotation(); } catch (NullPointerException e) { throw new IllegalStateException( "startListeningForDeviceOrientationChange must first be called to subscribe to device orientation changes in order to retrieve default rotation."); } return Long.valueOf(defaultRotation); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerHostApiImpl.java", "repo_id": "packages", "token_count": 1337 }
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. package io.flutter.plugins.camerax; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.camera.core.CameraState; import androidx.camera.core.ZoomState; import androidx.lifecycle.Observer; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ObserverFlutterApi; import java.util.Objects; /** * Flutter API implementation for {@link Observer}. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class ObserverFlutterApiWrapper { private static final String TAG = "ObserverFlutterApi"; private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private ObserverFlutterApi observerFlutterApi; @VisibleForTesting @Nullable public CameraStateFlutterApiWrapper cameraStateFlutterApiWrapper; @VisibleForTesting @Nullable public ZoomStateFlutterApiImpl zoomStateFlutterApiImpl; /** * Constructs a {@link ObserverFlutterApiWrapper}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public ObserverFlutterApiWrapper( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; observerFlutterApi = new ObserverFlutterApi(binaryMessenger); } /** * Sends a message to Dart to call {@link Observer.onChanged} on the Dart object representing * {@code instance}. */ public <T> void onChanged( @NonNull Observer<T> instance, @NonNull T value, @NonNull ObserverFlutterApi.Reply<Void> callback) { // Cast value to type of data that is being observed and create it on the Dart side // if supported by this plugin. // // The supported types can be found in GeneratedCameraXLibrary.java as the // LiveDataSupportedType enum. To add a new type, please follow the instructions // found in pigeons/camerax_library.dart in the documentation for LiveDataSupportedType. if (value instanceof CameraState) { createCameraState((CameraState) value); } else if (value instanceof ZoomState) { createZoomState((ZoomState) value); } else { throw new UnsupportedOperationException( "The type of value that was observed is not handled by this plugin."); } Long observerIdentifier = instanceManager.getIdentifierForStrongReference(instance); if (observerIdentifier == null) { Log.e( TAG, "The Observer that received a callback has been garbage collected. Please create a new instance to receive any further data changes."); return; } observerFlutterApi.onChanged( Objects.requireNonNull(observerIdentifier), instanceManager.getIdentifierForStrongReference(value), callback); } /** Creates a {@link CameraState} on the Dart side. */ private void createCameraState(CameraState cameraState) { if (cameraStateFlutterApiWrapper == null) { cameraStateFlutterApiWrapper = new CameraStateFlutterApiWrapper(binaryMessenger, instanceManager); } cameraStateFlutterApiWrapper.create( cameraState, CameraStateFlutterApiWrapper.getCameraStateType(cameraState.getType()), cameraState.getError(), reply -> {}); } /** Creates a {@link ZoomState} on the Dart side. */ private void createZoomState(ZoomState zoomState) { if (zoomStateFlutterApiImpl == null) { zoomStateFlutterApiImpl = new ZoomStateFlutterApiImpl(binaryMessenger, instanceManager); } zoomStateFlutterApiImpl.create(zoomState, reply -> {}); } /** Sets the Flutter API used to send messages to Dart. */ @VisibleForTesting void setApi(@NonNull ObserverFlutterApi api) { this.observerFlutterApi = api; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverFlutterApiWrapper.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverFlutterApiWrapper.java", "repo_id": "packages", "token_count": 1347 }
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. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesFlutterApi; public class SystemServicesFlutterApiImpl extends SystemServicesFlutterApi { public SystemServicesFlutterApiImpl(@NonNull BinaryMessenger binaryMessenger) { super(binaryMessenger); } public void sendCameraError(@NonNull String errorDescription, @NonNull Reply<Void> reply) { super.onCameraError(errorDescription, reply); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java", "repo_id": "packages", "token_count": 209 }
954
// 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.mockito.ArgumentMatchers.eq; 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 android.hardware.camera2.CaptureRequest; import androidx.camera.camera2.interop.CaptureRequestOptions; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CaptureRequestKeySupportedType; import java.util.HashMap; import java.util.Map; 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 CaptureRequestOptionsTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public CaptureRequestOptions mockCaptureRequestOptions; InstanceManager testInstanceManager; @Before public void setUp() { testInstanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { testInstanceManager.stopFinalizationListener(); } @Test public void create_buildsExpectedCaptureKeyRequestOptionsWhenOptionsNonNull() { final CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy proxySpy = spy(new CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy()); final CaptureRequestOptionsHostApiImpl hostApi = new CaptureRequestOptionsHostApiImpl(testInstanceManager, proxySpy); final CaptureRequestOptions.Builder mockBuilder = mock(CaptureRequestOptions.Builder.class); final long instanceIdentifier = 44; // Map between CaptureRequestOptions indices and a test value for that option. final Map<Long, Object> options = new HashMap<Long, Object>() { { put(0L, false); } }; when(proxySpy.getCaptureRequestOptionsBuilder()).thenReturn(mockBuilder); when(mockBuilder.build()).thenReturn(mockCaptureRequestOptions); hostApi.create(instanceIdentifier, options); for (CaptureRequestKeySupportedType supportedType : CaptureRequestKeySupportedType.values()) { final Long supportedTypeIndex = Long.valueOf(supportedType.index); final Object testValueForSupportedType = options.get(supportedTypeIndex); switch (supportedType) { case CONTROL_AE_LOCK: verify(mockBuilder) .setCaptureRequestOption( eq(CaptureRequest.CONTROL_AE_LOCK), eq((Boolean) testValueForSupportedType)); break; default: throw new IllegalArgumentException( "The capture request key is not currently supported by the plugin."); } } assertEquals(testInstanceManager.getInstance(instanceIdentifier), mockCaptureRequestOptions); } @Test public void create_buildsExpectedCaptureKeyRequestOptionsWhenAnOptionIsNull() { final CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy proxySpy = spy(new CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy()); final CaptureRequestOptionsHostApiImpl hostApi = new CaptureRequestOptionsHostApiImpl(testInstanceManager, proxySpy); final CaptureRequestOptions.Builder mockBuilder = mock(CaptureRequestOptions.Builder.class); final long instanceIdentifier = 44; // Map between CaptureRequestOptions.CONTROL_AE_LOCK index and test value. final Map<Long, Object> options = new HashMap<Long, Object>() { { put(0L, null); } }; when(proxySpy.getCaptureRequestOptionsBuilder()).thenReturn(mockBuilder); when(mockBuilder.build()).thenReturn(mockCaptureRequestOptions); hostApi.create(instanceIdentifier, options); verify(mockBuilder).clearCaptureRequestOption(CaptureRequest.CONTROL_AE_LOCK); assertEquals(testInstanceManager.getInstance(instanceIdentifier), mockCaptureRequestOptions); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CaptureRequestOptionsTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CaptureRequestOptionsTest.java", "repo_id": "packages", "token_count": 1368 }
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. package io.flutter.plugins.camerax; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import androidx.camera.core.ImageProxy; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PlaneProxyFlutterApi; import java.util.Objects; 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 PlaneProxyTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public ImageProxy.PlaneProxy mockPlaneProxy; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public PlaneProxyFlutterApi mockFlutterApi; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void flutterApiCreate_makesCallToCreateInstanceWithExpectedIdentifier() { final PlaneProxyFlutterApiImpl flutterApi = new PlaneProxyFlutterApiImpl(mockBinaryMessenger, instanceManager); final byte[] buffer = new byte[23]; final long pixelStride = 20; final long rowStride = 2; flutterApi.setApi(mockFlutterApi); flutterApi.create(mockPlaneProxy, buffer, pixelStride, rowStride, reply -> {}); final long instanceIdentifier = Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockPlaneProxy)); verify(mockFlutterApi) .create(eq(instanceIdentifier), eq(buffer), eq(pixelStride), eq(rowStride), any()); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PlaneProxyTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PlaneProxyTest.java", "repo_id": "packages", "token_count": 646 }
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. package io.flutter.plugins.cameraexample; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.plugins.camerax.InstanceManager; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class InstanceManagerTest { @Test public void managerDoesNotTriggerFinalizationListenerWhenStopped() throws InterruptedException { final boolean[] callbackTriggered = {false}; final InstanceManager instanceManager = InstanceManager.create(identifier -> callbackTriggered[0] = true); instanceManager.stopFinalizationListener(); Object object = new Object(); instanceManager.addDartCreatedInstance(object, 0); assertEquals(object, instanceManager.remove(0)); // To allow for object to be garbage collected. //noinspection UnusedAssignment object = null; Runtime.getRuntime().gc(); // Wait for the interval after finalized callbacks are made for garbage collected objects. // See InstanceManager.CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL. Thread.sleep(30000); assertNull(instanceManager.getInstance(0)); assertFalse(callbackTriggered[0]); } }
packages/packages/camera/camera_android_camerax/example/android/app/src/androidTest/java/io/flutter/plugins/cameraxexample/InstanceManagerTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/example/android/app/src/androidTest/java/io/flutter/plugins/cameraxexample/InstanceManagerTest.java", "repo_id": "packages", "token_count": 448 }
957
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/camera/camera_android_camerax/example/android/gradle.properties/0
{ "file_path": "packages/packages/camera/camera_android_camerax/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
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. import 'package:flutter/services.dart' show BinaryMessenger; import 'package:meta/meta.dart' show immutable; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camera_control.dart'; import 'camera_info.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; /// The interface used to control the flow of data of use cases, control the /// camera, and publich the state of the camera. /// /// See https://developer.android.com/reference/androidx/camera/core/Camera. @immutable class Camera extends JavaObject { /// Constructs a [Camera] that is not automatically attached to a native object. Camera.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _CameraHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } late final _CameraHostApiImpl _api; /// Retrieves the [CameraInfo] instance that contains information about this /// instance. Future<CameraInfo> getCameraInfo() async { return _api.getCameraInfoFromInstance(this); } /// Retrieves the [CameraControl] instance that provides asynchronous /// operations like zoom and focus & metering for this instance. Future<CameraControl> getCameraControl() async { return _api.getCameraControlFromInstance(this); } } /// Host API implementation of [Camera]. class _CameraHostApiImpl extends CameraHostApi { /// Constructs a [_CameraHostApiImpl]. /// /// An [instanceManager] is typically passed when a copy of an instance /// contained by an [InstanceManager] is being created. _CameraHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager}) : super(binaryMessenger: binaryMessenger) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Gets the [CameraInfo] associated with the specified [Camera] instance. Future<CameraInfo> getCameraInfoFromInstance(Camera instance) async { final int identifier = instanceManager.getIdentifier(instance)!; final int cameraInfoId = await getCameraInfo(identifier); return instanceManager .getInstanceWithWeakReference<CameraInfo>(cameraInfoId)!; } /// Gets the [CameraControl] associated with the specified [Camera] instance. Future<CameraControl> getCameraControlFromInstance(Camera instance) async { final int identifier = instanceManager.getIdentifier(instance)!; final int cameraControlId = await getCameraControl(identifier); return instanceManager .getInstanceWithWeakReference<CameraControl>(cameraControlId)!; } } /// Flutter API implementation of [Camera]. class CameraFlutterApiImpl implements CameraFlutterApi { /// Constructs a [CameraFlutterApiImpl]. /// /// 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]. CameraFlutterApiImpl({ 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) { _instanceManager.addHostCreatedInstance( Camera.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), identifier, onCopy: (Camera original) { return Camera.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager); }, ); } }
packages/packages/camera/camera_android_camerax/lib/src/camera.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/camera.dart", "repo_id": "packages", "token_count": 1341 }
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 'package:flutter/services.dart' show BinaryMessenger; import 'package:meta/meta.dart' show immutable; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'resolution_selector.dart'; import 'use_case.dart'; /// Use case for picture taking. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture. @immutable class ImageCapture extends UseCase { /// Creates an [ImageCapture]. ImageCapture({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, this.initialTargetRotation, this.targetFlashMode, this.resolutionSelector, }) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ) { _api = ImageCaptureHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); _api.createFromInstance( this, initialTargetRotation, targetFlashMode, resolutionSelector); } /// Constructs an [ImageCapture] that is not automatically attached to a /// native object. ImageCapture.detached({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, this.initialTargetRotation, this.targetFlashMode, this.resolutionSelector, }) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ) { _api = ImageCaptureHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); } late final ImageCaptureHostApiImpl _api; /// Initial target rotation of the camera used for the preview stream. /// /// Should be specified in terms of one of the [Surface] /// rotation constants that represents the counter-clockwise degrees of /// rotation relative to [DeviceOrientation.portraitUp]. /// // TODO(camsim99): Remove this parameter. https://github.com/flutter/flutter/issues/140664 final int? initialTargetRotation; /// Flash mode used to take a picture. final int? targetFlashMode; /// Target resolution of the image output from taking a picture. /// /// If not set, this [UseCase] will default to the behavior described in: /// https://developer.android.com/reference/androidx/camera/core/ImageCapture.Builder#setResolutionSelector(androidx.camera.core.resolutionselector.ResolutionSelector). final ResolutionSelector? resolutionSelector; /// Constant for automatic flash mode. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture#FLASH_MODE_AUTO(). static const int flashModeAuto = 0; /// Constant for on flash mode. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture#FLASH_MODE_ON(). static const int flashModeOn = 1; /// Constant for no flash mode. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture#FLASH_MODE_OFF(). static const int flashModeOff = 2; /// Dynamically sets the target rotation of this instance. /// /// [rotation] should be specified in terms of one of the [Surface] /// rotation constants that represents the counter-clockwise degrees of /// rotation relative to [DeviceOrientation.portraitUp]. Future<void> setTargetRotation(int rotation) => _api.setTargetRotationFromInstances(this, rotation); /// Sets the flash mode to use for image capture. Future<void> setFlashMode(int newFlashMode) async { return _api.setFlashModeFromInstances(this, newFlashMode); } /// Takes a picture and returns the absolute path of where the capture image /// was saved. /// /// This method is not a direct mapping of the takePicture method in the CameraX, /// as it also: /// /// * Configures an instance of the ImageCapture.OutputFileOptions to specify /// how to handle the captured image. /// * Configures an instance of ImageCapture.OnImageSavedCallback to receive /// the results of the image capture as an instance of /// ImageCapture.OutputFileResults. /// * Converts the ImageCapture.OutputFileResults output instance to a String /// that represents the full path where the captured image was saved in /// memory to return. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture /// for more information. Future<String> takePicture() async { return _api.takePictureFromInstances(this); } } /// Host API implementation of [ImageCapture]. class ImageCaptureHostApiImpl extends ImageCaptureHostApi { /// Constructs a [ImageCaptureHostApiImpl]. /// /// 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]. ImageCaptureHostApiImpl( {this.binaryMessenger, InstanceManager? instanceManager}) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default [BinaryMessenger] will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Creates an [ImageCapture] instance with the flash mode and target resolution /// if specified. void createFromInstance(ImageCapture instance, int? targetRotation, int? targetFlashMode, ResolutionSelector? resolutionSelector) { final int identifier = instanceManager.addDartCreatedInstance(instance, onCopy: (ImageCapture original) { return ImageCapture.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, initialTargetRotation: original.initialTargetRotation, targetFlashMode: original.targetFlashMode, resolutionSelector: original.resolutionSelector); }); create( identifier, targetRotation, targetFlashMode, resolutionSelector == null ? null : instanceManager.getIdentifier(resolutionSelector)); } /// Dynamically sets the target rotation of [instance] to [rotation]. Future<void> setTargetRotationFromInstances( ImageCapture instance, int rotation) { return setTargetRotation( instanceManager.getIdentifier(instance)!, rotation); } /// Sets the flash mode for the specified [ImageCapture] instance to take /// a picture with. Future<void> setFlashModeFromInstances( ImageCapture instance, int flashMode) async { final int? identifier = instanceManager.getIdentifier(instance); assert(identifier != null, 'No ImageCapture has the identifer of that requested to get the resolution information for.'); await setFlashMode(identifier!, flashMode); } /// Takes a picture with the specified [ImageCapture] instance. Future<String> takePictureFromInstances(ImageCapture instance) async { final int? identifier = instanceManager.getIdentifier(instance); assert(identifier != null, 'No ImageCapture has the identifer of that requested to get the resolution information for.'); final String picturePath = await takePicture(identifier!); return picturePath; } }
packages/packages/camera/camera_android_camerax/lib/src/image_capture.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/image_capture.dart", "repo_id": "packages", "token_count": 2255 }
960
// 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:meta/meta.dart' show immutable; import 'java_object.dart'; /// Handle onto the raw buffer managed by screen compositor. /// /// See https://developer.android.com/reference/android/view/Surface.html. @immutable class Surface extends JavaObject { /// Creates a detached [Surface]. Surface.detached({super.binaryMessenger, super.instanceManager}) : super.detached(); /// Rotation constant to signify the natural orientation. /// /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_0. static const int ROTATION_0 = 0; /// Rotation constant to signify a 90 degrees rotation. /// /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_90. static const int ROTATION_90 = 1; /// Rotation constant to signify a 180 degrees rotation. /// /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_180. static const int ROTATION_180 = 2; /// Rotation constant to signify a 270 degrees rotation. /// /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_270. static const int ROTATION_270 = 3; }
packages/packages/camera/camera_android_camerax/lib/src/surface.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/surface.dart", "repo_id": "packages", "token_count": 396 }
961
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/camera_control_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:camera_android_camerax/src/focus_metering_action.dart' as _i4; import 'package:camera_android_camerax/src/metering_point.dart' as _i5; 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 [TestCameraControlHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestCameraControlHostApi extends _i1.Mock implements _i2.TestCameraControlHostApi { MockTestCameraControlHostApi() { _i1.throwOnMissingStub(this); } @override _i3.Future<void> enableTorch( int? identifier, bool? torch, ) => (super.noSuchMethod( Invocation.method( #enableTorch, [ identifier, torch, ], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<void> setZoomRatio( int? identifier, double? ratio, ) => (super.noSuchMethod( Invocation.method( #setZoomRatio, [ identifier, ratio, ], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<int?> startFocusAndMetering( int? identifier, int? focusMeteringActionId, ) => (super.noSuchMethod( Invocation.method( #startFocusAndMetering, [ identifier, focusMeteringActionId, ], ), returnValue: _i3.Future<int?>.value(), ) as _i3.Future<int?>); @override _i3.Future<void> cancelFocusAndMetering(int? identifier) => (super.noSuchMethod( Invocation.method( #cancelFocusAndMetering, [identifier], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<int?> setExposureCompensationIndex( int? identifier, int? index, ) => (super.noSuchMethod( Invocation.method( #setExposureCompensationIndex, [ identifier, index, ], ), returnValue: _i3.Future<int?>.value(), ) as _i3.Future<int?>); } /// 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 [FocusMeteringAction]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockFocusMeteringAction extends _i1.Mock implements _i4.FocusMeteringAction { MockFocusMeteringAction() { _i1.throwOnMissingStub(this); } @override List<(_i5.MeteringPoint, int?)> get meteringPointInfos => (super.noSuchMethod( Invocation.getter(#meteringPointInfos), returnValue: <(_i5.MeteringPoint, int?)>[], ) as List<(_i5.MeteringPoint, int?)>); }
packages/packages/camera/camera_android_camerax/test/camera_control_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/camera_control_test.mocks.dart", "repo_id": "packages", "token_count": 1789 }
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:camera_android_camerax/src/camera_info.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/metering_point.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'metering_point_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks( <Type>[TestInstanceManagerHostApi, TestMeteringPointHostApi, CameraInfo]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); group('MeteringPoint', () { tearDown(() => TestMeteringPointHostApi.setup(null)); test('detached create does not call create on the Java side', () async { final MockTestMeteringPointHostApi mockApi = MockTestMeteringPointHostApi(); TestMeteringPointHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); MeteringPoint.detached( x: 0, y: 0.3, size: 4, cameraInfo: MockCameraInfo(), instanceManager: instanceManager, ); verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<int>()), argThat(isA<int>()), argThat(isA<int>()), argThat(isA<int>()))); }); test('create calls create on the Java side', () async { final MockTestMeteringPointHostApi mockApi = MockTestMeteringPointHostApi(); TestMeteringPointHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const double x = 0.5; const double y = 0.6; const double size = 3; final CameraInfo mockCameraInfo = MockCameraInfo(); const int mockCameraInfoId = 4; instanceManager.addHostCreatedInstance(mockCameraInfo, mockCameraInfoId, onCopy: (CameraInfo original) => MockCameraInfo()); MeteringPoint( x: x, y: y, size: size, cameraInfo: mockCameraInfo, instanceManager: instanceManager, ); verify(mockApi.create( argThat(isA<int>()), x, y, size, mockCameraInfoId, )); }); test('getDefaultPointSize returns expected size', () async { final MockTestMeteringPointHostApi mockApi = MockTestMeteringPointHostApi(); TestMeteringPointHostApi.setup(mockApi); const double defaultPointSize = 6; when(mockApi.getDefaultPointSize()).thenAnswer((_) => defaultPointSize); expect( await MeteringPoint.getDefaultPointSize(), equals(defaultPointSize)); verify(mockApi.getDefaultPointSize()); }); }); }
packages/packages/camera/camera_android_camerax/test/metering_point_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/metering_point_test.dart", "repo_id": "packages", "token_count": 1187 }
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. 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/recording.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'recording_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[TestRecordingHostApi, TestInstanceManagerHostApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); group('Recording', () { tearDown(() => TestRecorderHostApi.setup(null)); test('close calls close on Java side', () async { final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); TestRecordingHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Recording recording = Recording.detached(instanceManager: instanceManager); const int recordingId = 0; when(mockApi.close(recordingId)).thenAnswer((_) {}); instanceManager.addHostCreatedInstance(recording, recordingId, onCopy: (_) => Recording.detached(instanceManager: instanceManager)); await recording.close(); verify(mockApi.close(recordingId)); }); test('pause calls pause on Java side', () async { final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); TestRecordingHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Recording recording = Recording.detached(instanceManager: instanceManager); const int recordingId = 0; when(mockApi.pause(recordingId)).thenAnswer((_) {}); instanceManager.addHostCreatedInstance(recording, recordingId, onCopy: (_) => Recording.detached(instanceManager: instanceManager)); await recording.pause(); verify(mockApi.pause(recordingId)); }); test('resume calls resume on Java side', () async { final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); TestRecordingHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Recording recording = Recording.detached(instanceManager: instanceManager); const int recordingId = 0; when(mockApi.resume(recordingId)).thenAnswer((_) {}); instanceManager.addHostCreatedInstance(recording, recordingId, onCopy: (_) => Recording.detached(instanceManager: instanceManager)); await recording.resume(); verify(mockApi.resume(recordingId)); }); test('stop calls stop on Java side', () async { final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); TestRecordingHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Recording recording = Recording.detached(instanceManager: instanceManager); const int recordingId = 0; when(mockApi.stop(recordingId)).thenAnswer((_) {}); instanceManager.addHostCreatedInstance(recording, recordingId, onCopy: (_) => Recording.detached(instanceManager: instanceManager)); await recording.stop(); verify(mockApi.stop(recordingId)); }); test('flutterApiCreateTest', () async { final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final RecordingFlutterApi flutterApi = RecordingFlutterApiImpl( instanceManager: instanceManager, ); flutterApi.create(0); expect(instanceManager.getInstanceWithWeakReference(0), isA<Recording>()); }); }); }
packages/packages/camera/camera_android_camerax/test/recording_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/recording_test.dart", "repo_id": "packages", "token_count": 1477 }
964
// 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 "CameraTestUtils.h" #import <OCMock/OCMock.h> @import AVFoundation; FLTCam *FLTCreateCamWithCaptureSessionQueue(dispatch_queue_t captureSessionQueue) { id inputMock = OCMClassMock([AVCaptureDeviceInput class]); OCMStub([inputMock deviceInputWithDevice:[OCMArg any] error:[OCMArg setTo:nil]]) .andReturn(inputMock); id videoSessionMock = OCMClassMock([AVCaptureSession class]); OCMStub([videoSessionMock addInputWithNoConnections:[OCMArg any]]); OCMStub([videoSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES); id audioSessionMock = OCMClassMock([AVCaptureSession class]); OCMStub([audioSessionMock addInputWithNoConnections:[OCMArg any]]); OCMStub([audioSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES); return [[FLTCam alloc] initWithCameraName:@"camera" resolutionPreset:@"medium" enableAudio:true orientation:UIDeviceOrientationPortrait videoCaptureSession:videoSessionMock audioCaptureSession:audioSessionMock captureSessionQueue:captureSessionQueue error:nil]; } FLTCam *FLTCreateCamWithVideoCaptureSession(AVCaptureSession *captureSession, NSString *resolutionPreset) { id inputMock = OCMClassMock([AVCaptureDeviceInput class]); OCMStub([inputMock deviceInputWithDevice:[OCMArg any] error:[OCMArg setTo:nil]]) .andReturn(inputMock); id audioSessionMock = OCMClassMock([AVCaptureSession class]); OCMStub([audioSessionMock addInputWithNoConnections:[OCMArg any]]); OCMStub([audioSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES); return [[FLTCam alloc] initWithCameraName:@"camera" resolutionPreset:resolutionPreset enableAudio:true orientation:UIDeviceOrientationPortrait videoCaptureSession:captureSession audioCaptureSession:audioSessionMock captureSessionQueue:dispatch_queue_create("capture_session_queue", NULL) error:nil]; } FLTCam *FLTCreateCamWithVideoDimensionsForFormat( AVCaptureSession *captureSession, NSString *resolutionPreset, AVCaptureDevice *captureDevice, VideoDimensionsForFormat videoDimensionsForFormat) { id inputMock = OCMClassMock([AVCaptureDeviceInput class]); OCMStub([inputMock deviceInputWithDevice:[OCMArg any] error:[OCMArg setTo:nil]]) .andReturn(inputMock); id audioSessionMock = OCMClassMock([AVCaptureSession class]); OCMStub([audioSessionMock addInputWithNoConnections:[OCMArg any]]); OCMStub([audioSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES); return [[FLTCam alloc] initWithResolutionPreset:resolutionPreset enableAudio:true orientation:UIDeviceOrientationPortrait videoCaptureSession:captureSession audioCaptureSession:audioSessionMock captureSessionQueue:dispatch_queue_create("capture_session_queue", NULL) captureDeviceFactory:^AVCaptureDevice *(void) { return captureDevice; } videoDimensionsForFormat:videoDimensionsForFormat error:nil]; } CMSampleBufferRef FLTCreateTestSampleBuffer(void) { CVPixelBufferRef pixelBuffer; CVPixelBufferCreate(kCFAllocatorDefault, 100, 100, kCVPixelFormatType_32BGRA, NULL, &pixelBuffer); CMFormatDescriptionRef formatDescription; CMVideoFormatDescriptionCreateForImageBuffer(kCFAllocatorDefault, pixelBuffer, &formatDescription); CMSampleTimingInfo timingInfo = {CMTimeMake(1, 44100), kCMTimeZero, kCMTimeInvalid}; CMSampleBufferRef sampleBuffer; CMSampleBufferCreateReadyWithImageBuffer(kCFAllocatorDefault, pixelBuffer, formatDescription, &timingInfo, &sampleBuffer); CFRelease(pixelBuffer); CFRelease(formatDescription); return sampleBuffer; } CMSampleBufferRef FLTCreateTestAudioSampleBuffer(void) { CMBlockBufferRef blockBuffer; CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, NULL, 100, kCFAllocatorDefault, NULL, 0, 100, kCMBlockBufferAssureMemoryNowFlag, &blockBuffer); CMFormatDescriptionRef formatDescription; AudioStreamBasicDescription basicDescription = {44100, kAudioFormatLinearPCM, 0, 1, 1, 1, 1, 8}; CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &basicDescription, 0, NULL, 0, NULL, NULL, &formatDescription); CMSampleBufferRef sampleBuffer; CMAudioSampleBufferCreateReadyWithPacketDescriptions( kCFAllocatorDefault, blockBuffer, formatDescription, 1, kCMTimeZero, NULL, &sampleBuffer); CFRelease(blockBuffer); CFRelease(formatDescription); return sampleBuffer; }
packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.m/0
{ "file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.m", "repo_id": "packages", "token_count": 2254 }
965
// 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:io'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; /// Demonstrates using an XFile result as an [Image] source, for the README. Image getImageFromResultExample(XFile capturedImage) { // #docregion ImageFromXFile final Image image; if (kIsWeb) { image = Image.network(capturedImage.path); } else { image = Image.file(File(capturedImage.path)); } // #enddocregion ImageFromXFile return image; }
packages/packages/camera/camera_web/example/lib/readme_excerpts.dart/0
{ "file_path": "packages/packages/camera/camera_web/example/lib/readme_excerpts.dart", "repo_id": "packages", "token_count": 220 }
966
// 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:convert'; import 'dart:io'; import 'dart:typed_data'; import './base.dart'; // ignore_for_file: avoid_unused_constructor_parameters /// A CrossFile backed by a dart:io File. class XFile extends XFileBase { /// Construct a CrossFile object backed by a dart:io File. /// /// [bytes] is ignored; the parameter exists only to match the web version of /// the constructor. To construct a dart:io XFile from bytes, use /// [XFile.fromData]. /// /// [name] is ignored; the parameter exists only to match the web version of /// the constructor. /// /// [length] is ignored; the parameter exists only to match the web version of /// the constructor. /// // ignore: use_super_parameters XFile( String path, { String? mimeType, String? name, int? length, Uint8List? bytes, DateTime? lastModified, }) : _mimeType = mimeType, _file = File(path), _bytes = null, _lastModified = lastModified, super(path); /// Construct an CrossFile from its data /// /// [name] is ignored; the parameter exists only to match the web version of /// the constructor. XFile.fromData( Uint8List bytes, { String? mimeType, String? path, String? name, int? length, DateTime? lastModified, }) : _mimeType = mimeType, _bytes = bytes, _file = File(path ?? ''), _length = length, _lastModified = lastModified, super(path) { if (length == null) { _length = bytes.length; } } final File _file; final String? _mimeType; final DateTime? _lastModified; int? _length; final Uint8List? _bytes; @override Future<DateTime> lastModified() { if (_lastModified != null) { return Future<DateTime>.value(_lastModified); } // ignore: avoid_slow_async_io return _file.lastModified(); } @override Future<void> saveTo(String path) async { if (_bytes == null) { await _file.copy(path); } else { final File fileToSave = File(path); // TODO(kevmoo): Remove ignore and fix when the MIN Dart SDK is 3.3 // ignore: unnecessary_non_null_assertion await fileToSave.writeAsBytes(_bytes!); } } @override String? get mimeType => _mimeType; @override String get path => _file.path; @override String get name => _file.path.split(Platform.pathSeparator).last; @override Future<int> length() { if (_length != null) { return Future<int>.value(_length); } return _file.length(); } @override Future<String> readAsString({Encoding encoding = utf8}) { if (_bytes != null) { // TODO(kevmoo): Remove ignore and fix when the MIN Dart SDK is 3.3 // ignore: unnecessary_non_null_assertion return Future<String>.value(String.fromCharCodes(_bytes!)); } return _file.readAsString(encoding: encoding); } @override Future<Uint8List> readAsBytes() { if (_bytes != null) { return Future<Uint8List>.value(_bytes); } return _file.readAsBytes(); } Stream<Uint8List> _getBytes(int? start, int? end) async* { final Uint8List bytes = _bytes!; yield bytes.sublist(start ?? 0, end ?? bytes.length); } @override Stream<Uint8List> openRead([int? start, int? end]) { if (_bytes != null) { return _getBytes(start, end); } else { return _file .openRead(start ?? 0, end) .map((List<int> chunk) => Uint8List.fromList(chunk)); } } }
packages/packages/cross_file/lib/src/types/io.dart/0
{ "file_path": "packages/packages/cross_file/lib/src/types/io.dart", "repo_id": "packages", "token_count": 1383 }
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 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; /// Describes the placement of a child in a [RenderDynamicSliverGrid]. class DynamicSliverGridGeometry extends SliverGridGeometry { /// Creates an object that describes the placement of a child in a /// [RenderDynamicSliverGrid]. const DynamicSliverGridGeometry({ required super.scrollOffset, required super.crossAxisOffset, required super.mainAxisExtent, required super.crossAxisExtent, }); /// Returns [BoxConstraints] that will be tight if the /// [DynamicSliverGridLayout] has provided fixed extents, forcing the child to /// have the required size. /// /// If the [mainAxisExtent] is [double.infinity] the child will be allowed to /// choose its own size in the main axis. Similarly, an infinite /// [crossAxisExtent] will result in the child sizing itself in the cross /// axis. Otherwise, the provided cross axis size or the /// [SliverConstraints.crossAxisExtent] will be used to create tight /// constraints in the cross axis. /// /// This differs from [SliverGridGeometry.getBoxConstraints] in that it allows /// loose constraints, allowing the child to be its preferred size, or within /// a range of minimum and maximum extents. @override BoxConstraints getBoxConstraints(SliverConstraints constraints) { final double mainMinExtent = mainAxisExtent.isFinite ? mainAxisExtent : 0; final double crossMinExtent = crossAxisExtent.isInfinite ? 0.0 : crossAxisExtent; switch (constraints.axis) { case Axis.vertical: return BoxConstraints( minHeight: mainMinExtent, maxHeight: mainAxisExtent, minWidth: crossMinExtent, maxWidth: crossAxisExtent, ); case Axis.horizontal: return BoxConstraints( minHeight: crossMinExtent, maxHeight: crossAxisExtent, minWidth: mainMinExtent, maxWidth: mainAxisExtent, ); } } } /// Manages the size and position of all the tiles in a [RenderSliverGrid]. /// /// Rather than providing a grid with a [SliverGridLayout] directly, you instead /// provide the grid with a [SliverGridDelegate], which can compute a /// [SliverGridLayout] given the current [SliverConstraints]. /// /// {@template dynamicLayouts.garbageCollection} /// This grid does not currently collect leading garbage as the user scrolls /// further down. This is because the current implementation requires the /// leading tiles to maintain the current layout. Follow /// [this github issue](https://github.com/flutter/flutter/issues/112234) for /// tracking progress on dynamic leading garbage collection. /// {@endtemplate} abstract class DynamicSliverGridLayout extends SliverGridLayout { /// The estimated size and position of the child with the given index. /// /// The [DynamicSliverGridGeometry] that is returned will /// provide looser constraints to the child, whose size after layout can be /// reported back to the layout object in [updateGeometryForChildIndex]. @override DynamicSliverGridGeometry getGeometryForChildIndex(int index); /// Update the size and position of the child with the given index, /// considering the size of the child after layout. /// /// This is used to update the layout object after the child has laid out, /// allowing the layout pattern to adapt to the child's size. DynamicSliverGridGeometry updateGeometryForChildIndex( int index, Size childSize, ); /// Called by [RenderDynamicSliverGrid] to validate the layout pattern has /// filled the screen. /// /// A given child may have reached the target scroll offset of the current /// layout pass, but there may still be more children to lay out based on the /// pattern. bool reachedTargetScrollOffset(double targetOffset); // These methods are not relevant to dynamic grid building, but extending the // base [SliverGridLayout] class allows us to re-use existing // [SliverGridDelegate]s like [SliverGridDelegateWithFixedCrossAxisCount] and // [SliverGridDelegateWithMaxCrossAxisExtent]. @override @mustCallSuper double computeMaxScrollOffset(int childCount) => throw UnimplementedError(); @override @mustCallSuper int getMaxChildIndexForScrollOffset(double scrollOffset) => throw UnimplementedError(); @override @mustCallSuper int getMinChildIndexForScrollOffset(double scrollOffset) => throw UnimplementedError(); }
packages/packages/dynamic_layouts/lib/src/base_grid_layout.dart/0
{ "file_path": "packages/packages/dynamic_layouts/lib/src/base_grid_layout.dart", "repo_id": "packages", "token_count": 1381 }
968
# espresso Provides bindings for Espresso tests of Flutter Android apps. | | Android | |-------------|---------| | **Support** | SDK 16+ | ## Installation Add the `espresso` package as a `dev_dependency` in your app's pubspec.yaml. If you're testing the example app of a package, add it as a dev_dependency of the main package as well. Add ```android:usesCleartextTraffic="true"``` in the ```<application>``` in the AndroidManifest.xml of the Android app used for testing. It's best to put this in a debug or androidTest AndroidManifest.xml so that you don't ship it to end users. (See the example app of this package.) Add the following dependencies in android/app/build.gradle: ```groovy dependencies { testImplementation 'junit:junit:4.13.2' testImplementation "com.google.truth:truth:1.0" androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' api 'androidx.test:core:1.2.0' } ``` Create an `android/app/src/androidTest` folder and put a test file in a package-appropriate subfolder, e.g. `android/app/src/androidTest/java/com/example/MainActivityTest.java`: ```java package com.example.espresso_example; import static androidx.test.espresso.flutter.EspressoFlutter.onFlutterWidget; import static androidx.test.espresso.flutter.action.FlutterActions.click; import static androidx.test.espresso.flutter.action.FlutterActions.syntheticClick; import static androidx.test.espresso.flutter.assertion.FlutterAssertions.matches; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.isDescendantOf; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withText; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withTooltip; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withType; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withValueKey; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import androidx.test.core.app.ActivityScenario; import androidx.test.espresso.flutter.EspressoFlutter.WidgetInteraction; import androidx.test.espresso.flutter.assertion.FlutterAssertions; import androidx.test.espresso.flutter.matcher.FlutterMatchers; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** Unit tests for {@link EspressoFlutter}. */ @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Before public void setUp() throws Exception { ActivityScenario.launch(MainActivity.class); } @Test public void performClick() { onFlutterWidget(withTooltip("Increment")).perform(click()); onFlutterWidget(withValueKey("CountText")).check(matches(withText("Button tapped 1 time."))); } ``` You'll need to create a test app that enables the Flutter driver extension. You can put this in your test_driver/ folder, e.g. test_driver/example.dart. Replace `<app_package_name>` with the package name of your app. If you're developing a plugin, this will be the package name of the example app. ```dart import 'package:flutter_driver/driver_extension.dart'; import 'package:<app_package_name>/main.dart' as app; void main() { enableFlutterDriverExtension(); app.main(); } ``` The following command line command runs the test locally: ```sh ./gradlew app:connectedAndroidTest -Ptarget=`pwd`/../test_driver/example.dart ``` Espresso tests can also be run on [Firebase Test Lab](https://firebase.google.com/docs/test-lab): ```sh ./gradlew app:assembleAndroidTest ./gradlew app:assembleDebug -Ptarget=<path_to_test>.dart gcloud auth activate-service-account --key-file=<PATH_TO_KEY_FILE> gcloud --quiet config set project <PROJECT_NAME> gcloud firebase test android run --type instrumentation \ --app build/app/outputs/apk/debug/app-debug.apk \ --test build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk\ --timeout 2m \ --results-bucket=<RESULTS_BUCKET> \ --results-dir=<RESULTS_DIRECTORY> ```
packages/packages/espresso/README.md/0
{ "file_path": "packages/packages/espresso/README.md", "repo_id": "packages", "token_count": 1369 }
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. package androidx.test.espresso.flutter.action; import android.view.View; import androidx.test.espresso.UiController; import androidx.test.espresso.flutter.api.FlutterAction; import androidx.test.espresso.flutter.api.FlutterTestingProtocol; import androidx.test.espresso.flutter.api.WidgetMatcher; import androidx.test.espresso.flutter.model.WidgetInfo; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** A {@link FlutterAction} that retrieves the {@code WidgetInfo} of the matched Flutter widget. */ public final class WidgetInfoFetcher implements FlutterAction<WidgetInfo> { @Override public Future<WidgetInfo> perform( @Nullable WidgetMatcher targetWidget, @Nonnull View flutterView, @Nonnull FlutterTestingProtocol flutterTestingProtocol, @Nonnull UiController androidUiController) { return flutterTestingProtocol.matchWidget(targetWidget); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/WidgetInfoFetcher.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/WidgetInfoFetcher.java", "repo_id": "packages", "token_count": 345 }
970
// 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 androidx.test.espresso.flutter.internal.idgenerator; import static com.google.common.base.Preconditions.checkArgument; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; /** Some simple in-memory ID generators. */ public final class IdGenerators { private IdGenerators() {} private static final IdGenerator<String> UUID_STRING_GENERATOR = new IdGenerator<String>() { @Override public String next() { return UUID.randomUUID().toString(); } }; /** * Returns a {@code Integer} ID generator whose next value is the value passed in. The value * returned increases by one each time until {@code Integer.MAX_VALUE}. After that an {@code * IdException} is thrown. This IdGenerator is threadsafe. */ public static IdGenerator<Integer> newIntegerIdGenerator(int nextValue) { checkArgument(nextValue >= 0, "ID values must be non-negative"); final AtomicInteger nextInt = new AtomicInteger(nextValue); return new IdGenerator<Integer>() { @Override public Integer next() { int value = nextInt.getAndIncrement(); if (value >= 0) { return value; } // Make sure that all subsequent calls throw by setting to the most // negative value possible. nextInt.set(Integer.MIN_VALUE); throw new IdException("Returned the last integer value available"); } }; } /** * Returns a {@code Integer} ID generator whose next value is one. The value returned increases by * one each time until {@code Integer.MAX_VALUE}. After that an {@code IdException} is thrown. * This IdGenerator is threadsafe. */ public static IdGenerator<Integer> newIntegerIdGenerator() { return newIntegerIdGenerator(1); } /** * Returns a {@code String} ID generator that passes ID requests to {@link UUID#randomUUID()}, * thereby generating type-4 (pseudo-randomly generated) UUIDs. */ public static IdGenerator<String> randomUuidStringGenerator() { return UUID_STRING_GENERATOR; } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerators.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerators.java", "repo_id": "packages", "token_count": 743 }
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. package androidx.test.espresso.flutter.internal.protocol.impl; import static com.google.common.base.Preconditions.checkNotNull; /** The base class that represents a wait condition in the Flutter app. */ abstract class WaitCondition { // Used in JSON serialization. @SuppressWarnings("unused") private final String conditionName; public WaitCondition(String conditionName) { this.conditionName = checkNotNull(conditionName); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WaitCondition.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WaitCondition.java", "repo_id": "packages", "token_count": 168 }
972
# espresso_example Demonstrates how to use the espresso package. The espresso package only runs tests on Android. The example runs on iOS, but this is only to keep our continuous integration bots green. ## Getting Started To run the Espresso tests: ```java flutter build apk --debug ./gradlew app:connectedAndroidTest ```
packages/packages/espresso/example/README.md/0
{ "file_path": "packages/packages/espresso/example/README.md", "repo_id": "packages", "token_count": 86 }
973
# extension_google_sign_in_example Demonstrates how to use the google_sign_in plugin with the `googleapis` package.
packages/packages/extension_google_sign_in_as_googleapis_auth/example/README.md/0
{ "file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/example/README.md", "repo_id": "packages", "token_count": 35 }
974
# file_selector_example Demonstrates how to use the file_selector plugin.
packages/packages/file_selector/file_selector/example/README.md/0
{ "file_path": "packages/packages/file_selector/file_selector/example/README.md", "repo_id": "packages", "token_count": 23 }
975
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/file_selector/file_selector/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/file_selector/file_selector/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
976
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates compileSdk version to 34. ## 0.5.0+7 * Bumps androidx.annotation:annotation from 1.7.0 to 1.7.1. ## 0.5.0+6 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 0.5.0+5 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 0.5.0+4 * Updates annotations lib to 1.7.0. ## 0.5.0+3 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.5.0+2 * Adjusts SDK checks for better testability. ## 0.5.0+1 * Bumps androidx.annotation:annotation from 1.5.0 to 1.6.0. * Adds a dependency on kotlin-bom to align versions of Kotlin transitive dependencies. ## 0.5.0 * Implements file_selector_platform_interface for Android.
packages/packages/file_selector/file_selector_android/CHANGELOG.md/0
{ "file_path": "packages/packages/file_selector/file_selector_android/CHANGELOG.md", "repo_id": "packages", "token_count": 306 }
977
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/file_selector/file_selector_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/file_selector/file_selector_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
978
name: file_selector_android description: Android implementation of the file_selector package. repository: https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22 version: 0.5.0+7 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: file_selector platforms: android: dartPluginClass: FileSelectorAndroid package: dev.flutter.packages.file_selector_android pluginClass: FileSelectorAndroidPlugin dependencies: file_selector_platform_interface: ^2.5.0 flutter: sdk: flutter plugin_platform_interface: ^2.1.7 dev_dependencies: build_runner: ^2.1.4 flutter_test: sdk: flutter mockito: 5.4.4 pigeon: ^9.2.4 topics: - files - file-selection - file-selector
packages/packages/file_selector/file_selector_android/pubspec.yaml/0
{ "file_path": "packages/packages/file_selector/file_selector_android/pubspec.yaml", "repo_id": "packages", "token_count": 360 }
979
// 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_linux/file_selector_linux.dart'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); late FileSelectorLinux plugin; late List<MethodCall> log; setUp(() { plugin = FileSelectorLinux(); log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( plugin.channel, (MethodCall methodCall) async { log.add(methodCall); return null; }, ); }); test('registers instance', () { FileSelectorLinux.registerWith(); expect(FileSelectorPlatform.instance, isA<FileSelectorLinux>()); }); group('openFile', () { test('passes the accepted type groups correctly', () async { const XTypeGroup group = XTypeGroup( label: 'text', extensions: <String>['txt'], mimeTypes: <String>['text/plain'], ); const XTypeGroup groupTwo = XTypeGroup( label: 'image', extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], ); await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'text', 'extensions': <String>['*.txt'], 'mimeTypes': <String>['text/plain'], }, <String, Object>{ 'label': 'image', 'extensions': <String>['*.jpg'], 'mimeTypes': <String>['image/jpg'], }, ], 'initialDirectory': null, 'confirmButtonText': null, 'multiple': false, }, ); }); test('passes initialDirectory correctly', () async { await plugin.openFile(initialDirectory: '/example/directory'); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'initialDirectory': '/example/directory', 'confirmButtonText': null, 'multiple': false, }, ); }); test('passes confirmButtonText correctly', () async { await plugin.openFile(confirmButtonText: 'Open File'); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'initialDirectory': null, 'confirmButtonText': 'Open File', 'multiple': false, }, ); }); test('throws for a type group that does not support Linux', () async { const XTypeGroup group = XTypeGroup( label: 'images', webWildCards: <String>['images/*'], ); await expectLater( plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), throwsArgumentError); }); test('passes a wildcard group correctly', () async { const XTypeGroup group = XTypeGroup( label: 'any', ); await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'any', 'extensions': <String>['*'], }, ], 'initialDirectory': null, 'confirmButtonText': null, 'multiple': false, }, ); }); }); group('openFiles', () { test('passes the accepted type groups correctly', () async { const XTypeGroup group = XTypeGroup( label: 'text', extensions: <String>['txt'], mimeTypes: <String>['text/plain'], ); const XTypeGroup groupTwo = XTypeGroup( label: 'image', extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], ); await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'text', 'extensions': <String>['*.txt'], 'mimeTypes': <String>['text/plain'], }, <String, Object>{ 'label': 'image', 'extensions': <String>['*.jpg'], 'mimeTypes': <String>['image/jpg'], }, ], 'initialDirectory': null, 'confirmButtonText': null, 'multiple': true, }, ); }); test('passes initialDirectory correctly', () async { await plugin.openFiles(initialDirectory: '/example/directory'); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'initialDirectory': '/example/directory', 'confirmButtonText': null, 'multiple': true, }, ); }); test('passes confirmButtonText correctly', () async { await plugin.openFiles(confirmButtonText: 'Open File'); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'initialDirectory': null, 'confirmButtonText': 'Open File', 'multiple': true, }, ); }); test('throws for a type group that does not support Linux', () async { const XTypeGroup group = XTypeGroup( label: 'images', webWildCards: <String>['images/*'], ); await expectLater( plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), throwsArgumentError); }); test('passes a wildcard group correctly', () async { const XTypeGroup group = XTypeGroup( label: 'any', ); await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]); expectMethodCall( log, 'openFile', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'any', 'extensions': <String>['*'], }, ], 'initialDirectory': null, 'confirmButtonText': null, 'multiple': true, }, ); }); }); group('getSaveLocation', () { test('passes the accepted type groups correctly', () async { const XTypeGroup group = XTypeGroup( label: 'text', extensions: <String>['txt'], mimeTypes: <String>['text/plain'], ); const XTypeGroup groupTwo = XTypeGroup( label: 'image', extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], ); await plugin .getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'text', 'extensions': <String>['*.txt'], 'mimeTypes': <String>['text/plain'], }, <String, Object>{ 'label': 'image', 'extensions': <String>['*.jpg'], 'mimeTypes': <String>['image/jpg'], }, ], 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': null, }, ); }); test('passes initialDirectory correctly', () async { await plugin.getSaveLocation( options: const SaveDialogOptions(initialDirectory: '/example/directory')); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'initialDirectory': '/example/directory', 'suggestedName': null, 'confirmButtonText': null, }, ); }); test('passes confirmButtonText correctly', () async { await plugin.getSaveLocation( options: const SaveDialogOptions(confirmButtonText: 'Open File')); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': 'Open File', }, ); }); test('throws for a type group that does not support Linux', () async { const XTypeGroup group = XTypeGroup( label: 'images', webWildCards: <String>['images/*'], ); await expectLater( plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]), throwsArgumentError); }); test('passes a wildcard group correctly', () async { const XTypeGroup group = XTypeGroup( label: 'any', ); await plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'any', 'extensions': <String>['*'], }, ], 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': null, }, ); }); }); group('getSavePath (deprecated)', () { test('passes the accepted type groups correctly', () async { const XTypeGroup group = XTypeGroup( label: 'text', extensions: <String>['txt'], mimeTypes: <String>['text/plain'], ); const XTypeGroup groupTwo = XTypeGroup( label: 'image', extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], ); await plugin .getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'text', 'extensions': <String>['*.txt'], 'mimeTypes': <String>['text/plain'], }, <String, Object>{ 'label': 'image', 'extensions': <String>['*.jpg'], 'mimeTypes': <String>['image/jpg'], }, ], 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': null, }, ); }); test('passes initialDirectory correctly', () async { await plugin.getSavePath(initialDirectory: '/example/directory'); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'initialDirectory': '/example/directory', 'suggestedName': null, 'confirmButtonText': null, }, ); }); test('passes confirmButtonText correctly', () async { await plugin.getSavePath(confirmButtonText: 'Open File'); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': 'Open File', }, ); }); test('throws for a type group that does not support Linux', () async { const XTypeGroup group = XTypeGroup( label: 'images', webWildCards: <String>['images/*'], ); await expectLater( plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]), throwsArgumentError); }); test('passes a wildcard group correctly', () async { const XTypeGroup group = XTypeGroup( label: 'any', ); await plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]); expectMethodCall( log, 'getSavePath', arguments: <String, dynamic>{ 'acceptedTypeGroups': <Map<String, dynamic>>[ <String, Object>{ 'label': 'any', 'extensions': <String>['*'], }, ], 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': null, }, ); }); }); group('getDirectoryPath', () { test('passes initialDirectory correctly', () async { await plugin.getDirectoryPath(initialDirectory: '/example/directory'); expectMethodCall( log, 'getDirectoryPath', arguments: <String, dynamic>{ 'initialDirectory': '/example/directory', 'confirmButtonText': null, }, ); }); test('passes confirmButtonText correctly', () async { await plugin.getDirectoryPath(confirmButtonText: 'Select Folder'); expectMethodCall( log, 'getDirectoryPath', arguments: <String, dynamic>{ 'initialDirectory': null, 'confirmButtonText': 'Select Folder', }, ); }); }); group('getDirectoryPaths', () { test('passes initialDirectory correctly', () async { await plugin.getDirectoryPaths(initialDirectory: '/example/directory'); expectMethodCall( log, 'getDirectoryPath', arguments: <String, dynamic>{ 'initialDirectory': '/example/directory', 'confirmButtonText': null, 'multiple': true, }, ); }); test('passes confirmButtonText correctly', () async { await plugin.getDirectoryPaths( confirmButtonText: 'Select one or mode folders'); expectMethodCall( log, 'getDirectoryPath', arguments: <String, dynamic>{ 'initialDirectory': null, 'confirmButtonText': 'Select one or mode folders', 'multiple': true, }, ); }); test('passes multiple flag correctly', () async { await plugin.getDirectoryPaths(); expectMethodCall( log, 'getDirectoryPath', arguments: <String, dynamic>{ 'initialDirectory': null, 'confirmButtonText': null, 'multiple': true, }, ); }); }); } void expectMethodCall( List<MethodCall> log, String methodName, { Map<String, dynamic>? arguments, }) { expect(log, <Matcher>[isMethodCall(methodName, arguments: arguments)]); }
packages/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart", "repo_id": "packages", "token_count": 6615 }
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. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'src/messages.g.dart'; /// An implementation of [FileSelectorPlatform] for macOS. class FileSelectorMacOS extends FileSelectorPlatform { final FileSelectorApi _hostApi = FileSelectorApi(); /// Registers the macOS implementation. static void registerWith() { FileSelectorPlatform.instance = FileSelectorMacOS(); } @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions( allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.isEmpty ? null : XFile(paths.first!); } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: true, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions( allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.map((String? path) => XFile(path!)).toList(); } @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async { final FileSaveLocation? location = await getSaveLocation( acceptedTypeGroups: acceptedTypeGroups, options: SaveDialogOptions( initialDirectory: initialDirectory, suggestedName: suggestedName, confirmButtonText: confirmButtonText, )); return location?.path; } @override Future<FileSaveLocation?> getSaveLocation({ List<XTypeGroup>? acceptedTypeGroups, SaveDialogOptions options = const SaveDialogOptions(), }) async { final String? path = await _hostApi.displaySavePanel(SavePanelOptions( allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), directoryPath: options.initialDirectory, nameFieldStringValue: options.suggestedName, prompt: options.confirmButtonText, )); return path == null ? null : FileSaveLocation(path); } @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: true, canChooseFiles: false, baseOptions: SavePanelOptions( directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.isEmpty ? null : paths.first; } @override Future<List<String>> getDirectoryPaths({ String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: true, canChooseDirectories: true, canChooseFiles: false, baseOptions: SavePanelOptions( directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.isEmpty ? <String>[] : List<String>.from(paths); } // Converts the type group list into a flat list of all allowed types, since // macOS doesn't support filter groups. AllowedTypes? _allowedTypesFromTypeGroups(List<XTypeGroup>? typeGroups) { if (typeGroups == null || typeGroups.isEmpty) { return null; } final AllowedTypes allowedTypes = AllowedTypes( extensions: <String>[], mimeTypes: <String>[], utis: <String>[], ); for (final XTypeGroup typeGroup in typeGroups) { // If any group allows everything, no filtering should be done. if (typeGroup.allowsAny) { return null; } // Reject a filter that isn't an allow-any, but doesn't set any // macOS-supported filter categories. if ((typeGroup.extensions?.isEmpty ?? true) && (typeGroup.uniformTypeIdentifiers?.isEmpty ?? true) && (typeGroup.mimeTypes?.isEmpty ?? true)) { throw ArgumentError('Provided type group $typeGroup does not allow ' 'all files, but does not set any of the macOS-supported filter ' 'categories. At least one of "extensions", ' '"uniformTypeIdentifiers", or "mimeTypes" must be non-empty for ' 'macOS if anything is non-empty.'); } allowedTypes.extensions.addAll(typeGroup.extensions ?? <String>[]); allowedTypes.mimeTypes.addAll(typeGroup.mimeTypes ?? <String>[]); allowedTypes.utis.addAll(typeGroup.uniformTypeIdentifiers ?? <String>[]); } return allowedTypes; } }
packages/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart", "repo_id": "packages", "token_count": 2097 }
981
// 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 '../../file_selector_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/file_selector'); /// An implementation of [FileSelectorPlatform] that uses method channels. class MethodChannelFileSelector extends FileSelectorPlatform { /// The MethodChannel that is being used by this implementation of the plugin. @visibleForTesting MethodChannel get channel => _channel; @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String>? path = await _channel.invokeListMethod<String>( 'openFile', <String, dynamic>{ 'acceptedTypeGroups': acceptedTypeGroups ?.map((XTypeGroup group) => group.toJSON()) .toList(), 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, 'multiple': false, }, ); return path == null ? null : XFile(path.first); } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String>? pathList = await _channel.invokeListMethod<String>( 'openFile', <String, dynamic>{ 'acceptedTypeGroups': acceptedTypeGroups ?.map((XTypeGroup group) => group.toJSON()) .toList(), 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, 'multiple': true, }, ); return pathList?.map((String path) => XFile(path)).toList() ?? <XFile>[]; } @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async { return _channel.invokeMethod<String>( 'getSavePath', <String, dynamic>{ 'acceptedTypeGroups': acceptedTypeGroups ?.map((XTypeGroup group) => group.toJSON()) .toList(), 'initialDirectory': initialDirectory, 'suggestedName': suggestedName, 'confirmButtonText': confirmButtonText, }, ); } @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async { return _channel.invokeMethod<String>( 'getDirectoryPath', <String, dynamic>{ 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, }, ); } @override Future<List<String>> getDirectoryPaths( {String? initialDirectory, String? confirmButtonText}) async { final List<String>? pathList = await _channel.invokeListMethod<String>( 'getDirectoryPaths', <String, dynamic>{ 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, }, ); return pathList ?? <String>[]; } }
packages/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart", "repo_id": "packages", "token_count": 1174 }
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 'dart:js_interop'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_web/src/dom_helper.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:web/web.dart'; void main() { group('dom_helper', () { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); late DomHelper domHelper; late HTMLInputElement input; FileList? createFileList(List<File> files) { final DataTransfer dataTransfer = DataTransfer(); // Tear-offs of external extension type interop member 'add' are disallowed. // ignore: prefer_foreach for (final File e in files) { dataTransfer.items.add(e); } return dataTransfer.files; } void setFilesAndTriggerEvent(List<File> files, Event event) { input.files = createFileList(files); input.dispatchEvent(event); } void setFilesAndTriggerChange(List<File> files) { setFilesAndTriggerEvent(files, Event('change')); } void setFilesAndTriggerCancel(List<File> files) { setFilesAndTriggerEvent(files, Event('cancel')); } setUp(() { domHelper = DomHelper(); input = (document.createElement('input') as HTMLInputElement) ..type = 'file'; }); group('getFiles', () { final File mockFile1 = File(<JSAny>['123456'.toJS].toJS, 'file1.txt'); final File mockFile2 = File(<JSAny>[].toJS, 'file2.txt'); testWidgets('works', (_) async { final Future<List<XFile>> futureFiles = domHelper.getFiles( input: input, ); setFilesAndTriggerChange(<File>[mockFile1, mockFile2]); final List<XFile> files = await futureFiles; expect(files.length, 2); expect(files[0].name, 'file1.txt'); expect(await files[0].length(), 6); expect(await files[0].readAsString(), '123456'); expect(await files[0].lastModified(), isNotNull); expect(files[1].name, 'file2.txt'); expect(await files[1].length(), 0); expect(await files[1].readAsString(), ''); expect(await files[1].lastModified(), isNotNull); }); testWidgets('"cancel" returns an empty selection', (_) async { final Future<List<XFile>> futureFiles = domHelper.getFiles( input: input, ); setFilesAndTriggerCancel(<File>[mockFile1, mockFile2]); final List<XFile> files = await futureFiles; expect(files.length, 0); }); testWidgets('works multiple times', (_) async { Future<List<XFile>> futureFiles; List<XFile> files; // It should work the first time futureFiles = domHelper.getFiles(input: input); setFilesAndTriggerChange(<File>[mockFile1]); files = await futureFiles; expect(files.length, 1); expect(files.first.name, mockFile1.name); // The same input should work more than once futureFiles = domHelper.getFiles(input: input); setFilesAndTriggerChange(<File>[mockFile2]); files = await futureFiles; expect(files.length, 1); expect(files.first.name, mockFile2.name); }); testWidgets('sets the <input /> attributes and clicks it', (_) async { const String accept = '.jpg,.png'; const bool multiple = true; final Future<bool> wasClicked = input.onClick.first.then((_) => true); final Future<List<XFile>> futureFile = domHelper.getFiles( accept: accept, multiple: multiple, input: input, ); expect(input.isConnected, true, reason: 'input must be injected into the DOM'); expect(input.accept, accept); expect(input.multiple, multiple); expect(await wasClicked, true, reason: 'The <input /> should be clicked otherwise no dialog will be shown'); setFilesAndTriggerChange(<File>[]); await futureFile; // It should be already removed from the DOM after the file is resolved. expect(input.isConnected, isFalse); }); }); }); }
packages/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart", "repo_id": "packages", "token_count": 1732 }
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. #include "string_utils.h" #include <shobjidl.h> #include <windows.h> #include <string> namespace file_selector_windows { // Converts the given UTF-16 string to UTF-8. std::string Utf8FromUtf16(std::wstring_view utf16_string) { if (utf16_string.empty()) { return std::string(); } int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string.data(), static_cast<int>(utf16_string.length()), nullptr, 0, nullptr, nullptr); if (target_length == 0) { return std::string(); } std::string utf8_string; utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string.data(), static_cast<int>(utf16_string.length()), utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } return utf8_string; } // Converts the given UTF-8 string to UTF-16. std::wstring Utf16FromUtf8(std::string_view utf8_string) { if (utf8_string.empty()) { return std::wstring(); } int target_length = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(), static_cast<int>(utf8_string.length()), nullptr, 0); if (target_length == 0) { return std::wstring(); } std::wstring utf16_string; utf16_string.resize(target_length); int converted_length = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(), static_cast<int>(utf8_string.length()), utf16_string.data(), target_length); if (converted_length == 0) { return std::wstring(); } return utf16_string; } } // namespace file_selector_windows
packages/packages/file_selector/file_selector_windows/windows/string_utils.cpp/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/windows/string_utils.cpp", "repo_id": "packages", "token_count": 788 }
984
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/flutter_adaptive_scaffold/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
985
#include "Generated.xcconfig"
packages/packages/flutter_adaptive_scaffold/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/ios/Flutter/Release.xcconfig", "repo_id": "packages", "token_count": 12 }
986
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/flutter_adaptive_scaffold/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
987
// 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_image/flutter_image.dart'; void main() => runApp(const MyApp()); /// The main app. class MyApp extends StatelessWidget { /// Contructs main app. const MyApp({super.key}); /// Returns the URL to load an asset from this example app as a network source. String getUrlForAssetAsNetworkSource(String assetKey) { return 'https://github.com/flutter/packages/blob/b96a6dae0ca418cf1e91633f275866aa9cffe437/packages/flutter_image/example/$assetKey?raw=true'; } @override Widget build(BuildContext context) { final String imageUrl = getUrlForAssetAsNetworkSource('assets/flutter-mark-square-64.png'); return MaterialApp( title: 'flutter_image example app', home: HomeScreen(imageUrl: imageUrl), ); } } /// The home screen. class HomeScreen extends StatelessWidget { /// Contructs a [HomeScreen] const HomeScreen({ super.key, required this.imageUrl, }); /// URL of the network image. final String imageUrl; @override Widget build(BuildContext context) { const int maxAttempt = 3; const Duration attemptTimeout = Duration(seconds: 2); return Scaffold( appBar: AppBar( title: const Text('Flutter Image example'), ), body: Center( child: Image( image: NetworkImageWithRetry( imageUrl, scale: 0.8, fetchStrategy: (Uri uri, FetchFailure? failure) async { final FetchInstructions fetchInstruction = FetchInstructions.attempt( uri: uri, timeout: attemptTimeout, ); if (failure != null && failure.attemptCount > maxAttempt) { return FetchInstructions.giveUp(uri: uri); } return fetchInstruction; }, ), ), ), ); } }
packages/packages/flutter_image/example/lib/main.dart/0
{ "file_path": "packages/packages/flutter_image/example/lib/main.dart", "repo_id": "packages", "token_count": 838 }
988
name: flutter_image description: > Image utilities for Flutter: improved network providers, effects, etc. repository: https://github.com/flutter/packages/tree/main/packages/flutter_image issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+flutter_image%22 version: 4.1.11 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter quiver: ^3.0.0 test: any topics: - image - network
packages/packages/flutter_image/pubspec.yaml/0
{ "file_path": "packages/packages/flutter_image/pubspec.yaml", "repo_id": "packages", "token_count": 212 }
989
// 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 '../demos/basic_markdown_demo.dart'; import '../demos/centered_header_demo.dart'; import '../demos/extended_emoji_demo.dart'; import '../demos/markdown_body_shrink_wrap_demo.dart'; import '../demos/minimal_markdown_demo.dart'; import '../demos/original_demo.dart'; import '../demos/subscript_syntax_demo.dart'; import '../demos/wrap_alignment_demo.dart'; import '../screens/demo_card.dart'; import '../shared/markdown_demo_widget.dart'; // ignore_for_file: public_member_api_docs class HomeScreen extends StatelessWidget { HomeScreen({super.key}); static const String routeName = '/homeScreen'; final List<MarkdownDemoWidget> _demos = <MarkdownDemoWidget>[ const MinimalMarkdownDemo(), const BasicMarkdownDemo(), const WrapAlignmentDemo(), const SubscriptSyntaxDemo(), const ExtendedEmojiDemo(), OriginalMarkdownDemo(), const CenteredHeaderDemo(), const MarkdownBodyShrinkWrapDemo(), ]; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: const Text('Markdown Demos'), ), body: SafeArea( child: ColoredBox( color: Colors.black12, child: ListView( children: <Widget>[ for (final MarkdownDemoWidget demo in _demos) DemoCard(widget: demo), ], ), ), ), ); } }
packages/packages/flutter_markdown/example/lib/screens/home_screen.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/screens/home_screen.dart", "repo_id": "packages", "token_count": 652 }
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. import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:markdown/markdown.dart' as md; import '_functions_io.dart' if (dart.library.js_interop) '_functions_web.dart'; import 'style_sheet.dart'; import 'widget.dart'; final List<String> _kBlockTags = <String>[ 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre', 'ol', 'ul', 'hr', 'table', 'thead', 'tbody', 'tr', 'section', ]; const List<String> _kListTags = <String>['ul', 'ol']; bool _isBlockTag(String? tag) => _kBlockTags.contains(tag); bool _isListTag(String tag) => _kListTags.contains(tag); class _BlockElement { _BlockElement(this.tag); final String? tag; final List<Widget> children = <Widget>[]; int nextListIndex = 0; } class _TableElement { final List<TableRow> rows = <TableRow>[]; } /// A collection of widgets that should be placed adjacent to (inline with) /// other inline elements in the same parent block. /// /// Inline elements can be textual (a/em/strong) represented by [Text.rich] /// widgets or images (img) represented by [Image.network] widgets. /// /// Inline elements can be nested within other inline elements, inheriting their /// parent's style along with the style of the block they are in. /// /// When laying out inline widgets, first, any adjacent Text.rich widgets are /// merged, then, all inline widgets are enclosed in a parent [Wrap] widget. class _InlineElement { _InlineElement(this.tag, {this.style}); final String? tag; /// Created by merging the style defined for this element's [tag] in the /// delegate's [MarkdownStyleSheet] with the style of its parent. final TextStyle? style; final List<Widget> children = <Widget>[]; } /// A delegate used by [MarkdownBuilder] to control the widgets it creates. abstract class MarkdownBuilderDelegate { /// Returns the [BuildContext] of the [MarkdownWidget]. /// /// The context will be passed down to the /// [MarkdownElementBuilder.visitElementBefore] method and allows elements to /// get information from the context. BuildContext get context; /// Returns a gesture recognizer to use for an `a` element with the given /// text, `href` attribute, and title. GestureRecognizer createLink(String text, String? href, String title); /// Returns formatted text to use to display the given contents of a `pre` /// element. /// /// The `styleSheet` is the value of [MarkdownBuilder.styleSheet]. TextSpan formatText(MarkdownStyleSheet styleSheet, String code); } /// Builds a [Widget] tree from parsed Markdown. /// /// See also: /// /// * [Markdown], which is a widget that parses and displays Markdown. class MarkdownBuilder implements md.NodeVisitor { /// Creates an object that builds a [Widget] tree from parsed Markdown. MarkdownBuilder({ required this.delegate, required this.selectable, required this.styleSheet, required this.imageDirectory, required this.imageBuilder, required this.checkboxBuilder, required this.bulletBuilder, required this.builders, required this.paddingBuilders, required this.listItemCrossAxisAlignment, this.fitContent = false, this.onSelectionChanged, this.onTapText, this.softLineBreak = false, }); /// A delegate that controls how link and `pre` elements behave. final MarkdownBuilderDelegate delegate; /// If true, the text is selectable. /// /// Defaults to false. final bool selectable; /// Defines which [TextStyle] objects to use for each type of element. final MarkdownStyleSheet styleSheet; /// The base directory holding images referenced by Img tags with local or network file paths. final String? imageDirectory; /// Call when build an image widget. final MarkdownImageBuilder? imageBuilder; /// Call when build a checkbox widget. final MarkdownCheckboxBuilder? checkboxBuilder; /// Called when building a custom bullet. final MarkdownBulletBuilder? bulletBuilder; /// Call when build a custom widget. final Map<String, MarkdownElementBuilder> builders; /// Call when build a padding for widget. final Map<String, MarkdownPaddingBuilder> paddingBuilders; /// Whether to allow the widget to fit the child content. final bool fitContent; /// Controls the cross axis alignment for the bullet and list item content /// in lists. /// /// Defaults to [MarkdownListItemCrossAxisAlignment.baseline], which /// does not allow for intrinsic height measurements. final MarkdownListItemCrossAxisAlignment listItemCrossAxisAlignment; /// Called when the user changes selection when [selectable] is set to true. final MarkdownOnSelectionChangedCallback? onSelectionChanged; /// Default tap handler used when [selectable] is set to true final VoidCallback? onTapText; /// The soft line break is used to identify the spaces at the end of aline of /// text and the leading spaces in the immediately following the line of text. /// /// Default these spaces are removed in accordance with the Markdown /// specification on soft line breaks when lines of text are joined. final bool softLineBreak; final List<String> _listIndents = <String>[]; final List<_BlockElement> _blocks = <_BlockElement>[]; final List<_TableElement> _tables = <_TableElement>[]; final List<_InlineElement> _inlines = <_InlineElement>[]; final List<GestureRecognizer> _linkHandlers = <GestureRecognizer>[]; final ScrollController _preScrollController = ScrollController(); String? _currentBlockTag; String? _lastVisitedTag; bool _isInBlockquote = false; /// Returns widgets that display the given Markdown nodes. /// /// The returned widgets are typically used as children in a [ListView]. List<Widget> build(List<md.Node> nodes) { _listIndents.clear(); _blocks.clear(); _tables.clear(); _inlines.clear(); _linkHandlers.clear(); _isInBlockquote = false; builders.forEach((String key, MarkdownElementBuilder value) { if (value.isBlockElement()) { _kBlockTags.add(key); } }); _blocks.add(_BlockElement(null)); for (final md.Node node in nodes) { assert(_blocks.length == 1); node.accept(this); } assert(_tables.isEmpty); assert(_inlines.isEmpty); assert(!_isInBlockquote); return _blocks.single.children; } @override bool visitElementBefore(md.Element element) { final String tag = element.tag; _currentBlockTag ??= tag; _lastVisitedTag = tag; if (builders.containsKey(tag)) { builders[tag]!.visitElementBefore(element); } if (paddingBuilders.containsKey(tag)) { paddingBuilders[tag]!.visitElementBefore(element); } int? start; if (_isBlockTag(tag)) { _addAnonymousBlockIfNeeded(); if (_isListTag(tag)) { _listIndents.add(tag); if (element.attributes['start'] != null) { start = int.parse(element.attributes['start']!) - 1; } } else if (tag == 'blockquote') { _isInBlockquote = true; } else if (tag == 'table') { _tables.add(_TableElement()); } else if (tag == 'tr') { final int length = _tables.single.rows.length; BoxDecoration? decoration = styleSheet.tableCellsDecoration as BoxDecoration?; if (length == 0 || length.isOdd) { decoration = null; } _tables.single.rows.add(TableRow( decoration: decoration, // TODO(stuartmorgan): This should be fixed, not suppressed; enabling // this lint warning exposed that the builder is modifying the // children of TableRows, even though they are @immutable. // ignore: prefer_const_literals_to_create_immutables children: <Widget>[], )); } final _BlockElement bElement = _BlockElement(tag); if (start != null) { bElement.nextListIndex = start; } _blocks.add(bElement); } else { if (tag == 'a') { final String? text = extractTextFromElement(element); // Don't add empty links if (text == null) { return false; } final String? destination = element.attributes['href']; final String title = element.attributes['title'] ?? ''; _linkHandlers.add( delegate.createLink(text, destination, title), ); } _addParentInlineIfNeeded(_blocks.last.tag); // The Markdown parser passes empty table data tags for blank // table cells. Insert a text node with an empty string in this // case for the table cell to get properly created. if (element.tag == 'td' && element.children != null && element.children!.isEmpty) { element.children!.add(md.Text('')); } final TextStyle parentStyle = _inlines.last.style!; _inlines.add(_InlineElement( tag, style: parentStyle.merge(styleSheet.styles[tag]), )); } return true; } /// Returns the text, if any, from [element] and its descendants. String? extractTextFromElement(md.Node element) { return element is md.Element && (element.children?.isNotEmpty ?? false) ? element.children! .map((md.Node e) => e is md.Text ? e.text : extractTextFromElement(e)) .join() : (element is md.Element && (element.attributes.isNotEmpty) ? element.attributes['alt'] : ''); } @override void visitText(md.Text text) { // Don't allow text directly under the root. if (_blocks.last.tag == null) { return; } _addParentInlineIfNeeded(_blocks.last.tag); // Define trim text function to remove spaces from text elements in // accordance with Markdown specifications. String trimText(String text) { // The leading spaces pattern is used to identify spaces // at the beginning of a line of text. final RegExp leadingSpacesPattern = RegExp(r'^ *'); // The soft line break is used to identify the spaces at the end of a line // of text and the leading spaces in the immediately following the line // of text. These spaces are removed in accordance with the Markdown // specification on soft line breaks when lines of text are joined. final RegExp softLineBreakPattern = RegExp(r' ?\n *'); // Leading spaces following a hard line break are ignored. // https://github.github.com/gfm/#example-657 // Leading spaces in paragraph or list item are ignored // https://github.github.com/gfm/#example-192 // https://github.github.com/gfm/#example-236 if (const <String>['ul', 'ol', 'li', 'p', 'br'] .contains(_lastVisitedTag)) { text = text.replaceAll(leadingSpacesPattern, ''); } if (softLineBreak) { return text; } return text.replaceAll(softLineBreakPattern, ' '); } Widget? child; if (_blocks.isNotEmpty && builders.containsKey(_blocks.last.tag)) { child = builders[_blocks.last.tag!]! .visitText(text, styleSheet.styles[_blocks.last.tag!]); } else if (_blocks.last.tag == 'pre') { child = Scrollbar( controller: _preScrollController, child: SingleChildScrollView( controller: _preScrollController, scrollDirection: Axis.horizontal, padding: styleSheet.codeblockPadding, child: _buildRichText(delegate.formatText(styleSheet, text.text)), ), ); } else { child = _buildRichText( TextSpan( style: _isInBlockquote ? styleSheet.blockquote!.merge(_inlines.last.style) : _inlines.last.style, text: _isInBlockquote ? text.text : trimText(text.text), recognizer: _linkHandlers.isNotEmpty ? _linkHandlers.last : null, ), textAlign: _textAlignForBlockTag(_currentBlockTag), ); } if (child != null) { _inlines.last.children.add(child); } _lastVisitedTag = null; } @override void visitElementAfter(md.Element element) { final String tag = element.tag; if (_isBlockTag(tag)) { _addAnonymousBlockIfNeeded(); final _BlockElement current = _blocks.removeLast(); Widget child; if (current.children.isNotEmpty) { child = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: fitContent ? CrossAxisAlignment.start : CrossAxisAlignment.stretch, children: current.children, ); } else { child = const SizedBox(); } if (_isListTag(tag)) { assert(_listIndents.isNotEmpty); _listIndents.removeLast(); } else if (tag == 'li') { if (_listIndents.isNotEmpty) { if (element.children!.isEmpty) { element.children!.add(md.Text('')); } Widget bullet; final dynamic el = element.children![0]; if (el is md.Element && el.attributes['type'] == 'checkbox') { final bool val = el.attributes.containsKey('checked'); bullet = _buildCheckbox(val); } else { bullet = _buildBullet(_listIndents.last); } child = Row( mainAxisSize: fitContent ? MainAxisSize.min : MainAxisSize.max, textBaseline: listItemCrossAxisAlignment == MarkdownListItemCrossAxisAlignment.start ? null : TextBaseline.alphabetic, crossAxisAlignment: listItemCrossAxisAlignment == MarkdownListItemCrossAxisAlignment.start ? CrossAxisAlignment.start : CrossAxisAlignment.baseline, children: <Widget>[ SizedBox( width: styleSheet.listIndent! + styleSheet.listBulletPadding!.left + styleSheet.listBulletPadding!.right, child: bullet, ), Flexible( fit: fitContent ? FlexFit.loose : FlexFit.tight, child: child, ) ], ); } } else if (tag == 'table') { child = Table( defaultColumnWidth: styleSheet.tableColumnWidth!, defaultVerticalAlignment: styleSheet.tableVerticalAlignment, border: styleSheet.tableBorder, children: _tables.removeLast().rows, ); } else if (tag == 'blockquote') { _isInBlockquote = false; child = DecoratedBox( decoration: styleSheet.blockquoteDecoration!, child: Padding( padding: styleSheet.blockquotePadding!, child: child, ), ); } else if (tag == 'pre') { child = Container( clipBehavior: Clip.hardEdge, decoration: styleSheet.codeblockDecoration, child: child, ); } else if (tag == 'hr') { child = Container(decoration: styleSheet.horizontalRuleDecoration); } _addBlockChild(child); } else { final _InlineElement current = _inlines.removeLast(); final _InlineElement parent = _inlines.last; EdgeInsets padding = EdgeInsets.zero; if (paddingBuilders.containsKey(tag)) { padding = paddingBuilders[tag]!.getPadding(); } if (builders.containsKey(tag)) { final Widget? child = builders[tag]!.visitElementAfterWithContext( delegate.context, element, styleSheet.styles[tag], parent.style, ); if (child != null) { if (current.children.isEmpty) { current.children.add(child); } else { current.children[0] = child; } } } else if (tag == 'img') { // create an image widget for this image current.children.add(_buildPadding( padding, _buildImage( element.attributes['src']!, element.attributes['title'], element.attributes['alt'], ), )); } else if (tag == 'br') { current.children.add(_buildRichText(const TextSpan(text: '\n'))); } else if (tag == 'th' || tag == 'td') { TextAlign? align; final String? alignAttribute = element.attributes['align']; if (alignAttribute == null) { align = tag == 'th' ? styleSheet.tableHeadAlign : TextAlign.left; } else { switch (alignAttribute) { case 'left': align = TextAlign.left; case 'center': align = TextAlign.center; case 'right': align = TextAlign.right; } } final Widget child = _buildTableCell( _mergeInlineChildren(current.children, align), textAlign: align, ); _ambiguate(_tables.single.rows.last.children)!.add(child); } else if (tag == 'a') { _linkHandlers.removeLast(); } else if (tag == 'sup') { final Widget c = current.children.last; TextSpan? textSpan; if (c is Text && c.textSpan is TextSpan) { textSpan = c.textSpan! as TextSpan; } else if (c is SelectableText && c.textSpan is TextSpan) { textSpan = c.textSpan; } if (textSpan != null) { final Widget richText = _buildRichText( TextSpan( recognizer: textSpan.recognizer, text: element.textContent, style: textSpan.style?.copyWith( fontFeatures: <FontFeature>[ const FontFeature.enable('sups'), ], ), ), ); current.children.removeLast(); current.children.add(richText); } } if (current.children.isNotEmpty) { parent.children.addAll(current.children); } } if (_currentBlockTag == tag) { _currentBlockTag = null; } _lastVisitedTag = tag; } Widget _buildImage(String src, String? title, String? alt) { final List<String> parts = src.split('#'); if (parts.isEmpty) { return const SizedBox(); } final String path = parts.first; double? width; double? height; if (parts.length == 2) { final List<String> dimensions = parts.last.split('x'); if (dimensions.length == 2) { width = double.parse(dimensions[0]); height = double.parse(dimensions[1]); } } final Uri uri = Uri.parse(path); Widget child; if (imageBuilder != null) { child = imageBuilder!(uri, title, alt); } else { child = kDefaultImageBuilder(uri, imageDirectory, width, height); } if (_linkHandlers.isNotEmpty) { final TapGestureRecognizer recognizer = _linkHandlers.last as TapGestureRecognizer; return GestureDetector(onTap: recognizer.onTap, child: child); } else { return child; } } Widget _buildCheckbox(bool checked) { if (checkboxBuilder != null) { return checkboxBuilder!(checked); } return Padding( padding: styleSheet.listBulletPadding!, child: Icon( checked ? Icons.check_box : Icons.check_box_outline_blank, size: styleSheet.checkbox!.fontSize, color: styleSheet.checkbox!.color, ), ); } Widget _buildBullet(String listTag) { final int index = _blocks.last.nextListIndex; final bool isUnordered = listTag == 'ul'; if (bulletBuilder != null) { return Padding( padding: styleSheet.listBulletPadding!, child: bulletBuilder!(index, isUnordered ? BulletStyle.unorderedList : BulletStyle.orderedList), ); } if (isUnordered) { return Padding( padding: styleSheet.listBulletPadding!, child: Text( '•', textAlign: TextAlign.center, style: styleSheet.listBullet, ), ); } return Padding( padding: styleSheet.listBulletPadding!, child: Text( '${index + 1}.', textAlign: TextAlign.right, style: styleSheet.listBullet, ), ); } Widget _buildTableCell(List<Widget?> children, {TextAlign? textAlign}) { return TableCell( child: Padding( padding: styleSheet.tableCellsPadding!, child: DefaultTextStyle( style: styleSheet.tableBody!, textAlign: textAlign, child: Wrap(children: children as List<Widget>), ), ), ); } Widget _buildPadding(EdgeInsets padding, Widget child) { if (padding == EdgeInsets.zero) { return child; } return Padding(padding: padding, child: child); } void _addParentInlineIfNeeded(String? tag) { if (_inlines.isEmpty) { _inlines.add(_InlineElement( tag, style: styleSheet.styles[tag!], )); } } void _addBlockChild(Widget child) { final _BlockElement parent = _blocks.last; if (parent.children.isNotEmpty) { parent.children.add(SizedBox(height: styleSheet.blockSpacing)); } parent.children.add(child); parent.nextListIndex += 1; } void _addAnonymousBlockIfNeeded() { if (_inlines.isEmpty) { return; } WrapAlignment blockAlignment = WrapAlignment.start; TextAlign textAlign = TextAlign.start; EdgeInsets textPadding = EdgeInsets.zero; if (_isBlockTag(_currentBlockTag)) { blockAlignment = _wrapAlignmentForBlockTag(_currentBlockTag); textAlign = _textAlignForBlockTag(_currentBlockTag); textPadding = _textPaddingForBlockTag(_currentBlockTag); if (paddingBuilders.containsKey(_currentBlockTag)) { textPadding = paddingBuilders[_currentBlockTag]!.getPadding(); } } final _InlineElement inline = _inlines.single; if (inline.children.isNotEmpty) { final List<Widget> mergedInlines = _mergeInlineChildren( inline.children, textAlign, ); final Wrap wrap = Wrap( crossAxisAlignment: WrapCrossAlignment.center, alignment: blockAlignment, children: mergedInlines, ); if (textPadding == EdgeInsets.zero) { _addBlockChild(wrap); } else { final Padding padding = Padding(padding: textPadding, child: wrap); _addBlockChild(padding); } _inlines.clear(); } } /// Extracts all spans from an inline element and merges them into a single list Iterable<InlineSpan> _getInlineSpans(InlineSpan span) { // If the span is not a TextSpan or it has no children, return the span if (span is! TextSpan || span.children == null) { return <InlineSpan>[span]; } // Merge the style of the parent with the style of the children final Iterable<InlineSpan> spans = span.children!.map((InlineSpan childSpan) { if (childSpan is TextSpan) { return TextSpan( text: childSpan.text, recognizer: childSpan.recognizer, semanticsLabel: childSpan.semanticsLabel, style: childSpan.style?.merge(span.style), ); } else { return childSpan; } }); return spans; } /// Merges adjacent [TextSpan] children List<Widget> _mergeInlineChildren( List<Widget> children, TextAlign? textAlign, ) { // List of merged text spans and widgets final List<Widget> mergedTexts = <Widget>[]; for (final Widget child in children) { // If the list is empty, add the current widget to the list if (mergedTexts.isEmpty) { mergedTexts.add(child); continue; } // Remove last widget from the list to merge it with the current widget final Widget last = mergedTexts.removeLast(); // Extracted spans from the last and the current widget List<InlineSpan> spans = <InlineSpan>[]; // Extract the text spans from the last widget if (last is SelectableText) { final TextSpan span = last.textSpan!; spans.addAll(_getInlineSpans(span)); } else if (last is Text) { final InlineSpan span = last.textSpan!; spans.addAll(_getInlineSpans(span)); } else if (last is RichText) { final InlineSpan span = last.text; spans.addAll(_getInlineSpans(span)); } else { // If the last widget is not a text widget, // add both the last and the current widget to the list mergedTexts.addAll(<Widget>[last, child]); continue; } // Extract the text spans from the current widget if (child is Text) { final InlineSpan span = child.textSpan!; spans.addAll(_getInlineSpans(span)); } else if (child is SelectableText) { final TextSpan span = child.textSpan!; spans.addAll(_getInlineSpans(span)); } else if (child is RichText) { final InlineSpan span = child.text; spans.addAll(_getInlineSpans(span)); } else { // If the current widget is not a text widget, // add both the last and the current widget to the list mergedTexts.addAll(<Widget>[last, child]); continue; } if (spans.isNotEmpty) { // Merge similar text spans spans = _mergeSimilarTextSpans(spans); // Create a new text widget with the merged text spans InlineSpan child; if (spans.length == 1) { child = spans.first; } else { child = TextSpan(children: spans); } // Add the new text widget to the list if (selectable) { mergedTexts.add(SelectableText.rich( TextSpan(children: spans), textScaler: styleSheet.textScaler, textAlign: textAlign ?? TextAlign.start, onTap: onTapText, )); } else { mergedTexts.add(Text.rich( child, textScaler: styleSheet.textScaler, textAlign: textAlign ?? TextAlign.start, )); } } else { // If no text spans were found, add the current widget to the list mergedTexts.add(child); } } return mergedTexts; } TextAlign _textAlignForBlockTag(String? blockTag) { final WrapAlignment wrapAlignment = _wrapAlignmentForBlockTag(blockTag); switch (wrapAlignment) { case WrapAlignment.start: return TextAlign.start; case WrapAlignment.center: return TextAlign.center; case WrapAlignment.end: return TextAlign.end; case WrapAlignment.spaceAround: return TextAlign.justify; case WrapAlignment.spaceBetween: return TextAlign.justify; case WrapAlignment.spaceEvenly: return TextAlign.justify; } } WrapAlignment _wrapAlignmentForBlockTag(String? blockTag) { switch (blockTag) { case 'p': return styleSheet.textAlign; case 'h1': return styleSheet.h1Align; case 'h2': return styleSheet.h2Align; case 'h3': return styleSheet.h3Align; case 'h4': return styleSheet.h4Align; case 'h5': return styleSheet.h5Align; case 'h6': return styleSheet.h6Align; case 'ul': return styleSheet.unorderedListAlign; case 'ol': return styleSheet.orderedListAlign; case 'blockquote': return styleSheet.blockquoteAlign; case 'pre': return styleSheet.codeblockAlign; case 'hr': break; case 'li': break; } return WrapAlignment.start; } EdgeInsets _textPaddingForBlockTag(String? blockTag) { switch (blockTag) { case 'p': return styleSheet.pPadding!; case 'h1': return styleSheet.h1Padding!; case 'h2': return styleSheet.h2Padding!; case 'h3': return styleSheet.h3Padding!; case 'h4': return styleSheet.h4Padding!; case 'h5': return styleSheet.h5Padding!; case 'h6': return styleSheet.h6Padding!; } return EdgeInsets.zero; } /// Combine text spans with equivalent properties into a single span. List<InlineSpan> _mergeSimilarTextSpans(List<InlineSpan> textSpans) { if (textSpans.length < 2) { return textSpans; } final List<InlineSpan> mergedSpans = <InlineSpan>[]; for (int index = 1; index < textSpans.length; index++) { final InlineSpan previous = mergedSpans.isEmpty ? textSpans.first : mergedSpans.removeLast(); final InlineSpan nextChild = textSpans[index]; final bool previousIsTextSpan = previous is TextSpan; final bool nextIsTextSpan = nextChild is TextSpan; if (!previousIsTextSpan || !nextIsTextSpan) { mergedSpans.addAll(<InlineSpan>[previous, nextChild]); continue; } final bool matchStyle = nextChild.recognizer == previous.recognizer && nextChild.semanticsLabel == previous.semanticsLabel && nextChild.style == previous.style; if (matchStyle) { mergedSpans.add(TextSpan( text: previous.toPlainText() + nextChild.toPlainText(), recognizer: previous.recognizer, semanticsLabel: previous.semanticsLabel, style: previous.style, )); } else { mergedSpans.addAll(<InlineSpan>[previous, nextChild]); } } // When the mergered spans compress into a single TextSpan return just that // TextSpan, otherwise bundle the set of TextSpans under a single parent. return mergedSpans; } Widget _buildRichText(TextSpan? text, {TextAlign? textAlign, String? key}) { //Adding a unique key prevents the problem of using the same link handler for text spans with the same text final Key k = key == null ? UniqueKey() : Key(key); if (selectable) { return SelectableText.rich( text!, textScaler: styleSheet.textScaler, textAlign: textAlign ?? TextAlign.start, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) => onSelectionChanged!(text.text, selection, cause), onTap: onTapText, key: k, ); } else { return Text.rich( text!, textScaler: styleSheet.textScaler, textAlign: textAlign ?? TextAlign.start, key: k, ); } } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value; }
packages/packages/flutter_markdown/lib/src/builder.dart/0
{ "file_path": "packages/packages/flutter_markdown/lib/src/builder.dart", "repo_id": "packages", "token_count": 12632 }
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 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:mockito/mockito.dart'; class TestHttpOverrides extends HttpOverrides { @override HttpClient createHttpClient(SecurityContext? context) { return createMockImageHttpClient(context); } } MockHttpClient createMockImageHttpClient(SecurityContext? _) { final MockHttpClient client = MockHttpClient(); final MockHttpClientRequest request = MockHttpClientRequest(); final MockHttpClientResponse response = MockHttpClientResponse(); final MockHttpHeaders headers = MockHttpHeaders(); final List<int> transparentImage = getTestImageData(); when(client.getUrl(any)) .thenAnswer((_) => Future<MockHttpClientRequest>.value(request)); when(request.headers).thenReturn(headers); when(request.close()) .thenAnswer((_) => Future<MockHttpClientResponse>.value(response)); when(client.autoUncompress = any).thenAnswer((_) => null); when(response.contentLength).thenReturn(transparentImage.length); when(response.statusCode).thenReturn(HttpStatus.ok); when(response.compressionState) .thenReturn(HttpClientResponseCompressionState.notCompressed); // Define an image stream that streams the mock test image for all // image tests that request an image. StreamSubscription<List<int>> imageStream(Invocation invocation) { final void Function(List<int>)? onData = invocation.positionalArguments[0] as void Function(List<int>)?; final void Function()? onDone = invocation.namedArguments[#onDone] as void Function()?; final void Function(Object, [StackTrace?])? onError = invocation .namedArguments[#onError] as void Function(Object, [StackTrace?])?; final bool? cancelOnError = invocation.namedArguments[#cancelOnError] as bool?; return Stream<List<int>>.fromIterable(<List<int>>[transparentImage]).listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } when(response.listen(any, onError: anyNamed('onError'), onDone: anyNamed('onDone'), cancelOnError: anyNamed('cancelOnError'))) .thenAnswer(imageStream); return client; } // This string represents the hexidecial bytes of a transparent image. A // string is used to make the visual representation of the data compact. A // List<int> of the same data requires over 60 lines in a source file with // each element in the array on a single line. const String _imageBytesAsString = ''' 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, '''; // Convert the string representing the hexidecimal bytes in the image into // a list of integers that can be consumed as image data in a stream. final List<int> _transparentImage = const LineSplitter() .convert(_imageBytesAsString.replaceAllMapped( RegExp(r' *0x([A-F0-9]{2}),? *\n? *'), (Match m) => '${m[1]}\n')) .map<int>((String b) => int.parse(b, radix: 16)) .toList(); List<int> getTestImageData() { return _transparentImage; } /// Define the "fake" data types to be used in mock data type definitions. These /// fake data types are important in the definition of the return values of the /// properties and methods of the mock data types for null safety. // ignore: avoid_implementing_value_types class _FakeDuration extends Fake implements Duration {} class _FakeHttpClientRequest extends Fake implements HttpClientRequest {} class _FakeUri extends Fake implements Uri {} class _FakeHttpHeaders extends Fake implements HttpHeaders {} class _FakeHttpClientResponse extends Fake implements HttpClientResponse {} class _FakeSocket extends Fake implements Socket {} class _FakeStreamSubscription<T> extends Fake implements StreamSubscription<T> {} /// A class which mocks [HttpClient]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpClient extends Mock implements HttpClient { MockHttpClient() { throwOnMissingStub(this); } @override Duration get idleTimeout => super.noSuchMethod(Invocation.getter(#idleTimeout), returnValue: _FakeDuration()) as Duration; @override set idleTimeout(Duration? idleTimeout) => super.noSuchMethod(Invocation.setter(#idleTimeout, idleTimeout)); @override bool get autoUncompress => super.noSuchMethod(Invocation.getter(#autoUncompress), returnValue: false) as bool; @override set autoUncompress(bool? autoUncompress) => super.noSuchMethod(Invocation.setter(#autoUncompress, autoUncompress)); @override Future<HttpClientRequest> open( String? method, String? host, int? port, String? path) => super.noSuchMethod( Invocation.method(#open, <Object?>[method, host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> openUrl(String? method, Uri? url) => super.noSuchMethod(Invocation.method(#openUrl, <Object?>[method, url]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> get(String? host, int? port, String? path) => super.noSuchMethod(Invocation.method(#get, <Object?>[host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> getUrl(Uri? url) => super.noSuchMethod( Invocation.method(#getUrl, <Object?>[url]), returnValue: Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> post(String? host, int? port, String? path) => super.noSuchMethod(Invocation.method(#post, <Object?>[host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> postUrl(Uri? url) => super.noSuchMethod( Invocation.method(#postUrl, <Object?>[url]), returnValue: Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> put(String? host, int? port, String? path) => super.noSuchMethod(Invocation.method(#put, <Object?>[host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> putUrl(Uri? url) => super.noSuchMethod( Invocation.method(#putUrl, <Object?>[url]), returnValue: Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> delete(String? host, int? port, String? path) => super.noSuchMethod( Invocation.method(#delete, <Object?>[host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> deleteUrl(Uri? url) => super.noSuchMethod( Invocation.method(#deleteUrl, <Object?>[url]), returnValue: Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> patch(String? host, int? port, String? path) => super.noSuchMethod(Invocation.method(#patch, <Object?>[host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> patchUrl(Uri? url) => super.noSuchMethod( Invocation.method(#patchUrl, <Object?>[url]), returnValue: Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> head(String? host, int? port, String? path) => super.noSuchMethod(Invocation.method(#head, <Object?>[host, port, path]), returnValue: Future<_FakeHttpClientRequest>.value( _FakeHttpClientRequest())) as Future<HttpClientRequest>; @override Future<HttpClientRequest> headUrl(Uri? url) => super.noSuchMethod( Invocation.method(#headUrl, <Object?>[url]), returnValue: Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest())) as Future<HttpClientRequest>; @override void addCredentials( Uri? url, String? realm, HttpClientCredentials? credentials) => super.noSuchMethod(Invocation.method( #addCredentials, <Object?>[url, realm, credentials])); @override void addProxyCredentials(String? host, int? port, String? realm, HttpClientCredentials? credentials) => super.noSuchMethod(Invocation.method( #addProxyCredentials, <Object?>[host, port, realm, credentials])); @override void close({bool? force = false}) => super.noSuchMethod( Invocation.method(#close, <Object?>[], <Symbol, Object?>{#force: force})); } /// A class which mocks [HttpClientRequest]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpClientRequest extends Mock implements HttpClientRequest { MockHttpClientRequest() { throwOnMissingStub(this); } @override bool get persistentConnection => super.noSuchMethod(Invocation.getter(#persistentConnection), returnValue: false) as bool; @override set persistentConnection(bool? persistentConnection) => super.noSuchMethod( Invocation.setter(#persistentConnection, persistentConnection)); @override bool get followRedirects => super .noSuchMethod(Invocation.getter(#followRedirects), returnValue: false) as bool; @override set followRedirects(bool? followRedirects) => super.noSuchMethod(Invocation.setter(#followRedirects, followRedirects)); @override int get maxRedirects => super.noSuchMethod(Invocation.getter(#maxRedirects), returnValue: 0) as int; @override set maxRedirects(int? maxRedirects) => super.noSuchMethod(Invocation.setter(#maxRedirects, maxRedirects)); @override int get contentLength => super.noSuchMethod(Invocation.getter(#contentLength), returnValue: 0) as int; @override set contentLength(int? contentLength) => super.noSuchMethod(Invocation.setter(#contentLength, contentLength)); @override bool get bufferOutput => super.noSuchMethod(Invocation.getter(#bufferOutput), returnValue: false) as bool; @override set bufferOutput(bool? bufferOutput) => super.noSuchMethod(Invocation.setter(#bufferOutput, bufferOutput)); @override String get method => super.noSuchMethod(Invocation.getter(#method), returnValue: '') as String; @override Uri get uri => super.noSuchMethod(Invocation.getter(#uri), returnValue: _FakeUri()) as Uri; @override HttpHeaders get headers => super.noSuchMethod(Invocation.getter(#headers), returnValue: _FakeHttpHeaders()) as HttpHeaders; @override List<Cookie> get cookies => super.noSuchMethod(Invocation.getter(#cookies), returnValue: <Cookie>[]) as List<Cookie>; @override Future<HttpClientResponse> get done => super.noSuchMethod( Invocation.getter(#done), returnValue: Future<_FakeHttpClientResponse>.value(_FakeHttpClientResponse())) as Future<HttpClientResponse>; @override Future<HttpClientResponse> close() => super.noSuchMethod( Invocation.method(#close, <Object?>[]), returnValue: Future<_FakeHttpClientResponse>.value(_FakeHttpClientResponse())) as Future<HttpClientResponse>; } /// A class which mocks [HttpClientResponse]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpClientResponse extends Mock implements HttpClientResponse { MockHttpClientResponse() { throwOnMissingStub(this); } // Include an override method for the inherited listen method. This method // intercepts HttpClientResponse listen calls to return a mock image. @override StreamSubscription<List<int>> listen(void Function(List<int> event)? onData, {Function? onError, void Function()? onDone, bool? cancelOnError}) => super.noSuchMethod( Invocation.method( #listen, <Object?>[onData], <Symbol, Object?>{ #onError: onError, #onDone: onDone, #cancelOnError: cancelOnError }, ), returnValue: _FakeStreamSubscription<List<int>>()) as StreamSubscription<List<int>>; @override int get statusCode => super.noSuchMethod(Invocation.getter(#statusCode), returnValue: 0) as int; @override String get reasonPhrase => super.noSuchMethod(Invocation.getter(#reasonPhrase), returnValue: '') as String; @override int get contentLength => super.noSuchMethod(Invocation.getter(#contentLength), returnValue: 0) as int; @override HttpClientResponseCompressionState get compressionState => super.noSuchMethod(Invocation.getter(#compressionState), returnValue: HttpClientResponseCompressionState.notCompressed) as HttpClientResponseCompressionState; @override bool get persistentConnection => super.noSuchMethod(Invocation.getter(#persistentConnection), returnValue: false) as bool; @override bool get isRedirect => super.noSuchMethod(Invocation.getter(#isRedirect), returnValue: false) as bool; @override List<RedirectInfo> get redirects => super.noSuchMethod(Invocation.getter(#redirects), returnValue: <RedirectInfo>[]) as List<RedirectInfo>; @override HttpHeaders get headers => super.noSuchMethod(Invocation.getter(#headers), returnValue: _FakeHttpHeaders()) as HttpHeaders; @override List<Cookie> get cookies => super.noSuchMethod(Invocation.getter(#cookies), returnValue: <Cookie>[]) as List<Cookie>; @override Future<HttpClientResponse> redirect( [String? method, Uri? url, bool? followLoops]) => super.noSuchMethod( Invocation.method(#redirect, <Object?>[method, url, followLoops]), returnValue: Future<_FakeHttpClientResponse>.value( _FakeHttpClientResponse())) as Future<HttpClientResponse>; @override Future<Socket> detachSocket() => super.noSuchMethod( Invocation.method(#detachSocket, <Object?>[]), returnValue: Future<_FakeSocket>.value(_FakeSocket())) as Future<Socket>; } /// A class which mocks [HttpHeaders]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpHeaders extends Mock implements HttpHeaders { MockHttpHeaders() { throwOnMissingStub(this); } @override int get contentLength => super.noSuchMethod(Invocation.getter(#contentLength), returnValue: 0) as int; @override set contentLength(int? contentLength) => super.noSuchMethod(Invocation.setter(#contentLength, contentLength)); @override bool get persistentConnection => super.noSuchMethod(Invocation.getter(#persistentConnection), returnValue: false) as bool; @override set persistentConnection(bool? persistentConnection) => super.noSuchMethod( Invocation.setter(#persistentConnection, persistentConnection)); @override bool get chunkedTransferEncoding => super.noSuchMethod(Invocation.getter(#chunkedTransferEncoding), returnValue: false) as bool; @override set chunkedTransferEncoding(bool? chunkedTransferEncoding) => super.noSuchMethod( Invocation.setter(#chunkedTransferEncoding, chunkedTransferEncoding)); @override List<String>? operator [](String? name) => super.noSuchMethod(Invocation.method(#[], <Object?>[name])) as List<String>?; @override String? value(String? name) => super.noSuchMethod(Invocation.method(#value, <Object?>[name])) as String?; @override void add(String? name, Object? value, {bool? preserveHeaderCase = false}) => super.noSuchMethod(Invocation.method(#add, <Object?>[name, value], <Symbol, Object?>{#preserveHeaderCase: preserveHeaderCase})); @override void set(String? name, Object? value, {bool? preserveHeaderCase = false}) => super.noSuchMethod(Invocation.method(#set, <Object?>[name, value], <Symbol, Object?>{#preserveHeaderCase: preserveHeaderCase})); @override void remove(String? name, Object? value) => super.noSuchMethod(Invocation.method(#remove, <Object?>[name, value])); @override void removeAll(String? name) => super.noSuchMethod(Invocation.method(#removeAll, <Object?>[name])); @override void forEach(void Function(String, List<String>)? action) => super.noSuchMethod(Invocation.method(#forEach, <Object?>[action])); @override void noFolding(String? name) => super.noSuchMethod(Invocation.method(#noFolding, <Object?>[name])); }
packages/packages/flutter_markdown/test/image_test_mocks.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/image_test_mocks.dart", "repo_id": "packages", "token_count": 6533 }
992
name: flutter_migrate description: A tool to migrate legacy flutter projects to modern versions. version: 0.0.1+3 repository: https://github.com/flutter/packages/tree/main/packages/flutter_migrate issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ap%3A%20flutter_migrate publish_to: none environment: sdk: ^3.1.0 dependencies: args: ^2.3.1 convert: 3.0.2 file: 6.1.4 intl: 0.17.0 meta: 1.8.0 path: ^1.8.0 process: 4.2.4 vm_service: 9.3.0 yaml: 3.1.1 dev_dependencies: collection: 1.16.0 file_testing: 3.0.0 lints: ^2.0.0 test: ^1.16.0
packages/packages/flutter_migrate/pubspec.yaml/0
{ "file_path": "packages/packages/flutter_migrate/pubspec.yaml", "repo_id": "packages", "token_count": 270 }
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 'dart:async'; import 'package:flutter_migrate/src/base/context.dart'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:flutter_migrate/src/base/terminal.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'common.dart'; import 'fakes.dart'; /// Return the test logger. This assumes that the current Logger is a BufferLogger. BufferLogger get testLogger => context.get<Logger>()! as BufferLogger; @isTest void testUsingContext( String description, dynamic Function() testMethod, { Map<Type, Generator> overrides = const <Type, Generator>{}, bool initializeFlutterRoot = true, String? testOn, Timeout? timeout, bool? skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this }) { if (overrides[FileSystem] != null && overrides[ProcessManager] == null) { throw StateError( 'If you override the FileSystem context you must also provide a ProcessManager, ' 'otherwise the processes you launch will not be dealing with the same file system ' 'that you are dealing with in your test.'); } // Ensure we don't rely on the default [Config] constructor which will // leak a sticky $HOME/.flutter_settings behind! Directory? configDir; tearDown(() { if (configDir != null) { tryToDelete(configDir!); configDir = null; } }); test(description, () async { await runInContext<dynamic>(() { return context.run<dynamic>( name: 'mocks', overrides: <Type, Generator>{ AnsiTerminal: () => AnsiTerminal(stdio: FakeStdio()), OutputPreferences: () => OutputPreferences.test(), Logger: () => BufferLogger.test(), ProcessManager: () => const LocalProcessManager(), }, body: () { return runZonedGuarded<Future<dynamic>>(() { try { return context.run<dynamic>( // Apply the overrides to the test context in the zone since their // instantiation may reference items already stored on the context. overrides: overrides, name: 'test-specific overrides', body: () async { if (initializeFlutterRoot) { // Provide a sane default for the flutterRoot directory. Individual // tests can override this either in the test or during setup. // Cache.flutterRoot ??= flutterRoot; } return await testMethod(); }, ); // This catch rethrows, so doesn't need to catch only Exception. } catch (error) { // ignore: avoid_catches_without_on_clauses _printBufferedErrors(context); rethrow; } }, (Object error, StackTrace stackTrace) { // When things fail, it's ok to print to the console! print(error); // ignore: avoid_print print(stackTrace); // ignore: avoid_print _printBufferedErrors(context); throw error; //ignore: only_throw_errors }); }, ); }, overrides: <Type, Generator>{}); }, testOn: testOn, skip: skip, timeout: timeout); } void _printBufferedErrors(AppContext testContext) { if (testContext.get<Logger>() is BufferLogger) { final BufferLogger bufferLogger = testContext.get<Logger>()! as BufferLogger; if (bufferLogger.errorText.isNotEmpty) { // This is where the logger outputting errors is implemented, so it has // to use `print`. print(bufferLogger.errorText); // ignore: avoid_print } bufferLogger.clear(); } } Future<T> runInContext<T>( FutureOr<T> Function() runner, { Map<Type, Generator>? overrides, }) async { // Wrap runner with any asynchronous initialization that should run with the // overrides and callbacks. // late bool runningOnBot; FutureOr<T> runnerWrapper() async { return runner(); } return context.run<T>( name: 'global fallbacks', body: runnerWrapper, overrides: overrides, fallbacks: <Type, Generator>{}); }
packages/packages/flutter_migrate/test/src/context.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/src/context.dart", "repo_id": "packages", "token_count": 1748 }
994
# Flutter Android Lifecycle Plugin [![pub package](https://img.shields.io/pub/v/flutter_plugin_android_lifecycle.svg)](https://pub.dev/packages/flutter_plugin_android_lifecycle) A Flutter plugin for Android to allow other Flutter plugins to access Android `Lifecycle` objects in the plugin's binding. The purpose of having this plugin instead of exposing an Android `Lifecycle` object in the engine's Android embedding plugins API is to force plugins to have a pub constraint that signifies the major version of the Android `Lifecycle` API they expect. | | Android | |-------------|---------| | **Support** | SDK 16+ | ## Installation Add `flutter_plugin_android_lifecycle` as a [dependency in your pubspec.yaml file](https://flutter.dev/using-packages/). ## Example Use a `FlutterLifecycleAdapter` within another Flutter plugin's Android implementation, as shown below: ```java import androidx.lifecycle.Lifecycle; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter; public class MyPlugin implements FlutterPlugin, ActivityAware { @Override public void onAttachedToActivity(ActivityPluginBinding binding) { Lifecycle lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding); // Use lifecycle as desired. } //... } ``` [Feedback welcome](https://github.com/flutter/flutter/issues) and [Pull Requests](https://github.com/flutter/packages/pulls) are most welcome!
packages/packages/flutter_plugin_android_lifecycle/README.md/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/README.md", "repo_id": "packages", "token_count": 504 }
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. import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); /// MyApp is the Main Application. class MyApp extends StatelessWidget { /// Default Constructor const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Sample flutter_plugin_android_lifecycle usage'), ), body: const Center( child: Text( 'This plugin only provides Android Lifecycle API\n for other Android plugins.')), ), ); } }
packages/packages/flutter_plugin_android_lifecycle/example/lib/main.dart/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/example/lib/main.dart", "repo_id": "packages", "token_count": 268 }
996
# This custom rule set only exists to allow very targeted changes # relative to the default repo settings, for specific use cases. # Please do NOT add more changes here without consulting with # #hackers-ecosystem on Discord. include: ../../analysis_options.yaml analyzer: exclude: # This directory deliberately has errors, to test `fix`. - "test_fixes/**"
packages/packages/go_router/analysis_options.yaml/0
{ "file_path": "packages/packages/go_router/analysis_options.yaml", "repo_id": "packages", "token_count": 100 }
997
# Example Catalog ## [Get started](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/main.dart) `flutter run lib/main.dart` An example to demonstrate a simple two-page app. ## [Sub-routes](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/sub_routes.dart) `flutter run lib/sub_routes.dart` An example to demonstrate an app with multi-level routing. ## [Query parameters and path parameters](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/path_and_query_parameters.dart) `flutter run lib/path_and_query_parameters.dart` An example to demonstrate how to use path parameters and query parameters. ## [Named routes](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/named_routes.dart) `flutter run lib/named_routes.dart` An example to demonstrate how to navigate using named locations instead of URLs. ## [Redirection](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/redirection.dart) `flutter run lib/redirection.dart` An example to demonstrate how to use redirect to handle a synchronous sign-in flow. ## [Asynchronous Redirection](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/async_redirection.dart) `flutter run lib/async_redirection.dart` An example to demonstrate how to use handle a sign-in flow with a stream authentication service. ## [Stateful Nested Navigation](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stateful_shell_route.dart) `flutter run lib/stacked_shell_route.dart` An example to demonstrate how to use a `StatefulShellRoute` to create stateful nested navigation, with a `BottomNavigationBar`. ## [Exception Handling](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/exception_handling.dart) `flutter run lib/exception_handling.dart` An example to demonstrate how to handle exception in go_router. ## [Extra Codec](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/extra_codec.dart) `flutter run lib/extra_codec.dart` An example to demonstrate how to use a complex object as extra. ## [Books app](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/books) `flutter run lib/books/main.dart` A fully fledged example that showcases various go_router APIs.
packages/packages/go_router/example/README.md/0
{ "file_path": "packages/packages/go_router/example/README.md", "repo_id": "packages", "token_count": 766 }
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. import 'author.dart'; /// Book data class. class Book { /// Creates a book data object. Book({ required this.id, required this.title, required this.isPopular, required this.isNew, required this.author, }); /// The id of the book. final int id; /// The title of the book. final String title; /// The author of the book. final Author author; /// Whether the book is popular. final bool isPopular; /// Whether the book is new. final bool isNew; }
packages/packages/go_router/example/lib/books/src/data/book.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/data/book.dart", "repo_id": "packages", "token_count": 206 }
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 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> _tabANavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'tabANav'); // This example demonstrates how to setup nested navigation using a // BottomNavigationBar, where each bar item uses its own persistent navigator, // i.e. navigation state is maintained separately for each item. This setup also // enables deep linking into nested pages. // // This example also demonstrates how build a nested shell with a custom // container for the branch Navigators (in this case a TabBarView). void main() { runApp(NestedTabNavigationExampleApp()); } /// An example demonstrating how to use nested navigators class NestedTabNavigationExampleApp extends StatelessWidget { /// Creates a NestedTabNavigationExampleApp NestedTabNavigationExampleApp({super.key}); final GoRouter _router = GoRouter( navigatorKey: _rootNavigatorKey, initialLocation: '/a', routes: <RouteBase>[ StatefulShellRoute( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { // This nested StatefulShellRoute demonstrates the use of a // custom container for the branch Navigators. In this implementation, // no customization is done in the builder function (navigationShell // itself is simply used as the Widget for the route). Instead, the // navigatorContainerBuilder function below is provided to // customize the container for the branch Navigators. return navigationShell; }, navigatorContainerBuilder: (BuildContext context, StatefulNavigationShell navigationShell, List<Widget> children) { // Returning a customized container for the branch // Navigators (i.e. the `List<Widget> children` argument). // // See ScaffoldWithNavBar for more details on how the children // are managed (using AnimatedBranchContainer). return ScaffoldWithNavBar( navigationShell: navigationShell, children: children); }, branches: <StatefulShellBranch>[ // The route branch for the first tab of the bottom navigation bar. StatefulShellBranch( navigatorKey: _tabANavigatorKey, routes: <RouteBase>[ GoRoute( // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', builder: (BuildContext context, GoRouterState state) => const RootScreenA(), 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', builder: (BuildContext context, GoRouterState state) => const DetailsScreen(label: 'A'), ), ], ), ], ), // The route branch for the third tab of the bottom navigation bar. StatefulShellBranch( // StatefulShellBranch will automatically use the first descendant // GoRoute as the initial location of the branch. If another route // is desired, specify the location of it using the defaultLocation // parameter. // defaultLocation: '/c2', routes: <RouteBase>[ StatefulShellRoute( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { // Just like with the top level StatefulShellRoute, no // customization is done in the builder function. return navigationShell; }, navigatorContainerBuilder: (BuildContext context, StatefulNavigationShell navigationShell, List<Widget> children) { // Returning a customized container for the branch // Navigators (i.e. the `List<Widget> children` argument). // // See TabbedRootScreen for more details on how the children // are managed (in a TabBarView). return TabbedRootScreen( navigationShell: navigationShell, children: children); }, // This bottom tab uses a nested shell, wrapping sub routes in a // top TabBar. branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b1', builder: (BuildContext context, GoRouterState state) => const TabScreen( label: 'B1', detailsPath: '/b1/details'), routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => const DetailsScreen( label: 'B1', withScaffold: false, ), ), ], ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b2', builder: (BuildContext context, GoRouterState state) => const TabScreen( label: 'B2', detailsPath: '/b2/details'), routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => const DetailsScreen( label: 'B2', withScaffold: false, ), ), ], ), ]), ], ), ], ), ], ), ], ); @override Widget build(BuildContext context) { return MaterialApp.router( 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, required this.children, Key? key, }) : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; /// The children (branch Navigators) to display in a custom container /// ([AnimatedBranchContainer]). final List<Widget> children; @override Widget build(BuildContext context) { return Scaffold( body: AnimatedBranchContainer( currentIndex: navigationShell.currentIndex, children: children, ), bottomNavigationBar: BottomNavigationBar( // Here, the items of BottomNavigationBar are hard coded. In a real // world scenario, the items would most likely be generated from the // branches of the shell route, which can be fetched using // `navigationShell.route.branches`. items: const <BottomNavigationBarItem>[ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Section A'), BottomNavigationBarItem(icon: Icon(Icons.work), label: 'Section B'), ], currentIndex: navigationShell.currentIndex, onTap: (int index) => _onTap(context, index), ), ); } /// Navigate to the current location of the branch at the provided index when /// tapping an item in the BottomNavigationBar. void _onTap(BuildContext context, int index) { // When navigating to a new branch, it's recommended to use the goBranch // method, as doing so makes sure the last navigation state of the // Navigator for the branch is restored. navigationShell.goBranch( index, // A common pattern when using bottom navigation bars is to support // navigating to the initial location when tapping the item that is // already active. This example demonstrates how to support this behavior, // using the initialLocation parameter of goBranch. initialLocation: index == navigationShell.currentIndex, ); } } /// Custom branch Navigator container that provides animated transitions /// when switching branches. class AnimatedBranchContainer extends StatelessWidget { /// Creates a AnimatedBranchContainer const AnimatedBranchContainer( {super.key, required this.currentIndex, required this.children}); /// The index (in [children]) of the branch Navigator to display. final int currentIndex; /// The children (branch Navigators) to display in this container. final List<Widget> children; @override Widget build(BuildContext context) { return Stack( children: children.mapIndexed( (int index, Widget navigator) { return AnimatedScale( scale: index == currentIndex ? 1 : 1.5, duration: const Duration(milliseconds: 400), child: AnimatedOpacity( opacity: index == currentIndex ? 1 : 0, duration: const Duration(milliseconds: 400), child: _branchNavigatorWrapper(index, navigator), ), ); }, ).toList()); } Widget _branchNavigatorWrapper(int index, Widget navigator) => IgnorePointer( ignoring: index != currentIndex, child: TickerMode( enabled: index == currentIndex, child: navigator, ), ); } /// Widget for the root page for the first section of the bottom navigation bar. class RootScreenA extends StatelessWidget { /// Creates a RootScreenA const RootScreenA({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Root of section A'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('Screen A', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { GoRouter.of(context).go('/a/details'); }, 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, this.param, this.withScaffold = true, super.key, }); /// The label to display in the center of the screen. final String label; /// Optional param final String? param; /// Wrap in scaffold final bool withScaffold; @override State<StatefulWidget> createState() => DetailsScreenState(); } /// The state for DetailsScreen class DetailsScreenState extends State<DetailsScreen> { int _counter = 0; @override Widget build(BuildContext context) { if (widget.withScaffold) { return Scaffold( appBar: AppBar( title: Text('Details Screen - ${widget.label}'), ), body: _build(context), ); } else { return ColoredBox( color: Theme.of(context).scaffoldBackgroundColor, child: _build(context), ); } } Widget _build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('Details for ${widget.label} - Counter: $_counter', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { setState(() { _counter++; }); }, child: const Text('Increment counter'), ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) Text('Parameter: ${widget.param!}', style: Theme.of(context).textTheme.titleMedium), const Padding(padding: EdgeInsets.all(8)), if (!widget.withScaffold) ...<Widget>[ const Padding(padding: EdgeInsets.all(16)), TextButton( onPressed: () { GoRouter.of(context).pop(); }, child: const Text('< Back', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)), ), ] ], ), ); } } /// Builds a nested shell using a [TabBar] and [TabBarView]. class TabbedRootScreen extends StatefulWidget { /// Constructs a TabbedRootScreen const TabbedRootScreen( {required this.navigationShell, required this.children, super.key}); /// The current state of the parent StatefulShellRoute. final StatefulNavigationShell navigationShell; /// The children (branch Navigators) to display in the [TabBarView]. final List<Widget> children; @override State<StatefulWidget> createState() => _TabbedRootScreenState(); } class _TabbedRootScreenState extends State<TabbedRootScreen> with SingleTickerProviderStateMixin { late final TabController _tabController = TabController( length: widget.children.length, vsync: this, initialIndex: widget.navigationShell.currentIndex); @override void didUpdateWidget(covariant TabbedRootScreen oldWidget) { super.didUpdateWidget(oldWidget); _tabController.index = widget.navigationShell.currentIndex; } @override Widget build(BuildContext context) { final List<Tab> tabs = widget.children .mapIndexed((int i, _) => Tab(text: 'Tab ${i + 1}')) .toList(); return Scaffold( appBar: AppBar( title: const Text('Root of Section B (nested TabBar shell)'), bottom: TabBar( controller: _tabController, tabs: tabs, onTap: (int tappedIndex) => _onTabTap(context, tappedIndex), )), body: TabBarView( controller: _tabController, children: widget.children, ), ); } void _onTabTap(BuildContext context, int index) { widget.navigationShell.goBranch(index); } } /// Widget for the pages in the top tab bar. class TabScreen extends StatelessWidget { /// Creates a RootScreen const TabScreen({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 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'), ), ], ), ); } }
packages/packages/go_router/example/lib/others/custom_stateful_shell_route.dart/0
{ "file_path": "packages/packages/go_router/example/lib/others/custom_stateful_shell_route.dart", "repo_id": "packages", "token_count": 6826 }
1,000
// 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'; final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> _sectionANavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'sectionANav'); // This example demonstrates how to setup nested navigation using a // BottomNavigationBar, where each bar item uses its own persistent navigator, // i.e. navigation state is maintained separately for each item. This setup also // enables deep linking into nested pages. void main() { runApp(NestedTabNavigationExampleApp()); } /// An example demonstrating how to use nested navigators class NestedTabNavigationExampleApp extends StatelessWidget { /// Creates a NestedTabNavigationExampleApp NestedTabNavigationExampleApp({super.key}); final GoRouter _router = GoRouter( navigatorKey: _rootNavigatorKey, initialLocation: '/a', routes: <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { // Return the widget that implements the custom shell (in this case // using a BottomNavigationBar). The StatefulNavigationShell is passed // to be able access the state of the shell and to navigate to other // branches in a stateful way. return ScaffoldWithNavBar(navigationShell: navigationShell); }, branches: <StatefulShellBranch>[ // The route branch for the first tab of the bottom navigation bar. StatefulShellBranch( navigatorKey: _sectionANavigatorKey, routes: <RouteBase>[ GoRoute( // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', builder: (BuildContext context, GoRouterState state) => const RootScreen(label: 'A', detailsPath: '/a/details'), 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', builder: (BuildContext context, GoRouterState state) => const DetailsScreen(label: 'A'), ), ], ), ], ), // The route branch for the second tab of the bottom navigation bar. StatefulShellBranch( // It's not necessary to provide a navigatorKey if it isn't also // needed elsewhere. If not provided, a default key will be used. routes: <RouteBase>[ GoRoute( // The screen to display as the root in the second tab of the // bottom navigation bar. path: '/b', builder: (BuildContext context, GoRouterState state) => const RootScreen( label: 'B', detailsPath: '/b/details/1', secondDetailsPath: '/b/details/2', ), routes: <RouteBase>[ GoRoute( path: 'details/:param', builder: (BuildContext context, GoRouterState state) => DetailsScreen( label: 'B', param: state.pathParameters['param'], ), ), ], ), ], ), // The route branch for the third tab of the bottom navigation bar. StatefulShellBranch( routes: <RouteBase>[ GoRoute( // The screen to display as the root in the third tab of the // bottom navigation bar. path: '/c', builder: (BuildContext context, GoRouterState state) => const RootScreen( label: 'C', detailsPath: '/c/details', ), routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => DetailsScreen( label: 'C', extra: state.extra, ), ), ], ), ], ), ], ), ], ); @override Widget build(BuildContext context) { return MaterialApp.router( 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( // Here, the items of BottomNavigationBar are hard coded. In a real // world scenario, the items would most likely be generated from the // branches of the shell route, which can be fetched using // `navigationShell.route.branches`. items: const <BottomNavigationBarItem>[ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Section A'), BottomNavigationBarItem(icon: Icon(Icons.work), label: 'Section B'), BottomNavigationBarItem(icon: Icon(Icons.tab), label: 'Section C'), ], currentIndex: navigationShell.currentIndex, onTap: (int index) => _onTap(context, index), ), ); } /// Navigate to the current location of the branch at the provided index when /// tapping an item in the BottomNavigationBar. void _onTap(BuildContext context, int index) { // When navigating to a new branch, it's recommended to use the goBranch // method, as doing so makes sure the last navigation state of the // Navigator for the branch is restored. navigationShell.goBranch( index, // A common pattern when using bottom navigation bars is to support // navigating to the initial location when tapping the item that is // already active. This example demonstrates how to support this behavior, // using the initialLocation parameter of goBranch. initialLocation: index == navigationShell.currentIndex, ); } } /// 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, this.secondDetailsPath, super.key, }); /// The label final String label; /// The path to the detail page final String detailsPath; /// The path to another detail page final String? secondDetailsPath; @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, extra: '$label-XYZ'); }, child: const Text('View details'), ), const Padding(padding: EdgeInsets.all(4)), if (secondDetailsPath != null) TextButton( onPressed: () { GoRouter.of(context).go(secondDetailsPath!); }, child: const Text('View more details'), ), ], ), ), ); } } /// The details screen for either the A or B screen. class DetailsScreen extends StatefulWidget { /// Constructs a [DetailsScreen]. const DetailsScreen({ required this.label, this.param, this.extra, this.withScaffold = true, super.key, }); /// The label to display in the center of the screen. final String label; /// Optional param final String? param; /// Optional extra object final Object? extra; /// Wrap in scaffold final bool withScaffold; @override State<StatefulWidget> createState() => DetailsScreenState(); } /// The state for DetailsScreen class DetailsScreenState extends State<DetailsScreen> { int _counter = 0; @override Widget build(BuildContext context) { if (widget.withScaffold) { return Scaffold( appBar: AppBar( title: Text('Details Screen - ${widget.label}'), ), body: _build(context), ); } else { return ColoredBox( color: Theme.of(context).scaffoldBackgroundColor, child: _build(context), ); } } Widget _build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('Details for ${widget.label} - Counter: $_counter', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { setState(() { _counter++; }); }, child: const Text('Increment counter'), ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) Text('Parameter: ${widget.param!}', style: Theme.of(context).textTheme.titleMedium), const Padding(padding: EdgeInsets.all(8)), if (widget.extra != null) Text('Extra: ${widget.extra!}', style: Theme.of(context).textTheme.titleMedium), if (!widget.withScaffold) ...<Widget>[ const Padding(padding: EdgeInsets.all(16)), TextButton( onPressed: () { GoRouter.of(context).pop(); }, child: const Text('< Back', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)), ), ] ], ), ); } }
packages/packages/go_router/example/lib/stateful_shell_route.dart/0
{ "file_path": "packages/packages/go_router/example/lib/stateful_shell_route.dart", "repo_id": "packages", "token_count": 4764 }
1,001
// 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:go_router_examples/main.dart' as example; void main() { testWidgets('example works', (WidgetTester tester) async { await tester.pumpWidget(const example.MyApp()); expect(find.text('Go to the Details screen'), findsOneWidget); await tester.tap(find.text('Go to the Details screen')); await tester.pumpAndSettle(); expect(find.text('Go back to the Home screen'), findsOneWidget); await tester.tap(find.text('Go back to the Home screen')); await tester.pumpAndSettle(); expect(find.text('Go to the Details screen'), findsOneWidget); }); }
packages/packages/go_router/example/test/main_test.dart/0
{ "file_path": "packages/packages/go_router/example/test/main_test.dart", "repo_id": "packages", "token_count": 261 }
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 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'logging.dart'; import 'match.dart'; import 'misc/errors.dart'; import 'path_utils.dart'; import 'route.dart'; import 'router.dart'; import 'state.dart'; /// The signature of the redirect callback. typedef GoRouterRedirect = FutureOr<String?> Function( BuildContext context, GoRouterState state); /// The route configuration for GoRouter configured by the app. class RouteConfiguration { /// Constructs a [RouteConfiguration]. RouteConfiguration( this._routingConfig, { required this.navigatorKey, this.extraCodec, }) { _onRoutingTableChanged(); _routingConfig.addListener(_onRoutingTableChanged); } static bool _debugCheckPath(List<RouteBase> routes, bool isTopLevel) { for (final RouteBase route in routes) { late bool subRouteIsTopLevel; if (route is GoRoute) { if (isTopLevel) { assert(route.path.startsWith('/'), 'top-level path must start with "/": $route'); } else { assert(!route.path.startsWith('/') && !route.path.endsWith('/'), 'sub-route path may not start or end with "/": $route'); } subRouteIsTopLevel = false; } else if (route is ShellRouteBase) { subRouteIsTopLevel = isTopLevel; } _debugCheckPath(route.routes, subRouteIsTopLevel); } return true; } // Check that each parentNavigatorKey refers to either a ShellRoute's // navigatorKey or the root navigator key. static bool _debugCheckParentNavigatorKeys( List<RouteBase> routes, List<GlobalKey<NavigatorState>> allowedKeys) { for (final RouteBase route in routes) { if (route is GoRoute) { final GlobalKey<NavigatorState>? parentKey = route.parentNavigatorKey; if (parentKey != null) { // Verify that the root navigator or a ShellRoute ancestor has a // matching navigator key. assert( allowedKeys.contains(parentKey), 'parentNavigatorKey $parentKey must refer to' " an ancestor ShellRoute's navigatorKey or GoRouter's" ' navigatorKey'); _debugCheckParentNavigatorKeys( route.routes, <GlobalKey<NavigatorState>>[ // Once a parentNavigatorKey is used, only that navigator key // or keys above it can be used. ...allowedKeys.sublist(0, allowedKeys.indexOf(parentKey) + 1), ], ); } else { _debugCheckParentNavigatorKeys( route.routes, <GlobalKey<NavigatorState>>[ ...allowedKeys, ], ); } } else if (route is ShellRoute) { _debugCheckParentNavigatorKeys( route.routes, <GlobalKey<NavigatorState>>[...allowedKeys..add(route.navigatorKey)], ); } else if (route is StatefulShellRoute) { for (final StatefulShellBranch branch in route.branches) { assert( !allowedKeys.contains(branch.navigatorKey), 'StatefulShellBranch must not reuse an ancestor navigatorKey ' '(${branch.navigatorKey})'); _debugCheckParentNavigatorKeys( branch.routes, <GlobalKey<NavigatorState>>[ ...allowedKeys, branch.navigatorKey, ], ); } } } return true; } static bool _debugVerifyNoDuplicatePathParameter( List<RouteBase> routes, Map<String, GoRoute> usedPathParams) { for (final RouteBase route in routes) { if (route is! GoRoute) { continue; } for (final String pathParam in route.pathParameters) { if (usedPathParams.containsKey(pathParam)) { final bool sameRoute = usedPathParams[pathParam] == route; throw GoError( "duplicate path parameter, '$pathParam' found in ${sameRoute ? '$route' : '${usedPathParams[pathParam]}, and $route'}"); } usedPathParams[pathParam] = route; } _debugVerifyNoDuplicatePathParameter(route.routes, usedPathParams); route.pathParameters.forEach(usedPathParams.remove); } return true; } // Check to see that the configured initialLocation of StatefulShellBranches // points to a descendant route of the route branch. bool _debugCheckStatefulShellBranchDefaultLocations(List<RouteBase> routes) { for (final RouteBase route in routes) { if (route is StatefulShellRoute) { for (final StatefulShellBranch branch in route.branches) { if (branch.initialLocation == null) { // Recursively search for the first GoRoute descendant. Will // throw assertion error if not found. final GoRoute? route = branch.defaultRoute; final String? initialLocation = route != null ? locationForRoute(route) : null; assert( initialLocation != null, 'The default location of a StatefulShellBranch must be ' 'derivable from GoRoute descendant'); assert( route!.pathParameters.isEmpty, 'The default location of a StatefulShellBranch cannot be ' 'a parameterized route'); } else { final RouteMatchList matchList = findMatch(branch.initialLocation!); assert( !matchList.isError, 'initialLocation (${matchList.uri}) of StatefulShellBranch must ' 'be a valid location'); final List<RouteBase> matchRoutes = matchList.routes; final int shellIndex = matchRoutes.indexOf(route); bool matchFound = false; if (shellIndex >= 0 && (shellIndex + 1) < matchRoutes.length) { final RouteBase branchRoot = matchRoutes[shellIndex + 1]; matchFound = branch.routes.contains(branchRoot); } assert( matchFound, 'The initialLocation (${branch.initialLocation}) of ' 'StatefulShellBranch must match a descendant route of the ' 'branch'); } } } _debugCheckStatefulShellBranchDefaultLocations(route.routes); } return true; } /// The match used when there is an error during parsing. static RouteMatchList _errorRouteMatchList( Uri uri, GoException exception, { Object? extra, }) { return RouteMatchList( matches: const <RouteMatch>[], extra: extra, error: exception, uri: uri, pathParameters: const <String, String>{}, ); } void _onRoutingTableChanged() { final RoutingConfig routingTable = _routingConfig.value; assert(_debugCheckPath(routingTable.routes, true)); assert(_debugVerifyNoDuplicatePathParameter( routingTable.routes, <String, GoRoute>{})); assert(_debugCheckParentNavigatorKeys( routingTable.routes, <GlobalKey<NavigatorState>>[navigatorKey])); assert(_debugCheckStatefulShellBranchDefaultLocations(routingTable.routes)); _nameToPath.clear(); _cacheNameToPath('', routingTable.routes); log(debugKnownRoutes()); } /// Builds a [GoRouterState] suitable for top level callback such as /// `GoRouter.redirect` or `GoRouter.onException`. GoRouterState buildTopLevelGoRouterState(RouteMatchList matchList) { return GoRouterState( this, uri: matchList.uri, // No name available at the top level trim the query params off the // sub-location to match route.redirect fullPath: matchList.fullPath, pathParameters: matchList.pathParameters, matchedLocation: matchList.uri.path, extra: matchList.extra, pageKey: const ValueKey<String>('topLevel'), topRoute: matchList.lastOrNull?.route, ); } /// The routing table. final ValueListenable<RoutingConfig> _routingConfig; /// The list of top level routes used by [GoRouterDelegate]. List<RouteBase> get routes => _routingConfig.value.routes; /// Top level page redirect. GoRouterRedirect get topRedirect => _routingConfig.value.redirect; /// The limit for the number of consecutive redirects. int get redirectLimit => _routingConfig.value.redirectLimit; /// The global key for top level navigator. final GlobalKey<NavigatorState> navigatorKey; /// The codec used to encode and decode extra into a serializable format. /// /// When navigating using [GoRouter.go] or [GoRouter.push], one can provide /// an `extra` parameter along with it. If the extra contains complex data, /// consider provide a codec for serializing and deserializing the extra data. /// /// See also: /// * [Navigation](https://pub.dev/documentation/go_router/latest/topics/Navigation-topic.html) /// topic. /// * [extra_codec](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/extra_codec.dart) /// example. final Codec<Object?, Object?>? extraCodec; final Map<String, String> _nameToPath = <String, String>{}; /// Looks up the url location by a [GoRoute]'s name. String namedLocation( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, }) { assert(() { log('getting location for name: ' '"$name"' '${pathParameters.isEmpty ? '' : ', pathParameters: $pathParameters'}' '${queryParameters.isEmpty ? '' : ', queryParameters: $queryParameters'}'); return true; }()); assert(_nameToPath.containsKey(name), 'unknown route name: $name'); final String path = _nameToPath[name]!; assert(() { // Check that all required params are present final List<String> paramNames = <String>[]; patternToRegExp(path, paramNames); for (final String paramName in paramNames) { assert(pathParameters.containsKey(paramName), 'missing param "$paramName" for $path'); } // Check that there are no extra params for (final String key in pathParameters.keys) { assert(paramNames.contains(key), 'unknown param "$key" for $path'); } return true; }()); final Map<String, String> encodedParams = <String, String>{ for (final MapEntry<String, String> param in pathParameters.entries) param.key: Uri.encodeComponent(param.value) }; final String location = patternToPath(path, encodedParams); return Uri( path: location, queryParameters: queryParameters.isEmpty ? null : queryParameters) .toString(); } /// Finds the routes that matched the given URL. RouteMatchList findMatch(String location, {Object? extra}) { final Uri uri = Uri.parse(canonicalUri(location)); final Map<String, String> pathParameters = <String, String>{}; final List<RouteMatchBase> matches = _getLocRouteMatches(uri, pathParameters); if (matches.isEmpty) { return _errorRouteMatchList( uri, GoException('no routes for location: $uri'), extra: extra, ); } return RouteMatchList( matches: matches, uri: uri, pathParameters: pathParameters, extra: extra); } /// Reparse the input RouteMatchList RouteMatchList reparse(RouteMatchList matchList) { RouteMatchList result = findMatch(matchList.uri.toString(), extra: matchList.extra); for (final ImperativeRouteMatch imperativeMatch in matchList.matches.whereType<ImperativeRouteMatch>()) { final ImperativeRouteMatch match = ImperativeRouteMatch( pageKey: imperativeMatch.pageKey, matches: findMatch(imperativeMatch.matches.uri.toString(), extra: imperativeMatch.matches.extra), completer: imperativeMatch.completer); result = result.push(match); } return result; } List<RouteMatchBase> _getLocRouteMatches( Uri uri, Map<String, String> pathParameters) { for (final RouteBase route in _routingConfig.value.routes) { final List<RouteMatchBase> result = RouteMatchBase.match( rootNavigatorKey: navigatorKey, route: route, uri: uri, pathParameters: pathParameters, ); if (result.isNotEmpty) { return result; } } return const <RouteMatchBase>[]; } /// Processes redirects by returning a new [RouteMatchList] representing the new /// location. FutureOr<RouteMatchList> redirect( BuildContext context, FutureOr<RouteMatchList> prevMatchListFuture, {required List<RouteMatchList> redirectHistory}) { FutureOr<RouteMatchList> processRedirect(RouteMatchList prevMatchList) { final String prevLocation = prevMatchList.uri.toString(); FutureOr<RouteMatchList> processTopLevelRedirect( String? topRedirectLocation) { if (topRedirectLocation != null && topRedirectLocation != prevLocation) { final RouteMatchList newMatch = _getNewMatches( topRedirectLocation, prevMatchList.uri, redirectHistory, ); if (newMatch.isError) { return newMatch; } return redirect( context, newMatch, redirectHistory: redirectHistory, ); } FutureOr<RouteMatchList> processRouteLevelRedirect( String? routeRedirectLocation) { if (routeRedirectLocation != null && routeRedirectLocation != prevLocation) { final RouteMatchList newMatch = _getNewMatches( routeRedirectLocation, prevMatchList.uri, redirectHistory, ); if (newMatch.isError) { return newMatch; } return redirect( context, newMatch, redirectHistory: redirectHistory, ); } return prevMatchList; } final List<RouteMatch> routeMatches = <RouteMatch>[]; prevMatchList.visitRouteMatches((RouteMatchBase match) { if (match is RouteMatch) { routeMatches.add(match); } return true; }); final FutureOr<String?> routeLevelRedirectResult = _getRouteLevelRedirect(context, prevMatchList, routeMatches, 0); if (routeLevelRedirectResult is String?) { return processRouteLevelRedirect(routeLevelRedirectResult); } return routeLevelRedirectResult .then<RouteMatchList>(processRouteLevelRedirect); } redirectHistory.add(prevMatchList); // Check for top-level redirect final FutureOr<String?> topRedirectResult = _routingConfig.value.redirect( context, buildTopLevelGoRouterState(prevMatchList), ); if (topRedirectResult is String?) { return processTopLevelRedirect(topRedirectResult); } return topRedirectResult.then<RouteMatchList>(processTopLevelRedirect); } if (prevMatchListFuture is RouteMatchList) { return processRedirect(prevMatchListFuture); } return prevMatchListFuture.then<RouteMatchList>(processRedirect); } FutureOr<String?> _getRouteLevelRedirect( BuildContext context, RouteMatchList matchList, List<RouteMatch> routeMatches, int currentCheckIndex, ) { if (currentCheckIndex >= routeMatches.length) { return null; } final RouteMatch match = routeMatches[currentCheckIndex]; FutureOr<String?> processRouteRedirect(String? newLocation) => newLocation ?? _getRouteLevelRedirect( context, matchList, routeMatches, currentCheckIndex + 1); final GoRoute route = match.route; FutureOr<String?> routeRedirectResult; if (route.redirect != null) { routeRedirectResult = route.redirect!( context, match.buildState(this, matchList), ); } if (routeRedirectResult is String?) { return processRouteRedirect(routeRedirectResult); } return routeRedirectResult.then<String?>(processRouteRedirect); } RouteMatchList _getNewMatches( String newLocation, Uri previousLocation, List<RouteMatchList> redirectHistory, ) { try { final RouteMatchList newMatch = findMatch(newLocation); _addRedirect(redirectHistory, newMatch, previousLocation); return newMatch; } on GoException catch (e) { log('Redirection exception: ${e.message}'); return _errorRouteMatchList(previousLocation, e); } } /// Adds the redirect to [redirects] if it is valid. /// /// Throws if a loop is detected or the redirection limit is reached. void _addRedirect( List<RouteMatchList> redirects, RouteMatchList newMatch, Uri prevLocation, ) { if (redirects.contains(newMatch)) { throw GoException( 'redirect loop detected ${_formatRedirectionHistory(<RouteMatchList>[ ...redirects, newMatch ])}'); } if (redirects.length > _routingConfig.value.redirectLimit) { throw GoException( 'too many redirects ${_formatRedirectionHistory(<RouteMatchList>[ ...redirects, newMatch ])}'); } redirects.add(newMatch); log('redirecting to $newMatch'); } String _formatRedirectionHistory(List<RouteMatchList> redirections) { return redirections .map<String>( (RouteMatchList routeMatches) => routeMatches.uri.toString()) .join(' => '); } /// Get the location for the provided route. /// /// Builds the absolute path for the route, by concatenating the paths of the /// route and all its ancestors. String? locationForRoute(RouteBase route) => fullPathForRoute(route, '', _routingConfig.value.routes); @override String toString() { return 'RouterConfiguration: ${_routingConfig.value.routes}'; } /// Returns the full path of [routes]. /// /// Each path is indented based depth of the hierarchy, and its `name` /// is also appended if not null @visibleForTesting String debugKnownRoutes() { final StringBuffer sb = StringBuffer(); sb.writeln('Full paths for routes:'); _debugFullPathsFor(_routingConfig.value.routes, '', 0, sb); if (_nameToPath.isNotEmpty) { sb.writeln('known full paths for route names:'); for (final MapEntry<String, String> e in _nameToPath.entries) { sb.writeln(' ${e.key} => ${e.value}'); } } return sb.toString(); } void _debugFullPathsFor(List<RouteBase> routes, String parentFullpath, int depth, StringBuffer sb) { for (final RouteBase route in routes) { if (route is GoRoute) { final String fullPath = concatenatePaths(parentFullpath, route.path); sb.writeln(' => ${''.padLeft(depth * 2)}$fullPath'); _debugFullPathsFor(route.routes, fullPath, depth + 1, sb); } else if (route is ShellRouteBase) { _debugFullPathsFor(route.routes, parentFullpath, depth, sb); } } } void _cacheNameToPath(String parentFullPath, List<RouteBase> childRoutes) { for (final RouteBase route in childRoutes) { if (route is GoRoute) { final String fullPath = concatenatePaths(parentFullPath, route.path); if (route.name != null) { final String name = route.name!; assert( !_nameToPath.containsKey(name), 'duplication fullpaths for name ' '"$name":${_nameToPath[name]}, $fullPath'); _nameToPath[name] = fullPath; } if (route.routes.isNotEmpty) { _cacheNameToPath(fullPath, route.routes); } } else if (route is ShellRouteBase) { if (route.routes.isNotEmpty) { _cacheNameToPath(parentFullPath, route.routes); } } } } }
packages/packages/go_router/lib/src/configuration.dart/0
{ "file_path": "packages/packages/go_router/lib/src/configuration.dart", "repo_id": "packages", "token_count": 8105 }
1,003
// 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:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'configuration.dart'; import 'delegate.dart'; import 'information_provider.dart'; import 'logging.dart'; import 'match.dart'; import 'misc/inherited_router.dart'; import 'parser.dart'; import 'route.dart'; import 'state.dart'; /// The function signature of [GoRouter.onException]. /// /// Use `state.error` to access the exception. typedef GoExceptionHandler = void Function( BuildContext context, GoRouterState state, GoRouter router, ); /// A set of parameters that defines routing in GoRouter. /// /// This is typically used with [GoRouter.routingConfig] to create a go router /// with dynamic routing config. /// /// See [routing_config.dart](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/routing_config.dart). /// /// {@category Configuration} class RoutingConfig { /// Creates a routing config. /// /// The [routes] must not be empty. const RoutingConfig({ required this.routes, this.redirect = _defaultRedirect, this.redirectLimit = 5, }); static FutureOr<String?> _defaultRedirect( BuildContext context, GoRouterState state) => null; /// The supported routes. /// /// The `routes` list specifies the top-level routes for the app. It must not be /// empty and must contain an [GoRoute] to match `/`. /// /// See [GoRouter]. final List<RouteBase> routes; /// The top-level callback allows the app to redirect to a new location. /// /// Alternatively, you can specify a redirect for an individual route using /// [GoRoute.redirect]. If [BuildContext.dependOnInheritedWidgetOfExactType] is /// used during the redirection (which is how `of` methods are usually /// implemented), a re-evaluation will be triggered when the [InheritedWidget] /// changes. /// /// See [GoRouter]. final GoRouterRedirect redirect; /// The maximum number of redirection allowed. /// /// See [GoRouter]. final int redirectLimit; } /// The route configuration for the app. /// /// The `routes` list specifies the top-level routes for the app. It must not be /// empty and must contain an [GoRoute] to match `/`. /// /// See the [Get /// started](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/main.dart) /// example, which shows an app with a simple route configuration. /// /// The [redirect] callback allows the app to redirect to a new location. /// Alternatively, you can specify a redirect for an individual route using /// [GoRoute.redirect]. If [BuildContext.dependOnInheritedWidgetOfExactType] is /// used during the redirection (which is how `of` methods are usually /// implemented), a re-evaluation will be triggered when the [InheritedWidget] /// changes. /// /// To handle exceptions, use one of `onException`, `errorBuilder`, or /// `errorPageBuilder`. The `onException` is called when an exception is thrown. /// If `onException` is not provided, the exception is passed to /// `errorPageBuilder` to build a page for the Router if it is not null; /// otherwise, it is passed to `errorBuilder` instead. If none of them are /// provided, go_router builds a default error screen to show the exception. /// See [Error handling](https://pub.dev/documentation/go_router/latest/topics/Error%20handling-topic.html) /// for more details. /// /// To disable automatically requesting focus when new routes are pushed to the navigator, set `requestFocus` to false. /// /// See also: /// * [Configuration](https://pub.dev/documentation/go_router/latest/topics/Configuration-topic.html) /// * [GoRoute], which provides APIs to define the routing table. /// * [examples](https://github.com/flutter/packages/tree/main/packages/go_router/example), /// which contains examples for different routing scenarios. /// {@category Get started} /// {@category Upgrading} /// {@category Configuration} /// {@category Navigation} /// {@category Redirection} /// {@category Web} /// {@category Deep linking} /// {@category Error handling} /// {@category Named routes} class GoRouter implements RouterConfig<RouteMatchList> { /// Default constructor to configure a GoRouter with a routes builder /// and an error page builder. /// /// The `routes` must not be null and must contain an [GoRouter] to match `/`. factory GoRouter({ required List<RouteBase> routes, Codec<Object?, Object?>? extraCodec, GoExceptionHandler? onException, GoRouterPageBuilder? errorPageBuilder, GoRouterWidgetBuilder? errorBuilder, GoRouterRedirect? redirect, Listenable? refreshListenable, int redirectLimit = 5, bool routerNeglect = false, String? initialLocation, bool overridePlatformDefaultLocation = false, Object? initialExtra, List<NavigatorObserver>? observers, bool debugLogDiagnostics = false, GlobalKey<NavigatorState>? navigatorKey, String? restorationScopeId, bool requestFocus = true, }) { return GoRouter.routingConfig( routingConfig: _ConstantRoutingConfig( RoutingConfig( routes: routes, redirect: redirect ?? RoutingConfig._defaultRedirect, redirectLimit: redirectLimit), ), extraCodec: extraCodec, onException: onException, errorPageBuilder: errorPageBuilder, errorBuilder: errorBuilder, refreshListenable: refreshListenable, routerNeglect: routerNeglect, initialLocation: initialLocation, overridePlatformDefaultLocation: overridePlatformDefaultLocation, initialExtra: initialExtra, observers: observers, debugLogDiagnostics: debugLogDiagnostics, navigatorKey: navigatorKey, restorationScopeId: restorationScopeId, requestFocus: requestFocus, ); } /// Creates a [GoRouter] with a dynamic [RoutingConfig]. /// /// See [routing_config.dart](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/routing_config.dart). GoRouter.routingConfig({ required ValueListenable<RoutingConfig> routingConfig, Codec<Object?, Object?>? extraCodec, GoExceptionHandler? onException, GoRouterPageBuilder? errorPageBuilder, GoRouterWidgetBuilder? errorBuilder, Listenable? refreshListenable, bool routerNeglect = false, String? initialLocation, this.overridePlatformDefaultLocation = false, Object? initialExtra, List<NavigatorObserver>? observers, bool debugLogDiagnostics = false, GlobalKey<NavigatorState>? navigatorKey, String? restorationScopeId, bool requestFocus = true, }) : _routingConfig = routingConfig, backButtonDispatcher = RootBackButtonDispatcher(), assert( initialExtra == null || initialLocation != null, 'initialLocation must be set in order to use initialExtra', ), assert(!overridePlatformDefaultLocation || initialLocation != null, 'Initial location must be set to override platform default'), assert( (onException == null ? 0 : 1) + (errorPageBuilder == null ? 0 : 1) + (errorBuilder == null ? 0 : 1) < 2, 'Only one of onException, errorPageBuilder, or errorBuilder can be provided.') { setLogging(enabled: debugLogDiagnostics); WidgetsFlutterBinding.ensureInitialized(); navigatorKey ??= GlobalKey<NavigatorState>(); _routingConfig.addListener(_handleRoutingConfigChanged); configuration = RouteConfiguration( _routingConfig, navigatorKey: navigatorKey, extraCodec: extraCodec, ); final ParserExceptionHandler? parserExceptionHandler; if (onException != null) { parserExceptionHandler = (BuildContext context, RouteMatchList routeMatchList) { onException(context, configuration.buildTopLevelGoRouterState(routeMatchList), this); // Avoid updating GoRouterDelegate if onException is provided. return routerDelegate.currentConfiguration; }; } else { parserExceptionHandler = null; } routeInformationParser = GoRouteInformationParser( onParserException: parserExceptionHandler, configuration: configuration, ); routeInformationProvider = GoRouteInformationProvider( initialLocation: _effectiveInitialLocation(initialLocation), initialExtra: initialExtra, refreshListenable: refreshListenable, ); routerDelegate = GoRouterDelegate( configuration: configuration, errorPageBuilder: errorPageBuilder, errorBuilder: errorBuilder, routerNeglect: routerNeglect, observers: <NavigatorObserver>[ ...observers ?? <NavigatorObserver>[], ], restorationScopeId: restorationScopeId, requestFocus: requestFocus, // wrap the returned Navigator to enable GoRouter.of(context).go() et al, // allowing the caller to wrap the navigator themselves builderWithNav: (BuildContext context, Widget child) => InheritedGoRouter(goRouter: this, child: child), ); assert(() { log('setting initial location $initialLocation'); return true; }()); } /// Whether the imperative API affects browser URL bar. /// /// The Imperative APIs refer to [push], [pushReplacement], or [replace]. /// /// If this option is set to true. The URL bar reflects the top-most [GoRoute] /// regardless the [RouteBase]s underneath. /// /// If this option is set to false. The URL bar reflects the [RouteBase]s /// in the current state but ignores any [RouteBase]s that are results of /// imperative API calls. /// /// Defaults to false. /// /// This option is for backward compatibility. It is strongly suggested /// against setting this value to true, as the URL of the top-most [GoRoute] /// is not always deeplink-able. /// /// This option only affects web platform. static bool optionURLReflectsImperativeAPIs = false; /// The route configuration used in go_router. late final RouteConfiguration configuration; @override final BackButtonDispatcher backButtonDispatcher; /// The router delegate. Provide this to the MaterialApp or CupertinoApp's /// `.router()` constructor @override late final GoRouterDelegate routerDelegate; /// The route information provider used by [GoRouter]. @override late final GoRouteInformationProvider routeInformationProvider; /// The route information parser used by [GoRouter]. @override late final GoRouteInformationParser routeInformationParser; void _handleRoutingConfigChanged() { // Reparse is needed to update its builder restore(configuration.reparse(routerDelegate.currentConfiguration)); } /// Whether to ignore platform's default initial location when /// `initialLocation` is set. /// /// When set to [true], the [initialLocation] will take /// precedence over the platform's default initial location. /// This allows developers to control the starting route of the application /// independently of the platform. /// /// Platform's initial location is set when the app opens via a deeplink. /// Use [overridePlatformDefaultLocation] only if one wants to override /// platform implemented initial location. /// /// Setting this parameter to [false] (default) will allow the platform's /// default initial location to be used even if the `initialLocation` is set. /// It's advisable to only set this to [true] if one explicitly wants to. final bool overridePlatformDefaultLocation; final ValueListenable<RoutingConfig> _routingConfig; /// Returns `true` if there is at least two or more route can be pop. bool canPop() => routerDelegate.canPop(); /// Get a location from route name and parameters. /// This is useful for redirecting to a named location. String namedLocation( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, }) => configuration.namedLocation( name, pathParameters: pathParameters, queryParameters: queryParameters, ); /// Navigate to a URI location w/ optional query parameters, e.g. /// `/family/f2/person/p1?color=blue` void go(String location, {Object? extra}) { log('going to $location'); routeInformationProvider.go(location, extra: extra); } /// Restore the RouteMatchList void restore(RouteMatchList matchList) { log('restoring ${matchList.uri}'); routeInformationProvider.restore( matchList.uri.toString(), matchList: matchList, ); } /// Navigate to a named route w/ optional parameters, e.g. /// `name='person', pathParameters={'fid': 'f2', 'pid': 'p1'}` /// Navigate to the named route. void goNamed( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra, }) => go( namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); /// Push a URI location onto the page stack w/ optional query parameters, e.g. /// `/family/f2/person/p1?color=blue`. /// /// See also: /// * [pushReplacement] which replaces the top-most page of the page stack and /// always use a new page key. /// * [replace] which replaces the top-most page of the page stack but treats /// it as the same page. The page key will be reused. This will preserve the /// state and not run any page animation. Future<T?> push<T extends Object?>(String location, {Object? extra}) async { log('pushing $location'); return routeInformationProvider.push<T>( location, base: routerDelegate.currentConfiguration, extra: extra, ); } /// Push a named route onto the page stack w/ optional parameters, e.g. /// `name='person', pathParameters={'fid': 'f2', 'pid': 'p1'}` Future<T?> pushNamed<T extends Object?>( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra, }) => push<T>( namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); /// Replaces the top-most page of the page stack with the given URL location /// w/ optional query parameters, e.g. `/family/f2/person/p1?color=blue`. /// /// See also: /// * [go] which navigates to the location. /// * [push] which pushes the given location onto the page stack. /// * [replace] which replaces the top-most page of the page stack but treats /// it as the same page. The page key will be reused. This will preserve the /// state and not run any page animation. Future<T?> pushReplacement<T extends Object?>(String location, {Object? extra}) { log('pushReplacement $location'); return routeInformationProvider.pushReplacement<T>( location, base: routerDelegate.currentConfiguration, extra: extra, ); } /// Replaces the top-most page of the page stack with the named route w/ /// optional parameters, e.g. `name='person', pathParameters={'fid': 'f2', 'pid': /// 'p1'}`. /// /// See also: /// * [goNamed] which navigates a named route. /// * [pushNamed] which pushes a named route onto the page stack. Future<T?> pushReplacementNamed<T extends Object?>( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra, }) { return pushReplacement<T>( namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); } /// Replaces the top-most page of the page stack with the given one but treats /// it as the same page. /// /// The page key will be reused. This will preserve the state and not run any /// page animation. /// /// See also: /// * [push] which pushes the given location onto the page stack. /// * [pushReplacement] which replaces the top-most page of the page stack but /// always uses a new page key. Future<T?> replace<T>(String location, {Object? extra}) { log('replace $location'); return routeInformationProvider.replace<T>( location, base: routerDelegate.currentConfiguration, extra: extra, ); } /// Replaces the top-most page with the named route and optional parameters, /// preserving the page key. /// /// This will preserve the state and not run any page animation. Optional /// parameters can be providded to the named route, e.g. `name='person', /// pathParameters={'fid': 'f2', 'pid': 'p1'}`. /// /// See also: /// * [pushNamed] which pushes the given location onto the page stack. /// * [pushReplacementNamed] which replaces the top-most page of the page /// stack but always uses a new page key. Future<T?> replaceNamed<T>( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra, }) { return replace( namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); } /// Pop the top-most route off the current screen. /// /// If the top-most route is a pop up or dialog, this method pops it instead /// of any GoRoute under it. void pop<T extends Object?>([T? result]) { assert(() { log('popping ${routerDelegate.currentConfiguration.uri}'); return true; }()); routerDelegate.pop<T>(result); } /// Refresh the route. void refresh() { assert(() { log('refreshing ${routerDelegate.currentConfiguration.uri}'); return true; }()); routeInformationProvider.notifyListeners(); } /// Find the current GoRouter in the widget tree. /// /// This method throws when it is called during redirects. static GoRouter of(BuildContext context) { final GoRouter? inherited = maybeOf(context); assert(inherited != null, 'No GoRouter found in context'); return inherited!; } /// The current GoRouter in the widget tree, if any. /// /// This method returns null when it is called during redirects. static GoRouter? maybeOf(BuildContext context) { final InheritedGoRouter? inherited = context .getElementForInheritedWidgetOfExactType<InheritedGoRouter>() ?.widget as InheritedGoRouter?; return inherited?.goRouter; } /// Disposes resource created by this object. void dispose() { _routingConfig.removeListener(_handleRoutingConfigChanged); routeInformationProvider.dispose(); routerDelegate.dispose(); } String _effectiveInitialLocation(String? initialLocation) { if (overridePlatformDefaultLocation) { // The initialLocation must not be null as it's already // verified by assert() during the initialization. return initialLocation!; } Uri platformDefaultUri = Uri.parse( WidgetsBinding.instance.platformDispatcher.defaultRouteName, ); if (platformDefaultUri.hasEmptyPath) { // TODO(chunhtai): Clean up this once `RouteInformation.uri` is available // in packages repo. platformDefaultUri = Uri( path: '/', queryParameters: platformDefaultUri.queryParameters, ); } final String platformDefault = platformDefaultUri.toString(); if (initialLocation == null) { return platformDefault; } else if (platformDefault == '/') { return initialLocation; } else { return platformDefault; } } } /// A routing config that is never going to change. class _ConstantRoutingConfig extends ValueListenable<RoutingConfig> { const _ConstantRoutingConfig(this.value); @override void addListener(VoidCallback listener) { // Intentionally empty because listener will never be called. } @override void removeListener(VoidCallback listener) { // Intentionally empty because listener will never be called. } @override final RoutingConfig value; }
packages/packages/go_router/lib/src/router.dart/0
{ "file_path": "packages/packages/go_router/lib/src/router.dart", "repo_id": "packages", "token_count": 6518 }
1,004
// 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/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import '../test_helpers.dart'; WidgetTesterCallback testPageNotFound({required Widget widget}) { return (WidgetTester tester) async { await tester.pumpWidget(widget); expect(find.text('page not found'), findsOneWidget); }; } WidgetTesterCallback testPageShowsExceptionMessage({ required Exception exception, required Widget widget, }) { return (WidgetTester tester) async { await tester.pumpWidget(widget); expect(find.text('$exception'), findsOneWidget); }; } WidgetTesterCallback testClickingTheButtonRedirectsToRoot({ required Finder buttonFinder, required Widget widget, Widget Function(GoRouter router) appRouterBuilder = materialAppRouterBuilder, }) { return (WidgetTester tester) async { final GoRouter router = GoRouter( initialLocation: '/error', routes: <GoRoute>[ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), GoRoute( path: '/error', builder: (_, __) => widget, ), ], ); addTearDown(router.dispose); await tester.pumpWidget(appRouterBuilder(router)); await tester.tap(buttonFinder); await tester.pumpAndSettle(); expect(find.byType(DummyStatefulWidget), findsOneWidget); }; } Widget materialAppRouterBuilder(GoRouter router) { return MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ); } Widget cupertinoAppRouterBuilder(GoRouter router) { return CupertinoApp.router( routerConfig: router, title: 'GoRouter Example', ); }
packages/packages/go_router/test/helpers/error_screen_helpers.dart/0
{ "file_path": "packages/packages/go_router/test/helpers/error_screen_helpers.dart", "repo_id": "packages", "token_count": 659 }
1,005
// 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() { test('ShellRoute observers test', () { final ShellRoute shell = ShellRoute( observers: <NavigatorObserver>[HeroController()], builder: (BuildContext context, GoRouterState state, Widget child) { return SafeArea(child: child); }, routes: <RouteBase>[ GoRoute( path: '/home', builder: (BuildContext context, GoRouterState state) { return Container(); }, ), ], ); expect(shell.observers!.length, 1); }); }
packages/packages/go_router/test/shell_route_observers_test.dart/0
{ "file_path": "packages/packages/go_router/test/shell_route_observers_test.dart", "repo_id": "packages", "token_count": 315 }
1,006
test_on: vm
packages/packages/go_router_builder/example/dart_test.yaml/0
{ "file_path": "packages/packages/go_router_builder/example/dart_test.yaml", "repo_id": "packages", "token_count": 6 }
1,007
// 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:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; part 'stateful_shell_route_example.g.dart'; final GlobalKey<NavigatorState> _sectionANavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'sectionANav'); 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: '/detailsA', ); } class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('foo')), ); } @TypedStatefulShellRoute<MyShellRouteData>( branches: <TypedStatefulShellBranch<StatefulShellBranchData>>[ TypedStatefulShellBranch<BranchAData>( routes: <TypedRoute<RouteData>>[ TypedGoRoute<DetailsARouteData>(path: '/detailsA'), ], ), TypedStatefulShellBranch<BranchBData>( routes: <TypedRoute<RouteData>>[ TypedGoRoute<DetailsBRouteData>(path: '/detailsB'), ], ), ], ) class MyShellRouteData extends StatefulShellRouteData { const MyShellRouteData(); @override Widget builder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) { return navigationShell; } static const String $restorationScopeId = 'restorationScopeId'; static Widget $navigatorContainerBuilder(BuildContext context, StatefulNavigationShell navigationShell, List<Widget> children) { return ScaffoldWithNavBar( navigationShell: navigationShell, children: children, ); } } class BranchAData extends StatefulShellBranchData { const BranchAData(); } class BranchBData extends StatefulShellBranchData { const BranchBData(); static final GlobalKey<NavigatorState> $navigatorKey = _sectionANavigatorKey; static const String $restorationScopeId = 'restorationScopeId'; } class DetailsARouteData extends GoRouteData { const DetailsARouteData(); @override Widget build(BuildContext context, GoRouterState state) { return const DetailsScreen(label: 'A'); } } class DetailsBRouteData extends GoRouteData { const DetailsBRouteData(); @override Widget build(BuildContext context, GoRouterState state) { return const DetailsScreen(label: 'B'); } } /// 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, required this.children, Key? key, }) : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; /// The children (branch Navigators) to display in a custom container /// ([AnimatedBranchContainer]). final List<Widget> children; @override Widget build(BuildContext context) { return Scaffold( body: AnimatedBranchContainer( currentIndex: navigationShell.currentIndex, children: children, ), bottomNavigationBar: BottomNavigationBar( // Here, the items of BottomNavigationBar are hard coded. In a real // world scenario, the items would most likely be generated from the // branches of the shell route, which can be fetched using // `navigationShell.route.branches`. items: const <BottomNavigationBarItem>[ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Section A'), BottomNavigationBarItem(icon: Icon(Icons.work), label: 'Section B'), ], currentIndex: navigationShell.currentIndex, onTap: (int index) => _onTap(context, index), ), ); } /// Navigate to the current location of the branch at the provided index when /// tapping an item in the BottomNavigationBar. void _onTap(BuildContext context, int index) { // When navigating to a new branch, it's recommended to use the goBranch // method, as doing so makes sure the last navigation state of the // Navigator for the branch is restored. navigationShell.goBranch( index, // A common pattern when using bottom navigation bars is to support // navigating to the initial location when tapping the item that is // already active. This example demonstrates how to support this behavior, // using the initialLocation parameter of goBranch. initialLocation: index == navigationShell.currentIndex, ); } } /// Custom branch Navigator container that provides animated transitions /// when switching branches. class AnimatedBranchContainer extends StatelessWidget { /// Creates a AnimatedBranchContainer const AnimatedBranchContainer( {super.key, required this.currentIndex, required this.children}); /// The index (in [children]) of the branch Navigator to display. final int currentIndex; /// The children (branch Navigators) to display in this container. final List<Widget> children; @override Widget build(BuildContext context) { return Stack( children: children.mapIndexed( (int index, Widget navigator) { return AnimatedScale( scale: index == currentIndex ? 1 : 1.5, duration: const Duration(milliseconds: 400), child: AnimatedOpacity( opacity: index == currentIndex ? 1 : 0, duration: const Duration(milliseconds: 400), child: _branchNavigatorWrapper(index, navigator), ), ); }, ).toList()); } Widget _branchNavigatorWrapper(int index, Widget navigator) => IgnorePointer( ignoring: index != currentIndex, child: TickerMode( enabled: index == currentIndex, child: navigator, ), ); } /// The details screen for either the A or B screen. class DetailsScreen extends StatefulWidget { /// Constructs a [DetailsScreen]. const DetailsScreen({ required this.label, this.param, this.extra, super.key, }); /// The label to display in the center of the screen. final String label; /// Optional param final String? param; /// Optional extra object final Object? extra; @override State<StatefulWidget> createState() => DetailsScreenState(); } /// The state for DetailsScreen class DetailsScreenState extends State<DetailsScreen> { int _counter = 0; @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', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { setState(() { _counter++; }); }, child: const Text('Increment counter'), ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) Text('Parameter: ${widget.param!}', style: Theme.of(context).textTheme.titleMedium), const Padding(padding: EdgeInsets.all(8)), if (widget.extra != null) Text('Extra: ${widget.extra!}', style: Theme.of(context).textTheme.titleMedium), ], ), ); } }
packages/packages/go_router_builder/example/lib/stateful_shell_route_example.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/stateful_shell_route_example.dart", "repo_id": "packages", "token_count": 2842 }
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. import 'dart:collection'; import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:collection/collection.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:source_gen/source_gen.dart'; import 'package:source_helper/source_helper.dart'; import 'path_utils.dart'; import 'type_helpers.dart'; /// Custom [Iterable] implementation with extra info. class InfoIterable extends IterableBase<String> { InfoIterable._({ required this.members, required this.routeGetterName, }); /// Name of the getter associated with `this`. final String routeGetterName; /// The generated elements associated with `this`. final List<String> members; @override Iterator<String> get iterator => members.iterator; } /// The configuration to generate class declarations for a ShellRouteData. class ShellRouteConfig extends RouteBaseConfig { ShellRouteConfig._({ required this.navigatorKey, required this.parentNavigatorKey, required super.routeDataClass, required this.observers, required super.parent, }) : super._(); /// The command for calling the navigator key getter from the ShellRouteData. final String? navigatorKey; /// The parent navigator key. final String? parentNavigatorKey; /// The navigator observers. final String? observers; @override Iterable<String> classDeclarations() { if (routeDataClass.unnamedConstructor == null) { throw InvalidGenerationSourceError( 'The ShellRouteData "$_className" class must have an unnamed constructor.', element: routeDataClass, ); } final bool isConst = routeDataClass.unnamedConstructor!.isConst; return <String>[ ''' extension $_extensionName on $_className { static $_className _fromState(GoRouterState state) =>${isConst ? ' const' : ''} $_className(); } ''' ]; } @override String get routeConstructorParameters => '${navigatorKey == null ? '' : 'navigatorKey: $navigatorKey,'}' '${parentNavigatorKey == null ? '' : 'parentNavigatorKey: $parentNavigatorKey,'}' '${observers == null ? '' : 'observers: $observers,'}'; @override String get factorConstructorParameters => 'factory: $_extensionName._fromState,'; @override String get routeDataClassName => 'ShellRouteData'; @override String get dataConvertionFunctionName => r'$route'; } /// The configuration to generate class declarations for a StatefulShellRouteData. class StatefulShellRouteConfig extends RouteBaseConfig { StatefulShellRouteConfig._({ required this.parentNavigatorKey, required super.routeDataClass, required super.parent, required this.navigatorContainerBuilder, required this.restorationScopeId, }) : super._(); /// The parent navigator key. final String? parentNavigatorKey; /// The navigator container builder. final String? navigatorContainerBuilder; /// The restoration scope id. final String? restorationScopeId; @override Iterable<String> classDeclarations() => <String>[ ''' extension $_extensionName on $_className { static $_className _fromState(GoRouterState state) => const $_className(); } ''' ]; @override String get routeConstructorParameters => '${parentNavigatorKey == null ? '' : 'parentNavigatorKey: $parentNavigatorKey,'}' '${restorationScopeId == null ? '' : 'restorationScopeId: $restorationScopeId,'}' '${navigatorContainerBuilder == null ? '' : 'navigatorContainerBuilder: $navigatorContainerBuilder,'}'; @override String get factorConstructorParameters => 'factory: $_extensionName._fromState,'; @override String get routeDataClassName => 'StatefulShellRouteData'; @override String get dataConvertionFunctionName => r'$route'; } /// The configuration to generate class declarations for a StatefulShellBranchData. class StatefulShellBranchConfig extends RouteBaseConfig { StatefulShellBranchConfig._({ required this.navigatorKey, required super.routeDataClass, required super.parent, this.restorationScopeId, this.initialLocation, }) : super._(); /// The command for calling the navigator key getter from the ShellRouteData. final String? navigatorKey; /// The restoration scope id. final String? restorationScopeId; /// The initial route. final String? initialLocation; @override Iterable<String> classDeclarations() => <String>[]; @override String get factorConstructorParameters => ''; @override String get routeConstructorParameters => '${navigatorKey == null ? '' : 'navigatorKey: $navigatorKey,'}' '${restorationScopeId == null ? '' : 'restorationScopeId: $restorationScopeId,'}' '${initialLocation == null ? '' : 'initialLocation: $initialLocation,'}'; @override String get routeDataClassName => 'StatefulShellBranchData'; @override String get dataConvertionFunctionName => r'$branch'; } /// The configuration to generate class declarations for a GoRouteData. class GoRouteConfig extends RouteBaseConfig { GoRouteConfig._({ required this.path, required this.name, required this.parentNavigatorKey, required super.routeDataClass, required super.parent, }) : super._(); /// The path of the GoRoute to be created by this configuration. final String path; /// The name of the GoRoute to be created by this configuration. final String? name; /// The parent navigator key. final String? parentNavigatorKey; late final Set<String> _pathParams = pathParametersFromPattern(_rawJoinedPath); String get _rawJoinedPath { final List<String> pathSegments = <String>[]; RouteBaseConfig? config = this; while (config != null) { if (config is GoRouteConfig) { pathSegments.add(config.path); } config = config.parent; } return p.url.joinAll(pathSegments.reversed); } // construct path bits using parent bits // if there are any queryParam objects, add in the `queryParam` bits String get _locationArgs { final Map<String, String> pathParameters = Map<String, String>.fromEntries( _pathParams.map((String pathParameter) { // Enum types are encoded using a map, so we need a nullability check // here to ensure it matches Uri.encodeComponent nullability final DartType? type = _field(pathParameter)?.returnType; final String value = '\${Uri.encodeComponent(${_encodeFor(pathParameter)}${type?.isEnum ?? false ? '!' : ''})}'; return MapEntry<String, String>(pathParameter, value); }), ); final String location = patternToPath(_rawJoinedPath, pathParameters); return "'$location'"; } ParameterElement? get _extraParam => _ctor.parameters .singleWhereOrNull((ParameterElement element) => element.isExtraField); String get _fromStateConstructor { final StringBuffer buffer = StringBuffer('=>'); if (_ctor.isConst && _ctorParams.isEmpty && _ctorQueryParams.isEmpty && _extraParam == null) { buffer.writeln('const '); } buffer.writeln('$_className('); for (final ParameterElement param in <ParameterElement>[ ..._ctorParams, ..._ctorQueryParams, if (_extraParam != null) _extraParam!, ]) { buffer.write(_decodeFor(param)); } buffer.writeln(');'); return buffer.toString(); } String _decodeFor(ParameterElement element) { if (element.isRequired) { if (element.type.nullabilitySuffix == NullabilitySuffix.question && _pathParams.contains(element.name)) { throw InvalidGenerationSourceError( 'Required parameters in the path cannot be nullable.', element: element, ); } } final String fromStateExpression = decodeParameter(element, _pathParams); if (element.isPositional) { return '$fromStateExpression,'; } if (element.isNamed) { return '${element.name}: $fromStateExpression,'; } throw InvalidGenerationSourceError( '$likelyIssueMessage (param not named or positional)', element: element, ); } String _encodeFor(String fieldName) { final PropertyAccessorElement? field = _field(fieldName); if (field == null) { throw InvalidGenerationSourceError( 'Could not find a field for the path parameter "$fieldName".', element: routeDataClass, ); } return encodeField(field); } String get _locationQueryParams { if (_ctorQueryParams.isEmpty) { return ''; } final StringBuffer buffer = StringBuffer('queryParams: {\n'); for (final ParameterElement param in _ctorQueryParams) { final String parameterName = param.name; final List<String> conditions = <String>[]; if (param.hasDefaultValue) { if (param.type.isNullableType) { throw NullableDefaultValueError(param); } conditions.add('$parameterName != ${param.defaultValueCode!}'); } else if (param.type.isNullableType) { conditions.add('$parameterName != null'); } String line = ''; if (conditions.isNotEmpty) { line = 'if (${conditions.join(' && ')}) '; } line += '${escapeDartString(parameterName.kebab)}: ' '${_encodeFor(parameterName)},'; buffer.writeln(line); } buffer.writeln('},'); return buffer.toString(); } late final List<ParameterElement> _ctorParams = _ctor.parameters.where((ParameterElement element) { if (_pathParams.contains(element.name)) { return true; } return false; }).toList(); late final List<ParameterElement> _ctorQueryParams = _ctor.parameters .where((ParameterElement element) => !_pathParams.contains(element.name) && !element.isExtraField) .toList(); ConstructorElement get _ctor { final ConstructorElement? ctor = routeDataClass.unnamedConstructor; if (ctor == null) { throw InvalidGenerationSourceError( 'Missing default constructor', element: routeDataClass, ); } return ctor; } @override Iterable<String> classDeclarations() => <String>[ _extensionDefinition, ..._enumDeclarations(), ]; String get _extensionDefinition => ''' extension $_extensionName on $_className { static $_className _fromState(GoRouterState state) $_fromStateConstructor String get location => GoRouteData.\$location($_locationArgs,$_locationQueryParams); void go(BuildContext context) => context.go(location${_extraParam != null ? ', extra: $extraFieldName' : ''}); Future<T?> push<T>(BuildContext context) => context.push<T>(location${_extraParam != null ? ', extra: $extraFieldName' : ''}); void pushReplacement(BuildContext context) => context.pushReplacement(location${_extraParam != null ? ', extra: $extraFieldName' : ''}); void replace(BuildContext context) => context.replace(location${_extraParam != null ? ', extra: $extraFieldName' : ''}); } '''; /// Returns code representing the constant maps that contain the `enum` to /// [String] mapping for each referenced enum. Iterable<String> _enumDeclarations() { final Set<InterfaceType> enumParamTypes = <InterfaceType>{}; for (final ParameterElement ctorParam in <ParameterElement>[ ..._ctorParams, ..._ctorQueryParams, ]) { DartType potentialEnumType = ctorParam.type; if (potentialEnumType is ParameterizedType && (ctorParam.type as ParameterizedType).typeArguments.isNotEmpty) { potentialEnumType = (ctorParam.type as ParameterizedType).typeArguments.first; } if (potentialEnumType.isEnum) { enumParamTypes.add(potentialEnumType as InterfaceType); } } return enumParamTypes.map<String>(_enumMapConst); } @override String get factorConstructorParameters => 'factory: $_extensionName._fromState,'; @override String get routeConstructorParameters => ''' path: ${escapeDartString(path)}, ${name != null ? 'name: ${escapeDartString(name!)},' : ''} ${parentNavigatorKey == null ? '' : 'parentNavigatorKey: $parentNavigatorKey,'} '''; @override String get routeDataClassName => 'GoRouteData'; @override String get dataConvertionFunctionName => r'$route'; } /// Represents a `TypedGoRoute` annotation to the builder. abstract class RouteBaseConfig { RouteBaseConfig._({ required this.routeDataClass, required this.parent, }); /// Creates a new [RouteBaseConfig] represented the annotation data in [reader]. factory RouteBaseConfig.fromAnnotation( ConstantReader reader, InterfaceElement element, ) { final RouteBaseConfig definition = RouteBaseConfig._fromAnnotation(reader, element, null); if (element != definition.routeDataClass) { throw InvalidGenerationSourceError( 'The @TypedGoRoute annotation must have a type parameter that matches ' 'the annotated element.', element: element, ); } return definition; } factory RouteBaseConfig._fromAnnotation( ConstantReader reader, InterfaceElement element, RouteBaseConfig? parent, ) { assert(!reader.isNull, 'reader should not be null'); final InterfaceType type = reader.objectValue.type! as InterfaceType; final String typeName = type.element.name; final DartType typeParamType = type.typeArguments.single; if (typeParamType is! InterfaceType) { throw InvalidGenerationSourceError( 'The type parameter on one of the @TypedGoRoute declarations could not ' 'be parsed.', element: element, ); } // TODO(kevmoo): validate that this MUST be a subtype of `GoRouteData` final InterfaceElement classElement = typeParamType.element; final RouteBaseConfig value; switch (typeName) { case 'TypedShellRoute': value = ShellRouteConfig._( routeDataClass: classElement, parent: parent, navigatorKey: _generateParameterGetterCode( classElement, parameterName: r'$navigatorKey', ), parentNavigatorKey: _generateParameterGetterCode( classElement, parameterName: r'$parentNavigatorKey', ), observers: _generateParameterGetterCode( classElement, parameterName: r'$observers', ), ); case 'TypedStatefulShellRoute': value = StatefulShellRouteConfig._( routeDataClass: classElement, parent: parent, parentNavigatorKey: _generateParameterGetterCode( classElement, parameterName: r'$parentNavigatorKey', ), restorationScopeId: _generateParameterGetterCode( classElement, parameterName: r'$restorationScopeId', ), navigatorContainerBuilder: _generateParameterGetterCode( classElement, parameterName: r'$navigatorContainerBuilder', ), ); case 'TypedStatefulShellBranch': value = StatefulShellBranchConfig._( routeDataClass: classElement, parent: parent, navigatorKey: _generateParameterGetterCode( classElement, parameterName: r'$navigatorKey', ), restorationScopeId: _generateParameterGetterCode( classElement, parameterName: r'$restorationScopeId', ), initialLocation: _generateParameterGetterCode( classElement, parameterName: r'$initialLocation', ), ); case 'TypedGoRoute': final ConstantReader pathValue = reader.read('path'); if (pathValue.isNull) { throw InvalidGenerationSourceError( 'Missing `path` value on annotation.', element: element, ); } final ConstantReader nameValue = reader.read('name'); value = GoRouteConfig._( path: pathValue.stringValue, name: nameValue.isNull ? null : nameValue.stringValue, routeDataClass: classElement, parent: parent, parentNavigatorKey: _generateParameterGetterCode( classElement, parameterName: r'$parentNavigatorKey', ), ); default: throw UnsupportedError('Unrecognized type $typeName'); } value._children.addAll(reader .read(_generateChildrenGetterName(typeName)) .listValue .map<RouteBaseConfig>((DartObject e) => RouteBaseConfig._fromAnnotation( ConstantReader(e), element, value))); return value; } final List<RouteBaseConfig> _children = <RouteBaseConfig>[]; /// The `RouteData` class this class represents. final InterfaceElement routeDataClass; /// The parent of this route config. final RouteBaseConfig? parent; static String _generateChildrenGetterName(String name) { return (name == 'TypedStatefulShellRoute' || name == 'StatefulShellRouteData') ? 'branches' : 'routes'; } static String? _generateParameterGetterCode(InterfaceElement classElement, {required String parameterName}) { final String? fieldDisplayName = classElement.fields .where((FieldElement element) { if (!element.isStatic || element.name != parameterName) { return false; } if (parameterName .toLowerCase() .contains(RegExp('navigatorKey | observers'))) { final DartType type = element.type; if (type is! ParameterizedType) { return false; } final List<DartType> typeArguments = type.typeArguments; if (typeArguments.length != 1) { return false; } final DartType typeArgument = typeArguments.single; if (typeArgument.getDisplayString(withNullability: false) != 'NavigatorState') { return false; } } return true; }) .map<String>((FieldElement e) => e.displayName) .firstOrNull; if (fieldDisplayName != null) { return '${classElement.name}.$fieldDisplayName'; } final String? methodDisplayName = classElement.methods .where((MethodElement element) { return element.isStatic && element.name == parameterName; }) .map<String>((MethodElement e) => e.displayName) .firstOrNull; if (methodDisplayName != null) { return '${classElement.name}.$methodDisplayName'; } return null; } /// Generates all of the members that correspond to `this`. InfoIterable generateMembers() => InfoIterable._( members: _generateMembers().toList(), routeGetterName: _routeGetterName, ); Iterable<String> _generateMembers() sync* { final List<String> items = <String>[ _rootDefinition(), ]; for (final RouteBaseConfig def in _flatten()) { items.addAll(def.classDeclarations()); } yield* items; yield* items .expand( (String e) => helperNames.entries .where( (MapEntry<String, String> element) => e.contains(element.key)) .map((MapEntry<String, String> e) => e.value), ) .toSet(); } /// Returns this [GoRouteConfig] and all child [GoRouteConfig] instances. Iterable<RouteBaseConfig> _flatten() sync* { yield this; for (final RouteBaseConfig child in _children) { yield* child._flatten(); } } late final String _routeGetterName = r'$' + _className.substring(0, 1).toLowerCase() + _className.substring(1); /// Returns the `GoRoute` code for the annotated class. String _rootDefinition() => ''' RouteBase get $_routeGetterName => ${_invokesRouteConstructor()}; '''; String get _className => routeDataClass.name; String get _extensionName => '\$${_className}Extension'; String _invokesRouteConstructor() { final String routesBit = _children.isEmpty ? '' : ''' ${_generateChildrenGetterName(routeDataClassName)}: [${_children.map((RouteBaseConfig e) => '${e._invokesRouteConstructor()},').join()}], '''; return ''' $routeDataClassName.$dataConvertionFunctionName( $routeConstructorParameters $factorConstructorParameters $routesBit ) '''; } PropertyAccessorElement? _field(String name) => routeDataClass.getGetter(name); /// The name of `RouteData` subclass this configuration represents. @protected String get routeDataClassName; /// The function name of `RouteData` to get Routes or branches. @protected String get dataConvertionFunctionName; /// Additional factory constructor. @protected String get factorConstructorParameters; /// Additional constructor parameter for invoking route constructor. @protected String get routeConstructorParameters; /// Returns all class declarations code. @protected Iterable<String> classDeclarations(); } String _enumMapConst(InterfaceType type) { assert(type.isEnum); final String enumName = type.element.name; final StringBuffer buffer = StringBuffer('const ${enumMapName(type)} = {'); for (final FieldElement enumField in type.element.fields .where((FieldElement element) => element.isEnumConstant)) { buffer.writeln( '$enumName.${enumField.name}: ${escapeDartString(enumField.name.kebab)},', ); } buffer.writeln('};'); return buffer.toString(); } /// [Map] from the name of a generated helper to its definition. const Map<String, String> helperNames = <String, String>{ convertMapValueHelperName: _convertMapValueHelper, boolConverterHelperName: _boolConverterHelper, enumExtensionHelperName: _enumConverterHelper, }; const String _convertMapValueHelper = ''' T? $convertMapValueHelperName<T>( String key, Map<String, String> map, T Function(String) converter, ) { final value = map[key]; return value == null ? null : converter(value); } '''; const String _boolConverterHelper = ''' bool $boolConverterHelperName(String value) { switch (value) { case 'true': return true; case 'false': return false; default: throw UnsupportedError('Cannot convert "\$value" into a bool.'); } } '''; const String _enumConverterHelper = ''' extension<T extends Enum> on Map<T, String> { T $enumExtensionHelperName(String value) => entries.singleWhere((element) => element.value == value).key; }''';
packages/packages/go_router_builder/lib/src/route_config.dart/0
{ "file_path": "packages/packages/go_router_builder/lib/src/route_config.dart", "repo_id": "packages", "token_count": 8270 }
1,009
# google_identity_services_web A JS-interop layer for Google Identity's Sign In With Google SDK. See the original JS SDK reference: * [Sign In With Google](https://developers.google.com/identity/gsi/web) ## Usage This package is the Dart JS-interop layer of the new **Sign In With Google** SDK. Here's the API references for both of the sub-libraries: * `id.dart`: [Sign In With Google JavaScript API reference](https://developers.google.com/identity/gsi/web/reference/js-reference) * `oauth2.dart`: [Google 3P Authorization JavaScript Library for websites - API reference](https://developers.google.com/identity/oauth2/web/reference/js-reference) * `loader.dart`: An (optional) loader mechanism that installs the library and resolves a `Future<void>` when it's ready. ### Loading the SDK There are two ways to load the JS SDK in your app. #### Modify your index.html (most performant) The most performant way is to modify your `web/index.html` file to insert a script tag [as recommended](https://developers.google.com/identity/gsi/web/guides/client-library). Place the `script` tag in the `<head>` of your site, next to the script tag that loads `flutter.js`, so the browser can downloaded both in parallel: <?code-excerpt "example/web/index-with-script-tag.html (script-tag)"?> ```html <head> <!-- ··· --> <!-- Include the GSI SDK below --> <script src="https://accounts.google.com/gsi/client" async defer></script> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> </head> ``` #### With the `loadWebSdk` function (on-demand) An alternative way, that downloads the SDK on demand, is to use the **`loadWebSdk`** function provided by the library. A simple location to embed this in a Flutter Web only app can be the `main.dart`: <?code-excerpt "example/lib/main.dart (use-loader)"?> ```dart import 'package:google_identity_services_web/loader.dart' as gis; // ··· void main() async { await gis.loadWebSdk(); // Load the GIS SDK // The rest of your code... // ··· } ``` (Note that the above won't compile for mobile apps, so if you're developing a cross-platform app, you'll probably need to hide the call to `loadWebSdk` behind a [conditional import/export](https://dart.dev/guides/libraries/create-library-packages#conditionally-importing-and-exporting-library-files).) ### Using the SDK Once the SDK has been loaded, it can be used by importing the correct library: * `import 'package:google_identity_services/id.dart';` for Authentication. * This will expose an `id` JSObject that binds to `google.accounts.id`. * `import 'package:google_identity_services/oauth2.dart';` for Authorization. * This will expose an `oauth2` JSObject that binds to `google.accounts.oauth2`. ### Troubleshooting Watch the browser's development tools JS console while using this package. Information about errors during initialization and use of the library will be displayed there. Some common issues identified so far: #### The given origin is not allowed for the given client ID > When you perform local tests or development, **you must add both** > `http://localhost` and `http://localhost:<port_number>` to the > **Authorized JavaScript origins** box. > The [Referrer-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) > response header must also be set to `no-referrer-when-downgrade` when using > http and localhost. * Read more: [Sign In with Google for Web - Setup - Get your Google API client ID](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#get_your_google_api_client_id). ## Browser compatibility The new SDK is introducing concepts that are on track for standardization to most browsers, and it might not be compatible with older browsers. Refer to the official documentation site for the latest browser compatibility information of the underlying JS SDK: * **Sign In With Google > [Supported browsers and platforms](https://developers.google.com/identity/gsi/web/guides/supported-browsers)** ## Testing This web-only package uses `dart:test` to test its features. They can be run with `dart test -p chrome`. _(Look at `test/README.md` and `tool/run_tests.dart` for more info.)_
packages/packages/google_identity_services_web/README.md/0
{ "file_path": "packages/packages/google_identity_services_web/README.md", "repo_id": "packages", "token_count": 1256 }
1,010
name: google_identity_services_web description: A Dart JS-interop layer for Google Identity Services. Google's new sign-in SDK for Web that supports multiple types of credentials. repository: https://github.com/flutter/packages/tree/main/packages/google_identity_services_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_identiy_services_web%22 version: 0.3.1+1 environment: sdk: ^3.3.0 dependencies: meta: ^1.3.0 web: ^0.5.1 dev_dependencies: path: ^1.8.1 test: ^1.21.1 topics: - authentication - google-identity-services
packages/packages/google_identity_services_web/pubspec.yaml/0
{ "file_path": "packages/packages/google_identity_services_web/pubspec.yaml", "repo_id": "packages", "token_count": 222 }
1,011
name: google_maps_flutter_example description: Demonstrates how to use the google_maps_flutter plugin. publish_to: none environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: cupertino_icons: ^1.0.5 flutter: sdk: flutter flutter_plugin_android_lifecycle: ^2.0.1 google_maps_flutter: # When depending on this package from a real application you should use: # google_maps_flutter: ^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_maps_flutter_android: ^2.5.0 google_maps_flutter_platform_interface: ^2.5.0 dev_dependencies: build_runner: ^2.1.10 espresso: ^0.2.0 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true assets: - assets/
packages/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml", "repo_id": "packages", "token_count": 353 }
1,012
// 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/widgets.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 'fake_google_maps_flutter_platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); late FakeGoogleMapsFlutterPlatform platform; setUp(() { // Use a mock platform so we never need to hit the MethodChannel code. platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; }); testWidgets('_webOnlyMapCreationId increments with each GoogleMap widget', ( WidgetTester tester, ) async { // Inject two map widgets... await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ GoogleMap( initialCameraPosition: CameraPosition( target: LatLng(43.362, -5.849), ), ), GoogleMap( initialCameraPosition: CameraPosition( target: LatLng(47.649, -122.350), ), ), ], ), ), ); // Verify that each one was created with a different _webOnlyMapCreationId. expect(platform.createdIds.length, 2); expect(platform.createdIds[0], 0); expect(platform.createdIds[1], 1); }); testWidgets('Calls platform.dispose when GoogleMap is disposed of', ( WidgetTester tester, ) async { await tester.pumpWidget(const GoogleMap( initialCameraPosition: CameraPosition( target: LatLng(43.3608, -5.8702), ), )); // Now dispose of the map... await tester.pumpWidget(Container()); expect(platform.disposed, true); }); }
packages/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart", "repo_id": "packages", "token_count": 792 }
1,013
// 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.googlemaps; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import androidx.annotation.VisibleForTesting; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.ButtCap; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Cap; import com.google.android.gms.maps.model.CustomCap; import com.google.android.gms.maps.model.Dash; import com.google.android.gms.maps.model.Dot; import com.google.android.gms.maps.model.Gap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.PatternItem; import com.google.android.gms.maps.model.RoundCap; import com.google.android.gms.maps.model.SquareCap; import com.google.android.gms.maps.model.Tile; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** Conversions between JSON-like values and GoogleMaps data types. */ class Convert { // TODO(hamdikahloun): FlutterMain has been deprecated and should be replaced with FlutterLoader // when it's available in Stable channel: https://github.com/flutter/flutter/issues/70923. @SuppressWarnings("deprecation") private static BitmapDescriptor toBitmapDescriptor(Object o) { final List<?> data = toList(o); switch (toString(data.get(0))) { case "defaultMarker": if (data.size() == 1) { return BitmapDescriptorFactory.defaultMarker(); } else { return BitmapDescriptorFactory.defaultMarker(toFloat(data.get(1))); } case "fromAsset": if (data.size() == 2) { return BitmapDescriptorFactory.fromAsset( io.flutter.view.FlutterMain.getLookupKeyForAsset(toString(data.get(1)))); } else { return BitmapDescriptorFactory.fromAsset( io.flutter.view.FlutterMain.getLookupKeyForAsset( toString(data.get(1)), toString(data.get(2)))); } case "fromAssetImage": if (data.size() == 3) { return BitmapDescriptorFactory.fromAsset( io.flutter.view.FlutterMain.getLookupKeyForAsset(toString(data.get(1)))); } else { throw new IllegalArgumentException( "'fromAssetImage' Expected exactly 3 arguments, got: " + data.size()); } case "fromBytes": return getBitmapFromBytes(data); default: throw new IllegalArgumentException("Cannot interpret " + o + " as BitmapDescriptor"); } } private static BitmapDescriptor getBitmapFromBytes(List<?> data) { if (data.size() == 2) { try { Bitmap bitmap = toBitmap(data.get(1)); return BitmapDescriptorFactory.fromBitmap(bitmap); } catch (Exception e) { throw new IllegalArgumentException("Unable to interpret bytes as a valid image.", e); } } else { throw new IllegalArgumentException( "fromBytes should have exactly one argument, interpretTileOverlayOptions the bytes. Got: " + data.size()); } } private static boolean toBoolean(Object o) { return (Boolean) o; } static CameraPosition toCameraPosition(Object o) { final Map<?, ?> data = toMap(o); final CameraPosition.Builder builder = CameraPosition.builder(); builder.bearing(toFloat(data.get("bearing"))); builder.target(toLatLng(data.get("target"))); builder.tilt(toFloat(data.get("tilt"))); builder.zoom(toFloat(data.get("zoom"))); return builder.build(); } static CameraUpdate toCameraUpdate(Object o, float density) { final List<?> data = toList(o); switch (toString(data.get(0))) { case "newCameraPosition": return CameraUpdateFactory.newCameraPosition(toCameraPosition(data.get(1))); case "newLatLng": return CameraUpdateFactory.newLatLng(toLatLng(data.get(1))); case "newLatLngBounds": return CameraUpdateFactory.newLatLngBounds( toLatLngBounds(data.get(1)), toPixels(data.get(2), density)); case "newLatLngZoom": return CameraUpdateFactory.newLatLngZoom(toLatLng(data.get(1)), toFloat(data.get(2))); case "scrollBy": return CameraUpdateFactory.scrollBy( // toFractionalPixels(data.get(1), density), // toFractionalPixels(data.get(2), density)); case "zoomBy": if (data.size() == 2) { return CameraUpdateFactory.zoomBy(toFloat(data.get(1))); } else { return CameraUpdateFactory.zoomBy(toFloat(data.get(1)), toPoint(data.get(2), density)); } case "zoomIn": return CameraUpdateFactory.zoomIn(); case "zoomOut": return CameraUpdateFactory.zoomOut(); case "zoomTo": return CameraUpdateFactory.zoomTo(toFloat(data.get(1))); default: throw new IllegalArgumentException("Cannot interpret " + o + " as CameraUpdate"); } } private static double toDouble(Object o) { return ((Number) o).doubleValue(); } private static float toFloat(Object o) { return ((Number) o).floatValue(); } private static Float toFloatWrapper(Object o) { return (o == null) ? null : toFloat(o); } private static int toInt(Object o) { return ((Number) o).intValue(); } static Object cameraPositionToJson(CameraPosition position) { if (position == null) { return null; } final Map<String, Object> data = new HashMap<>(); data.put("bearing", position.bearing); data.put("target", latLngToJson(position.target)); data.put("tilt", position.tilt); data.put("zoom", position.zoom); return data; } static Object latlngBoundsToJson(LatLngBounds latLngBounds) { final Map<String, Object> arguments = new HashMap<>(2); arguments.put("southwest", latLngToJson(latLngBounds.southwest)); arguments.put("northeast", latLngToJson(latLngBounds.northeast)); return arguments; } static Object markerIdToJson(String markerId) { if (markerId == null) { return null; } final Map<String, Object> data = new HashMap<>(1); data.put("markerId", markerId); return data; } static Object polygonIdToJson(String polygonId) { if (polygonId == null) { return null; } final Map<String, Object> data = new HashMap<>(1); data.put("polygonId", polygonId); return data; } static Object polylineIdToJson(String polylineId) { if (polylineId == null) { return null; } final Map<String, Object> data = new HashMap<>(1); data.put("polylineId", polylineId); return data; } static Object circleIdToJson(String circleId) { if (circleId == null) { return null; } final Map<String, Object> data = new HashMap<>(1); data.put("circleId", circleId); return data; } static Map<String, Object> tileOverlayArgumentsToJson( String tileOverlayId, int x, int y, int zoom) { if (tileOverlayId == null) { return null; } final Map<String, Object> data = new HashMap<>(4); data.put("tileOverlayId", tileOverlayId); data.put("x", x); data.put("y", y); data.put("zoom", zoom); return data; } static Object latLngToJson(LatLng latLng) { return Arrays.asList(latLng.latitude, latLng.longitude); } static LatLng toLatLng(Object o) { final List<?> data = toList(o); return new LatLng(toDouble(data.get(0)), toDouble(data.get(1))); } static Point toPoint(Object o) { Object x = toMap(o).get("x"); Object y = toMap(o).get("y"); return new Point((int) x, (int) y); } static Map<String, Integer> pointToJson(Point point) { final Map<String, Integer> data = new HashMap<>(2); data.put("x", point.x); data.put("y", point.y); return data; } private static LatLngBounds toLatLngBounds(Object o) { if (o == null) { return null; } final List<?> data = toList(o); return new LatLngBounds(toLatLng(data.get(0)), toLatLng(data.get(1))); } private static List<?> toList(Object o) { return (List<?>) o; } private static Map<?, ?> toMap(Object o) { return (Map<?, ?>) o; } private static Map<String, Object> toObjectMap(Object o) { Map<String, Object> hashMap = new HashMap<>(); Map<?, ?> map = (Map<?, ?>) o; for (Object key : map.keySet()) { Object object = map.get(key); if (object != null) { hashMap.put((String) key, object); } } return hashMap; } private static float toFractionalPixels(Object o, float density) { return toFloat(o) * density; } private static int toPixels(Object o, float density) { return (int) toFractionalPixels(o, density); } private static Bitmap toBitmap(Object o) { byte[] bmpData = (byte[]) o; Bitmap bitmap = BitmapFactory.decodeByteArray(bmpData, 0, bmpData.length); if (bitmap == null) { throw new IllegalArgumentException("Unable to decode bytes as a valid bitmap."); } else { return bitmap; } } private static Point toPoint(Object o, float density) { final List<?> data = toList(o); return new Point(toPixels(data.get(0), density), toPixels(data.get(1), density)); } private static String toString(Object o) { return (String) o; } static void interpretGoogleMapOptions(Object o, GoogleMapOptionsSink sink) { final Map<?, ?> data = toMap(o); final Object cameraTargetBounds = data.get("cameraTargetBounds"); if (cameraTargetBounds != null) { final List<?> targetData = toList(cameraTargetBounds); sink.setCameraTargetBounds(toLatLngBounds(targetData.get(0))); } final Object compassEnabled = data.get("compassEnabled"); if (compassEnabled != null) { sink.setCompassEnabled(toBoolean(compassEnabled)); } final Object mapToolbarEnabled = data.get("mapToolbarEnabled"); if (mapToolbarEnabled != null) { sink.setMapToolbarEnabled(toBoolean(mapToolbarEnabled)); } final Object mapType = data.get("mapType"); if (mapType != null) { sink.setMapType(toInt(mapType)); } final Object minMaxZoomPreference = data.get("minMaxZoomPreference"); if (minMaxZoomPreference != null) { final List<?> zoomPreferenceData = toList(minMaxZoomPreference); sink.setMinMaxZoomPreference( // toFloatWrapper(zoomPreferenceData.get(0)), // toFloatWrapper(zoomPreferenceData.get(1))); } final Object padding = data.get("padding"); if (padding != null) { final List<?> paddingData = toList(padding); sink.setPadding( toFloat(paddingData.get(0)), toFloat(paddingData.get(1)), toFloat(paddingData.get(2)), toFloat(paddingData.get(3))); } final Object rotateGesturesEnabled = data.get("rotateGesturesEnabled"); if (rotateGesturesEnabled != null) { sink.setRotateGesturesEnabled(toBoolean(rotateGesturesEnabled)); } final Object scrollGesturesEnabled = data.get("scrollGesturesEnabled"); if (scrollGesturesEnabled != null) { sink.setScrollGesturesEnabled(toBoolean(scrollGesturesEnabled)); } final Object tiltGesturesEnabled = data.get("tiltGesturesEnabled"); if (tiltGesturesEnabled != null) { sink.setTiltGesturesEnabled(toBoolean(tiltGesturesEnabled)); } final Object trackCameraPosition = data.get("trackCameraPosition"); if (trackCameraPosition != null) { sink.setTrackCameraPosition(toBoolean(trackCameraPosition)); } final Object zoomGesturesEnabled = data.get("zoomGesturesEnabled"); if (zoomGesturesEnabled != null) { sink.setZoomGesturesEnabled(toBoolean(zoomGesturesEnabled)); } final Object liteModeEnabled = data.get("liteModeEnabled"); if (liteModeEnabled != null) { sink.setLiteModeEnabled(toBoolean(liteModeEnabled)); } final Object myLocationEnabled = data.get("myLocationEnabled"); if (myLocationEnabled != null) { sink.setMyLocationEnabled(toBoolean(myLocationEnabled)); } final Object zoomControlsEnabled = data.get("zoomControlsEnabled"); if (zoomControlsEnabled != null) { sink.setZoomControlsEnabled(toBoolean(zoomControlsEnabled)); } final Object myLocationButtonEnabled = data.get("myLocationButtonEnabled"); if (myLocationButtonEnabled != null) { sink.setMyLocationButtonEnabled(toBoolean(myLocationButtonEnabled)); } final Object indoorEnabled = data.get("indoorEnabled"); if (indoorEnabled != null) { sink.setIndoorEnabled(toBoolean(indoorEnabled)); } final Object trafficEnabled = data.get("trafficEnabled"); if (trafficEnabled != null) { sink.setTrafficEnabled(toBoolean(trafficEnabled)); } final Object buildingsEnabled = data.get("buildingsEnabled"); if (buildingsEnabled != null) { sink.setBuildingsEnabled(toBoolean(buildingsEnabled)); } final Object style = data.get("style"); if (style != null) { sink.setMapStyle(toString(style)); } } /** Returns the dartMarkerId of the interpreted marker. */ static String interpretMarkerOptions(Object o, MarkerOptionsSink sink) { final Map<?, ?> data = toMap(o); final Object alpha = data.get("alpha"); if (alpha != null) { sink.setAlpha(toFloat(alpha)); } final Object anchor = data.get("anchor"); if (anchor != null) { final List<?> anchorData = toList(anchor); sink.setAnchor(toFloat(anchorData.get(0)), toFloat(anchorData.get(1))); } final Object consumeTapEvents = data.get("consumeTapEvents"); if (consumeTapEvents != null) { sink.setConsumeTapEvents(toBoolean(consumeTapEvents)); } final Object draggable = data.get("draggable"); if (draggable != null) { sink.setDraggable(toBoolean(draggable)); } final Object flat = data.get("flat"); if (flat != null) { sink.setFlat(toBoolean(flat)); } final Object icon = data.get("icon"); if (icon != null) { sink.setIcon(toBitmapDescriptor(icon)); } final Object infoWindow = data.get("infoWindow"); if (infoWindow != null) { interpretInfoWindowOptions(sink, toObjectMap(infoWindow)); } final Object position = data.get("position"); if (position != null) { sink.setPosition(toLatLng(position)); } final Object rotation = data.get("rotation"); if (rotation != null) { sink.setRotation(toFloat(rotation)); } final Object visible = data.get("visible"); if (visible != null) { sink.setVisible(toBoolean(visible)); } final Object zIndex = data.get("zIndex"); if (zIndex != null) { sink.setZIndex(toFloat(zIndex)); } final String markerId = (String) data.get("markerId"); if (markerId == null) { throw new IllegalArgumentException("markerId was null"); } else { return markerId; } } private static void interpretInfoWindowOptions( MarkerOptionsSink sink, Map<String, Object> infoWindow) { String title = (String) infoWindow.get("title"); String snippet = (String) infoWindow.get("snippet"); // snippet is nullable. if (title != null) { sink.setInfoWindowText(title, snippet); } Object infoWindowAnchor = infoWindow.get("anchor"); if (infoWindowAnchor != null) { final List<?> anchorData = toList(infoWindowAnchor); sink.setInfoWindowAnchor(toFloat(anchorData.get(0)), toFloat(anchorData.get(1))); } } static String interpretPolygonOptions(Object o, PolygonOptionsSink sink) { final Map<?, ?> data = toMap(o); final Object consumeTapEvents = data.get("consumeTapEvents"); if (consumeTapEvents != null) { sink.setConsumeTapEvents(toBoolean(consumeTapEvents)); } final Object geodesic = data.get("geodesic"); if (geodesic != null) { sink.setGeodesic(toBoolean(geodesic)); } final Object visible = data.get("visible"); if (visible != null) { sink.setVisible(toBoolean(visible)); } final Object fillColor = data.get("fillColor"); if (fillColor != null) { sink.setFillColor(toInt(fillColor)); } final Object strokeColor = data.get("strokeColor"); if (strokeColor != null) { sink.setStrokeColor(toInt(strokeColor)); } final Object strokeWidth = data.get("strokeWidth"); if (strokeWidth != null) { sink.setStrokeWidth(toInt(strokeWidth)); } final Object zIndex = data.get("zIndex"); if (zIndex != null) { sink.setZIndex(toFloat(zIndex)); } final Object points = data.get("points"); if (points != null) { sink.setPoints(toPoints(points)); } final Object holes = data.get("holes"); if (holes != null) { sink.setHoles(toHoles(holes)); } final String polygonId = (String) data.get("polygonId"); if (polygonId == null) { throw new IllegalArgumentException("polygonId was null"); } else { return polygonId; } } static String interpretPolylineOptions(Object o, PolylineOptionsSink sink) { final Map<?, ?> data = toMap(o); final Object consumeTapEvents = data.get("consumeTapEvents"); if (consumeTapEvents != null) { sink.setConsumeTapEvents(toBoolean(consumeTapEvents)); } final Object color = data.get("color"); if (color != null) { sink.setColor(toInt(color)); } final Object endCap = data.get("endCap"); if (endCap != null) { sink.setEndCap(toCap(endCap)); } final Object geodesic = data.get("geodesic"); if (geodesic != null) { sink.setGeodesic(toBoolean(geodesic)); } final Object jointType = data.get("jointType"); if (jointType != null) { sink.setJointType(toInt(jointType)); } final Object startCap = data.get("startCap"); if (startCap != null) { sink.setStartCap(toCap(startCap)); } final Object visible = data.get("visible"); if (visible != null) { sink.setVisible(toBoolean(visible)); } final Object width = data.get("width"); if (width != null) { sink.setWidth(toInt(width)); } final Object zIndex = data.get("zIndex"); if (zIndex != null) { sink.setZIndex(toFloat(zIndex)); } final Object points = data.get("points"); if (points != null) { sink.setPoints(toPoints(points)); } final Object pattern = data.get("pattern"); if (pattern != null) { sink.setPattern(toPattern(pattern)); } final String polylineId = (String) data.get("polylineId"); if (polylineId == null) { throw new IllegalArgumentException("polylineId was null"); } else { return polylineId; } } static String interpretCircleOptions(Object o, CircleOptionsSink sink) { final Map<?, ?> data = toMap(o); final Object consumeTapEvents = data.get("consumeTapEvents"); if (consumeTapEvents != null) { sink.setConsumeTapEvents(toBoolean(consumeTapEvents)); } final Object fillColor = data.get("fillColor"); if (fillColor != null) { sink.setFillColor(toInt(fillColor)); } final Object strokeColor = data.get("strokeColor"); if (strokeColor != null) { sink.setStrokeColor(toInt(strokeColor)); } final Object visible = data.get("visible"); if (visible != null) { sink.setVisible(toBoolean(visible)); } final Object strokeWidth = data.get("strokeWidth"); if (strokeWidth != null) { sink.setStrokeWidth(toInt(strokeWidth)); } final Object zIndex = data.get("zIndex"); if (zIndex != null) { sink.setZIndex(toFloat(zIndex)); } final Object center = data.get("center"); if (center != null) { sink.setCenter(toLatLng(center)); } final Object radius = data.get("radius"); if (radius != null) { sink.setRadius(toDouble(radius)); } final String circleId = (String) data.get("circleId"); if (circleId == null) { throw new IllegalArgumentException("circleId was null"); } else { return circleId; } } @VisibleForTesting static List<LatLng> toPoints(Object o) { final List<?> data = toList(o); final List<LatLng> points = new ArrayList<>(data.size()); for (Object rawPoint : data) { final List<?> point = toList(rawPoint); points.add(new LatLng(toDouble(point.get(0)), toDouble(point.get(1)))); } return points; } private static List<List<LatLng>> toHoles(Object o) { final List<?> data = toList(o); final List<List<LatLng>> holes = new ArrayList<>(data.size()); for (Object rawHole : data) { holes.add(toPoints(rawHole)); } return holes; } private static List<PatternItem> toPattern(Object o) { final List<?> data = toList(o); if (data.isEmpty()) { return null; } final List<PatternItem> pattern = new ArrayList<>(data.size()); for (Object ob : data) { final List<?> patternItem = toList(ob); switch (toString(patternItem.get(0))) { case "dot": pattern.add(new Dot()); break; case "dash": pattern.add(new Dash(toFloat(patternItem.get(1)))); break; case "gap": pattern.add(new Gap(toFloat(patternItem.get(1)))); break; default: throw new IllegalArgumentException("Cannot interpret " + pattern + " as PatternItem"); } } return pattern; } private static Cap toCap(Object o) { final List<?> data = toList(o); switch (toString(data.get(0))) { case "buttCap": return new ButtCap(); case "roundCap": return new RoundCap(); case "squareCap": return new SquareCap(); case "customCap": if (data.size() == 2) { return new CustomCap(toBitmapDescriptor(data.get(1))); } else { return new CustomCap(toBitmapDescriptor(data.get(1)), toFloat(data.get(2))); } default: throw new IllegalArgumentException("Cannot interpret " + o + " as Cap"); } } static String interpretTileOverlayOptions(Map<String, ?> data, TileOverlaySink sink) { final Object fadeIn = data.get("fadeIn"); if (fadeIn != null) { sink.setFadeIn(toBoolean(fadeIn)); } final Object transparency = data.get("transparency"); if (transparency != null) { sink.setTransparency(toFloat(transparency)); } final Object zIndex = data.get("zIndex"); if (zIndex != null) { sink.setZIndex(toFloat(zIndex)); } final Object visible = data.get("visible"); if (visible != null) { sink.setVisible(toBoolean(visible)); } final String tileOverlayId = (String) data.get("tileOverlayId"); if (tileOverlayId == null) { throw new IllegalArgumentException("tileOverlayId was null"); } else { return tileOverlayId; } } static Tile interpretTile(Map<String, ?> data) { int width = toInt(data.get("width")); int height = toInt(data.get("height")); byte[] dataArray = null; if (data.get("data") != null) { dataArray = (byte[]) data.get("data"); } return new Tile(width, height, dataArray); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/Convert.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/Convert.java", "repo_id": "packages", "token_count": 9199 }
1,014
// 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.googlemaps; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import io.flutter.plugin.common.MethodChannel; import java.util.HashMap; import java.util.List; import java.util.Map; class PolygonsController { private final Map<String, PolygonController> polygonIdToController; private final Map<String, String> googleMapsPolygonIdToDartPolygonId; private final MethodChannel methodChannel; private final float density; private GoogleMap googleMap; PolygonsController(MethodChannel methodChannel, float density) { this.polygonIdToController = new HashMap<>(); this.googleMapsPolygonIdToDartPolygonId = new HashMap<>(); this.methodChannel = methodChannel; this.density = density; } void setGoogleMap(GoogleMap googleMap) { this.googleMap = googleMap; } void addPolygons(List<Object> polygonsToAdd) { if (polygonsToAdd != null) { for (Object polygonToAdd : polygonsToAdd) { addPolygon(polygonToAdd); } } } void changePolygons(List<Object> polygonsToChange) { if (polygonsToChange != null) { for (Object polygonToChange : polygonsToChange) { changePolygon(polygonToChange); } } } void removePolygons(List<Object> polygonIdsToRemove) { if (polygonIdsToRemove == null) { return; } for (Object rawPolygonId : polygonIdsToRemove) { if (rawPolygonId == null) { continue; } String polygonId = (String) rawPolygonId; final PolygonController polygonController = polygonIdToController.remove(polygonId); if (polygonController != null) { polygonController.remove(); googleMapsPolygonIdToDartPolygonId.remove(polygonController.getGoogleMapsPolygonId()); } } } boolean onPolygonTap(String googlePolygonId) { String polygonId = googleMapsPolygonIdToDartPolygonId.get(googlePolygonId); if (polygonId == null) { return false; } methodChannel.invokeMethod("polygon#onTap", Convert.polygonIdToJson(polygonId)); PolygonController polygonController = polygonIdToController.get(polygonId); if (polygonController != null) { return polygonController.consumeTapEvents(); } return false; } private void addPolygon(Object polygon) { if (polygon == null) { return; } PolygonBuilder polygonBuilder = new PolygonBuilder(density); String polygonId = Convert.interpretPolygonOptions(polygon, polygonBuilder); PolygonOptions options = polygonBuilder.build(); addPolygon(polygonId, options, polygonBuilder.consumeTapEvents()); } private void addPolygon( String polygonId, PolygonOptions polygonOptions, boolean consumeTapEvents) { final Polygon polygon = googleMap.addPolygon(polygonOptions); PolygonController controller = new PolygonController(polygon, consumeTapEvents, density); polygonIdToController.put(polygonId, controller); googleMapsPolygonIdToDartPolygonId.put(polygon.getId(), polygonId); } private void changePolygon(Object polygon) { if (polygon == null) { return; } String polygonId = getPolygonId(polygon); PolygonController polygonController = polygonIdToController.get(polygonId); if (polygonController != null) { Convert.interpretPolygonOptions(polygon, polygonController); } } @SuppressWarnings("unchecked") private static String getPolygonId(Object polygon) { Map<String, Object> polygonMap = (Map<String, Object>) polygon; return (String) polygonMap.get("polygonId"); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonsController.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonsController.java", "repo_id": "packages", "token_count": 1328 }
1,015
// 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.googlemaps; import static junit.framework.TestCase.assertEquals; import com.google.android.gms.maps.model.PolygonOptions; import org.junit.Test; public class PolygonBuilderTest { @Test public void density_AppliesToStrokeWidth() { final float density = 5; final float strokeWidth = 3; final PolygonBuilder builder = new PolygonBuilder(density); builder.setStrokeWidth(strokeWidth); final PolygonOptions options = builder.build(); final float width = options.getStrokeWidth(); assertEquals(density * strokeWidth, width); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolygonBuilderTest.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolygonBuilderTest.java", "repo_id": "packages", "token_count": 230 }
1,016
// 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 <GoogleMaps/GoogleMaps.h> // Defines polyline controllable by Flutter. @interface FLTGoogleMapPolylineController : NSObject - (instancetype)initPolylineWithPath:(GMSMutablePath *)path identifier:(NSString *)identifier mapView:(GMSMapView *)mapView; - (void)removePolyline; @end @interface FLTPolylinesController : NSObject - (instancetype)init:(FlutterMethodChannel *)methodChannel mapView:(GMSMapView *)mapView registrar:(NSObject<FlutterPluginRegistrar> *)registrar; - (void)addPolylines:(NSArray *)polylinesToAdd; - (void)changePolylines:(NSArray *)polylinesToChange; - (void)removePolylineWithIdentifiers:(NSArray *)identifiers; - (void)didTapPolylineWithIdentifier:(NSString *)identifier; - (bool)hasPolylineWithIdentifier:(NSString *)identifier; @end
packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolylineController.h/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolylineController.h", "repo_id": "packages", "token_count": 372 }
1,017
// 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 '../../google_maps_flutter_platform_interface.dart'; /// Generic Event coming from the native side of Maps. /// /// All MapEvents contain the `mapId` that originated the event. This should /// never be `null`. /// /// The `<T>` on this event represents the type of the `value` that is /// contained within the event. /// /// This class is used as a base class for all the events that might be /// triggered from a Map, but it is never used directly as an event type. /// /// Do NOT instantiate new events like `MapEvent<ValueType>(mapId, val)` directly, /// use a specific class instead: /// /// Do `class NewEvent extend MapEvent<ValueType>` when creating your own events. /// See below for examples: `CameraMoveStartedEvent`, `MarkerDragEndEvent`... /// These events are more semantic and pleasant to use than raw generics. They /// can be (and in fact, are) filtered by the `instanceof`-operator. /// /// (See [MethodChannelGoogleMapsFlutter.onCameraMoveStarted], for example) /// /// If your event needs a `position`, alongside the `value`, do /// `extends _PositionedMapEvent<ValueType>` instead. This adds a `LatLng position` /// attribute. /// /// If your event *only* needs a `position`, do `extend _PositionedMapEvent<void>` /// do NOT `extend MapEvent<LatLng>`. The former lets consumers of these /// events to access the `.position` property, rather than the more generic `.value` /// yielded from the latter. class MapEvent<T> { /// Build a Map Event, that relates a mapId with a given value. /// /// The `mapId` is the id of the map that triggered the event. /// `value` may be `null` in events that don't transport any meaningful data. MapEvent(this.mapId, this.value); /// The ID of the Map this event is associated to. final int mapId; /// The value wrapped by this event final T value; } /// A `MapEvent` associated to a `position`. class _PositionedMapEvent<T> extends MapEvent<T> { /// Build a Positioned MapEvent, that relates a mapId and a position with a value. /// /// The `mapId` is the id of the map that triggered the event. /// `value` may be `null` in events that don't transport any meaningful data. _PositionedMapEvent(int mapId, this.position, T value) : super(mapId, value); /// The position where this event happened. final LatLng position; } // The following events are the ones exposed to the end user. They are semantic extensions // of the two base classes above. // // These events are used to create the appropriate [Stream] objects, with information // coming from the native side. /// An event fired when the Camera of a [mapId] starts moving. class CameraMoveStartedEvent extends MapEvent<void> { /// Build a CameraMoveStarted Event triggered from the map represented by `mapId`. CameraMoveStartedEvent(int mapId) : super(mapId, null); } /// An event fired while the Camera of a [mapId] moves. class CameraMoveEvent extends MapEvent<CameraPosition> { /// Build a CameraMove Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [CameraPosition] object with the current position of the Camera. CameraMoveEvent(super.mapId, super.position); } /// An event fired when the Camera of a [mapId] becomes idle. class CameraIdleEvent extends MapEvent<void> { /// Build a CameraIdle Event triggered from the map represented by `mapId`. CameraIdleEvent(int mapId) : super(mapId, null); } /// An event fired when a [Marker] is tapped. class MarkerTapEvent extends MapEvent<MarkerId> { /// Build a MarkerTap Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [MarkerId] object that represents the tapped Marker. MarkerTapEvent(super.mapId, super.markerId); } /// An event fired when an [InfoWindow] is tapped. class InfoWindowTapEvent extends MapEvent<MarkerId> { /// Build an InfoWindowTap Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [MarkerId] object that represents the tapped InfoWindow. InfoWindowTapEvent(super.mapId, super.markerId); } /// An event fired when a [Marker] is starting to be dragged to a new [LatLng]. class MarkerDragStartEvent extends _PositionedMapEvent<MarkerId> { /// Build a MarkerDragStart Event triggered from the map represented by `mapId`. /// /// The `position` on this event is the [LatLng] on which the Marker was picked up from. /// The `value` of this event is a [MarkerId] object that represents the Marker. MarkerDragStartEvent(super.mapId, super.position, super.markerId); } /// An event fired when a [Marker] is being dragged to a new [LatLng]. class MarkerDragEvent extends _PositionedMapEvent<MarkerId> { /// Build a MarkerDrag Event triggered from the map represented by `mapId`. /// /// The `position` on this event is the [LatLng] on which the Marker was dragged to. /// The `value` of this event is a [MarkerId] object that represents the Marker. MarkerDragEvent(super.mapId, super.position, super.markerId); } /// An event fired when a [Marker] is dragged to a new [LatLng]. class MarkerDragEndEvent extends _PositionedMapEvent<MarkerId> { /// Build a MarkerDragEnd Event triggered from the map represented by `mapId`. /// /// The `position` on this event is the [LatLng] on which the Marker was dropped. /// The `value` of this event is a [MarkerId] object that represents the moved Marker. MarkerDragEndEvent(super.mapId, super.position, super.markerId); } /// An event fired when a [Polyline] is tapped. class PolylineTapEvent extends MapEvent<PolylineId> { /// Build an PolylineTap Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [PolylineId] object that represents the tapped Polyline. PolylineTapEvent(super.mapId, super.polylineId); } /// An event fired when a [Polygon] is tapped. class PolygonTapEvent extends MapEvent<PolygonId> { /// Build an PolygonTap Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [PolygonId] object that represents the tapped Polygon. PolygonTapEvent(super.mapId, super.polygonId); } /// An event fired when a [Circle] is tapped. class CircleTapEvent extends MapEvent<CircleId> { /// Build an CircleTap Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [CircleId] object that represents the tapped Circle. CircleTapEvent(super.mapId, super.circleId); } /// An event fired when a Map is tapped. class MapTapEvent extends _PositionedMapEvent<void> { /// Build an MapTap Event triggered from the map represented by `mapId`. /// /// The `position` of this event is the LatLng where the Map was tapped. MapTapEvent(int mapId, LatLng position) : super(mapId, position, null); } /// An event fired when a Map is long pressed. class MapLongPressEvent extends _PositionedMapEvent<void> { /// Build an MapTap Event triggered from the map represented by `mapId`. /// /// The `position` of this event is the LatLng where the Map was long pressed. MapLongPressEvent(int mapId, LatLng position) : super(mapId, position, null); } /// An event fired when a cluster icon managed by [ClusterManager] is tapped. class ClusterTapEvent extends MapEvent<Cluster> { /// Build a ClusterTapEvent Event triggered from the map represented by `mapId`. /// /// The `value` of this event is a [Cluster] object that represents the tapped /// cluster icon managed by [ClusterManager]. ClusterTapEvent(super.mapId, super.cluster); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/events/map_event.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/events/map_event.dart", "repo_id": "packages", "token_count": 2191 }
1,018
// 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 import 'package:flutter/foundation.dart'; import 'types.dart'; /// A container object for all the types of maps objects. /// /// This is intended for use as a parameter in platform interface methods, to /// allow adding new object types to existing methods. @immutable class MapObjects { /// Creates a new set of map objects with all the given object types. const MapObjects({ this.markers = const <Marker>{}, this.polygons = const <Polygon>{}, this.polylines = const <Polyline>{}, this.circles = const <Circle>{}, this.tileOverlays = const <TileOverlay>{}, this.clusterManagers = const <ClusterManager>{}, }); final Set<Marker> markers; final Set<Polygon> polygons; final Set<Polyline> polylines; final Set<Circle> circles; final Set<TileOverlay> tileOverlays; final Set<ClusterManager> clusterManagers; }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_objects.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_objects.dart", "repo_id": "packages", "token_count": 336 }
1,019
// 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. // All the public types exposed by this package. export 'bitmap.dart'; export 'callbacks.dart'; export 'camera.dart'; export 'cap.dart'; export 'circle.dart'; export 'circle_updates.dart'; export 'cluster.dart'; export 'cluster_manager.dart'; export 'cluster_manager_updates.dart'; export 'joint_type.dart'; export 'location.dart'; export 'map_configuration.dart'; export 'map_objects.dart'; export 'map_widget_configuration.dart'; export 'maps_object.dart'; export 'maps_object_updates.dart'; export 'marker.dart'; export 'marker_updates.dart'; export 'pattern_item.dart'; export 'polygon.dart'; export 'polygon_updates.dart'; export 'polyline.dart'; export 'polyline_updates.dart'; export 'screen_coordinate.dart'; export 'tile.dart'; export 'tile_overlay.dart'; export 'tile_provider.dart'; export 'ui.dart'; // Export the utils used by the Widget export 'utils/circle.dart'; export 'utils/cluster_manager.dart'; export 'utils/marker.dart'; export 'utils/polygon.dart'; export 'utils/polyline.dart'; export 'utils/tile_overlay.dart'; export 'web_gesture_handling.dart';
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/types.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/types.dart", "repo_id": "packages", "token_count": 432 }
1,020
// 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_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('toMap / fromMap', () { const CameraPosition cameraPosition = CameraPosition( target: LatLng(10.0, 15.0), bearing: 0.5, tilt: 30.0, zoom: 1.5); // Cast to <dynamic, dynamic> to ensure that recreating from JSON, where // type information will have likely been lost, still works. final Map<dynamic, dynamic> json = (cameraPosition.toMap() as Map<String, dynamic>) .cast<dynamic, dynamic>(); final CameraPosition? cameraPositionFromJson = CameraPosition.fromMap(json); expect(cameraPosition, cameraPositionFromJson); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/camera_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/camera_test.dart", "repo_id": "packages", "token_count": 313 }
1,021
name: google_sign_in description: Flutter plugin for Google Sign-In, a secure authentication system for signing in with a Google account. repository: https://github.com/flutter/packages/tree/main/packages/google_sign_in/google_sign_in issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22 version: 6.2.1 environment: sdk: ">=3.2.0 <4.0.0" flutter: ">=3.16.0" flutter: plugin: platforms: android: default_package: google_sign_in_android ios: default_package: google_sign_in_ios macos: default_package: google_sign_in_ios web: default_package: google_sign_in_web dependencies: flutter: sdk: flutter google_sign_in_android: ^6.1.0 google_sign_in_ios: ^5.7.0 google_sign_in_platform_interface: ^2.4.0 google_sign_in_web: ^0.12.0 dev_dependencies: build_runner: ^2.1.10 flutter_test: sdk: flutter http: ">=0.13.0 <2.0.0" integration_test: sdk: flutter mockito: 5.4.4 topics: - authentication - google-sign-in # The example deliberately includes limited-use secrets. false_secrets: - /example/android/app/google-services.json - /example/ios/Runner/Info.plist - /example/ios/RunnerTests/GoogleService-Info.plist - /example/ios/RunnerTests/GoogleSignInTests.m - /example/macos/Runner/Info.plist
packages/packages/google_sign_in/google_sign_in/pubspec.yaml/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/pubspec.yaml", "repo_id": "packages", "token_count": 571 }
1,022
// 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.googlesignin; import android.accounts.Account; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.tasks.RuntimeExecutionException; import com.google.android.gms.tasks.Task; import com.google.common.base.Joiner; import com.google.common.base.Strings; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugins.googlesignin.Messages.FlutterError; import io.flutter.plugins.googlesignin.Messages.GoogleSignInApi; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; /** Google sign-in plugin for Flutter. */ public class GoogleSignInPlugin implements FlutterPlugin, ActivityAware { private Delegate delegate; private @Nullable BinaryMessenger messenger; private ActivityPluginBinding activityPluginBinding; @SuppressWarnings("deprecation") public static void registerWith( @NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) { GoogleSignInPlugin instance = new GoogleSignInPlugin(); instance.initInstance(registrar.messenger(), registrar.context(), new GoogleSignInWrapper()); instance.setUpRegistrar(registrar); } @VisibleForTesting public void initInstance( @NonNull BinaryMessenger messenger, @NonNull Context context, @NonNull GoogleSignInWrapper googleSignInWrapper) { this.messenger = messenger; delegate = new Delegate(context, googleSignInWrapper); GoogleSignInApi.setup(messenger, delegate); } @VisibleForTesting @SuppressWarnings("deprecation") public void setUpRegistrar(@NonNull PluginRegistry.Registrar registrar) { delegate.setUpRegistrar(registrar); } private void dispose() { delegate = null; if (messenger != null) { GoogleSignInApi.setup(messenger, null); messenger = null; } } private void attachToActivity(ActivityPluginBinding activityPluginBinding) { this.activityPluginBinding = activityPluginBinding; activityPluginBinding.addActivityResultListener(delegate); delegate.setActivity(activityPluginBinding.getActivity()); } private void disposeActivity() { activityPluginBinding.removeActivityResultListener(delegate); delegate.setActivity(null); activityPluginBinding = null; } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { initInstance( binding.getBinaryMessenger(), binding.getApplicationContext(), new GoogleSignInWrapper()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { dispose(); } @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) { attachToActivity(activityPluginBinding); } @Override public void onDetachedFromActivityForConfigChanges() { disposeActivity(); } @Override public void onReattachedToActivityForConfigChanges( @NonNull ActivityPluginBinding activityPluginBinding) { attachToActivity(activityPluginBinding); } @Override public void onDetachedFromActivity() { disposeActivity(); } // TODO(stuartmorgan): Remove this, and convert the unit tests to IDelegate tests. This is left // here only to allow the existing tests to continue to work unchanged during the Pigeon migration // to ensure that the refactoring didn't change any behavior, and is not actually used by the // plugin. @VisibleForTesting void onMethodCall( @NonNull io.flutter.plugin.common.MethodCall call, @NonNull MethodChannel.Result result) { switch (call.method) { case "init": String signInOption = Objects.requireNonNull(call.argument("signInOption")); List<String> requestedScopes = Objects.requireNonNull(call.argument("scopes")); String hostedDomain = call.argument("hostedDomain"); String clientId = call.argument("clientId"); String serverClientId = call.argument("serverClientId"); boolean forceCodeForRefreshToken = Objects.requireNonNull(call.argument("forceCodeForRefreshToken")); delegate.init( result, signInOption, requestedScopes, hostedDomain, clientId, serverClientId, forceCodeForRefreshToken); break; case "signInSilently": delegate.signInSilently(result); break; case "signIn": delegate.signIn(result); break; case "getTokens": String email = Objects.requireNonNull(call.argument("email")); boolean shouldRecoverAuth = Objects.requireNonNull(call.argument("shouldRecoverAuth")); delegate.getTokens(result, email, shouldRecoverAuth); break; case "signOut": delegate.signOut(result); break; case "clearAuthCache": String token = Objects.requireNonNull(call.argument("token")); delegate.clearAuthCache(result, token); break; case "disconnect": delegate.disconnect(result); break; case "isSignedIn": delegate.isSignedIn(result); break; case "requestScopes": List<String> scopes = Objects.requireNonNull(call.argument("scopes")); delegate.requestScopes(result, scopes); break; default: result.notImplemented(); } } /** * A delegate interface that exposes all of the sign-in functionality for other plugins to use. * The below {@link Delegate} implementation should be used by any clients unless they need to * override some of these functions, such as for testing. */ public interface IDelegate { /** Initializes this delegate so that it is ready to perform other operations. */ void init( @NonNull MethodChannel.Result result, @NonNull String signInOption, @NonNull List<String> requestedScopes, @Nullable String hostedDomain, @Nullable String clientId, @Nullable String serverClientId, boolean forceCodeForRefreshToken); /** * Returns the account information for the user who is signed in to this app. If no user is * signed in, tries to sign the user in without displaying any user interface. */ void signInSilently(@NonNull MethodChannel.Result result); /** * Signs the user in via the sign-in user interface, including the OAuth consent flow if scopes * were requested. */ void signIn(@NonNull MethodChannel.Result result); /** * Gets an OAuth access token with the scopes that were specified during initialization for the * user with the specified email address. * * <p>If shouldRecoverAuth is set to true and user needs to recover authentication for method to * complete, the method will attempt to recover authentication and rerun method. */ void getTokens( final @NonNull MethodChannel.Result result, final @NonNull String email, final boolean shouldRecoverAuth); /** * Clears the token from any client cache forcing the next {@link #getTokens} call to fetch a * new one. */ void clearAuthCache(final @NonNull MethodChannel.Result result, final @NonNull String token); /** * Signs the user out. Their credentials may remain valid, meaning they'll be able to silently * sign back in. */ void signOut(@NonNull MethodChannel.Result result); /** Signs the user out, and revokes their credentials. */ void disconnect(@NonNull MethodChannel.Result result); /** Checks if there is a signed in user. */ void isSignedIn(@NonNull MethodChannel.Result result); /** Prompts the user to grant an additional Oauth scopes. */ void requestScopes( final @NonNull MethodChannel.Result result, final @NonNull List<String> scopes); } /** * Helper class for supporting the legacy IDelegate interface based on raw method channels, which * handles converting any FlutterErrors (or other {@code Throwable}s in case any non- FlutterError * exceptions slip through) thrown by the new code paths into {@code error} callbacks. * * @param <T> The Result type of the result to convert from. */ private abstract static class ErrorConvertingMethodChannelResult<T> implements Messages.Result<T> { final @NonNull MethodChannel.Result result; public ErrorConvertingMethodChannelResult(@NonNull MethodChannel.Result result) { this.result = result; } @Override public void error(@NonNull Throwable error) { if (error instanceof FlutterError) { FlutterError flutterError = (FlutterError) error; result.error(flutterError.code, flutterError.getMessage(), flutterError.details); } else { result.error("exception", error.getMessage(), null); } } } /** * Helper class for supporting the legacy IDelegate interface based on raw method channels, which * handles converting responses from methods that return {@code Messages.UserData}. */ private static class UserDataMethodChannelResult extends ErrorConvertingMethodChannelResult<Messages.UserData> { public UserDataMethodChannelResult(MethodChannel.Result result) { super(result); } @Override public void success(Messages.UserData data) { Map<String, Object> response = new HashMap<>(); response.put("email", data.getEmail()); response.put("id", data.getId()); response.put("idToken", data.getIdToken()); response.put("serverAuthCode", data.getServerAuthCode()); response.put("displayName", data.getDisplayName()); if (data.getPhotoUrl() != null) { response.put("photoUrl", data.getPhotoUrl()); } result.success(response); } } /** * Helper class for supporting the legacy IDelegate interface based on raw method channels, which * handles converting responses from methods that return {@code Void}. */ private static class VoidMethodChannelResult extends ErrorConvertingMethodChannelResult<Void> { public VoidMethodChannelResult(MethodChannel.Result result) { super(result); } @Override public void success(Void unused) { result.success(null); } } /** * Delegate class that does the work for the Google sign-in plugin. This is exposed as a dedicated * class for use in other plugins that wrap basic sign-in functionality. * * <p>All methods in this class assume that they are run to completion before any other method is * invoked. In this context, "run to completion" means that their {@link MethodChannel.Result} * argument has been completed (either successfully or in error). This class provides no * synchronization constructs to guarantee such behavior; callers are responsible for providing * such guarantees. */ // TODO(stuartmorgan): Remove this in a breaking change, replacing it with something using // structured types rather than strings and dictionaries left over from the pre-Pigeon method // channel implementation. public static class Delegate implements IDelegate, PluginRegistry.ActivityResultListener, GoogleSignInApi { private static final int REQUEST_CODE_SIGNIN = 53293; private static final int REQUEST_CODE_RECOVER_AUTH = 53294; @VisibleForTesting static final int REQUEST_CODE_REQUEST_SCOPE = 53295; private static final String ERROR_REASON_EXCEPTION = "exception"; private static final String ERROR_REASON_STATUS = "status"; // These error codes must match with ones declared on iOS and Dart sides. private static final String ERROR_REASON_SIGN_IN_CANCELED = "sign_in_canceled"; private static final String ERROR_REASON_SIGN_IN_REQUIRED = "sign_in_required"; private static final String ERROR_REASON_NETWORK_ERROR = "network_error"; private static final String ERROR_REASON_SIGN_IN_FAILED = "sign_in_failed"; private static final String ERROR_FAILURE_TO_RECOVER_AUTH = "failed_to_recover_auth"; private static final String ERROR_USER_RECOVERABLE_AUTH = "user_recoverable_auth"; private static final String DEFAULT_SIGN_IN = "SignInOption.standard"; private static final String DEFAULT_GAMES_SIGN_IN = "SignInOption.games"; private final @NonNull Context context; // Only set registrar for v1 embedder. @SuppressWarnings("deprecation") private PluginRegistry.Registrar registrar; // Only set activity for v2 embedder. Always access activity from getActivity() method. private @Nullable Activity activity; // TODO(stuartmorgan): See whether this can be replaced with background channels. private final BackgroundTaskRunner backgroundTaskRunner = new BackgroundTaskRunner(1); private final GoogleSignInWrapper googleSignInWrapper; private GoogleSignInClient signInClient; private List<String> requestedScopes; private PendingOperation pendingOperation; public Delegate(@NonNull Context context, @NonNull GoogleSignInWrapper googleSignInWrapper) { this.context = context; this.googleSignInWrapper = googleSignInWrapper; } @SuppressWarnings("deprecation") public void setUpRegistrar(@NonNull PluginRegistry.Registrar registrar) { this.registrar = registrar; registrar.addActivityResultListener(this); } public void setActivity(@Nullable Activity activity) { this.activity = activity; } // Only access activity with this method. public @Nullable Activity getActivity() { return registrar != null ? registrar.activity() : activity; } private void checkAndSetPendingOperation( String method, Messages.Result<Messages.UserData> userDataResult, Messages.Result<Void> voidResult, Messages.Result<Boolean> boolResult, Messages.Result<String> stringResult, Object data) { if (pendingOperation != null) { throw new IllegalStateException( "Concurrent operations detected: " + pendingOperation.method + ", " + method); } pendingOperation = new PendingOperation(method, userDataResult, voidResult, boolResult, stringResult, data); } private void checkAndSetPendingSignInOperation( String method, @NonNull Messages.Result<Messages.UserData> result) { checkAndSetPendingOperation(method, result, null, null, null, null); } private void checkAndSetPendingVoidOperation( String method, @NonNull Messages.Result<Void> result) { checkAndSetPendingOperation(method, null, result, null, null, null); } private void checkAndSetPendingBoolOperation( String method, @NonNull Messages.Result<Boolean> result) { checkAndSetPendingOperation(method, null, null, result, null, null); } private void checkAndSetPendingStringOperation( String method, @NonNull Messages.Result<String> result, @Nullable Object data) { checkAndSetPendingOperation(method, null, null, null, result, data); } private void checkAndSetPendingAccessTokenOperation( String method, Messages.Result<String> result, @NonNull Object data) { checkAndSetPendingStringOperation(method, result, data); } /** * Initializes this delegate so that it is ready to perform other operations. The Dart code * guarantees that this will be called and completed before any other methods are invoked. */ @Override public void init(@NonNull Messages.InitParams params) { try { GoogleSignInOptions.Builder optionsBuilder; switch (params.getSignInType()) { case GAMES: optionsBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); break; case STANDARD: optionsBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail(); break; default: throw new IllegalStateException("Unknown signInOption"); } // The clientId parameter is not supported on Android. // Android apps are identified by their package name and the SHA-1 of their signing key. // https://developers.google.com/android/guides/client-auth // https://developers.google.com/identity/sign-in/android/start#configure-a-google-api-project String serverClientId = params.getServerClientId(); if (!Strings.isNullOrEmpty(params.getClientId()) && Strings.isNullOrEmpty(serverClientId)) { Log.w( "google_sign_in", "clientId is not supported on Android and is interpreted as serverClientId. " + "Use serverClientId instead to suppress this warning."); serverClientId = params.getClientId(); } if (Strings.isNullOrEmpty(serverClientId)) { // Only requests a clientId if google-services.json was present and parsed // by the google-services Gradle script. // TODO(jackson): Perhaps we should provide a mechanism to override this // behavior. @SuppressLint("DiscouragedApi") int webClientIdIdentifier = context .getResources() .getIdentifier("default_web_client_id", "string", context.getPackageName()); if (webClientIdIdentifier != 0) { serverClientId = context.getString(webClientIdIdentifier); } } if (!Strings.isNullOrEmpty(serverClientId)) { optionsBuilder.requestIdToken(serverClientId); optionsBuilder.requestServerAuthCode( serverClientId, params.getForceCodeForRefreshToken()); } requestedScopes = params.getScopes(); for (String scope : requestedScopes) { optionsBuilder.requestScopes(new Scope(scope)); } if (!Strings.isNullOrEmpty(params.getHostedDomain())) { optionsBuilder.setHostedDomain(params.getHostedDomain()); } signInClient = googleSignInWrapper.getClient(context, optionsBuilder.build()); } catch (Exception e) { throw new FlutterError(ERROR_REASON_EXCEPTION, e.getMessage(), null); } } // IDelegate version, for backwards compatibility. @Override public void init( @NonNull MethodChannel.Result result, @NonNull String signInOption, @NonNull List<String> requestedScopes, @Nullable String hostedDomain, @Nullable String clientId, @Nullable String serverClientId, boolean forceCodeForRefreshToken) { try { Messages.SignInType type; switch (signInOption) { case DEFAULT_GAMES_SIGN_IN: type = Messages.SignInType.GAMES; break; case DEFAULT_SIGN_IN: type = Messages.SignInType.STANDARD; break; default: throw new IllegalStateException("Unknown signInOption"); } init( new Messages.InitParams.Builder() .setSignInType(type) .setScopes(requestedScopes) .setHostedDomain(hostedDomain) .setClientId(clientId) .setServerClientId(serverClientId) .setForceCodeForRefreshToken(forceCodeForRefreshToken) .build()); result.success(null); } catch (FlutterError e) { result.error(e.code, e.getMessage(), e.details); } } /** * Returns the account information for the user who is signed in to this app. If no user is * signed in, tries to sign the user in without displaying any user interface. */ @Override public void signInSilently(@NonNull Messages.Result<Messages.UserData> result) { checkAndSetPendingSignInOperation("signInSilently", result); Task<GoogleSignInAccount> task = signInClient.silentSignIn(); if (task.isComplete()) { // There's immediate result available. onSignInResult(task); } else { task.addOnCompleteListener(this::onSignInResult); } } // IDelegate version, for backwards compatibility. @Override public void signInSilently(@NonNull MethodChannel.Result result) { signInSilently(new UserDataMethodChannelResult(result)); } /** * Signs the user in via the sign-in user interface, including the OAuth consent flow if scopes * were requested. */ @Override public void signIn(@NonNull Messages.Result<Messages.UserData> result) { if (getActivity() == null) { throw new IllegalStateException("signIn needs a foreground activity"); } checkAndSetPendingSignInOperation("signIn", result); Intent signInIntent = signInClient.getSignInIntent(); getActivity().startActivityForResult(signInIntent, REQUEST_CODE_SIGNIN); } // IDelegate version, for backwards compatibility. @Override public void signIn(@NonNull MethodChannel.Result result) { signIn(new UserDataMethodChannelResult(result)); } /** * Signs the user out. Their credentials may remain valid, meaning they'll be able to silently * sign back in. */ @Override public void signOut(@NonNull Messages.Result<Void> result) { checkAndSetPendingVoidOperation("signOut", result); signInClient .signOut() .addOnCompleteListener( task -> { if (task.isSuccessful()) { finishWithSuccess(); } else { finishWithError(ERROR_REASON_STATUS, "Failed to signout."); } }); } // IDelegate version, for backwards compatibility. @Override public void signOut(@NonNull MethodChannel.Result result) { signOut(new VoidMethodChannelResult(result)); } /** Signs the user out, and revokes their credentials. */ @Override public void disconnect(@NonNull Messages.Result<Void> result) { checkAndSetPendingVoidOperation("disconnect", result); signInClient .revokeAccess() .addOnCompleteListener( task -> { if (task.isSuccessful()) { finishWithSuccess(); } else { finishWithError(ERROR_REASON_STATUS, "Failed to disconnect."); } }); } // IDelegate version, for backwards compatibility. @Override public void disconnect(@NonNull MethodChannel.Result result) { signOut(new VoidMethodChannelResult(result)); } /** Checks if there is a signed in user. */ @NonNull @Override public Boolean isSignedIn() { return GoogleSignIn.getLastSignedInAccount(context) != null; } // IDelegate version, for backwards compatibility. @Override public void isSignedIn(final @NonNull MethodChannel.Result result) { result.success(isSignedIn()); } @Override public void requestScopes( @NonNull List<String> scopes, @NonNull Messages.Result<Boolean> result) { checkAndSetPendingBoolOperation("requestScopes", result); GoogleSignInAccount account = googleSignInWrapper.getLastSignedInAccount(context); if (account == null) { finishWithError(ERROR_REASON_SIGN_IN_REQUIRED, "No account to grant scopes."); return; } List<Scope> wrappedScopes = new ArrayList<>(); for (String scope : scopes) { Scope wrappedScope = new Scope(scope); if (!googleSignInWrapper.hasPermissions(account, wrappedScope)) { wrappedScopes.add(wrappedScope); } } if (wrappedScopes.isEmpty()) { finishWithBoolean(true); return; } googleSignInWrapper.requestPermissions( getActivity(), REQUEST_CODE_REQUEST_SCOPE, account, wrappedScopes.toArray(new Scope[0])); } // IDelegate version, for backwards compatibility. @Override public void requestScopes(@NonNull MethodChannel.Result result, @NonNull List<String> scopes) { requestScopes( scopes, new ErrorConvertingMethodChannelResult<Boolean>(result) { @Override public void success(Boolean value) { result.success(value); } }); } private void onSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); onSignInAccount(account); } catch (ApiException e) { // Forward all errors and let Dart decide how to handle. String errorCode = errorCodeForStatus(e.getStatusCode()); finishWithError(errorCode, e.toString()); } catch (RuntimeExecutionException e) { finishWithError(ERROR_REASON_EXCEPTION, e.toString()); } } private void onSignInAccount(GoogleSignInAccount account) { final Messages.UserData.Builder builder = new Messages.UserData.Builder() // TODO(stuartmorgan): Test with games sign-in; according to docs these could be null // as the games login request is currently constructed, but the public Dart API // assumes they are non-null, so the sign-in query may need to change to // include requestEmail() and requestProfile(). .setEmail(account.getEmail()) .setId(account.getId()) .setIdToken(account.getIdToken()) .setServerAuthCode(account.getServerAuthCode()) .setDisplayName(account.getDisplayName()); if (account.getPhotoUrl() != null) { builder.setPhotoUrl(account.getPhotoUrl().toString()); } finishWithUserData(builder.build()); } private String errorCodeForStatus(int statusCode) { switch (statusCode) { case GoogleSignInStatusCodes.SIGN_IN_CANCELLED: return ERROR_REASON_SIGN_IN_CANCELED; case CommonStatusCodes.SIGN_IN_REQUIRED: return ERROR_REASON_SIGN_IN_REQUIRED; case CommonStatusCodes.NETWORK_ERROR: return ERROR_REASON_NETWORK_ERROR; case GoogleSignInStatusCodes.SIGN_IN_CURRENTLY_IN_PROGRESS: case GoogleSignInStatusCodes.SIGN_IN_FAILED: case CommonStatusCodes.INVALID_ACCOUNT: case CommonStatusCodes.INTERNAL_ERROR: default: return ERROR_REASON_SIGN_IN_FAILED; } } private void finishWithSuccess() { Objects.requireNonNull(pendingOperation.voidResult).success(null); pendingOperation = null; } private void finishWithBoolean(Boolean value) { Objects.requireNonNull(pendingOperation.boolResult).success(value); pendingOperation = null; } private void finishWithUserData(Messages.UserData data) { Objects.requireNonNull(pendingOperation.userDataResult).success(data); pendingOperation = null; } private void finishWithError(String errorCode, String errorMessage) { Messages.Result<?> result; if (pendingOperation.userDataResult != null) { result = pendingOperation.userDataResult; } else if (pendingOperation.boolResult != null) { result = pendingOperation.boolResult; } else if (pendingOperation.stringResult != null) { result = pendingOperation.stringResult; } else { result = pendingOperation.voidResult; } Objects.requireNonNull(result).error(new FlutterError(errorCode, errorMessage, null)); pendingOperation = null; } private static class PendingOperation { final @NonNull String method; final @Nullable Messages.Result<Messages.UserData> userDataResult; final @Nullable Messages.Result<Void> voidResult; final @Nullable Messages.Result<Boolean> boolResult; final @Nullable Messages.Result<String> stringResult; final @Nullable Object data; PendingOperation( @NonNull String method, @Nullable Messages.Result<Messages.UserData> userDataResult, @Nullable Messages.Result<Void> voidResult, @Nullable Messages.Result<Boolean> boolResult, @Nullable Messages.Result<String> stringResult, @Nullable Object data) { assert (userDataResult != null || voidResult != null || boolResult != null || stringResult != null); this.method = method; this.userDataResult = userDataResult; this.voidResult = voidResult; this.boolResult = boolResult; this.stringResult = stringResult; this.data = data; } } /** Clears the token kept in the client side cache. */ @Override public void clearAuthCache(@NonNull String token, @NonNull Messages.Result<Void> result) { Callable<Void> clearTokenTask = () -> { GoogleAuthUtil.clearToken(context, token); return null; }; backgroundTaskRunner.runInBackground( clearTokenTask, clearTokenFuture -> { try { result.success(clearTokenFuture.get()); } catch (ExecutionException e) { @Nullable Throwable cause = e.getCause(); result.error( new FlutterError( ERROR_REASON_EXCEPTION, cause == null ? null : cause.getMessage(), null)); } catch (InterruptedException e) { result.error(new FlutterError(ERROR_REASON_EXCEPTION, e.getMessage(), null)); Thread.currentThread().interrupt(); } }); } // IDelegate version, for backwards compatibility. @Override public void clearAuthCache( final @NonNull MethodChannel.Result result, final @NonNull String token) { clearAuthCache(token, new VoidMethodChannelResult(result)); } /** * Gets an OAuth access token with the scopes that were specified during initialization for the * user with the specified email address. * * <p>If shouldRecoverAuth is set to true and user needs to recover authentication for method to * complete, the method will attempt to recover authentication and rerun method. */ @Override public void getAccessToken( @NonNull String email, @NonNull Boolean shouldRecoverAuth, @NonNull Messages.Result<String> result) { Callable<String> getTokenTask = () -> { Account account = new Account(email, "com.google"); String scopesStr = "oauth2:" + Joiner.on(' ').join(requestedScopes); return GoogleAuthUtil.getToken(context, account, scopesStr); }; // Background task runner has a single thread effectively serializing // the getToken calls. 1p apps can then enjoy the token cache if multiple // getToken calls are coming in. backgroundTaskRunner.runInBackground( getTokenTask, tokenFuture -> { try { result.success(tokenFuture.get()); } catch (ExecutionException e) { if (e.getCause() instanceof UserRecoverableAuthException) { if (shouldRecoverAuth && pendingOperation == null) { Activity activity = getActivity(); if (activity == null) { result.error( new FlutterError( ERROR_USER_RECOVERABLE_AUTH, "Cannot recover auth because app is not in foreground. " + e.getLocalizedMessage(), null)); } else { checkAndSetPendingAccessTokenOperation("getTokens", result, email); Intent recoveryIntent = ((UserRecoverableAuthException) e.getCause()).getIntent(); activity.startActivityForResult(recoveryIntent, REQUEST_CODE_RECOVER_AUTH); } } else { result.error( new FlutterError(ERROR_USER_RECOVERABLE_AUTH, e.getLocalizedMessage(), null)); } } else { @Nullable Throwable cause = e.getCause(); result.error( new FlutterError( ERROR_REASON_EXCEPTION, cause == null ? null : cause.getMessage(), null)); } } catch (InterruptedException e) { result.error(new FlutterError(ERROR_REASON_EXCEPTION, e.getMessage(), null)); Thread.currentThread().interrupt(); } }); } // IDelegate version, for backwards compatibility. @Override public void getTokens( @NonNull final MethodChannel.Result result, @NonNull final String email, final boolean shouldRecoverAuth) { getAccessToken( email, shouldRecoverAuth, new ErrorConvertingMethodChannelResult<String>(result) { @Override public void success(String value) { HashMap<String, String> tokenResult = new HashMap<>(); tokenResult.put("accessToken", value); result.success(tokenResult); } }); } @Override public boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (pendingOperation == null) { return false; } switch (requestCode) { case REQUEST_CODE_RECOVER_AUTH: if (resultCode == Activity.RESULT_OK) { // Recover the previous result and data and attempt to get tokens again. Messages.Result<String> result = Objects.requireNonNull(pendingOperation.stringResult); String email = (String) Objects.requireNonNull(pendingOperation.data); pendingOperation = null; getAccessToken(email, false, result); } else { finishWithError( ERROR_FAILURE_TO_RECOVER_AUTH, "Failed attempt to recover authentication"); } return true; case REQUEST_CODE_SIGNIN: // Whether resultCode is OK or not, the Task returned by GoogleSigIn will determine // failure with better specifics which are extracted in onSignInResult method. if (data != null) { onSignInResult(GoogleSignIn.getSignedInAccountFromIntent(data)); } else { // data is null which is highly unusual for a sign in result. finishWithError(ERROR_REASON_SIGN_IN_FAILED, "Signin failed"); } return true; case REQUEST_CODE_REQUEST_SCOPE: finishWithBoolean(resultCode == Activity.RESULT_OK); return true; default: return false; } } } }
packages/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/GoogleSignInPlugin.java/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/GoogleSignInPlugin.java", "repo_id": "packages", "token_count": 13645 }
1,023
// 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 (v10.1.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'; /// Pigeon version of SignInOption. enum SignInType { /// Default configuration. standard, /// Recommended configuration for game sign in. games, } /// Pigeon version of SignInInitParams. /// /// See SignInInitParams for details. class InitParams { InitParams({ required this.scopes, required this.signInType, this.hostedDomain, this.clientId, this.serverClientId, required this.forceCodeForRefreshToken, }); List<String?> scopes; SignInType signInType; String? hostedDomain; String? clientId; String? serverClientId; bool forceCodeForRefreshToken; Object encode() { return <Object?>[ scopes, signInType.index, hostedDomain, clientId, serverClientId, forceCodeForRefreshToken, ]; } static InitParams decode(Object result) { result as List<Object?>; return InitParams( scopes: (result[0] as List<Object?>?)!.cast<String?>(), signInType: SignInType.values[result[1]! as int], hostedDomain: result[2] as String?, clientId: result[3] as String?, serverClientId: result[4] as String?, forceCodeForRefreshToken: result[5]! as bool, ); } } /// Pigeon version of GoogleSignInUserData. /// /// See GoogleSignInUserData for details. class UserData { UserData({ this.displayName, required this.email, required this.id, this.photoUrl, this.idToken, this.serverAuthCode, }); String? displayName; String email; String id; String? photoUrl; String? idToken; String? serverAuthCode; Object encode() { return <Object?>[ displayName, email, id, photoUrl, idToken, serverAuthCode, ]; } static UserData decode(Object result) { result as List<Object?>; return UserData( displayName: result[0] as String?, email: result[1]! as String, id: result[2]! as String, photoUrl: result[3] as String?, idToken: result[4] as String?, serverAuthCode: result[5] as String?, ); } } class _GoogleSignInApiCodec extends StandardMessageCodec { const _GoogleSignInApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is InitParams) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is UserData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return InitParams.decode(readValue(buffer)!); case 129: return UserData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class GoogleSignInApi { /// Constructor for [GoogleSignInApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. GoogleSignInApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _GoogleSignInApiCodec(); /// Initializes a sign in request with the given parameters. Future<void> init(InitParams arg_params) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.init', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_params]) 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 { return; } } /// Starts a silent sign in. Future<UserData> signInSilently() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.signInSilently', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) 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 UserData?)!; } } /// Starts a sign in with user interaction. Future<UserData> signIn() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.signIn', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) 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 UserData?)!; } } /// Requests the access token for the current sign in. Future<String> getAccessToken( String arg_email, bool arg_shouldRecoverAuth) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.getAccessToken', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_email, arg_shouldRecoverAuth]) 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 String?)!; } } /// Signs out the current user. Future<void> signOut() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.signOut', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) 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 { return; } } /// Revokes scope grants to the application. Future<void> disconnect() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.disconnect', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) 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 { return; } } /// Returns whether the user is currently signed in. Future<bool> isSignedIn() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.isSignedIn', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) 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?)!; } } /// Clears the authentication caching for the given token, requiring a /// new sign in. Future<void> clearAuthCache(String arg_token) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.clearAuthCache', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_token]) 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 { return; } } /// Requests access to the given scopes. Future<bool> requestScopes(List<String?> arg_scopes) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.GoogleSignInApi.requestScopes', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_scopes]) 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?)!; } } }
packages/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 4609 }
1,024
// 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 (v11.0.1), 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 @class FSIInitParams; @class FSIUserData; @class FSITokenData; /// Pigeon version of SignInInitParams. /// /// See SignInInitParams for details. @interface FSIInitParams : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithScopes:(NSArray<NSString *> *)scopes hostedDomain:(nullable NSString *)hostedDomain clientId:(nullable NSString *)clientId serverClientId:(nullable NSString *)serverClientId; @property(nonatomic, strong) NSArray<NSString *> *scopes; @property(nonatomic, copy, nullable) NSString *hostedDomain; @property(nonatomic, copy, nullable) NSString *clientId; @property(nonatomic, copy, nullable) NSString *serverClientId; @end /// Pigeon version of GoogleSignInUserData. /// /// See GoogleSignInUserData for details. @interface FSIUserData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithDisplayName:(nullable NSString *)displayName email:(NSString *)email userId:(NSString *)userId photoUrl:(nullable NSString *)photoUrl serverAuthCode:(nullable NSString *)serverAuthCode idToken:(nullable NSString *)idToken; @property(nonatomic, copy, nullable) NSString *displayName; @property(nonatomic, copy) NSString *email; @property(nonatomic, copy) NSString *userId; @property(nonatomic, copy, nullable) NSString *photoUrl; @property(nonatomic, copy, nullable) NSString *serverAuthCode; @property(nonatomic, copy, nullable) NSString *idToken; @end /// Pigeon version of GoogleSignInTokenData. /// /// See GoogleSignInTokenData for details. @interface FSITokenData : NSObject + (instancetype)makeWithIdToken:(nullable NSString *)idToken accessToken:(nullable NSString *)accessToken; @property(nonatomic, copy, nullable) NSString *idToken; @property(nonatomic, copy, nullable) NSString *accessToken; @end /// The codec used by FSIGoogleSignInApi. NSObject<FlutterMessageCodec> *FSIGoogleSignInApiGetCodec(void); @protocol FSIGoogleSignInApi /// Initializes a sign in request with the given parameters. - (void)initializeSignInWithParameters:(FSIInitParams *)params error:(FlutterError *_Nullable *_Nonnull)error; /// Starts a silent sign in. - (void)signInSilentlyWithCompletion:(void (^)(FSIUserData *_Nullable, FlutterError *_Nullable))completion; /// Starts a sign in with user interaction. - (void)signInWithCompletion:(void (^)(FSIUserData *_Nullable, FlutterError *_Nullable))completion; /// Requests the access token for the current sign in. - (void)getAccessTokenWithCompletion:(void (^)(FSITokenData *_Nullable, FlutterError *_Nullable))completion; /// Signs out the current user. - (void)signOutWithError:(FlutterError *_Nullable *_Nonnull)error; /// Revokes scope grants to the application. - (void)disconnectWithCompletion:(void (^)(FlutterError *_Nullable))completion; /// Returns whether the user is currently signed in. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)isSignedInWithError:(FlutterError *_Nullable *_Nonnull)error; /// Requests access to the given scopes. - (void)requestScopes:(NSArray<NSString *> *)scopes completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; @end extern void FSIGoogleSignInApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FSIGoogleSignInApi> *_Nullable api); NS_ASSUME_NONNULL_END
packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/messages.g.h/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/messages.g.h", "repo_id": "packages", "token_count": 1600 }
1,025
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/google_sign_in/google_sign_in_ios/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,026
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 2.4.5 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 2.4.4 * Updates `clearAuthCache` override to match base class declaration. ## 2.4.3 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Drop dependency on `package:quiver`. ## 2.4.2 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.4.1 * Clarifies `canAccessScopes` method documentation. ## 2.4.0 * Introduces: `canAccessScopes` method and `userDataEvents` stream. * These enable separation of Authentication and Authorization, and asynchronous sign-in operations where needed (on the web, for example!) * Updates minimum Flutter version to 3.3. * Aligns Dart and Flutter SDK constraints. ## 2.3.1 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.3.0 * Adopts `plugin_platform_interface`. As a result, `isMock` is deprecated in favor of the now-standard `MockPlatformInterfaceMixin`. ## 2.2.0 * Adds support for the `serverClientId` parameter. ## 2.1.3 * Enables mocking models by changing overridden operator == parameter type from `dynamic` to `Object`. * Removes unnecessary imports. * Adds `SignInInitParameters` class to hold all sign in params, including the new `forceCodeForRefreshToken`. ## 2.1.2 * Internal code cleanup for stricter analysis options. ## 2.1.1 * Removes dependency on `meta`. ## 2.1.0 * Add serverAuthCode attribute to user data ## 2.0.1 * Updates `init` function in `MethodChannelGoogleSignIn` to parametrize `clientId` property. ## 2.0.0 * Migrate to null-safety. ## 1.1.3 * Update Flutter SDK constraint. ## 1.1.2 * Update lower bound of dart dependency to 2.1.0. ## 1.1.1 * Add attribute serverAuthCode. ## 1.1.0 * Add hasRequestedScope method to determine if an Oauth scope has been granted. * Add requestScope Method to request new Oauth scopes be granted by the user. ## 1.0.4 * Make the pedantic dev_dependency explicit. ## 1.0.3 * Remove the deprecated `author:` field from pubspec.yaml * Require Flutter SDK 1.10.0 or greater. ## 1.0.2 * Add missing documentation. ## 1.0.1 * Switch away from quiver_hashcode. ## 1.0.0 * Initial release.
packages/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 760 }
1,027
// 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_web' as ui_web; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_web/src/flexible_size_html_element_view.dart'; import 'package:integration_test/integration_test.dart'; import 'package:web/web.dart' as web; /// Used to keep track of the number of HtmlElementView factories the test has registered. int widgetFactoryNumber = 0; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('FlexHtmlElementView', () { tearDown(() { widgetFactoryNumber++; }); testWidgets('empty case, calls onElementCreated', (WidgetTester tester) async { final Completer<Object> viewCreatedCompleter = Completer<Object>(); await pumpResizableWidget(tester, onElementCreated: (Object view) { viewCreatedCompleter.complete(view); }); await tester.pumpAndSettle(); await expectLater(viewCreatedCompleter.future, completes); }); testWidgets('empty case, renders with initial size', (WidgetTester tester) async { const Size initialSize = Size(160, 100); final Element element = await pumpResizableWidget( tester, initialSize: initialSize, ); await tester.pumpAndSettle(); // Expect that the element matches the initialSize. expect(element.size!.width, initialSize.width); expect(element.size!.height, initialSize.height); }); testWidgets('initialSize null, adopts size of injected element', (WidgetTester tester) async { const Size childSize = Size(300, 40); final web.HTMLDivElement resizable = web.document.createElement('div') as web.HTMLDivElement; resize(resizable, childSize); final Element element = await pumpResizableWidget( tester, onElementCreated: injectElement(resizable), ); await tester.pumpAndSettle(); // Expect that the element matches the initialSize. expect(element.size!.width, childSize.width); expect(element.size!.height, childSize.height); }); testWidgets('with initialSize, adopts size of injected element', (WidgetTester tester) async { const Size initialSize = Size(160, 100); const Size newSize = Size(300, 40); final web.HTMLDivElement resizable = web.document.createElement('div') as web.HTMLDivElement; resize(resizable, newSize); final Element element = await pumpResizableWidget( tester, initialSize: initialSize, onElementCreated: injectElement(resizable), ); await tester.pumpAndSettle(); // Expect that the element matches the initialSize. expect(element.size!.width, newSize.width); expect(element.size!.height, newSize.height); }); testWidgets('with injected element that resizes, follows resizes', (WidgetTester tester) async { const Size initialSize = Size(160, 100); final Size expandedSize = initialSize * 2; final Size contractedSize = initialSize / 2; final web.HTMLDivElement resizable = web.document.createElement('div') as web.HTMLDivElement ..setAttribute( 'style', 'width: 100%; height: 100%; background: #fabada;'); final Element element = await pumpResizableWidget( tester, initialSize: initialSize, onElementCreated: injectElement(resizable), ); await tester.pumpAndSettle(); // Expect that the element matches the initialSize, because the // resizable is defined as width:100%, height:100%. expect(element.size!.width, initialSize.width); expect(element.size!.height, initialSize.height); // Expands resize(resizable, expandedSize); await tester.pumpAndSettle(); expect(element.size!.width, expandedSize.width); expect(element.size!.height, expandedSize.height); // Contracts resize(resizable, contractedSize); await tester.pumpAndSettle(); expect(element.size!.width, contractedSize.width); expect(element.size!.height, contractedSize.height); }); }); } /// Injects a ResizableFromJs widget into the `tester`. Future<Element> pumpResizableWidget( WidgetTester tester, { void Function(Object)? onElementCreated, Size? initialSize, }) async { await tester.pumpWidget(ResizableFromJs( instanceId: widgetFactoryNumber, onElementCreated: onElementCreated, initialSize: initialSize, )); // Needed for JS to have time to kick-off. await tester.pump(); // Return the element we just pumped final Iterable<Element> elements = find.byKey(Key('resizable_from_js_$widgetFactoryNumber')).evaluate(); expect(elements, hasLength(1)); return elements.first; } class ResizableFromJs extends StatelessWidget { ResizableFromJs({ required this.instanceId, this.onElementCreated, this.initialSize, super.key, }) { ui_web.platformViewRegistry.registerViewFactory( 'resizable_from_js_$instanceId', (int viewId) { final web.HTMLDivElement element = web.document.createElement('div') as web.HTMLDivElement; element.setAttribute('style', 'width: 100%; height: 100%; overflow: hidden; background: red;'); element.id = 'test_element_$viewId'; return element; }, ); } final int instanceId; final void Function(Object)? onElementCreated; final Size? initialSize; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: FlexHtmlElementView( viewType: 'resizable_from_js_$instanceId', key: Key('resizable_from_js_$instanceId'), onElementCreated: onElementCreated, initialSize: initialSize ?? const Size(640, 480), ), ), ), ); } } /// Resizes `resizable` to `size`. void resize(web.HTMLElement resizable, Size size) { resizable.setAttribute('style', 'width: ${size.width}px; height: ${size.height}px; background: #fabada'); } /// Returns an `onElementCreated` callback that injects [element]. ElementCreatedCallback injectElement(web.HTMLElement element) { return (Object root) { (root as web.HTMLElement).appendChild(element); }; }
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart", "repo_id": "packages", "token_count": 2380 }
1,028
// 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:js_interop'; import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart' show kDebugMode, visibleForTesting; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show PlatformException; import 'package:flutter/widgets.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:google_identity_services_web/loader.dart' as loader; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:web/web.dart' as web; import 'src/button_configuration.dart' show GSIButtonConfiguration; import 'src/flexible_size_html_element_view.dart'; import 'src/gis_client.dart'; // Export the configuration types for the renderButton method. export 'src/button_configuration.dart' show GSIButtonConfiguration, GSIButtonLogoAlignment, GSIButtonShape, GSIButtonSize, GSIButtonText, GSIButtonTheme, GSIButtonType; /// The `name` of the meta-tag to define a ClientID in HTML. const String clientIdMetaName = 'google-signin-client_id'; /// The selector used to find the meta-tag that defines a ClientID in HTML. const String clientIdMetaSelector = 'meta[name=$clientIdMetaName]'; /// The attribute name that stores the Client ID in the meta-tag that defines a Client ID in HTML. const String clientIdAttributeName = 'content'; /// Implementation of the google_sign_in plugin for Web. class GoogleSignInPlugin extends GoogleSignInPlatform { /// Constructs the plugin immediately and begins initializing it in the /// background. /// /// For tests, the plugin can skip its loading process with [debugOverrideLoader], /// and the implementation of the underlying GIS SDK client through [debugOverrideGisSdkClient]. GoogleSignInPlugin({ @visibleForTesting bool debugOverrideLoader = false, @visibleForTesting GisSdkClient? debugOverrideGisSdkClient, @visibleForTesting StreamController<GoogleSignInUserData?>? debugOverrideUserDataController, }) : _gisSdkClient = debugOverrideGisSdkClient, _userDataController = debugOverrideUserDataController ?? StreamController<GoogleSignInUserData?>.broadcast() { autoDetectedClientId = web.document .querySelector(clientIdMetaSelector) ?.getAttribute(clientIdAttributeName); _registerButtonFactory(); if (debugOverrideLoader) { _jsSdkLoadedFuture = Future<bool>.value(true); } else { _jsSdkLoadedFuture = loader.loadWebSdk(); } } // A future that completes when the JS loader is done. late Future<void> _jsSdkLoadedFuture; // A future that completes when the `init` call is done. Completer<void>? _initCalled; // A StreamController to communicate status changes from the GisSdkClient. final StreamController<GoogleSignInUserData?> _userDataController; // The instance of [GisSdkClient] backing the plugin. GisSdkClient? _gisSdkClient; // A convenience getter to avoid using ! when accessing _gisSdkClient, and // providing a slightly better error message when it is Null. GisSdkClient get _gisClient { assert( _gisSdkClient != null, 'GIS Client not initialized. ' 'GoogleSignInPlugin::init() or GoogleSignInPlugin::initWithParams() ' 'must be called before any other method in this plugin.', ); return _gisSdkClient!; } // This method throws if init or initWithParams hasn't been called at some // point in the past. It is used by the [initialized] getter to ensure that // users can't await on a Future that will never resolve. void _assertIsInitCalled() { if (_initCalled == null) { throw StateError( 'GoogleSignInPlugin::init() or GoogleSignInPlugin::initWithParams() ' 'must be called before any other method in this plugin.', ); } } /// A future that resolves when the plugin is fully initialized. /// /// This ensures that the SDK has been loaded, and that the `initWithParams` /// method has finished running. @visibleForTesting Future<void> get initialized { _assertIsInitCalled(); return Future.wait<void>( <Future<void>>[_jsSdkLoadedFuture, _initCalled!.future]); } /// Stores the client ID if it was set in a meta-tag of the page. @visibleForTesting late String? autoDetectedClientId; /// Factory method that initializes the plugin with [GoogleSignInPlatform]. static void registerWith(Registrar registrar) { GoogleSignInPlatform.instance = GoogleSignInPlugin(); } @override Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) { return initWithParams(SignInInitParameters( scopes: scopes, signInOption: signInOption, hostedDomain: hostedDomain, clientId: clientId, )); } @override Future<void> initWithParams(SignInInitParameters params) async { final String? appClientId = params.clientId ?? autoDetectedClientId; assert( appClientId != null, 'ClientID not set. Either set it on a ' '<meta name="google-signin-client_id" content="CLIENT_ID" /> tag,' ' or pass clientId when initializing GoogleSignIn'); assert(params.serverClientId == null, 'serverClientId is not supported on Web.'); assert( !params.scopes.any((String scope) => scope.contains(' ')), "OAuth 2.0 Scopes for Google APIs can't contain spaces. " 'Check https://developers.google.com/identity/protocols/googlescopes ' 'for a list of valid OAuth 2.0 scopes.'); _initCalled = Completer<void>(); await _jsSdkLoadedFuture; _gisSdkClient ??= GisSdkClient( clientId: appClientId!, hostedDomain: params.hostedDomain, initialScopes: List<String>.from(params.scopes), userDataController: _userDataController, loggingEnabled: kDebugMode, ); _initCalled!.complete(); // Signal that `init` is fully done. } // Register a factory for the Button HtmlElementView. void _registerButtonFactory() { ui_web.platformViewRegistry.registerViewFactory( 'gsi_login_button', (int viewId) { final web.Element element = web.document.createElement('div'); element.setAttribute('style', 'width: 100%; height: 100%; overflow: hidden; display: flex; flex-wrap: wrap; align-content: center; justify-content: center;'); element.id = 'sign_in_button_$viewId'; return element; }, ); } /// Render the GSI button web experience. Widget renderButton({GSIButtonConfiguration? configuration}) { final GSIButtonConfiguration config = configuration ?? GSIButtonConfiguration(); return FutureBuilder<void>( key: Key(config.hashCode.toString()), future: initialized, builder: (BuildContext context, AsyncSnapshot<void> snapshot) { if (snapshot.hasData) { return FlexHtmlElementView( viewType: 'gsi_login_button', onElementCreated: (Object element) { _gisClient.renderButton(element, config); }); } return const Text('Getting ready'); }, ); } @override Future<GoogleSignInUserData?> signInSilently() async { await initialized; // The new user is being injected from the `userDataEvents` Stream. return _gisClient.signInSilently(); } @override Future<GoogleSignInUserData?> signIn() async { if (kDebugMode) { web.console.warn( "The `signIn` method is discouraged on the web because it can't reliably provide an `idToken`.\n" 'Use `signInSilently` and `renderButton` to authenticate your users instead.\n' 'Read more: https://pub.dev/packages/google_sign_in_web' .toJS); } await initialized; // This method mainly does oauth2 authorization, which happens to also do // authentication if needed. However, the authentication information is not // returned anymore. // // This method will synthesize authentication information from the People API // if needed (or use the last identity seen from signInSilently). try { return _gisClient.signIn(); } catch (reason) { throw PlatformException( code: reason.toString(), message: 'Exception raised from signIn', details: 'https://developers.google.com/identity/oauth2/web/guides/error', ); } } @override Future<GoogleSignInTokenData> getTokens({ required String email, bool? shouldRecoverAuth, }) async { await initialized; return _gisClient.getTokens(); } @override Future<void> signOut() async { await initialized; await _gisClient.signOut(); } @override Future<void> disconnect() async { await initialized; await _gisClient.disconnect(); } @override Future<bool> isSignedIn() async { await initialized; return _gisClient.isSignedIn(); } @override Future<void> clearAuthCache({required String token}) async { await initialized; await _gisClient.clearAuthCache(); } @override Future<bool> requestScopes(List<String> scopes) async { await initialized; return _gisClient.requestScopes(scopes); } @override Future<bool> canAccessScopes(List<String> scopes, {String? accessToken}) async { await initialized; return _gisClient.canAccessScopes(scopes, accessToken); } @override Stream<GoogleSignInUserData?>? get userDataEvents => _userDataController.stream; /// Requests server auth code from GIS Client per: /// https://developers.google.com/identity/oauth2/web/guides/use-code-model#initialize_a_code_client Future<String?> requestServerAuthCode() async { await initialized; return _gisClient.requestServerAuthCode(); } }
packages/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart", "repo_id": "packages", "token_count": 3520 }
1,029
// 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.imagepicker; import androidx.exifinterface.media.ExifInterface; import java.io.IOException; import java.util.Arrays; import java.util.List; class ExifDataCopier { /** * Copies all exif data not related to image structure and orientation tag. Data not related to * image structure consists of category II (Shooting condition related metadata) and category III * (Metadata storing other information) tags. Category I tags are not copied because they may be * invalidated as a result of resizing. The exception is the orientation tag which is known to not * be invalidated and is crucial for proper display of the image. * * <p>The categories mentioned refer to standard "CIPA DC-008-Translation-2012 Exchangeable image * file format for digital still cameras: Exif Version 2.3" * https://www.cipa.jp/std/documents/e/DC-008-2012_E.pdf. Version 2.3 has been chosen because * {@code ExifInterface} is based on it. */ void copyExif(ExifInterface oldExif, ExifInterface newExif) throws IOException { @SuppressWarnings("deprecation") List<String> attributes = Arrays.asList( ExifInterface.TAG_IMAGE_DESCRIPTION, ExifInterface.TAG_MAKE, ExifInterface.TAG_MODEL, ExifInterface.TAG_SOFTWARE, ExifInterface.TAG_DATETIME, ExifInterface.TAG_ARTIST, ExifInterface.TAG_COPYRIGHT, ExifInterface.TAG_EXPOSURE_TIME, ExifInterface.TAG_F_NUMBER, ExifInterface.TAG_EXPOSURE_PROGRAM, ExifInterface.TAG_SPECTRAL_SENSITIVITY, ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY, ExifInterface.TAG_ISO_SPEED_RATINGS, ExifInterface.TAG_OECF, ExifInterface.TAG_SENSITIVITY_TYPE, ExifInterface.TAG_STANDARD_OUTPUT_SENSITIVITY, ExifInterface.TAG_RECOMMENDED_EXPOSURE_INDEX, ExifInterface.TAG_ISO_SPEED, ExifInterface.TAG_ISO_SPEED_LATITUDE_YYY, ExifInterface.TAG_ISO_SPEED_LATITUDE_ZZZ, ExifInterface.TAG_EXIF_VERSION, ExifInterface.TAG_DATETIME_ORIGINAL, ExifInterface.TAG_DATETIME_DIGITIZED, ExifInterface.TAG_OFFSET_TIME, ExifInterface.TAG_OFFSET_TIME_ORIGINAL, ExifInterface.TAG_OFFSET_TIME_DIGITIZED, ExifInterface.TAG_SHUTTER_SPEED_VALUE, ExifInterface.TAG_APERTURE_VALUE, ExifInterface.TAG_BRIGHTNESS_VALUE, ExifInterface.TAG_EXPOSURE_BIAS_VALUE, ExifInterface.TAG_MAX_APERTURE_VALUE, ExifInterface.TAG_SUBJECT_DISTANCE, ExifInterface.TAG_METERING_MODE, ExifInterface.TAG_LIGHT_SOURCE, ExifInterface.TAG_FLASH, ExifInterface.TAG_FOCAL_LENGTH, ExifInterface.TAG_MAKER_NOTE, ExifInterface.TAG_USER_COMMENT, ExifInterface.TAG_SUBSEC_TIME, ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, ExifInterface.TAG_FLASHPIX_VERSION, ExifInterface.TAG_FLASH_ENERGY, ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE, ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION, ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION, ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT, ExifInterface.TAG_EXPOSURE_INDEX, ExifInterface.TAG_SENSING_METHOD, ExifInterface.TAG_FILE_SOURCE, ExifInterface.TAG_SCENE_TYPE, ExifInterface.TAG_CFA_PATTERN, ExifInterface.TAG_CUSTOM_RENDERED, ExifInterface.TAG_EXPOSURE_MODE, ExifInterface.TAG_WHITE_BALANCE, ExifInterface.TAG_DIGITAL_ZOOM_RATIO, ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM, ExifInterface.TAG_SCENE_CAPTURE_TYPE, ExifInterface.TAG_GAIN_CONTROL, ExifInterface.TAG_CONTRAST, ExifInterface.TAG_SATURATION, ExifInterface.TAG_SHARPNESS, ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION, ExifInterface.TAG_SUBJECT_DISTANCE_RANGE, ExifInterface.TAG_IMAGE_UNIQUE_ID, ExifInterface.TAG_CAMERA_OWNER_NAME, ExifInterface.TAG_BODY_SERIAL_NUMBER, ExifInterface.TAG_LENS_SPECIFICATION, ExifInterface.TAG_LENS_MAKE, ExifInterface.TAG_LENS_MODEL, ExifInterface.TAG_LENS_SERIAL_NUMBER, ExifInterface.TAG_GPS_VERSION_ID, ExifInterface.TAG_GPS_LATITUDE_REF, ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LONGITUDE_REF, ExifInterface.TAG_GPS_LONGITUDE, ExifInterface.TAG_GPS_ALTITUDE_REF, ExifInterface.TAG_GPS_ALTITUDE, ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_GPS_SATELLITES, ExifInterface.TAG_GPS_STATUS, ExifInterface.TAG_GPS_MEASURE_MODE, ExifInterface.TAG_GPS_DOP, ExifInterface.TAG_GPS_SPEED_REF, ExifInterface.TAG_GPS_SPEED, ExifInterface.TAG_GPS_TRACK_REF, ExifInterface.TAG_GPS_TRACK, ExifInterface.TAG_GPS_IMG_DIRECTION_REF, ExifInterface.TAG_GPS_IMG_DIRECTION, ExifInterface.TAG_GPS_MAP_DATUM, ExifInterface.TAG_GPS_DEST_LATITUDE_REF, ExifInterface.TAG_GPS_DEST_LATITUDE, ExifInterface.TAG_GPS_DEST_LONGITUDE_REF, ExifInterface.TAG_GPS_DEST_LONGITUDE, ExifInterface.TAG_GPS_DEST_BEARING_REF, ExifInterface.TAG_GPS_DEST_BEARING, ExifInterface.TAG_GPS_DEST_DISTANCE_REF, ExifInterface.TAG_GPS_DEST_DISTANCE, ExifInterface.TAG_GPS_PROCESSING_METHOD, ExifInterface.TAG_GPS_AREA_INFORMATION, ExifInterface.TAG_GPS_DATESTAMP, ExifInterface.TAG_GPS_DIFFERENTIAL, ExifInterface.TAG_GPS_H_POSITIONING_ERROR, ExifInterface.TAG_INTEROPERABILITY_INDEX, ExifInterface.TAG_ORIENTATION); for (String attribute : attributes) { setIfNotNull(oldExif, newExif, attribute); } newExif.saveAttributes(); } private static void setIfNotNull(ExifInterface oldExif, ExifInterface newExif, String property) { if (oldExif.getAttribute(property) != null) { newExif.setAttribute(property, oldExif.getAttribute(property)); } } }
packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java", "repo_id": "packages", "token_count": 3283 }
1,030
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 166 202"> <defs> <linearGradient id="triangleGradient"> <stop offset="20%" stop-color="#000000" stop-opacity=".55" /> <stop offset="85%" stop-color="#616161" stop-opacity=".01" /> </linearGradient> <linearGradient id="rectangleGradient" x1="0%" x2="0%" y1="0%" y2="100%"> <stop offset="20%" stop-color="#000000" stop-opacity=".15" /> <stop offset="85%" stop-color="#616161" stop-opacity=".01" /> </linearGradient> </defs> <path fill="#42A5F5" fill-opacity=".8" d="M37.7 128.9 9.8 101 100.4 10.4 156.2 10.4"/> <path fill="#42A5F5" fill-opacity=".8" d="M156.2 94 100.4 94 79.5 114.9 107.4 142.8"/> <path fill="#0D47A1" d="M79.5 170.7 100.4 191.6 156.2 191.6 156.2 191.6 107.4 142.8"/> <g transform="matrix(0.7071, -0.7071, 0.7071, 0.7071, -77.667, 98.057)"> <rect width="39.4" height="39.4" x="59.8" y="123.1" fill="#42A5F5" /> <rect width="39.4" height="5.5" x="59.8" y="162.5" fill="url(#rectangleGradient)" /> </g> <path d="M79.5 170.7 120.9 156.4 107.4 142.8" fill="url(#triangleGradient)" /> </svg>
packages/packages/image_picker/image_picker_android/android/src/test/resources/flutter_image.svg/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/test/resources/flutter_image.svg", "repo_id": "packages", "token_count": 592 }
1,031
name: image_picker_for_web_integration_tests publish_to: none environment: sdk: ^3.3.0 flutter: ">=3.19.0" dependencies: flutter: sdk: flutter image_picker_for_web: path: ../ image_picker_platform_interface: ^2.8.0 web: ^0.5.1 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter
packages/packages/image_picker/image_picker_for_web/example/pubspec.yaml/0
{ "file_path": "packages/packages/image_picker/image_picker_for_web/example/pubspec.yaml", "repo_id": "packages", "token_count": 155 }
1,032
// 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 <Foundation/Foundation.h> #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef enum : NSUInteger { FLTImagePickerMIMETypePNG, FLTImagePickerMIMETypeJPEG, FLTImagePickerMIMETypeGIF, FLTImagePickerMIMETypeOther, } FLTImagePickerMIMEType; extern NSString *const kFLTImagePickerDefaultSuffix; extern const FLTImagePickerMIMEType kFLTImagePickerMIMETypeDefault; @interface FLTImagePickerMetaDataUtil : NSObject // Retrieve MIME type by reading the image data. We currently only support some popular types. + (FLTImagePickerMIMEType)getImageMIMETypeFromImageData:(NSData *)imageData; // Get corresponding surfix from type. + (nullable NSString *)imageTypeSuffixFromType:(FLTImagePickerMIMEType)type; + (NSDictionary *)getMetaDataFromImageData:(NSData *)imageData; // Creates and returns data for a new image based on imageData, but with the // given metadata. // // If creating a new image fails, returns nil. + (nullable NSData *)imageFromImage:(NSData *)imageData withMetaData:(NSDictionary *)metadata; // Converting UIImage to a NSData with the type proveide. // // The quality is for JPEG type only, it defaults to 1. It throws exception if setting a non-nil // quality with type other than FLTImagePickerMIMETypeJPEG. Converting UIImage to // FLTImagePickerMIMETypeGIF or FLTImagePickerMIMETypeTIFF is not supported in iOS. This // method throws exception if trying to do so. + (nonnull NSData *)convertImage:(nonnull UIImage *)image usingType:(FLTImagePickerMIMEType)type quality:(nullable NSNumber *)quality; @end NS_ASSUME_NONNULL_END
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerMetaDataUtil.h/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerMetaDataUtil.h", "repo_id": "packages", "token_count": 608 }
1,033
// 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]; } enum SourceCamera { rear, front, } enum SourceType { camera, gallery, } class MaxSize { MaxSize({ this.width, this.height, }); double? width; double? height; Object encode() { return <Object?>[ width, height, ]; } static MaxSize decode(Object result) { result as List<Object?>; return MaxSize( width: result[0] as double?, height: result[1] as double?, ); } } class MediaSelectionOptions { MediaSelectionOptions({ required this.maxSize, this.imageQuality, required this.requestFullMetadata, required this.allowMultiple, }); MaxSize maxSize; int? imageQuality; bool requestFullMetadata; bool allowMultiple; Object encode() { return <Object?>[ maxSize.encode(), imageQuality, requestFullMetadata, allowMultiple, ]; } static MediaSelectionOptions decode(Object result) { result as List<Object?>; return MediaSelectionOptions( maxSize: MaxSize.decode(result[0]! as List<Object?>), imageQuality: result[1] as int?, requestFullMetadata: result[2]! as bool, allowMultiple: result[3]! as bool, ); } } class SourceSpecification { SourceSpecification({ required this.type, required this.camera, }); SourceType type; SourceCamera camera; Object encode() { return <Object?>[ type.index, camera.index, ]; } static SourceSpecification decode(Object result) { result as List<Object?>; return SourceSpecification( type: SourceType.values[result[0]! as int], camera: SourceCamera.values[result[1]! as int], ); } } class _ImagePickerApiCodec extends StandardMessageCodec { const _ImagePickerApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MaxSize) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is MediaSelectionOptions) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is SourceSpecification) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MaxSize.decode(readValue(buffer)!); case 129: return MediaSelectionOptions.decode(readValue(buffer)!); case 130: return SourceSpecification.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class ImagePickerApi { /// Constructor for [ImagePickerApi]. 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. ImagePickerApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _ImagePickerApiCodec(); Future<String?> pickImage(SourceSpecification arg_source, MaxSize arg_maxSize, int? arg_imageQuality, bool arg_requestFullMetadata) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickImage', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[ arg_source, arg_maxSize, arg_imageQuality, arg_requestFullMetadata ]) 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 { return (replyList[0] as String?); } } Future<List<String?>> pickMultiImage(MaxSize arg_maxSize, int? arg_imageQuality, bool arg_requestFullMetadata) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMultiImage', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send( <Object?>[arg_maxSize, arg_imageQuality, arg_requestFullMetadata]) 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?>(); } } Future<String?> pickVideo( SourceSpecification arg_source, int? arg_maxDurationSeconds) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickVideo', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_source, arg_maxDurationSeconds]) 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 { return (replyList[0] as String?); } } /// Selects images and videos and returns their paths. Future<List<String?>> pickMedia( MediaSelectionOptions arg_mediaSelectionOptions) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMedia', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_mediaSelectionOptions]) 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/image_picker/image_picker_ios/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 3063 }
1,034
// 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 '../types.dart'; /// The response object of [ImagePicker.retrieveLostData]. /// /// Only applies to Android. /// See also: /// * [ImagePicker.retrieveLostData] for more details on retrieving lost data. class LostData { /// Creates an instance with the given [file], [exception], and [type]. Any of /// the params may be null, but this is never considered to be empty. LostData({this.file, this.exception, this.type}); /// Initializes an instance with all member params set to null and considered /// to be empty. LostData.empty() : file = null, exception = null, type = null, _empty = true; /// Whether it is an empty response. /// /// An empty response should have [file], [exception] and [type] to be null. bool get isEmpty => _empty; /// The file that was lost in a previous [pickImage] or [pickVideo] call due to MainActivity being destroyed. /// /// Can be null if [exception] exists. final PickedFile? file; /// The exception of the last [pickImage] or [pickVideo]. /// /// If the last [pickImage] or [pickVideo] threw some exception before the MainActivity destruction, this variable keeps that /// exception. /// You should handle this exception as if the [pickImage] or [pickVideo] got an exception when the MainActivity was not destroyed. /// /// Note that it is not the exception that caused the destruction of the MainActivity. final PlatformException? exception; /// Can either be [RetrieveType.image] or [RetrieveType.video]; /// /// If the lost data is empty, this will be null. final RetrieveType? type; bool _empty = false; }
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/lost_data.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/lost_data.dart", "repo_id": "packages", "token_count": 530 }
1,035
# See https://pub.dev/packages/build_config targets: $default: builders: json_serializable: options: any_map: true create_to_json: false
packages/packages/in_app_purchase/in_app_purchase_android/build.yaml/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/build.yaml", "repo_id": "packages", "token_count": 83 }
1,036
// 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/widgets.dart'; import 'billing_client_wrapper.dart'; import 'purchase_wrapper.dart'; import 'user_choice_details_wrapper.dart'; /// Abstraction of result of [BillingClient] operation that includes /// a [BillingResponse]. abstract class HasBillingResponse { /// The status of the operation. abstract final BillingResponse responseCode; } /// Utility class that manages a [BillingClient] connection. /// /// Connection is initialized on creation of [BillingClientManager]. /// If [BillingClient] sends `onBillingServiceDisconnected` event or any /// operation returns [BillingResponse.serviceDisconnected], connection is /// re-initialized. /// /// [BillingClient] instance is not exposed directly. It can be accessed via /// [runWithClient] and [runWithClientNonRetryable] methods that handle the /// connection management. /// /// Consider calling [dispose] after the [BillingClient] is no longer needed. class BillingClientManager { /// Creates the [BillingClientManager]. /// /// Immediately initializes connection to the underlying [BillingClient]. BillingClientManager() : _billingChoiceMode = BillingChoiceMode.playBillingOnly { _connect(); } /// Stream of `userSelectedAlternativeBilling` events from the [BillingClient]. /// /// This is a broadcast stream, so it can be listened to multiple times. /// A "done" event will be sent after [dispose] is called. late final Stream<UserChoiceDetailsWrapper> userChoiceDetailsStream = _userChoiceAlternativeBillingController.stream; /// Stream of `onPurchasesUpdated` events from the [BillingClient]. /// /// This is a broadcast stream, so it can be listened to multiple times. /// A "done" event will be sent after [dispose] is called. late final Stream<PurchasesResultWrapper> purchasesUpdatedStream = _purchasesUpdatedController.stream; /// [BillingClient] instance managed by this [BillingClientManager]. /// /// In order to access the [BillingClient], use [runWithClient] /// and [runWithClientNonRetryable] methods. @visibleForTesting late final BillingClient client = BillingClient(_onPurchasesUpdated, onUserChoiceAlternativeBilling); final StreamController<PurchasesResultWrapper> _purchasesUpdatedController = StreamController<PurchasesResultWrapper>.broadcast(); final StreamController<UserChoiceDetailsWrapper> _userChoiceAlternativeBillingController = StreamController<UserChoiceDetailsWrapper>.broadcast(); BillingChoiceMode _billingChoiceMode; bool _isConnecting = false; bool _isDisposed = false; // Initialized immediately in the constructor, so it's always safe to access. late Future<void> _readyFuture; /// Executes the given [action] with access to the underlying [BillingClient]. /// /// If necessary, waits for the underlying [BillingClient] to connect. /// If given [action] returns [BillingResponse.serviceDisconnected], it will /// be transparently retried after the connection is restored. Because /// of this, [action] may be called multiple times. /// /// A response with [BillingResponse.serviceDisconnected] may be returned /// in case of [dispose] being called during the operation. /// /// See [runWithClientNonRetryable] for operations that do not return /// a subclass of [HasBillingResponse]. Future<R> runWithClient<R extends HasBillingResponse>( Future<R> Function(BillingClient client) action, ) async { _debugAssertNotDisposed(); await _readyFuture; final R result = await action(client); if (result.responseCode == BillingResponse.serviceDisconnected && !_isDisposed) { await _connect(); return runWithClient(action); } else { return result; } } /// Executes the given [action] with access to the underlying [BillingClient]. /// /// If necessary, waits for the underlying [BillingClient] to connect. /// Designed only for operations that do not return a subclass /// of [HasBillingResponse] (e.g. [BillingClient.isReady], /// [BillingClient.isFeatureSupported]). /// /// See [runWithClient] for operations that return a subclass /// of [HasBillingResponse]. Future<R> runWithClientNonRetryable<R>( Future<R> Function(BillingClient client) action, ) async { _debugAssertNotDisposed(); await _readyFuture; return action(client); } /// Ends connection to the [BillingClient]. /// /// Consider calling [dispose] after you no longer need the [BillingClient] /// API to free up the resources. /// /// After calling [dispose]: /// - Further connection attempts will not be made. /// - [purchasesUpdatedStream] will be closed. /// - [userChoiceDetailsStream] will be closed. /// - Calls to [runWithClient] and [runWithClientNonRetryable] will throw. void dispose() { _debugAssertNotDisposed(); _isDisposed = true; client.endConnection(); _purchasesUpdatedController.close(); _userChoiceAlternativeBillingController.close(); } /// Ends connection to [BillingClient] and reconnects with [billingChoiceMode]. /// /// Callers need to check if [BillingChoiceMode.alternativeBillingOnly] is /// available by calling [BillingClientWrapper.isAlternativeBillingOnlyAvailable] /// first. Future<void> reconnectWithBillingChoiceMode( BillingChoiceMode billingChoiceMode) async { _billingChoiceMode = billingChoiceMode; // Ends connection and triggers OnBillingServiceDisconnected, which causes reconnect. await client.endConnection(); await _connect(); } // If disposed, does nothing. // If currently connecting, waits for it to complete. // Otherwise, starts a new connection. Future<void> _connect() { if (_isDisposed) { return Future<void>.value(); } if (_isConnecting) { return _readyFuture; } _isConnecting = true; _readyFuture = Future<void>.sync(() async { await client.startConnection( onBillingServiceDisconnected: _connect, billingChoiceMode: _billingChoiceMode); _isConnecting = false; }); return _readyFuture; } void _onPurchasesUpdated(PurchasesResultWrapper event) { if (_isDisposed) { return; } _purchasesUpdatedController.add(event); } void _debugAssertNotDisposed() { assert( !_isDisposed, 'A BillingClientManager was used after being disposed. Once you have ' 'called dispose() on a BillingClientManager, it can no longer be used.', ); } /// Callback passed to [BillingClient] to use when customer chooses /// alternative billing. @visibleForTesting void onUserChoiceAlternativeBilling(UserChoiceDetailsWrapper event) { if (_isDisposed) { return; } _userChoiceAlternativeBillingController.add(event); } }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_manager.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_manager.dart", "repo_id": "packages", "token_count": 2095 }
1,037
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'subscription_offer_details_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SubscriptionOfferDetailsWrapper _$SubscriptionOfferDetailsWrapperFromJson( Map json) => SubscriptionOfferDetailsWrapper( basePlanId: json['basePlanId'] as String? ?? '', offerId: json['offerId'] as String?, offerTags: (json['offerTags'] as List<dynamic>?) ?.map((e) => e as String) .toList() ?? [], offerIdToken: json['offerIdToken'] as String? ?? '', pricingPhases: (json['pricingPhases'] as List<dynamic>?) ?.map((e) => PricingPhaseWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? [], ); PricingPhaseWrapper _$PricingPhaseWrapperFromJson(Map json) => PricingPhaseWrapper( billingCycleCount: json['billingCycleCount'] as int? ?? 0, billingPeriod: json['billingPeriod'] as String? ?? '', formattedPrice: json['formattedPrice'] as String? ?? '', priceAmountMicros: json['priceAmountMicros'] as int? ?? 0, priceCurrencyCode: json['priceCurrencyCode'] as String? ?? '', recurrenceMode: json['recurrenceMode'] == null ? RecurrenceMode.nonRecurring : const RecurrenceModeConverter() .fromJson(json['recurrenceMode'] as int?), );
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.g.dart", "repo_id": "packages", "token_count": 597 }
1,038
// 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/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/src/channel.dart'; import '../stub_in_app_purchase_platform.dart'; import 'purchase_wrapper_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final StubInAppPurchasePlatform stubPlatform = StubInAppPurchasePlatform(); late BillingClientManager manager; late Completer<void> connectedCompleter; const String startConnectionCall = 'BillingClient#startConnection(BillingClientStateListener)'; const String endConnectionCall = 'BillingClient#endConnection()'; const String onBillingServiceDisconnectedCallback = 'BillingClientStateListener#onBillingServiceDisconnected()'; setUpAll(() => TestDefaultBinaryMessengerBinding .instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, stubPlatform.fakeMethodCallHandler)); setUp(() { WidgetsFlutterBinding.ensureInitialized(); connectedCompleter = Completer<void>.sync(); stubPlatform.addResponse( name: startConnectionCall, value: buildBillingResultMap( const BillingResultWrapper(responseCode: BillingResponse.ok), ), additionalStepBeforeReturn: (dynamic _) => connectedCompleter.future, ); stubPlatform.addResponse(name: endConnectionCall); manager = BillingClientManager(); }); tearDown(() => stubPlatform.reset()); group('BillingClientWrapper', () { test('connects on initialization', () { expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(1)); }); test('waits for connection before executing the operations', () async { final Completer<void> calledCompleter1 = Completer<void>(); final Completer<void> calledCompleter2 = Completer<void>(); unawaited(manager.runWithClient((BillingClient _) async { calledCompleter1.complete(); return const BillingResultWrapper(responseCode: BillingResponse.ok); })); unawaited(manager.runWithClientNonRetryable( (BillingClient _) async => calledCompleter2.complete(), )); expect(calledCompleter1.isCompleted, equals(false)); expect(calledCompleter1.isCompleted, equals(false)); connectedCompleter.complete(); await expectLater(calledCompleter1.future, completes); await expectLater(calledCompleter2.future, completes); }); test('re-connects when client sends onBillingServiceDisconnected', () async { connectedCompleter.complete(); // Ensures all asynchronous connected code finishes. await manager.runWithClientNonRetryable((_) async {}); await manager.client.callHandler( const MethodCall(onBillingServiceDisconnectedCallback, <String, dynamic>{'handle': 0}), ); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(2)); }); test('re-connects when host calls reconnectWithBillingChoiceMode', () async { connectedCompleter.complete(); // Ensures all asynchronous connected code finishes. await manager.runWithClientNonRetryable((_) async {}); await manager.reconnectWithBillingChoiceMode( BillingChoiceMode.alternativeBillingOnly); // Verify that connection was ended. expect(stubPlatform.countPreviousCalls(endConnectionCall), equals(1)); stubPlatform.reset(); late Map<Object?, Object?> arguments; stubPlatform.addResponse( name: startConnectionCall, additionalStepBeforeReturn: (dynamic value) => arguments = value as Map<dynamic, dynamic>, ); /// Fake the disconnect that we would expect from a endConnectionCall. await manager.client.callHandler( const MethodCall(onBillingServiceDisconnectedCallback, <String, dynamic>{'handle': 0}), ); // Verify that after connection ended reconnect was called. expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(1)); expect(arguments['billingChoiceMode'], 1); }); test( 're-connects when operation returns BillingResponse.serviceDisconnected', () async { connectedCompleter.complete(); int timesCalled = 0; final BillingResultWrapper result = await manager.runWithClient( (BillingClient _) async { timesCalled++; return BillingResultWrapper( responseCode: timesCalled == 1 ? BillingResponse.serviceDisconnected : BillingResponse.ok, ); }, ); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(2)); expect(timesCalled, equals(2)); expect(result.responseCode, equals(BillingResponse.ok)); }, ); test('does not re-connect when disposed', () { connectedCompleter.complete(); manager.dispose(); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(1)); expect(stubPlatform.countPreviousCalls(endConnectionCall), equals(1)); }); test( 'Emits UserChoiceDetailsWrapper when onUserChoiceAlternativeBilling is called', () async { connectedCompleter.complete(); // Ensures all asynchronous connected code finishes. await manager.runWithClientNonRetryable((_) async {}); const UserChoiceDetailsWrapper expected = UserChoiceDetailsWrapper( originalExternalTransactionId: 'TransactionId', externalTransactionToken: 'TransactionToken', products: <UserChoiceDetailsProductWrapper>[ UserChoiceDetailsProductWrapper( id: 'id1', offerToken: 'offerToken1', productType: ProductType.inapp), UserChoiceDetailsProductWrapper( id: 'id2', offerToken: 'offerToken2', productType: ProductType.inapp), ], ); final Future<UserChoiceDetailsWrapper> detailsFuture = manager.userChoiceDetailsStream.first; manager.onUserChoiceAlternativeBilling(expected); expect(await detailsFuture, expected); }); }); }
packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_manager_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_manager_test.dart", "repo_id": "packages", "token_count": 2325 }
1,039
// 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/services.dart'; import '../messages.g.dart'; import 'sk_product_wrapper.dart'; InAppPurchaseAPI _hostApi = InAppPurchaseAPI(); /// A request maker that handles all the requests made by SKRequest subclasses. /// /// There are multiple [SKRequest](https://developer.apple.com/documentation/storekit/skrequest?language=objc) subclasses handling different requests in the `StoreKit` with multiple delegate methods, /// we consolidated all the `SKRequest` subclasses into this class to make requests in a more straightforward way. /// The request maker will create a SKRequest object, immediately starting it, and completing the future successfully or throw an exception depending on what happened to the request. class SKRequestMaker { /// Fetches product information for a list of given product identifiers. /// /// The `productIdentifiers` should contain legitimate product identifiers that you declared for the products in the iTunes Connect. Invalid identifiers /// will be stored and returned in [SkProductResponseWrapper.invalidProductIdentifiers]. Duplicate values in `productIdentifiers` will be omitted. /// If `productIdentifiers` is null, an `storekit_invalid_argument` error will be returned. If `productIdentifiers` is empty, a [SkProductResponseWrapper] /// will still be returned with [SkProductResponseWrapper.products] being null. /// /// [SkProductResponseWrapper] is returned if there is no error during the request. /// A [PlatformException] is thrown if the platform code making the request fails. Future<SkProductResponseWrapper> startProductRequest( List<String> productIdentifiers) async { final SKProductsResponseMessage productResponsePigeon = await _hostApi.startProductRequest(productIdentifiers); // should products be null or <String>[] ? if (productResponsePigeon.products == null) { throw PlatformException( code: 'storekit_no_response', message: 'StoreKit: Failed to get response from platform.', ); } return SkProductResponseWrapper.convertFromPigeon(productResponsePigeon); } /// Uses [SKReceiptRefreshRequest](https://developer.apple.com/documentation/storekit/skreceiptrefreshrequest?language=objc) to request a new receipt. /// /// If the receipt is invalid or missing, you can use this API to request a new receipt. /// The [receiptProperties] is optional and it exists only for [sandbox testing](https://developer.apple.com/apple-pay/sandbox-testing/). In the production app, call this API without pass in the [receiptProperties] parameter. /// To test in the sandbox, you can request a receipt with any combination of properties to test the state transitions related to [`Volume Purchase Plan`](https://www.apple.com/business/site/docs/VPP_Business_Guide.pdf) receipts. /// The valid keys in the receiptProperties are below (All of them are of type bool): /// * isExpired: whether the receipt is expired. /// * isRevoked: whether the receipt has been revoked. /// * isVolumePurchase: whether the receipt is a Volume Purchase Plan receipt. Future<void> startRefreshReceiptRequest( {Map<String, dynamic>? receiptProperties}) { return _hostApi.refreshReceipt(receiptProperties: receiptProperties); } }
packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_request_maker.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_request_maker.dart", "repo_id": "packages", "token_count": 938 }
1,040
// 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:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; import '../fakes/fake_storekit_platform.dart'; import '../test_api.g.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform(); setUpAll(() { TestInAppPurchaseApi.setup(fakeStoreKitPlatform); }); test( 'handlePaymentQueueDelegateCallbacks should call SKPaymentQueueDelegateWrapper.shouldContinueTransaction', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); final TestPaymentQueueDelegate testDelegate = TestPaymentQueueDelegate(); await queue.setDelegate(testDelegate); final Map<String, dynamic> arguments = <String, dynamic>{ 'storefront': <String, String>{ 'countryCode': 'USA', 'identifier': 'unique_identifier', }, 'transaction': <String, dynamic>{ 'payment': <String, dynamic>{ 'productIdentifier': 'product_identifier', } }, }; final Object? result = await queue.handlePaymentQueueDelegateCallbacks( MethodCall('shouldContinueTransaction', arguments), ); expect(result, false); expect( testDelegate.log, <Matcher>{ equals('shouldContinueTransaction'), }, ); }); test( 'handlePaymentQueueDelegateCallbacks should call SKPaymentQueueDelegateWrapper.shouldShowPriceConsent', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); final TestPaymentQueueDelegate testDelegate = TestPaymentQueueDelegate(); await queue.setDelegate(testDelegate); final bool result = (await queue.handlePaymentQueueDelegateCallbacks( const MethodCall('shouldShowPriceConsent'), ))! as bool; expect(result, false); expect( testDelegate.log, <Matcher>{ equals('shouldShowPriceConsent'), }, ); }); test( 'handleObserverCallbacks should call SKTransactionObserverWrapper.restoreCompletedTransactionsFailed', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); final TestTransactionObserverWrapper testObserver = TestTransactionObserverWrapper(); queue.setTransactionObserver(testObserver); final Map<dynamic, dynamic> arguments = <dynamic, dynamic>{ 'code': 100, 'domain': 'domain', 'userInfo': <String, dynamic>{'error': 'underlying_error'}, }; await queue.handleObserverCallbacks( MethodCall('restoreCompletedTransactionsFailed', arguments), ); expect( testObserver.log, <Matcher>{ equals('restoreCompletedTransactionsFailed'), }, ); }); } class TestTransactionObserverWrapper extends SKTransactionObserverWrapper { final List<String> log = <String>[]; @override void updatedTransactions( {required List<SKPaymentTransactionWrapper> transactions}) { log.add('updatedTransactions'); } @override void removedTransactions( {required List<SKPaymentTransactionWrapper> transactions}) { log.add('removedTransactions'); } @override void restoreCompletedTransactionsFailed({required SKError error}) { log.add('restoreCompletedTransactionsFailed'); } @override void paymentQueueRestoreCompletedTransactionsFinished() { log.add('paymentQueueRestoreCompletedTransactionsFinished'); } @override bool shouldAddStorePayment( {required SKPaymentWrapper payment, required SKProductWrapper product}) { log.add('shouldAddStorePayment'); return false; } } class TestPaymentQueueDelegate extends SKPaymentQueueDelegateWrapper { final List<String> log = <String>[]; @override bool shouldContinueTransaction( SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) { log.add('shouldContinueTransaction'); return false; } @override bool shouldShowPriceConsent() { log.add('shouldShowPriceConsent'); return false; } }
packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_payment_queue_delegate_api_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_payment_queue_delegate_api_test.dart", "repo_id": "packages", "token_count": 1456 }
1,041
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.localauth"> <uses-permission android:name="android.permission.USE_BIOMETRIC" /> </manifest>
packages/packages/local_auth/local_auth_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 71 }
1,042
// 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.1.2), do not edit directly. // See also: https://pub.dev/packages/pigeon #import "messages.g.h" #if TARGET_OS_OSX #import <FlutterMacOS/FlutterMacOS.h> #else #import <Flutter/Flutter.h> #endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSArray *wrapResult(id result, FlutterError *error) { if (error) { return @[ error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] ]; } return @[ result ?: [NSNull null] ]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } /// Possible outcomes of an authentication attempt. @implementation FLADAuthResultBox - (instancetype)initWithValue:(FLADAuthResult)value { self = [super init]; if (self) { _value = value; } return self; } @end /// Pigeon equivalent of the subset of BiometricType used by iOS. @implementation FLADAuthBiometricBox - (instancetype)initWithValue:(FLADAuthBiometric)value { self = [super init]; if (self) { _value = value; } return self; } @end @interface FLADAuthStrings () + (FLADAuthStrings *)fromList:(NSArray *)list; + (nullable FLADAuthStrings *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FLADAuthOptions () + (FLADAuthOptions *)fromList:(NSArray *)list; + (nullable FLADAuthOptions *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FLADAuthResultDetails () + (FLADAuthResultDetails *)fromList:(NSArray *)list; + (nullable FLADAuthResultDetails *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FLADAuthBiometricWrapper () + (FLADAuthBiometricWrapper *)fromList:(NSArray *)list; + (nullable FLADAuthBiometricWrapper *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @implementation FLADAuthStrings + (instancetype)makeWithReason:(NSString *)reason lockOut:(NSString *)lockOut goToSettingsButton:(NSString *)goToSettingsButton goToSettingsDescription:(NSString *)goToSettingsDescription cancelButton:(NSString *)cancelButton localizedFallbackTitle:(nullable NSString *)localizedFallbackTitle { FLADAuthStrings *pigeonResult = [[FLADAuthStrings alloc] init]; pigeonResult.reason = reason; pigeonResult.lockOut = lockOut; pigeonResult.goToSettingsButton = goToSettingsButton; pigeonResult.goToSettingsDescription = goToSettingsDescription; pigeonResult.cancelButton = cancelButton; pigeonResult.localizedFallbackTitle = localizedFallbackTitle; return pigeonResult; } + (FLADAuthStrings *)fromList:(NSArray *)list { FLADAuthStrings *pigeonResult = [[FLADAuthStrings alloc] init]; pigeonResult.reason = GetNullableObjectAtIndex(list, 0); pigeonResult.lockOut = GetNullableObjectAtIndex(list, 1); pigeonResult.goToSettingsButton = GetNullableObjectAtIndex(list, 2); pigeonResult.goToSettingsDescription = GetNullableObjectAtIndex(list, 3); pigeonResult.cancelButton = GetNullableObjectAtIndex(list, 4); pigeonResult.localizedFallbackTitle = GetNullableObjectAtIndex(list, 5); return pigeonResult; } + (nullable FLADAuthStrings *)nullableFromList:(NSArray *)list { return (list) ? [FLADAuthStrings fromList:list] : nil; } - (NSArray *)toList { return @[ self.reason ?: [NSNull null], self.lockOut ?: [NSNull null], self.goToSettingsButton ?: [NSNull null], self.goToSettingsDescription ?: [NSNull null], self.cancelButton ?: [NSNull null], self.localizedFallbackTitle ?: [NSNull null], ]; } @end @implementation FLADAuthOptions + (instancetype)makeWithBiometricOnly:(BOOL)biometricOnly sticky:(BOOL)sticky useErrorDialogs:(BOOL)useErrorDialogs { FLADAuthOptions *pigeonResult = [[FLADAuthOptions alloc] init]; pigeonResult.biometricOnly = biometricOnly; pigeonResult.sticky = sticky; pigeonResult.useErrorDialogs = useErrorDialogs; return pigeonResult; } + (FLADAuthOptions *)fromList:(NSArray *)list { FLADAuthOptions *pigeonResult = [[FLADAuthOptions alloc] init]; pigeonResult.biometricOnly = [GetNullableObjectAtIndex(list, 0) boolValue]; pigeonResult.sticky = [GetNullableObjectAtIndex(list, 1) boolValue]; pigeonResult.useErrorDialogs = [GetNullableObjectAtIndex(list, 2) boolValue]; return pigeonResult; } + (nullable FLADAuthOptions *)nullableFromList:(NSArray *)list { return (list) ? [FLADAuthOptions fromList:list] : nil; } - (NSArray *)toList { return @[ @(self.biometricOnly), @(self.sticky), @(self.useErrorDialogs), ]; } @end @implementation FLADAuthResultDetails + (instancetype)makeWithResult:(FLADAuthResult)result errorMessage:(nullable NSString *)errorMessage errorDetails:(nullable NSString *)errorDetails { FLADAuthResultDetails *pigeonResult = [[FLADAuthResultDetails alloc] init]; pigeonResult.result = result; pigeonResult.errorMessage = errorMessage; pigeonResult.errorDetails = errorDetails; return pigeonResult; } + (FLADAuthResultDetails *)fromList:(NSArray *)list { FLADAuthResultDetails *pigeonResult = [[FLADAuthResultDetails alloc] init]; pigeonResult.result = [GetNullableObjectAtIndex(list, 0) integerValue]; pigeonResult.errorMessage = GetNullableObjectAtIndex(list, 1); pigeonResult.errorDetails = GetNullableObjectAtIndex(list, 2); return pigeonResult; } + (nullable FLADAuthResultDetails *)nullableFromList:(NSArray *)list { return (list) ? [FLADAuthResultDetails fromList:list] : nil; } - (NSArray *)toList { return @[ @(self.result), self.errorMessage ?: [NSNull null], self.errorDetails ?: [NSNull null], ]; } @end @implementation FLADAuthBiometricWrapper + (instancetype)makeWithValue:(FLADAuthBiometric)value { FLADAuthBiometricWrapper *pigeonResult = [[FLADAuthBiometricWrapper alloc] init]; pigeonResult.value = value; return pigeonResult; } + (FLADAuthBiometricWrapper *)fromList:(NSArray *)list { FLADAuthBiometricWrapper *pigeonResult = [[FLADAuthBiometricWrapper alloc] init]; pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue]; return pigeonResult; } + (nullable FLADAuthBiometricWrapper *)nullableFromList:(NSArray *)list { return (list) ? [FLADAuthBiometricWrapper fromList:list] : nil; } - (NSArray *)toList { return @[ @(self.value), ]; } @end @interface FLADLocalAuthApiCodecReader : FlutterStandardReader @end @implementation FLADLocalAuthApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FLADAuthBiometricWrapper fromList:[self readValue]]; case 129: return [FLADAuthOptions fromList:[self readValue]]; case 130: return [FLADAuthResultDetails fromList:[self readValue]]; case 131: return [FLADAuthStrings fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FLADLocalAuthApiCodecWriter : FlutterStandardWriter @end @implementation FLADLocalAuthApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FLADAuthBiometricWrapper class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLADAuthOptions class]]) { [self writeByte:129]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLADAuthResultDetails class]]) { [self writeByte:130]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLADAuthStrings class]]) { [self writeByte:131]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FLADLocalAuthApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FLADLocalAuthApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FLADLocalAuthApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FLADLocalAuthApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FLADLocalAuthApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FLADLocalAuthApiCodecReaderWriter *readerWriter = [[FLADLocalAuthApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void SetUpFLADLocalAuthApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLADLocalAuthApi> *api) { /// Returns true if this device supports authentication. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.isDeviceSupported" binaryMessenger:binaryMessenger codec:FLADLocalAuthApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(isDeviceSupportedWithError:)], @"FLADLocalAuthApi api (%@) doesn't respond to @selector(isDeviceSupportedWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; NSNumber *output = [api isDeviceSupportedWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns true if this device can support biometric authentication, whether /// any biometrics are enrolled or not. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.deviceCanSupportBiometrics" binaryMessenger:binaryMessenger codec:FLADLocalAuthApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(deviceCanSupportBiometricsWithError:)], @"FLADLocalAuthApi api (%@) doesn't respond to " @"@selector(deviceCanSupportBiometricsWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; NSNumber *output = [api deviceCanSupportBiometricsWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the biometric types that are enrolled, and can thus be used /// without additional setup. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.getEnrolledBiometrics" binaryMessenger:binaryMessenger codec:FLADLocalAuthApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(getEnrolledBiometricsWithError:)], @"FLADLocalAuthApi api (%@) doesn't respond to " @"@selector(getEnrolledBiometricsWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; NSArray<FLADAuthBiometricWrapper *> *output = [api getEnrolledBiometricsWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.authenticate" binaryMessenger:binaryMessenger codec:FLADLocalAuthApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(authenticateWithOptions:strings:completion:)], @"FLADLocalAuthApi api (%@) doesn't respond to " @"@selector(authenticateWithOptions:strings:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLADAuthOptions *arg_options = GetNullableObjectAtIndex(args, 0); FLADAuthStrings *arg_strings = GetNullableObjectAtIndex(args, 1); [api authenticateWithOptions:arg_options strings:arg_strings completion:^(FLADAuthResultDetails *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } }
packages/packages/local_auth/local_auth_darwin/darwin/Classes/messages.g.m/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/darwin/Classes/messages.g.m", "repo_id": "packages", "token_count": 4807 }
1,043
// 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. #include <UserConsentVerifierInterop.h> #include <flutter/encodable_value.h> #include <flutter/method_channel.h> #include <flutter/plugin_registrar_windows.h> #include <flutter/standard_method_codec.h> #include <pplawait.h> #include <ppltasks.h> // Include prior to C++/WinRT Headers #include <wil/cppwinrt.h> #include <wil/win32_helpers.h> #include <windows.h> #include <winrt/Windows.Foundation.h> #include <winrt/Windows.Security.Credentials.UI.h> #include <map> #include <memory> #include <sstream> #include "messages.g.h" namespace local_auth_windows { // Abstract class that is used to determine whether a user // has given consent to a particular action, and if the system // supports asking this question. class UserConsentVerifier { public: UserConsentVerifier() {} virtual ~UserConsentVerifier() = default; // Abstract method that request the user's verification // given the provided reason. virtual winrt::Windows::Foundation::IAsyncOperation< winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult> RequestVerificationForWindowAsync(std::wstring localized_reason) = 0; // Abstract method that returns weather the system supports Windows Hello. virtual winrt::Windows::Foundation::IAsyncOperation< winrt::Windows::Security::Credentials::UI:: UserConsentVerifierAvailability> CheckAvailabilityAsync() = 0; // Disallow copy and move. UserConsentVerifier(const UserConsentVerifier&) = delete; UserConsentVerifier& operator=(const UserConsentVerifier&) = delete; }; class LocalAuthPlugin : public flutter::Plugin, public LocalAuthApi { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); // Creates a plugin instance that will create the dialog and associate // it with the HWND returned from the provided function. LocalAuthPlugin(std::function<HWND()> window_provider); // Creates a plugin instance with the given UserConsentVerifier instance. // Exists for unit testing with mock implementations. LocalAuthPlugin(std::unique_ptr<UserConsentVerifier> user_consent_verifier); virtual ~LocalAuthPlugin(); // LocalAuthApi: void IsDeviceSupported( std::function<void(ErrorOr<bool> reply)> result) override; void Authenticate(const std::string& localized_reason, std::function<void(ErrorOr<bool> reply)> result) override; private: std::unique_ptr<UserConsentVerifier> user_consent_verifier_; // Starts authentication process. winrt::fire_and_forget AuthenticateCoroutine( const std::string& localized_reason, std::function<void(ErrorOr<bool> reply)> result); // Returns whether the system supports Windows Hello. winrt::fire_and_forget IsDeviceSupportedCoroutine( std::function<void(ErrorOr<bool> reply)> result); }; } // namespace local_auth_windows
packages/packages/local_auth/local_auth_windows/windows/local_auth.h/0
{ "file_path": "packages/packages/local_auth/local_auth_windows/windows/local_auth.h", "repo_id": "packages", "token_count": 931 }
1,044
// 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 'common.dart'; import 'constants.dart'; import 'skiaperf.dart'; /// Convenient class to capture the benchmarks in the Flutter engine repo. class FlutterEngineMetricPoint extends MetricPoint { /// Creates a metric point for the Flutter engine repository. /// /// The `name`, `value`, and `gitRevision` parameters must not be null. FlutterEngineMetricPoint( String name, double value, String gitRevision, { Map<String, String> moreTags = const <String, String>{}, }) : super( value, <String, String>{ kNameKey: name, kGithubRepoKey: kFlutterEngineRepo, kGitRevisionKey: gitRevision, }..addAll(moreTags), ); } /// All Flutter performance metrics (framework, engine, ...) should be written /// to this destination. class FlutterDestination extends MetricDestination { FlutterDestination._(this._skiaPerfDestination); /// Creates a [FlutterDestination] from service account JSON. static Future<FlutterDestination> makeFromCredentialsJson( Map<String, dynamic> json, {bool isTesting = false}) async { final SkiaPerfDestination skiaPerfDestination = await SkiaPerfDestination.makeFromGcpCredentials(json, isTesting: isTesting); return FlutterDestination._(skiaPerfDestination); } /// Creates a [FlutterDestination] from an OAuth access token. static Future<FlutterDestination> makeFromAccessToken( String accessToken, String projectId, {bool isTesting = false}) async { final SkiaPerfDestination skiaPerfDestination = await SkiaPerfDestination.makeFromAccessToken(accessToken, projectId, isTesting: isTesting); return FlutterDestination._(skiaPerfDestination); } @override Future<void> update( List<MetricPoint> points, DateTime commitTime, String taskName) async { await _skiaPerfDestination.update(points, commitTime, taskName); } final SkiaPerfDestination _skiaPerfDestination; }
packages/packages/metrics_center/lib/src/flutter.dart/0
{ "file_path": "packages/packages/metrics_center/lib/src/flutter.dart", "repo_id": "packages", "token_count": 753 }
1,045
// 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. // Test that the resource record cache works correctly. In particular, make // sure that it removes all entries for a name before insertingrecords // of that name. import 'dart:io'; import 'package:multicast_dns/src/native_protocol_client.dart' show ResourceRecordCache; import 'package:multicast_dns/src/resource_record.dart'; import 'package:test/test.dart'; void main() { testOverwrite(); testTimeout(); } void testOverwrite() { test('Cache can overwrite entries', () { final InternetAddress ip1 = InternetAddress('192.168.1.1'); final InternetAddress ip2 = InternetAddress('192.168.1.2'); final int valid = DateTime.now().millisecondsSinceEpoch + 86400 * 1000; final ResourceRecordCache cache = ResourceRecordCache(); // Add two different records. cache.updateRecords(<ResourceRecord>[ IPAddressResourceRecord('hest', valid, address: ip1), IPAddressResourceRecord('fisk', valid, address: ip2) ]); expect(cache.entryCount, 2); // Update these records. cache.updateRecords(<ResourceRecord>[ IPAddressResourceRecord('hest', valid, address: ip1), IPAddressResourceRecord('fisk', valid, address: ip2) ]); expect(cache.entryCount, 2); // Add two records with the same name (should remove the old one // with that name only.) cache.updateRecords(<ResourceRecord>[ IPAddressResourceRecord('hest', valid, address: ip1), IPAddressResourceRecord('hest', valid, address: ip2) ]); expect(cache.entryCount, 3); // Overwrite the two cached entries with one with the same name. cache.updateRecords(<ResourceRecord>[ IPAddressResourceRecord('hest', valid, address: ip1), ]); expect(cache.entryCount, 2); }); } void testTimeout() { test('Cache can evict records after timeout', () { final InternetAddress ip1 = InternetAddress('192.168.1.1'); final int valid = DateTime.now().millisecondsSinceEpoch + 86400 * 1000; final int notValid = DateTime.now().millisecondsSinceEpoch - 1; final ResourceRecordCache cache = ResourceRecordCache(); cache.updateRecords( <ResourceRecord>[IPAddressResourceRecord('hest', valid, address: ip1)]); expect(cache.entryCount, 1); cache.updateRecords(<ResourceRecord>[ IPAddressResourceRecord('fisk', notValid, address: ip1) ]); List<ResourceRecord> results = <ResourceRecord>[]; cache.lookup('hest', ResourceRecordType.addressIPv4, results); expect(results.isEmpty, isFalse); results = <ResourceRecord>[]; cache.lookup('fisk', ResourceRecordType.addressIPv4, results); expect(results.isEmpty, isTrue); expect(cache.entryCount, 1); }); }
packages/packages/multicast_dns/test/resource_record_cache_test.dart/0
{ "file_path": "packages/packages/multicast_dns/test/resource_record_cache_test.dart", "repo_id": "packages", "token_count": 941 }
1,046
#include "Generated.xcconfig"
packages/packages/palette_generator/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "packages/packages/palette_generator/example/ios/Flutter/Release.xcconfig", "repo_id": "packages", "token_count": 12 }
1,047
name: palette_generator description: Flutter package for generating palette colors from a source image. repository: https://github.com/flutter/packages/tree/main/packages/palette_generator issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+palette_generator%22 version: 0.3.3+3 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: collection: ^1.15.0 flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter topics: - color - ui
packages/packages/palette_generator/pubspec.yaml/0
{ "file_path": "packages/packages/palette_generator/pubspec.yaml", "repo_id": "packages", "token_count": 206 }
1,048
// 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.pathprovider; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import android.os.Environment; import org.junit.Test; public class StorageDirectoryMapperTest { @org.junit.Test public void testAndroidType_null() { assertNull(StorageDirectoryMapper.androidType(null)); } @org.junit.Test public void testAndroidType_valid() { assertEquals(Environment.DIRECTORY_MUSIC, StorageDirectoryMapper.androidType(0)); assertEquals(Environment.DIRECTORY_PODCASTS, StorageDirectoryMapper.androidType(1)); assertEquals(Environment.DIRECTORY_RINGTONES, StorageDirectoryMapper.androidType(2)); assertEquals(Environment.DIRECTORY_ALARMS, StorageDirectoryMapper.androidType(3)); assertEquals(Environment.DIRECTORY_NOTIFICATIONS, StorageDirectoryMapper.androidType(4)); assertEquals(Environment.DIRECTORY_PICTURES, StorageDirectoryMapper.androidType(5)); assertEquals(Environment.DIRECTORY_MOVIES, StorageDirectoryMapper.androidType(6)); assertEquals(Environment.DIRECTORY_DOWNLOADS, StorageDirectoryMapper.androidType(7)); assertEquals(Environment.DIRECTORY_DCIM, StorageDirectoryMapper.androidType(8)); } @Test public void testAndroidType_invalid() { try { assertEquals(Environment.DIRECTORY_DCIM, StorageDirectoryMapper.androidType(10)); fail(); } catch (IllegalArgumentException e) { assertEquals("Unknown index: " + 10, e.getMessage()); } } }
packages/packages/path_provider/path_provider_android/android/src/test/java/io/flutter/plugins/pathprovider/StorageDirectoryMapperTest.java/0
{ "file_path": "packages/packages/path_provider/path_provider_android/android/src/test/java/io/flutter/plugins/pathprovider/StorageDirectoryMapperTest.java", "repo_id": "packages", "token_count": 548 }
1,049